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