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