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