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