]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: prepared fullscreen support and clean-up
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2011 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Christophe Massiot <massiot@via.ecp.fr>
9  *          Derk-Jan Hartman <hartman at videolan.org>
10  *          Felix Paul Kühne <fkuehne at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>                                      /* malloc(), free() */
31 #include <sys/param.h>                                    /* for MAXPATHLEN */
32 #include <string.h>
33 #include <vlc_common.h>
34 #include <vlc_keys.h>
35 #include <vlc_dialog.h>
36 #include <vlc_url.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
41
42 #import "intf.h"
43 #import "MainMenu.h"
44 #import "MainWindow.h"
45 #import "fspanel.h"
46 #import "vout.h"
47 #import "prefs.h"
48 #import "playlist.h"
49 #import "playlistinfo.h"
50 #import "controls.h"
51 #import "open.h"
52 #import "wizard.h"
53 #import "bookmarks.h"
54 #import "coredialogs.h"
55 #import "embeddedwindow.h"
56 #import "AppleRemote.h"
57 #import "eyetv.h"
58 #import "simple_prefs.h"
59 #import "CoreInteraction.h"
60 #import "TrackSynchronization.h"
61
62 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
63 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
64
65 /*****************************************************************************
66  * Local prototypes.
67  *****************************************************************************/
68 static void Run ( intf_thread_t *p_intf );
69
70 static void updateProgressPanel (void *, const char *, float);
71 static bool checkProgressPanel (void *);
72 static void destroyProgressPanel (void *);
73
74 static void MsgCallback( msg_cb_data_t *, const msg_item_t * );
75
76 static int InputEvent( vlc_object_t *, const char *,
77                       vlc_value_t, vlc_value_t, void * );
78 static int PLItemChanged( vlc_object_t *, const char *,
79                          vlc_value_t, vlc_value_t, void * );
80 static int PlaylistUpdated( vlc_object_t *, const char *,
81                            vlc_value_t, vlc_value_t, void * );
82 static int PlaybackModeUpdated( vlc_object_t *, const char *,
83                                vlc_value_t, vlc_value_t, void * );
84 static int VolumeUpdated( vlc_object_t *, const char *,
85                          vlc_value_t, vlc_value_t, void * );
86
87 #pragma mark -
88 #pragma mark VLC Interface Object Callbacks
89
90 /*****************************************************************************
91  * OpenIntf: initialize interface
92  *****************************************************************************/
93 int OpenIntf ( vlc_object_t *p_this )
94 {
95     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
96     [VLCApplication sharedApplication];
97     intf_thread_t *p_intf = (intf_thread_t*) p_this;
98
99     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
100     if( p_intf->p_sys == NULL )
101         return VLC_ENOMEM;
102
103     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
104
105     /* subscribe to LibVLCCore's messages */
106     p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
107     p_intf->pf_run = Run;
108     p_intf->b_should_run_on_first_thread = true;
109
110     [o_pool release];
111     return VLC_SUCCESS;
112 }
113
114 /*****************************************************************************
115  * CloseIntf: destroy interface
116  *****************************************************************************/
117 void CloseIntf ( vlc_object_t *p_this )
118 {
119     intf_thread_t *p_intf = (intf_thread_t*) p_this;
120
121     free( p_intf->p_sys );
122 }
123
124 static int WindowControl( vout_window_t *, int i_query, va_list );
125
126 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
127 {
128     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
129     intf_thread_t *p_intf = VLCIntf;
130     if (!p_intf) {
131         msg_Err( p_wnd, "Mac OS X interface not found" );
132         return VLC_EGENERIC;
133     }
134
135     int i_x = cfg->x;
136     int i_y = cfg->y;
137     unsigned i_width = cfg->width;
138     unsigned i_height = cfg->height;
139     p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
140
141     if ( !p_wnd->handle.nsobject ) {
142         msg_Err( p_wnd, "got no video view from the interface" );
143         [o_pool release];
144         return VLC_EGENERIC;
145     }
146
147     [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
148     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
149     p_wnd->control = WindowControl;
150     p_wnd->sys = (vout_window_sys_t *)VLCIntf;
151     [o_pool release];
152     return VLC_SUCCESS;
153 }
154
155 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
156 {
157     /* TODO */
158     if( i_query == VOUT_WINDOW_SET_STATE )
159         NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
160     else if( i_query == VOUT_WINDOW_SET_SIZE )
161     {
162         NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
163         unsigned int i_width  = va_arg( args, unsigned int );
164         unsigned int i_height = va_arg( args, unsigned int );
165         [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
166     }
167     else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
168         NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
169     else
170         NSLog( @"WindowControl: unknown query" );
171     return VLC_SUCCESS;
172 }
173
174 void WindowClose( vout_window_t *p_wnd )
175 {
176     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
177     [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
178     NSLog( @"Window Close" );
179     // tell the interface to get rid of the video, TODO
180     [o_pool release];
181 }
182
183 /*****************************************************************************
184  * Run: main loop
185  *****************************************************************************/
186 static NSLock * o_appLock = nil;    // controls access to f_appExit
187 static int f_appExit = 0;           // set to 1 when application termination signaled
188
189 static void Run( intf_thread_t *p_intf )
190 {
191     sigset_t set;
192
193     /* Make sure the "force quit" menu item does quit instantly.
194      * VLC overrides SIGTERM which is sent by the "force quit"
195      * menu item to make sure daemon mode quits gracefully, so
196      * we un-override SIGTERM here. */
197     sigemptyset( &set );
198     sigaddset( &set, SIGTERM );
199     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
200
201     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
202     [VLCApplication sharedApplication];
203
204     o_appLock = [[NSLock alloc] init];
205
206     [[VLCMain sharedInstance] setIntf: p_intf];
207     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
208
209     [NSApp run];
210     [[VLCMain sharedInstance] applicationWillTerminate:nil];
211     [o_appLock release];
212     [o_pool release];
213 }
214
215 #pragma mark -
216 #pragma mark Variables Callback
217
218 /*****************************************************************************
219  * MsgCallback: Callback triggered by the core once a new debug message is
220  * ready to be displayed. We store everything in a NSArray in our Cocoa part
221  * of this file.
222  *****************************************************************************/
223 static void MsgCallback( msg_cb_data_t *data, const msg_item_t *item )
224 {
225     int canc = vlc_savecancel();
226
227     /* this may happen from time to time, let's bail out as info would be useless anyway */
228     if( !item->psz_module || !item->psz_msg )
229         return;
230
231     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
232     [[VLCMain sharedInstance] processReceivedlibvlcMessage: item];
233     [o_pool release];
234
235     vlc_restorecancel( canc );
236 }
237
238 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
239                        vlc_value_t oldval, vlc_value_t new_val, void *param )
240 {
241     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
242     switch (new_val.i_int) {
243         case INPUT_EVENT_STATE:
244             [[VLCMain sharedInstance] playbackStatusUpdated];
245             break;
246         case INPUT_EVENT_RATE:
247             [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
248             break;
249         case INPUT_EVENT_POSITION:
250             [[VLCMain sharedInstance] updatePlaybackPosition];
251             break;
252         case INPUT_EVENT_TITLE:
253         case INPUT_EVENT_CHAPTER:
254             break;
255         case INPUT_EVENT_CACHE:
256             [[VLCMain sharedInstance] updateMainWindow];
257             break;
258         case INPUT_EVENT_STATISTICS:
259             [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
260             break;
261         case INPUT_EVENT_ES:
262             break;
263         case INPUT_EVENT_TELETEXT:
264             NSLog( @"teletext" );
265             break;
266         case INPUT_EVENT_AOUT:
267             break;
268         case INPUT_EVENT_VOUT:
269             break;
270         case INPUT_EVENT_ITEM_META:
271         case INPUT_EVENT_ITEM_INFO:
272             [[VLCMain sharedInstance] updateName];
273             [[VLCMain sharedInstance] updateInfoandMetaPanel];
274             break;
275         case INPUT_EVENT_BOOKMARK:
276             break;
277         case INPUT_EVENT_RECORD:
278             break;
279         case INPUT_EVENT_PROGRAM:
280             break;
281         case INPUT_EVENT_ITEM_EPG:
282             break;
283         case INPUT_EVENT_SIGNAL:
284             break;
285
286         case INPUT_EVENT_ITEM_NAME:
287             [[VLCMain sharedInstance] updateName];
288             [[VLCMain sharedInstance] playlistUpdated];
289             break;
290
291         case INPUT_EVENT_AUDIO_DELAY:
292         case INPUT_EVENT_SUBTITLE_DELAY:
293             [[VLCMain sharedInstance] updateDelays];
294             break;
295
296         case INPUT_EVENT_DEAD:
297             [[VLCMain sharedInstance] updateName];
298             [[VLCMain sharedInstance] updatePlaybackPosition];
299             break;
300
301         case INPUT_EVENT_ABORT:
302             //NSLog( @"input stopped by user" );
303             break;
304
305         default:
306             //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
307             break;
308     }
309
310     [o_pool release];
311     return VLC_SUCCESS;
312 }
313
314 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
315                          vlc_value_t oldval, vlc_value_t new_val, void *param )
316 {
317     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
318     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
319
320     [o_pool release];
321     return VLC_SUCCESS;
322 }
323
324 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
325                          vlc_value_t oldval, vlc_value_t new_val, void *param )
326 {
327     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
328     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
329
330     [o_pool release];
331     return VLC_SUCCESS;
332 }
333
334 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
335                          vlc_value_t oldval, vlc_value_t new_val, void *param )
336 {
337     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
338     [[VLCMain sharedInstance] playbackModeUpdated];
339
340     [o_pool release];
341     return VLC_SUCCESS;
342 }
343
344 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
345                          vlc_value_t oldval, vlc_value_t new_val, void *param )
346 {
347     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
348     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
349
350     [o_pool release];
351     return VLC_SUCCESS;
352 }
353
354 /*****************************************************************************
355  * ShowController: Callback triggered by the show-intf playlist variable
356  * through the ShowIntf-control-intf, to let us show the controller-win;
357  * usually when in fullscreen-mode
358  *****************************************************************************/
359 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
360                      vlc_value_t old_val, vlc_value_t new_val, void *param )
361 {
362     intf_thread_t * p_intf = VLCIntf;
363     if( p_intf && p_intf->p_sys )
364     {
365         NSLog( @"fixme! we should implement ShowController here" );
366     }
367     return VLC_SUCCESS;
368 }
369
370 /*****************************************************************************
371  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
372  * variable, to let the intf update the controller.
373  *****************************************************************************/
374 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
375                      vlc_value_t old_val, vlc_value_t new_val, void *param )
376 {
377     intf_thread_t * p_intf = VLCIntf;
378     if (p_intf)
379     {
380         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
381         [[VLCMain sharedInstance] fullscreenChanged];
382         [o_pool release];
383     }
384     return VLC_SUCCESS;
385 }
386
387 /*****************************************************************************
388  * DialogCallback: Callback triggered by the "dialog-*" variables
389  * to let the intf display error and interaction dialogs
390  *****************************************************************************/
391 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
392 {
393     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
394     VLCMain *interface = (VLCMain *)data;
395
396     if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
397     {
398         /* the progress panel needs to update itself and therefore wants special treatment within this context */
399         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
400
401         p_dialog->pf_update = updateProgressPanel;
402         p_dialog->pf_check = checkProgressPanel;
403         p_dialog->pf_destroy = destroyProgressPanel;
404         p_dialog->p_sys = VLCIntf->p_libvlc;
405     }
406
407     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
408     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
409
410     [o_pool release];
411     return VLC_SUCCESS;
412 }
413
414 void updateProgressPanel (void *priv, const char *text, float value)
415 {
416     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
417
418     NSString *o_txt;
419     if( text != NULL )
420         o_txt = [NSString stringWithUTF8String: text];
421     else
422         o_txt = @"";
423
424     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
425
426     [o_pool release];
427 }
428
429 void destroyProgressPanel (void *priv)
430 {
431     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
432     [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
433     [o_pool release];
434 }
435
436 bool checkProgressPanel (void *priv)
437 {
438     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
439     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
440     [o_pool release];
441 }
442
443 #pragma mark -
444 #pragma mark Helpers
445
446 input_thread_t *getInput(void)
447 {
448     intf_thread_t *p_intf = VLCIntf;
449     if (!p_intf)
450         return NULL;
451     return pl_CurrentInput(p_intf);
452 }
453
454 vout_thread_t *getVout(void)
455 {
456     input_thread_t *p_input = getInput();
457     if (!p_input)
458         return NULL;
459     vout_thread_t *p_vout = input_GetVout(p_input);
460     vlc_object_release(p_input);
461     return p_vout;
462 }
463
464 audio_output_t *getAout(void)
465 {
466     input_thread_t *p_input = getInput();
467     if (!p_input)
468         return NULL;
469     audio_output_t *p_aout = input_GetAout(p_input);
470     vlc_object_release(p_input);
471     return p_aout;
472 }
473
474 #pragma mark -
475 #pragma mark Private
476
477 @interface VLCMain ()
478 - (void)_removeOldPreferences;
479 @end
480
481 /*****************************************************************************
482  * VLCMain implementation
483  *****************************************************************************/
484 @implementation VLCMain
485
486 #pragma mark -
487 #pragma mark Initialization
488
489 static VLCMain *_o_sharedMainInstance = nil;
490
491 + (VLCMain *)sharedInstance
492 {
493     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
494 }
495
496 - (id)init
497 {
498     if( _o_sharedMainInstance)
499     {
500         [self dealloc];
501         return _o_sharedMainInstance;
502     }
503     else
504         _o_sharedMainInstance = [super init];
505
506     p_intf = NULL;
507
508     o_msg_lock = [[NSLock alloc] init];
509     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
510     /* subscribe to LibVLC's debug messages as early as possible (for us) */
511     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
512
513     o_open = [[VLCOpen alloc] init];
514     //o_embedded_list = [[VLCEmbeddedList alloc] init];
515     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
516     o_info = [[VLCInfo alloc] init];
517     o_mainmenu = [[VLCMainMenu alloc] init];
518     o_coreinteraction = [[VLCCoreInteraction alloc] init];
519     o_eyetv = [[VLCEyeTVController alloc] init];
520     o_mainwindow = [[VLCMainWindow alloc] init];
521
522     /* announce our launch to a potential eyetv plugin */
523     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
524                                                                    object: @"VLCEyeTVSupport"
525                                                                  userInfo: NULL
526                                                        deliverImmediately: YES];
527     return _o_sharedMainInstance;
528 }
529
530 - (void)setIntf: (intf_thread_t *)p_mainintf {
531     p_intf = p_mainintf;
532 }
533
534 - (intf_thread_t *)intf {
535     return p_intf;
536 }
537
538 - (void)awakeFromNib
539 {
540     playlist_t *p_playlist;
541     vlc_value_t val;
542     if( !p_intf ) return;
543     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
544
545     /* Check if we already did this once. Opening the other nibs calls it too,
546      because VLCMain is the owner */
547     if( nib_main_loaded ) return;
548
549     [o_msgs_panel setExcludedFromWindowsMenu: YES];
550     [o_msgs_panel setDelegate: self];
551
552     p_playlist = pl_Get( p_intf );
553
554     val.b_bool = false;
555
556     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
557     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
558 //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
559     var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
560     var_AddCallback(p_playlist, "activity", PLItemChanged, self);
561     var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
562     var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
563     var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
564     var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
565     var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
566     var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
567     var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
568     var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
569
570     /* load our Core Dialogs nib */
571     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
572
573     /* subscribe to various interactive dialogues */
574     var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
575     var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
576     var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
577     var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
578     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
579     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
580     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
581     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
582     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
583     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
584     dialog_Register( p_intf );
585
586     [self playbackModeUpdated];
587
588     /* init Apple Remote support */
589     o_remote = [[AppleRemote alloc] init];
590     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
591     [o_remote setDelegate: _o_sharedMainInstance];
592
593     /* yeah, we are done */
594     nib_main_loaded = TRUE;
595 }
596
597 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
598 {
599     if( !p_intf ) return;
600
601     /* init media key support */
602     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
603     if( b_mediaKeySupport )
604     {
605         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
606         [o_mediaKeyController startWatchingMediaKeys];
607         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
608                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
609                                                                  nil]];
610     }
611     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
612
613     [self _removeOldPreferences];
614
615     [o_mainwindow makeKeyAndOrderFront: self];
616
617     /* Handle sleep notification */
618     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
619            name:NSWorkspaceWillSleepNotification object:nil];
620
621     [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
622 }
623
624 - (void)initStrings
625 {
626     if( !p_intf ) return;
627
628     /* messages panel */
629     [o_msgs_panel setTitle: _NS("Messages")];
630     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
631     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
632
633     /* crash reporter panel */
634     [o_crashrep_send_btn setTitle: _NS("Send")];
635     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
636     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
637     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
638     [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
639     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
640     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
641 }
642
643 #pragma mark -
644 #pragma mark Termination
645
646 - (void)applicationWillTerminate:(NSNotification *)notification
647 {
648     playlist_t * p_playlist;
649     vout_thread_t * p_vout;
650     int returnedValue = 0;
651
652     if( !p_intf )
653         return;
654
655     // don't allow a double termination call. If the user has
656     // already invoked the quit then simply return this time.
657     int isTerminating = false;
658
659     [o_appLock lock];
660     isTerminating = (f_appExit++ > 0 ? 1 : 0);
661     [o_appLock unlock];
662
663     if (isTerminating)
664         return;
665
666     msg_Dbg( p_intf, "Terminating" );
667
668     /* Make sure the intf object is getting killed */
669     vlc_object_kill( p_intf );
670     p_playlist = pl_Get( p_intf );
671
672     /* unsubscribe from the interactive dialogues */
673     dialog_Unregister( p_intf );
674     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
675     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
676     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
677     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
678     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
679     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
680     var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
681     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
682     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
683     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
684     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
685     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
686     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
687     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
688     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
689     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
690
691     /* remove global observer watching for vout device changes correctly */
692     [[NSNotificationCenter defaultCenter] removeObserver: self];
693
694     /* release some other objects here, because it isn't sure whether dealloc
695      * will be called later on */
696     if( o_sprefs )
697         [o_sprefs release];
698
699     if( o_prefs )
700         [o_prefs release];
701
702     [o_open release];
703
704     if( o_info )
705         [o_info release];
706
707     if( o_wizard )
708         [o_wizard release];
709
710     [crashLogURLConnection cancel];
711     [crashLogURLConnection release];
712
713     [o_embedded_list release];
714     [o_coredialogs release];
715     [o_eyetv release];
716     [o_mainwindow release];
717
718     /* unsubscribe from libvlc's debug messages */
719     msg_Unsubscribe( p_intf->p_sys->p_sub );
720
721     [o_msg_arr removeAllObjects];
722     [o_msg_arr release];
723
724     [o_msg_lock release];
725
726     /* write cached user defaults to disk */
727     [[NSUserDefaults standardUserDefaults] synchronize];
728
729     /* Make sure the Menu doesn't have any references to vlc objects anymore */
730     //FIXME: this should be moved to VLCMainMenu
731     [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
732     [o_mainmenu release];
733
734     /* Kill the playlist, so that it doesn't accept new request
735      * such as the play request from vlc.c (we are a blocking interface). */
736     vlc_object_kill( p_playlist );
737     libvlc_Quit( p_intf->p_libvlc );
738
739     [self setIntf:nil];
740 }
741
742 #pragma mark -
743 #pragma mark Sparkle delegate
744 /* received directly before the update gets installed, so let's shut down a bit */
745 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
746 {
747     [NSApp activateIgnoringOtherApps:YES];
748     [o_remote stopListening: self];
749     var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
750
751     /* Close the window directly, because we do know that there
752      * won't be anymore video. It's currently waiting a bit. */
753     [[[o_coreinteraction voutView] window] orderOut:self];
754 }
755
756 #pragma mark -
757 #pragma mark Media Key support
758
759 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
760 {
761     if( b_mediaKeySupport )
762        {
763         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
764
765         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
766         int keyFlags = ([event data1] & 0x0000FFFF);
767         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
768         int keyRepeat = (keyFlags & 0x1);
769
770         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
771             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
772
773         if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
774         {
775             if( keyState == 0 && keyRepeat == 0 )
776                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
777             else if( keyRepeat == 1 )
778             {
779                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
780                 b_mediakeyJustJumped = YES;
781                 [self performSelector:@selector(resetMediaKeyJump)
782                            withObject: NULL
783                            afterDelay:0.25];
784             }
785         }
786
787         if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
788         {
789             if( keyState == 0 && keyRepeat == 0 )
790                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
791             else if( keyRepeat == 1 )
792             {
793                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
794                 b_mediakeyJustJumped = YES;
795                 [self performSelector:@selector(resetMediaKeyJump)
796                            withObject: NULL
797                            afterDelay:0.25];
798             }
799         }
800     }
801 }
802
803 #pragma mark -
804 #pragma mark Other notification
805
806 /* Listen to the remote in exclusive mode, only when VLC is the active
807    application */
808 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
809 {
810     if( !p_intf ) return;
811         if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
812                 [o_remote startListening: self];
813 }
814 - (void)applicationDidResignActive:(NSNotification *)aNotification
815 {
816     if( !p_intf ) return;
817     [o_remote stopListening: self];
818 }
819
820 /* Triggered when the computer goes to sleep */
821 - (void)computerWillSleep: (NSNotification *)notification
822 {
823     input_thread_t * p_input;
824
825     p_input = pl_CurrentInput( p_intf );
826     if( p_input )
827     {
828         int state = var_GetInteger( p_input, "state" );
829         if( state == PLAYING_S )
830             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
831         vlc_object_release( p_input );
832     }
833 }
834
835 #pragma mark -
836 #pragma mark File opening
837
838 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
839 {
840     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
841     char *psz_uri = make_URI([o_filename UTF8String], "file" );
842     if( !psz_uri )
843         return( FALSE );
844
845     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
846
847     free( psz_uri );
848
849     if( b_autoplay )
850         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
851     else
852         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
853
854     return( TRUE );
855 }
856
857 /* When user click in the Dock icon our double click in the finder */
858 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
859 {
860     if(!hasVisibleWindows)
861         [o_mainwindow makeKeyAndOrderFront:self];
862
863     return YES;
864 }
865
866 #pragma mark -
867 #pragma mark Apple Remote Control
868
869 /* Helper method for the remote control interface in order to trigger forward/backward and volume
870    increase/decrease as long as the user holds the left/right, plus/minus button */
871 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
872 {
873     if(b_remote_button_hold)
874     {
875         switch([buttonIdentifierNumber intValue])
876         {
877             case kRemoteButtonRight_Hold:
878                 [[VLCCoreInteraction sharedInstance] forward];
879             break;
880             case kRemoteButtonLeft_Hold:
881                 [[VLCCoreInteraction sharedInstance] backward];
882             break;
883             case kRemoteButtonVolume_Plus_Hold:
884                 [[VLCCoreInteraction sharedInstance] volumeUp];
885             break;
886             case kRemoteButtonVolume_Minus_Hold:
887                 [[VLCCoreInteraction sharedInstance] volumeDown];
888             break;
889         }
890         if(b_remote_button_hold)
891         {
892             /* trigger event */
893             [self performSelector:@selector(executeHoldActionForRemoteButton:)
894                          withObject:buttonIdentifierNumber
895                          afterDelay:0.25];
896         }
897     }
898 }
899
900 /* Apple Remote callback */
901 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
902                pressedDown: (BOOL) pressedDown
903                 clickCount: (unsigned int) count
904 {
905     switch( buttonIdentifier )
906     {
907         case k2009RemoteButtonFullscreen:
908             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
909             break;
910         case k2009RemoteButtonPlay:
911             [[VLCCoreInteraction sharedInstance] play];
912             break;
913         case kRemoteButtonPlay:
914             if(count >= 2) {
915                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
916             } else {
917                 [[VLCCoreInteraction sharedInstance] play];
918             }
919             break;
920         case kRemoteButtonVolume_Plus:
921             [[VLCCoreInteraction sharedInstance] volumeUp];
922             break;
923         case kRemoteButtonVolume_Minus:
924             [[VLCCoreInteraction sharedInstance] volumeDown];
925             break;
926         case kRemoteButtonRight:
927             [[VLCCoreInteraction sharedInstance] next];
928             break;
929         case kRemoteButtonLeft:
930             [[VLCCoreInteraction sharedInstance] previous];
931             break;
932         case kRemoteButtonRight_Hold:
933         case kRemoteButtonLeft_Hold:
934         case kRemoteButtonVolume_Plus_Hold:
935         case kRemoteButtonVolume_Minus_Hold:
936             /* simulate an event as long as the user holds the button */
937             b_remote_button_hold = pressedDown;
938             if( pressedDown )
939             {
940                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
941                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
942                            withObject:buttonIdentifierNumber];
943             }
944             break;
945         case kRemoteButtonMenu:
946             [o_controls showPosition: self]; //FIXME
947             break;
948         default:
949             /* Add here whatever you want other buttons to do */
950             break;
951     }
952 }
953
954 #pragma mark -
955 #pragma mark String utility
956 // FIXME: this has nothing to do here
957
958 - (NSString *)localizedString:(const char *)psz
959 {
960     NSString * o_str = nil;
961
962     if( psz != NULL )
963     {
964         o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
965
966         if( o_str == NULL )
967         {
968             msg_Err( VLCIntf, "could not translate: %s", psz );
969             return( @"" );
970         }
971     }
972     else
973     {
974         msg_Warn( VLCIntf, "can't translate empty strings" );
975         return( @"" );
976     }
977
978     return( o_str );
979 }
980
981
982
983 - (char *)delocalizeString:(NSString *)id
984 {
985     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
986                           allowLossyConversion: NO];
987     char * psz_string;
988
989     if( o_data == nil )
990     {
991         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
992                      allowLossyConversion: YES];
993         psz_string = malloc( [o_data length] + 1 );
994         [o_data getBytes: psz_string];
995         psz_string[ [o_data length] ] = '\0';
996         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
997                  psz_string );
998     }
999     else
1000     {
1001         psz_string = malloc( [o_data length] + 1 );
1002         [o_data getBytes: psz_string];
1003         psz_string[ [o_data length] ] = '\0';
1004     }
1005
1006     return psz_string;
1007 }
1008
1009 /* i_width is in pixels */
1010 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1011 {
1012     NSMutableString *o_wrapped;
1013     NSString *o_out_string;
1014     NSRange glyphRange, effectiveRange, charRange;
1015     NSRect lineFragmentRect;
1016     unsigned glyphIndex, breaksInserted = 0;
1017
1018     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1019         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1020         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1021     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1022     NSTextContainer *o_container = [[NSTextContainer alloc]
1023         initWithContainerSize: NSMakeSize(i_width, 2000)];
1024
1025     [o_layout_manager addTextContainer: o_container];
1026     [o_container release];
1027     [o_storage addLayoutManager: o_layout_manager];
1028     [o_layout_manager release];
1029
1030     o_wrapped = [o_in_string mutableCopy];
1031     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1032
1033     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1034             glyphIndex += effectiveRange.length) {
1035         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1036                                             effectiveRange: &effectiveRange];
1037         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1038                                     actualGlyphRange: &effectiveRange];
1039         if([o_wrapped lineRangeForRange:
1040                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1041             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1042             breaksInserted++;
1043         }
1044     }
1045     o_out_string = [NSString stringWithString: o_wrapped];
1046     [o_wrapped release];
1047     [o_storage release];
1048
1049     return o_out_string;
1050 }
1051
1052
1053 #pragma mark -
1054 #pragma mark Key Shortcuts
1055
1056 static struct
1057 {
1058     unichar i_nskey;
1059     unsigned int i_vlckey;
1060 } nskeys_to_vlckeys[] =
1061 {
1062     { NSUpArrowFunctionKey, KEY_UP },
1063     { NSDownArrowFunctionKey, KEY_DOWN },
1064     { NSLeftArrowFunctionKey, KEY_LEFT },
1065     { NSRightArrowFunctionKey, KEY_RIGHT },
1066     { NSF1FunctionKey, KEY_F1 },
1067     { NSF2FunctionKey, KEY_F2 },
1068     { NSF3FunctionKey, KEY_F3 },
1069     { NSF4FunctionKey, KEY_F4 },
1070     { NSF5FunctionKey, KEY_F5 },
1071     { NSF6FunctionKey, KEY_F6 },
1072     { NSF7FunctionKey, KEY_F7 },
1073     { NSF8FunctionKey, KEY_F8 },
1074     { NSF9FunctionKey, KEY_F9 },
1075     { NSF10FunctionKey, KEY_F10 },
1076     { NSF11FunctionKey, KEY_F11 },
1077     { NSF12FunctionKey, KEY_F12 },
1078     { NSInsertFunctionKey, KEY_INSERT },
1079     { NSHomeFunctionKey, KEY_HOME },
1080     { NSEndFunctionKey, KEY_END },
1081     { NSPageUpFunctionKey, KEY_PAGEUP },
1082     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1083     { NSMenuFunctionKey, KEY_MENU },
1084     { NSTabCharacter, KEY_TAB },
1085     { NSCarriageReturnCharacter, KEY_ENTER },
1086     { NSEnterCharacter, KEY_ENTER },
1087     { NSBackspaceCharacter, KEY_BACKSPACE },
1088     {0,0}
1089 };
1090
1091 unsigned int CocoaKeyToVLC( unichar i_key )
1092 {
1093     unsigned int i;
1094
1095     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1096     {
1097         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1098         {
1099             return nskeys_to_vlckeys[i].i_vlckey;
1100         }
1101     }
1102     return (unsigned int)i_key;
1103 }
1104
1105 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1106 {
1107     unsigned int new = 0;
1108
1109     if([theString rangeOfString:@"Command"].location != NSNotFound)
1110         new |= NSCommandKeyMask;
1111     if([theString rangeOfString:@"Alt"].location != NSNotFound)
1112         new |= NSAlternateKeyMask;
1113     if([theString rangeOfString:@"Shift"].location != NSNotFound)
1114         new |= NSShiftKeyMask;
1115     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1116         new |= NSControlKeyMask;
1117     return new;
1118 }
1119
1120 - (NSString *)VLCKeyToString:(NSString *)theString
1121 {
1122     if (![theString isEqualToString:@""]) {
1123         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1124         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1125         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1126         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1127         theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1128         theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1129     }
1130     return theString;
1131 }
1132
1133
1134 /*****************************************************************************
1135  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1136  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1137  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1138  *****************************************************************************/
1139 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1140 {
1141     unichar key = 0;
1142     vlc_value_t val;
1143     unsigned int i_pressed_modifiers = 0;
1144     const struct hotkey *p_hotkeys;
1145     int i;
1146     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1147     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1148
1149     val.i_int = 0;
1150     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1151
1152     i_pressed_modifiers = [o_event modifierFlags];
1153
1154     if( i_pressed_modifiers & NSShiftKeyMask ) {
1155         val.i_int |= KEY_MODIFIER_SHIFT;
1156         [tempString appendString:@"Shift-"];
1157         [tempStringPlus appendString:@"Shift+"];
1158     }
1159     if( i_pressed_modifiers & NSControlKeyMask ) {
1160         val.i_int |= KEY_MODIFIER_CTRL;
1161         [tempString appendString:@"Ctrl-"];
1162         [tempStringPlus appendString:@"Ctrl+"];
1163     }
1164     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1165         val.i_int |= KEY_MODIFIER_ALT;
1166         [tempString appendString:@"Alt-"];
1167         [tempStringPlus appendString:@"Alt+"];
1168     }
1169     if( i_pressed_modifiers & NSCommandKeyMask ) {
1170         val.i_int |= KEY_MODIFIER_COMMAND;
1171         [tempString appendString:@"Command-"];
1172         [tempStringPlus appendString:@"Command+"];
1173     }
1174
1175     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1176     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1177
1178     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1179
1180     switch( key )
1181     {
1182         case NSDeleteCharacter:
1183         case NSDeleteFunctionKey:
1184         case NSDeleteCharFunctionKey:
1185         case NSBackspaceCharacter:
1186         case NSUpArrowFunctionKey:
1187         case NSDownArrowFunctionKey:
1188         case NSRightArrowFunctionKey:
1189         case NSLeftArrowFunctionKey:
1190         case NSEnterCharacter:
1191         case NSCarriageReturnCharacter:
1192             return NO;
1193     }
1194
1195     val.i_int |= CocoaKeyToVLC( key );
1196
1197     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1198     {
1199         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1200         return YES;
1201     }
1202
1203     return NO;
1204 }
1205
1206 - (void)updateCurrentlyUsedHotkeys
1207 {
1208     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1209     /* Get the main Module */
1210     module_t *p_main = module_get_main();
1211     assert( p_main );
1212     unsigned confsize;
1213     module_config_t *p_config;
1214
1215     p_config = module_config_get (p_main, &confsize);
1216
1217     for (size_t i = 0; i < confsize; i++)
1218     {
1219         module_config_t *p_item = p_config + i;
1220
1221         if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1222            && !strncmp( p_item->psz_name , "key-", 4 )
1223            && !EMPTY_STR( p_item->psz_text ) )
1224         {
1225             if (p_item->value.psz)
1226                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1227         }
1228     }
1229     module_config_free (p_config);
1230     module_release (p_main);
1231     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1232 }
1233
1234 #pragma mark -
1235 #pragma mark Interface updaters
1236 - (void)fullscreenChanged
1237 {
1238     if(! [o_mainwindow isFullscreen] )
1239         [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1240     else
1241         [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1242 }
1243
1244 - (void)PlaylistItemChanged
1245 {
1246     input_thread_t * p_input;
1247
1248     p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1249     if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1250     {
1251         var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1252         [o_mainmenu setRateControlsEnabled: YES];
1253         vlc_object_release( p_input );
1254     }
1255     else
1256         [o_mainmenu setRateControlsEnabled: NO];
1257
1258     [o_playlist updateRowSelection];
1259     [o_mainwindow updateWindow];
1260     [o_mainmenu setupMenus];
1261     [o_mainmenu updatePlaybackRate];
1262 }
1263
1264 - (void)updateMainWindow
1265 {
1266     [o_mainwindow updateWindow];
1267 }
1268
1269 - (void)updateDelays
1270 {
1271     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1272 }
1273
1274 - (void)updateName
1275 {
1276     [o_mainwindow updateName];
1277 }
1278
1279 - (void)updatePlaybackPosition
1280 {
1281     [o_mainwindow updateTimeSlider];
1282 }
1283
1284 - (void)updateVolume
1285 {
1286     [o_mainwindow updateVolumeSlider];
1287 }
1288
1289 - (void)playlistUpdated
1290 {
1291     [self playbackStatusUpdated];
1292     [o_playlist playlistUpdated];
1293     [o_mainwindow updateWindow];
1294 }
1295
1296 - (void)updateInfoandMetaPanel
1297 {
1298     [o_playlist outlineViewSelectionDidChange:nil];
1299 }
1300
1301 - (void)playbackStatusUpdated
1302 {
1303     input_thread_t * p_input;
1304
1305     p_input = pl_CurrentInput( p_intf );
1306     if( p_input )
1307     {
1308         int state = var_GetInteger( p_input, "state" );
1309         if( state == PLAYING_S )
1310         {
1311             [[[self controls] fspanel] setPause];
1312             [[self mainMenu] setPause];
1313             [o_mainwindow setPause];
1314         }
1315         else
1316         {
1317             if (state == END_S)
1318                 [o_mainmenu setSubmenusEnabled: FALSE];
1319             [[[self controls] fspanel] setPlay];
1320             [[self mainMenu] setPlay];
1321             [o_mainwindow setPlay];
1322         }
1323         vlc_object_release( p_input );
1324     }
1325 }
1326
1327 - (void)playbackModeUpdated
1328 {
1329     vlc_value_t looping,repeating;
1330     playlist_t * p_playlist = pl_Get( VLCIntf );
1331
1332     bool loop = var_GetBool( p_playlist, "loop" );
1333     bool repeat = var_GetBool( p_playlist, "repeat" );
1334     if( repeat ) {
1335         [o_mainwindow setRepeatOne];
1336         [o_mainmenu setRepeatOne];
1337     } else if( loop ) {
1338         [o_mainwindow setRepeatAll];
1339         [o_mainmenu setRepeatAll];
1340     } else {
1341         [o_mainwindow setRepeatOff];
1342         [o_mainmenu setRepeatOff];
1343     }
1344
1345     [o_mainwindow setShuffle];
1346     [o_mainmenu setShuffle];
1347 }
1348
1349 #pragma mark -
1350 #pragma mark Other objects getters
1351
1352 - (id)mainMenu
1353 {
1354     return o_mainmenu;
1355 }
1356
1357 - (id)controls
1358 {
1359     if( o_controls )
1360         return o_controls;
1361
1362     return nil;
1363 }
1364
1365 - (id)bookmarks
1366 {
1367     if (!o_bookmarks )
1368         o_bookmarks = [[VLCBookmarks alloc] init];
1369
1370     if( !nib_bookmarks_loaded )
1371         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1372
1373     return o_bookmarks;
1374 }
1375
1376 - (id)open
1377 {
1378     if (!o_open)
1379         return nil;
1380
1381     if (!nib_open_loaded)
1382         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1383
1384     return o_open;
1385 }
1386
1387 - (id)simplePreferences
1388 {
1389     if (!o_sprefs)
1390         o_sprefs = [[VLCSimplePrefs alloc] init];
1391
1392     if (!nib_prefs_loaded)
1393         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1394
1395     return o_sprefs;
1396 }
1397
1398 - (id)preferences
1399 {
1400     if( !o_prefs )
1401         o_prefs = [[VLCPrefs alloc] init];
1402
1403     if( !nib_prefs_loaded )
1404         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1405
1406     return o_prefs;
1407 }
1408
1409 - (id)playlist
1410 {
1411     if( o_playlist )
1412         return o_playlist;
1413
1414     return nil;
1415 }
1416
1417 - (id)info
1418 {
1419     if(! nib_info_loaded )
1420         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1421
1422     if( o_info )
1423         return o_info;
1424
1425     return nil;
1426 }
1427
1428 - (id)wizard
1429 {
1430     if( !o_wizard )
1431         o_wizard = [[VLCWizard alloc] init];
1432
1433     if( !nib_wizard_loaded )
1434     {
1435         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1436         [o_wizard initStrings];
1437     }
1438     return o_wizard;
1439 }
1440
1441 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1442 {
1443     id videoView = [o_mainwindow videoView];
1444     NSRect videoRect = [videoView frame];
1445     int i_x = (int)videoRect.origin.x;
1446     int i_y = (int)videoRect.origin.y;
1447     unsigned int i_width = (int)videoRect.size.width;
1448     unsigned int i_height = (int)videoRect.size.height;
1449     pi_x = (int *)i_x;
1450     pi_y = (int *)i_y;
1451     pi_width = (unsigned int*)i_width;
1452     pi_height = (unsigned int*)i_height;
1453     msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1454     return videoView;
1455 }
1456
1457 - (void)setNativeVideoSize:(NSSize)size
1458 {
1459     [o_mainwindow setNativeVideoSize:size];
1460 }
1461
1462 - (id)embeddedList
1463 {
1464     if( o_embedded_list )
1465         return o_embedded_list;
1466
1467     return nil;
1468 }
1469
1470 - (id)coreDialogProvider
1471 {
1472     if( o_coredialogs )
1473         return o_coredialogs;
1474
1475     return nil;
1476 }
1477
1478 - (id)eyeTVController
1479 {
1480     if( o_eyetv )
1481         return o_eyetv;
1482
1483     return nil;
1484 }
1485
1486 - (id)appleRemoteController
1487 {
1488         return o_remote;
1489 }
1490
1491 - (void)setActiveVideoPlayback:(BOOL)b_value
1492 {
1493     b_active_videoplayback = b_value;
1494     [o_mainwindow setVideoplayEnabled];
1495     [o_mainwindow togglePlaylist:nil];
1496 }
1497
1498 - (BOOL)activeVideoPlayback
1499 {
1500     return b_active_videoplayback;
1501 }
1502
1503 #pragma mark -
1504 #pragma mark Crash Log
1505 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1506 {
1507     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1508     NSURL *url = [NSURL URLWithString:urlStr];
1509
1510     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1511     [req setHTTPMethod:@"POST"];
1512
1513     NSString * email;
1514     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1515     {
1516         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1517         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1518         email = [emails valueAtIndex:[emails indexForIdentifier:
1519                     [emails primaryIdentifier]]];
1520     }
1521     else
1522         email = [NSString string];
1523
1524     NSString *postBody;
1525     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1526             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1527             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1528             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1529
1530     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1531
1532     /* Released from delegate */
1533     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1534 }
1535
1536 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1537 {
1538     [crashLogURLConnection release];
1539     crashLogURLConnection = nil;
1540 }
1541
1542 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1543 {
1544     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1545     [crashLogURLConnection release];
1546     crashLogURLConnection = nil;
1547 }
1548
1549 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1550 {
1551     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1552     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1553     NSString *fname;
1554     NSString * latestLog = nil;
1555     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1556     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1557     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
1558     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1559
1560     while (fname = [direnum nextObject])
1561     {
1562         [direnum skipDescendents];
1563         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1564         {
1565             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1566             if( [compo count] < 3 ) continue;
1567             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1568             if( [compo count] < 4 ) continue;
1569
1570             // Dooh. ugly.
1571             if( year < [[compo objectAtIndex:0] intValue] ||
1572                 (year ==[[compo objectAtIndex:0] intValue] &&
1573                  (month < [[compo objectAtIndex:1] intValue] ||
1574                   (month ==[[compo objectAtIndex:1] intValue] &&
1575                    (day   < [[compo objectAtIndex:2] intValue] ||
1576                     (day   ==[[compo objectAtIndex:2] intValue] &&
1577                       hours < [[compo objectAtIndex:3] intValue] ))))))
1578             {
1579                 year  = [[compo objectAtIndex:0] intValue];
1580                 month = [[compo objectAtIndex:1] intValue];
1581                 day   = [[compo objectAtIndex:2] intValue];
1582                 hours = [[compo objectAtIndex:3] intValue];
1583                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1584             }
1585         }
1586     }
1587
1588     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1589         return nil;
1590
1591     if( !previouslySeen )
1592     {
1593         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
1594         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1595         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
1596         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1597     }
1598     return latestLog;
1599 }
1600
1601 - (NSString *)latestCrashLogPath
1602 {
1603     return [self latestCrashLogPathPreviouslySeen:YES];
1604 }
1605
1606 - (void)lookForCrashLog
1607 {
1608     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1609     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1610     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1611     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1612     if( latestLog && !areCrashLogsTooOld )
1613         [NSApp runModalForWindow: o_crashrep_win];
1614     [o_pool release];
1615 }
1616
1617 - (IBAction)crashReporterAction:(id)sender
1618 {
1619     if( sender == o_crashrep_send_btn )
1620         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1621
1622     [NSApp stopModal];
1623     [o_crashrep_win orderOut: sender];
1624 }
1625
1626 - (IBAction)openCrashLog:(id)sender
1627 {
1628     NSString * latestLog = [self latestCrashLogPath];
1629     if( latestLog )
1630     {
1631         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1632     }
1633     else
1634     {
1635         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), _NS("Continue"), nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Couldn't find any trace of a previous crash.") );
1636     }
1637 }
1638
1639 #pragma mark -
1640 #pragma mark Remove old prefs
1641
1642 - (void)_removeOldPreferences
1643 {
1644     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1645     static const int kCurrentPreferencesVersion = 1;
1646     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1647     if( version >= kCurrentPreferencesVersion ) return;
1648
1649     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1650         NSUserDomainMask, YES);
1651     if( !libraries || [libraries count] == 0) return;
1652     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1653
1654     /* File not found, don't attempt anything */
1655     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1656        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1657     {
1658         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1659         return;
1660     }
1661
1662     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1663                 _NS("We just found an older version of VLC's preferences files."),
1664                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1665     if( res != NSOKButton )
1666     {
1667         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1668         return;
1669     }
1670
1671     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1672
1673     /* Move the file to trash so that user can find them later */
1674     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1675
1676     /* really reset the defaults from now on */
1677     [NSUserDefaults resetStandardUserDefaults];
1678
1679     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1680     [[NSUserDefaults standardUserDefaults] synchronize];
1681
1682     /* Relaunch now */
1683     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1684
1685     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1686     if(fork() != 0)
1687     {
1688         exit(0);
1689         return;
1690     }
1691     execl(path, path, NULL);
1692 }
1693
1694 #pragma mark -
1695 #pragma mark Errors, warnings and messages
1696 - (IBAction)showMessagesPanel:(id)sender
1697 {
1698     [o_msgs_panel makeKeyAndOrderFront: sender];
1699 }
1700
1701 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1702 {
1703     if( [o_notification object] == o_msgs_panel )
1704         [self updateMessageDisplay];
1705 }
1706
1707 - (void)updateMessageDisplay
1708 {
1709     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1710     {
1711         id o_msg;
1712         NSEnumerator * o_enum;
1713
1714         [o_messages setString: @""];
1715
1716         [o_msg_lock lock];
1717
1718         o_enum = [o_msg_arr objectEnumerator];
1719
1720         while( ( o_msg = [o_enum nextObject] ) != nil )
1721         {
1722             [o_messages insertText: o_msg];
1723         }
1724
1725         b_msg_arr_changed = NO;
1726         [o_msg_lock unlock];
1727     }
1728 }
1729
1730 - (void)processReceivedlibvlcMessage:(const msg_item_t *)item
1731 {
1732     NSColor *o_white = [NSColor whiteColor];
1733     NSColor *o_red = [NSColor redColor];
1734     NSColor *o_yellow = [NSColor yellowColor];
1735     NSColor *o_gray = [NSColor grayColor];
1736
1737     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1738     static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1739
1740     NSDictionary *o_attr;
1741     NSAttributedString *o_msg_color;
1742
1743     int i_type = item->i_type;
1744
1745     [o_msg_lock lock];
1746
1747     if( [o_msg_arr count] + 2 > 600 )
1748     {
1749         [o_msg_arr removeObjectAtIndex: 0];
1750         [o_msg_arr removeObjectAtIndex: 1];
1751     }
1752
1753     o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1754     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1755     [o_msg_arr addObject: [o_msg_color autorelease]];
1756
1757     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1758     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", item->psz_msg] attributes: o_attr];
1759     [o_msg_arr addObject: [o_msg_color autorelease]];
1760
1761     b_msg_arr_changed = YES;
1762     [o_msg_lock unlock];
1763
1764     [self updateMessageDisplay];
1765 }
1766
1767 - (IBAction)saveDebugLog:(id)sender
1768 {
1769     NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1770
1771     [saveFolderPanel setCanSelectHiddenExtension: NO];
1772     [saveFolderPanel setCanCreateDirectories: YES];
1773     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1774     [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VERSION_MESSAGE] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
1775 }
1776
1777 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1778 {
1779     BOOL b_returned;
1780     if( returnCode == NSOKButton )
1781     {
1782         b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1783         if(! b_returned )
1784             msg_Warn( p_intf, "Error while saving the debug log" );
1785     }
1786 }
1787
1788 #pragma mark -
1789 #pragma mark Playlist toggling
1790
1791 - (void)updateTogglePlaylistState
1792 {
1793     [[self playlist] outlineViewSelectionDidChange: NULL];
1794 }
1795
1796 #pragma mark -
1797
1798 @end
1799
1800 @implementation VLCMain (Internal)
1801
1802 - (void)handlePortMessage:(NSPortMessage *)o_msg
1803 {
1804     id ** val;
1805     NSData * o_data;
1806     NSValue * o_value;
1807     NSInvocation * o_inv;
1808     NSConditionLock * o_lock;
1809
1810     o_data = [[o_msg components] lastObject];
1811     o_inv = *((NSInvocation **)[o_data bytes]);
1812     [o_inv getArgument: &o_value atIndex: 2];
1813     val = (id **)[o_value pointerValue];
1814     [o_inv setArgument: val[1] atIndex: 2];
1815     o_lock = *(val[0]);
1816
1817     [o_lock lock];
1818     [o_inv invoke];
1819     [o_lock unlockWithCondition: 1];
1820 }
1821 - (void)resetMediaKeyJump
1822 {
1823     b_mediakeyJustJumped = NO;
1824 }
1825 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1826 {
1827     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1828     if (b_mediaKeySupport) {
1829         if (!o_mediaKeyController)
1830             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1831         [o_mediaKeyController startWatchingMediaKeys];
1832     }
1833     else if (!b_mediaKeySupport && o_mediaKeyController)
1834     {
1835         int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1836                                                _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1837                                                _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1838         if( returnedValue == NSOKButton )
1839         {
1840             /* Relaunch now */
1841             const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1842
1843             /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1844             if(fork() != 0)
1845             {
1846                 exit(0);
1847                 return;
1848             }
1849             execl(path, path, NULL);
1850         }
1851     }
1852 }
1853
1854 @end
1855
1856 /*****************************************************************************
1857  * VLCApplication interface
1858  *****************************************************************************/
1859
1860 @implementation VLCApplication
1861 // when user selects the quit menu from dock it sends a terminate:
1862 // but we need to send a stop: to properly exits libvlc.
1863 // However, we are not able to change the action-method sent by this standard menu item.
1864 // thus we override terminat: to send a stop:
1865 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1866 - (void)terminate:(id)sender
1867 {
1868     [self activateIgnoringOtherApps:YES];
1869     [self stop:sender];
1870 }
1871
1872 @end