]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: Fix startup delays by loading Open.nib only on demand
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Derk-Jan Hartman <hartman at videolan.org>
9  *          Felix Paul Kühne <fkuehne at videolan dot org>
10  *          Pierre d'Herbemont <pdherbemont # videolan org>
11  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <stdlib.h>                                      /* malloc(), free() */
36 #include <string.h>
37 #include <vlc_common.h>
38 #include <vlc_keys.h>
39 #include <vlc_dialog.h>
40 #include <vlc_url.h>
41 #include <vlc_modules.h>
42 #include <vlc_plugin.h>
43 #include <vlc_vout_display.h>
44 #include <unistd.h> /* execl() */
45
46 #import "CompatibilityFixes.h"
47 #import "intf.h"
48 #import "MainMenu.h"
49 #import "VideoView.h"
50 #import "prefs.h"
51 #import "playlist.h"
52 #import "playlistinfo.h"
53 #import "controls.h"
54 #import "open.h"
55 #import "wizard.h"
56 #import "bookmarks.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.h"
59 #import "eyetv.h"
60 #import "simple_prefs.h"
61 #import "CoreInteraction.h"
62 #import "TrackSynchronization.h"
63 #import "ExtensionsManager.h"
64 #import "BWQuincyManager.h"
65 #import "ControlsBar.h"
66
67 #import "VideoEffects.h"
68 #import "AudioEffects.h"
69
70 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
71
72 #import "iTunes.h"
73 #import "Spotify.h"
74
75 /*****************************************************************************
76  * Local prototypes.
77  *****************************************************************************/
78 static void Run (intf_thread_t *p_intf);
79
80 static void updateProgressPanel (void *, const char *, float);
81 static bool checkProgressPanel (void *);
82 static void destroyProgressPanel (void *);
83
84 static int InputEvent(vlc_object_t *, const char *,
85                       vlc_value_t, vlc_value_t, void *);
86 static int PLItemChanged(vlc_object_t *, const char *,
87                          vlc_value_t, vlc_value_t, void *);
88 static int PlaylistUpdated(vlc_object_t *, const char *,
89                            vlc_value_t, vlc_value_t, void *);
90 static int PlaybackModeUpdated(vlc_object_t *, const char *,
91                                vlc_value_t, vlc_value_t, void *);
92 static int VolumeUpdated(vlc_object_t *, const char *,
93                          vlc_value_t, vlc_value_t, void *);
94 static int BossCallback(vlc_object_t *, const char *,
95                          vlc_value_t, vlc_value_t, void *);
96
97 #pragma mark -
98 #pragma mark VLC Interface Object Callbacks
99
100 /*****************************************************************************
101  * OpenIntf: initialize interface
102  *****************************************************************************/
103 int OpenIntf (vlc_object_t *p_this)
104 {
105     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
106     [VLCApplication sharedApplication];
107
108     intf_thread_t *p_intf = (intf_thread_t*) p_this;
109     Run(p_intf);
110
111     [o_pool release];
112     return VLC_SUCCESS;
113 }
114
115 static NSLock * o_vout_provider_lock = nil;
116
117 static int WindowControl(vout_window_t *, int i_query, va_list);
118
119 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
120 {
121     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
122     intf_thread_t *p_intf = VLCIntf;
123     if (!p_intf) {
124         msg_Err(p_wnd, "Mac OS X interface not found");
125         [o_pool release];
126         return VLC_EGENERIC;
127     }
128     NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
129
130     [o_vout_provider_lock lock];
131     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
132     if (!o_vout_controller) {
133         [o_vout_provider_lock unlock];
134         [o_pool release];
135         return VLC_EGENERIC;
136     }
137
138     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
139
140     SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
141     NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
142     [inv setTarget:o_vout_controller];
143     [inv setSelector:sel];
144     [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
145     [inv setArgument:&proposedVideoViewPosition atIndex:3];
146
147     [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
148                        waitUntilDone:YES];
149
150     VLCVoutView *videoView = nil;
151     [inv getReturnValue:&videoView];
152
153     // this method is not supposed to fail
154     assert(videoView != nil);
155
156     msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
157     p_wnd->handle.nsobject = videoView;
158
159     [o_vout_provider_lock unlock];
160
161     p_wnd->control = WindowControl;
162
163     [o_pool release];
164     return VLC_SUCCESS;
165 }
166
167 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
168 {
169     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
170
171     [o_vout_provider_lock lock];
172     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
173     if (!o_vout_controller) {
174         [o_vout_provider_lock unlock];
175         [o_pool release];
176         return VLC_EGENERIC;
177     }
178
179     switch(i_query) {
180         case VOUT_WINDOW_SET_STATE:
181         {
182             unsigned i_state = va_arg(args, unsigned);
183
184             NSInteger i_cooca_level = NSNormalWindowLevel;
185             if (i_state & VOUT_WINDOW_STATE_ABOVE)
186                 i_cooca_level = NSStatusWindowLevel;
187
188             SEL sel = @selector(setWindowLevel:forWindow:);
189             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
190             [inv setTarget:o_vout_controller];
191             [inv setSelector:sel];
192             [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
193             [inv setArgument:&p_wnd atIndex:3];
194             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
195                                waitUntilDone:NO];
196
197             break;
198         }
199         case VOUT_WINDOW_SET_SIZE:
200         {
201
202             unsigned int i_width  = va_arg(args, unsigned int);
203             unsigned int i_height = va_arg(args, unsigned int);
204
205             NSSize newSize = NSMakeSize(i_width, i_height);
206             SEL sel = @selector(setNativeVideoSize:forWindow:);
207             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
208             [inv setTarget:o_vout_controller];
209             [inv setSelector:sel];
210             [inv setArgument:&newSize atIndex:2]; // starting at 2!
211             [inv setArgument:&p_wnd atIndex:3];
212             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
213                                waitUntilDone:NO];
214
215             break;
216         }
217         case VOUT_WINDOW_SET_FULLSCREEN:
218         {
219             int i_full = va_arg(args, int);
220             BOOL b_animation = YES;
221
222             SEL sel = @selector(setFullscreen:forWindow:withAnimation:);
223             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
224             [inv setTarget:o_vout_controller];
225             [inv setSelector:sel];
226             [inv setArgument:&i_full atIndex:2]; // starting at 2!
227             [inv setArgument:&p_wnd atIndex:3];
228             [inv setArgument:&b_animation atIndex:4];
229             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
230                                waitUntilDone:NO];
231
232             break;
233         }
234         default:
235         {
236             msg_Warn(p_wnd, "unsupported control query");
237             [o_vout_provider_lock unlock];
238             [o_pool release];
239             return VLC_EGENERIC;
240         }
241     }
242
243     [o_vout_provider_lock unlock];
244     [o_pool release];
245     return VLC_SUCCESS;
246 }
247
248 void WindowClose(vout_window_t *p_wnd)
249 {
250     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
251
252     [o_vout_provider_lock lock];
253     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
254     if (!o_vout_controller) {
255         [o_vout_provider_lock unlock];
256         [o_pool release];
257         return;
258     }
259
260     [o_vout_controller performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
261     [o_vout_provider_lock unlock];
262
263     [o_pool release];
264 }
265
266 /* Used to abort the app.exec() on OSX after libvlc_Quit is called */
267 #include "../../../lib/libvlc_internal.h" /* libvlc_SetExitHandler */
268
269 static void QuitVLC( void *obj )
270 {
271     [[VLCApplication sharedApplication] performSelectorOnMainThread:@selector(terminate:) withObject:nil waitUntilDone:NO];
272 }
273
274 /*****************************************************************************
275  * Run: main loop
276  *****************************************************************************/
277 static NSLock * o_appLock = nil;    // controls access to f_appExit
278 static NSLock * o_plItemChangedLock = nil;
279
280 static void Run(intf_thread_t *p_intf)
281 {
282     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
283     [VLCApplication sharedApplication];
284
285     o_appLock = [[NSLock alloc] init];
286     o_plItemChangedLock = [[NSLock alloc] init];
287     o_vout_provider_lock = [[NSLock alloc] init];
288
289     libvlc_SetExitHandler(p_intf->p_libvlc, QuitVLC, p_intf);
290
291     [[VLCMain sharedInstance] setIntf: p_intf];
292
293     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
294
295     [NSApp run];
296     [[VLCMain sharedInstance] applicationWillTerminate:nil];
297     [o_plItemChangedLock release];
298     [o_appLock release];
299     [o_vout_provider_lock release];
300     o_vout_provider_lock = nil;
301     [o_pool release];
302
303     raise(SIGTERM);
304 }
305
306 #pragma mark -
307 #pragma mark Variables Callback
308
309 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
310                        vlc_value_t oldval, vlc_value_t new_val, void *param)
311 {
312     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
313     switch (new_val.i_int) {
314         case INPUT_EVENT_STATE:
315             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
316             break;
317         case INPUT_EVENT_RATE:
318             [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
319             break;
320         case INPUT_EVENT_POSITION:
321             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
322             break;
323         case INPUT_EVENT_TITLE:
324         case INPUT_EVENT_CHAPTER:
325             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
326             break;
327         case INPUT_EVENT_CACHE:
328             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
329             break;
330         case INPUT_EVENT_STATISTICS:
331             [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
332             break;
333         case INPUT_EVENT_ES:
334             break;
335         case INPUT_EVENT_TELETEXT:
336             break;
337         case INPUT_EVENT_AOUT:
338             break;
339         case INPUT_EVENT_VOUT:
340             break;
341         case INPUT_EVENT_ITEM_META:
342         case INPUT_EVENT_ITEM_INFO:
343             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
344             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
345             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
346             break;
347         case INPUT_EVENT_BOOKMARK:
348             break;
349         case INPUT_EVENT_RECORD:
350             [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
351             break;
352         case INPUT_EVENT_PROGRAM:
353             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
354             break;
355         case INPUT_EVENT_ITEM_EPG:
356             break;
357         case INPUT_EVENT_SIGNAL:
358             break;
359
360         case INPUT_EVENT_ITEM_NAME:
361             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
362             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
363             break;
364
365         case INPUT_EVENT_AUDIO_DELAY:
366         case INPUT_EVENT_SUBTITLE_DELAY:
367             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
368             break;
369
370         case INPUT_EVENT_DEAD:
371             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
372             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
373             break;
374
375         case INPUT_EVENT_ABORT:
376             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
377             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
378             break;
379
380         default:
381             break;
382     }
383
384     [o_pool release];
385     return VLC_SUCCESS;
386 }
387
388 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
389                          vlc_value_t oldval, vlc_value_t new_val, void *param)
390 {
391     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
392
393     /* Due to constraints within NSAttributedString's main loop runtime handling
394      * and other issues, we need to wait for -PlaylistItemChanged to finish and
395      * then -informInputChanged on this non-main thread. */
396     [o_plItemChangedLock lock];
397     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES]; // MUST BE ON MAIN THREAD
398     [[VLCMain sharedInstance] informInputChanged]; // DO NOT MOVE TO MAIN THREAD
399     [o_plItemChangedLock unlock];
400
401     [o_pool release];
402     return VLC_SUCCESS;
403 }
404
405 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
406                          vlc_value_t oldval, vlc_value_t new_val, void *param)
407 {
408     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
409
410     /* Avoid event queue flooding with playlistUpdated selectors, leading to UI freezes.
411      * Therefore, only enqueue if no selector already enqueued.
412      */
413     VLCMain *o_main = [VLCMain sharedInstance];
414     @synchronized(o_main) {
415         if(![o_main playlistUpdatedSelectorInQueue]) {
416             [o_main setPlaylistUpdatedSelectorInQueue:YES];
417             [o_main performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
418         }
419     }
420
421     [o_pool release];
422     return VLC_SUCCESS;
423 }
424
425 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
426                          vlc_value_t oldval, vlc_value_t new_val, void *param)
427 {
428     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
429     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
430
431     [o_pool release];
432     return VLC_SUCCESS;
433 }
434
435 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
436                          vlc_value_t oldval, vlc_value_t new_val, void *param)
437 {
438     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
439     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
440
441     [o_pool release];
442     return VLC_SUCCESS;
443 }
444
445 static int BossCallback(vlc_object_t *p_this, const char *psz_var,
446                         vlc_value_t oldval, vlc_value_t new_val, void *param)
447 {
448     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
449
450     [[VLCCoreInteraction sharedInstance] performSelectorOnMainThread:@selector(pause) withObject:nil waitUntilDone:NO];
451     [[VLCApplication sharedApplication] hide:nil];
452
453     [o_pool release];
454     return VLC_SUCCESS;
455 }
456
457 /*****************************************************************************
458  * ShowController: Callback triggered by the show-intf playlist variable
459  * through the ShowIntf-control-intf, to let us show the controller-win;
460  * usually when in fullscreen-mode
461  *****************************************************************************/
462 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
463                      vlc_value_t old_val, vlc_value_t new_val, void *param)
464 {
465     intf_thread_t * p_intf = VLCIntf;
466     if (p_intf && p_intf->p_sys) {
467         playlist_t * p_playlist = pl_Get(p_intf);
468         BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
469         if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
470             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
471         else
472             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
473     }
474     return VLC_SUCCESS;
475 }
476
477 /*****************************************************************************
478  * DialogCallback: Callback triggered by the "dialog-*" variables
479  * to let the intf display error and interaction dialogs
480  *****************************************************************************/
481 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
482 {
483     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
484
485     if ([[NSString stringWithUTF8String:type] isEqualToString: @"dialog-progress-bar"]) {
486         /* the progress panel needs to update itself and therefore wants special treatment within this context */
487         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
488
489         p_dialog->pf_update = updateProgressPanel;
490         p_dialog->pf_check = checkProgressPanel;
491         p_dialog->pf_destroy = destroyProgressPanel;
492         p_dialog->p_sys = VLCIntf->p_libvlc;
493     }
494
495     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
496     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
497
498     [o_pool release];
499     return VLC_SUCCESS;
500 }
501
502 void updateProgressPanel (void *priv, const char *text, float value)
503 {
504     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
505
506     NSString *o_txt;
507     if (text != NULL)
508         o_txt = [NSString stringWithUTF8String:text];
509     else
510         o_txt = @"";
511
512     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
513
514     [o_pool release];
515 }
516
517 void destroyProgressPanel (void *priv)
518 {
519     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
520
521     if ([[NSApplication sharedApplication] isRunning])
522         [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
523
524     [o_pool release];
525 }
526
527 bool checkProgressPanel (void *priv)
528 {
529     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
530 }
531
532 #pragma mark -
533 #pragma mark Helpers
534
535 input_thread_t *getInput(void)
536 {
537     intf_thread_t *p_intf = VLCIntf;
538     if (!p_intf)
539         return NULL;
540     return pl_CurrentInput(p_intf);
541 }
542
543 vout_thread_t *getVout(void)
544 {
545     input_thread_t *p_input = getInput();
546     if (!p_input)
547         return NULL;
548     vout_thread_t *p_vout = input_GetVout(p_input);
549     vlc_object_release(p_input);
550     return p_vout;
551 }
552
553 vout_thread_t *getVoutForActiveWindow(void)
554 {
555     vout_thread_t *p_vout = nil;
556
557     id currentWindow = [NSApp keyWindow];
558     if ([currentWindow respondsToSelector:@selector(videoView)]) {
559         VLCVoutView *videoView = [currentWindow videoView];
560         if (videoView) {
561             p_vout = [videoView voutThread];
562         }
563     }
564
565     if (!p_vout)
566         p_vout = getVout();
567
568     return p_vout;
569 }
570
571 audio_output_t *getAout(void)
572 {
573     intf_thread_t *p_intf = VLCIntf;
574     if (!p_intf)
575         return NULL;
576     return playlist_GetAout(pl_Get(p_intf));
577 }
578
579 #pragma mark -
580 #pragma mark Private
581
582 @interface VLCMain () <BWQuincyManagerDelegate>
583 - (void)removeOldPreferences;
584 @end
585
586 @interface VLCMain (Internal)
587 - (void)resetMediaKeyJump;
588 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
589 @end
590
591 /*****************************************************************************
592  * VLCMain implementation
593  *****************************************************************************/
594 @implementation VLCMain
595
596 @synthesize voutController=o_vout_controller;
597 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
598 @synthesize playlistUpdatedSelectorInQueue=b_playlist_updated_selector_in_queue;
599
600 #pragma mark -
601 #pragma mark Initialization
602
603 static VLCMain *_o_sharedMainInstance = nil;
604
605 + (VLCMain *)sharedInstance
606 {
607     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
608 }
609
610 - (id)init
611 {
612     if (_o_sharedMainInstance) {
613         [self dealloc];
614         return _o_sharedMainInstance;
615     } else
616         _o_sharedMainInstance = [super init];
617
618     p_intf = NULL;
619     p_current_input = p_input_changed = NULL;
620
621     o_open = [[VLCOpen alloc] init];
622     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
623     o_info = [[VLCInfo alloc] init];
624     o_mainmenu = [[VLCMainMenu alloc] init];
625     o_coreinteraction = [[VLCCoreInteraction alloc] init];
626     o_eyetv = [[VLCEyeTVController alloc] init];
627
628     /* announce our launch to a potential eyetv plugin */
629     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
630                                                                    object: @"VLCEyeTVSupport"
631                                                                  userInfo: NULL
632                                                        deliverImmediately: YES];
633
634     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
635     NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
636     [defaults registerDefaults:appDefaults];
637
638     o_vout_controller = [[VLCVoutWindowController alloc] init];
639
640     return _o_sharedMainInstance;
641 }
642
643 - (void)setIntf: (intf_thread_t *)p_mainintf
644 {
645     p_intf = p_mainintf;
646 }
647
648 - (intf_thread_t *)intf
649 {
650     return p_intf;
651 }
652
653 - (void)awakeFromNib
654 {
655     playlist_t *p_playlist;
656     if (!p_intf) return;
657     var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
658
659     /* Check if we already did this once. Opening the other nibs calls it too,
660      because VLCMain is the owner */
661     if (nib_main_loaded)
662         return;
663
664     p_playlist = pl_Get(p_intf);
665
666     var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
667     var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
668     var_AddCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
669     //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
670     var_AddCallback(p_playlist, "activity", PLItemChanged, self);
671     var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
672     var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
673     var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
674     var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
675     var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
676     var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
677     var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
678     var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
679
680     if (!OSX_SNOW_LEOPARD) {
681         if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
682             var_SetBool(p_playlist, "fullscreen", YES);
683     }
684
685     /* load our Core and Shared Dialogs nibs */
686     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
687     [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
688
689     /* subscribe to various interactive dialogues */
690     var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
691     var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
692     var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
693     var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
694     var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
695     var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
696     var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
697     var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
698     var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
699     var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
700     dialog_Register(p_intf);
701
702     /* init Apple Remote support */
703     o_remote = [[AppleRemote alloc] init];
704     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
705     [o_remote setDelegate: _o_sharedMainInstance];
706
707     /* yeah, we are done */
708     b_nativeFullscreenMode = NO;
709 #ifdef MAC_OS_X_VERSION_10_7
710     if (!OSX_SNOW_LEOPARD)
711         b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
712 #endif
713
714     if (config_GetInt(VLCIntf, "macosx-icon-change")) {
715         /* After day 354 of the year, the usual VLC cone is replaced by another cone
716          * wearing a Father Xmas hat.
717          * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
718          */
719         NSCalendar *gregorian =
720         [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
721         NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
722         [gregorian release];
723
724         if (dayOfYear >= 354)
725             [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
726     }
727
728     nib_main_loaded = TRUE;
729 }
730
731 - (void)applicationWillFinishLaunching:(NSNotification *)aNotification
732 {
733     playlist_t * p_playlist = pl_Get(VLCIntf);
734     PL_LOCK;
735     items_at_launch = p_playlist->p_local_category->i_children;
736     PL_UNLOCK;
737
738     [NSBundle loadNibNamed:@"MainWindow" owner: self];
739     [o_mainwindow makeKeyAndOrderFront:nil];
740
741     [[SUUpdater sharedUpdater] setDelegate:self];
742 }
743
744 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
745 {
746     launched = YES;
747
748     if (!p_intf)
749         return;
750
751     NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey: @"CFBundleVersion"];
752     NSRange endRande = [appVersion rangeOfString:@"-"];
753     if (endRande.location != NSNotFound)
754         appVersion = [appVersion substringToIndex:endRande.location];
755
756     BWQuincyManager *quincyManager = [BWQuincyManager sharedQuincyManager];
757     [quincyManager setApplicationVersion:appVersion];
758     [quincyManager setSubmissionURL:@"http://crash.videolan.org/crash_v200.php"];
759     [quincyManager setDelegate:self];
760     [quincyManager setCompanyName:@"VideoLAN"];
761
762     [self updateCurrentlyUsedHotkeys];
763
764     /* init media key support */
765     b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
766     if (b_mediaKeySupport) {
767         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
768         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
769                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
770                                                                  nil]];
771     }
772     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
773
774     [self removeOldPreferences];
775
776     /* Handle sleep notification */
777     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
778            name:NSWorkspaceWillSleepNotification object:nil];
779
780     /* update the main window */
781     [o_mainwindow updateWindow];
782     [o_mainwindow updateTimeSlider];
783     [o_mainwindow updateVolumeSlider];
784
785     playlist_t * p_playlist = pl_Get(VLCIntf);
786     PL_LOCK;
787     BOOL kidsAround = p_playlist->p_local_category->i_children != 0;
788     PL_UNLOCK;
789     if (kidsAround && var_GetBool(p_playlist, "playlist-autostart"))
790         [[self playlist] playItem:nil];
791 }
792
793 #pragma mark -
794 #pragma mark Termination
795
796 - (void)applicationWillTerminate:(NSNotification *)notification
797 {
798     /* don't allow a double termination call. If the user has
799      * already invoked the quit then simply return this time. */
800     static bool f_appExit = false;
801     bool isTerminating;
802
803     [o_appLock lock];
804     isTerminating = f_appExit;
805     f_appExit = true;
806     [o_appLock unlock];
807
808     if (isTerminating)
809         return;
810
811     [self resumeItunesPlayback:nil];
812
813     if (notification == nil)
814         [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
815
816     playlist_t * p_playlist = pl_Get(p_intf);
817
818     /* save current video and audio profiles */
819     [[VLCVideoEffects sharedInstance] saveCurrentProfile];
820     [[VLCAudioEffects sharedInstance] saveCurrentProfile];
821
822     /* Save some interface state in configuration, at module quit */
823     config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
824     config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
825     config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
826
827     msg_Dbg(p_intf, "Terminating");
828
829     /* unsubscribe from the interactive dialogues */
830     dialog_Unregister(p_intf);
831     var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
832     var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
833     var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
834     var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
835     var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
836     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
837     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
838     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
839     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
840     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
841     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
842     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
843     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
844     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
845     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
846     var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
847     var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
848     var_DelCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
849
850     if (p_current_input) {
851         var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
852         vlc_object_release(p_current_input);
853         p_current_input = NULL;
854     }
855
856     /* remove global observer watching for vout device changes correctly */
857     [[NSNotificationCenter defaultCenter] removeObserver: self];
858
859     [o_vout_provider_lock lock];
860     // release before o_info!
861     [o_vout_controller release];
862     o_vout_controller = nil;
863     [o_vout_provider_lock unlock];
864
865     /* release some other objects here, because it isn't sure whether dealloc
866      * will be called later on */
867     if (o_sprefs)
868         [o_sprefs release];
869
870     if (o_prefs)
871         [o_prefs release];
872
873     [o_open release];
874
875     if (o_info)
876         [o_info release];
877
878     if (o_wizard)
879         [o_wizard release];
880
881     if (!o_bookmarks)
882         [o_bookmarks release];
883
884     [o_coredialogs release];
885     [o_eyetv release];
886     [o_remote release];
887
888     /* unsubscribe from libvlc's debug messages */
889     vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
890
891     [o_usedHotkeys release];
892     o_usedHotkeys = NULL;
893
894     [o_mediaKeyController release];
895
896     /* write cached user defaults to disk */
897     [[NSUserDefaults standardUserDefaults] synchronize];
898
899     [o_mainmenu release];
900     [o_coreinteraction release];
901
902     libvlc_Quit(p_intf->p_libvlc);
903
904     o_mainwindow = NULL;
905
906     [self setIntf:nil];
907 }
908
909 #pragma mark -
910 #pragma mark Sparkle delegate
911 /* received directly before the update gets installed, so let's shut down a bit */
912 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
913 {
914     [NSApp activateIgnoringOtherApps:YES];
915     [o_remote stopListening: self];
916     [[VLCCoreInteraction sharedInstance] stop];
917 }
918
919 /* don't be enthusiastic about an update if we currently play a video */
920 - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle
921 {
922     if ([self activeVideoPlayback])
923         return NO;
924
925     return YES;
926 }
927
928 #pragma mark -
929 #pragma mark Media Key support
930
931 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
932 {
933     if (b_mediaKeySupport) {
934         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
935
936         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
937         int keyFlags = ([event data1] & 0x0000FFFF);
938         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
939         int keyRepeat = (keyFlags & 0x1);
940
941         if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
942             [[VLCCoreInteraction sharedInstance] playOrPause];
943
944         if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
945             if (keyState == 0 && keyRepeat == 0)
946                 [[VLCCoreInteraction sharedInstance] next];
947             else if (keyRepeat == 1) {
948                 [[VLCCoreInteraction sharedInstance] forwardShort];
949                 b_mediakeyJustJumped = YES;
950                 [self performSelector:@selector(resetMediaKeyJump)
951                            withObject: NULL
952                            afterDelay:0.25];
953             }
954         }
955
956         if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
957             if (keyState == 0 && keyRepeat == 0)
958                 [[VLCCoreInteraction sharedInstance] previous];
959             else if (keyRepeat == 1) {
960                 [[VLCCoreInteraction sharedInstance] backwardShort];
961                 b_mediakeyJustJumped = YES;
962                 [self performSelector:@selector(resetMediaKeyJump)
963                            withObject: NULL
964                            afterDelay:0.25];
965             }
966         }
967     }
968 }
969
970 #pragma mark -
971 #pragma mark Other notification
972
973 /* Listen to the remote in exclusive mode, only when VLC is the active
974    application */
975 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
976 {
977     if (!p_intf)
978         return;
979     if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
980         [o_remote startListening: self];
981 }
982 - (void)applicationDidResignActive:(NSNotification *)aNotification
983 {
984     if (!p_intf)
985         return;
986     [o_remote stopListening: self];
987 }
988
989 /* Triggered when the computer goes to sleep */
990 - (void)computerWillSleep: (NSNotification *)notification
991 {
992     [[VLCCoreInteraction sharedInstance] pause];
993 }
994
995 #pragma mark -
996 #pragma mark File opening over dock icon
997
998 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
999 {
1000     char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], NULL);
1001
1002     if (launched == NO) {
1003         if (items_at_launch) {
1004             int items = [o_names count];
1005             if (items > items_at_launch)
1006                 items_at_launch = 0;
1007             else
1008                 items_at_launch -= items;
1009             return;
1010         }
1011     }
1012
1013     // try to add file as subtitle
1014     if ([o_names count] == 1 && psz_uri) {
1015         input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1016         if (p_input) {
1017             int i_result = input_AddSubtitleOSD(p_input, [[o_names objectAtIndex:0] UTF8String], true, true);
1018             vlc_object_release(p_input);
1019             if (i_result == VLC_SUCCESS) {
1020                 free(psz_uri);
1021                 return;
1022             }
1023         }
1024     }
1025     free(psz_uri);
1026
1027     NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1028     NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1029     for (NSUInteger i = 0; i < [o_sorted_names count]; i++) {
1030         psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex:i] UTF8String], "file");
1031         if (!psz_uri)
1032             continue;
1033
1034         NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1035         free(psz_uri);
1036         [o_result addObject: o_dic];
1037     }
1038
1039     [o_playlist appendArray: o_result atPos: -1 enqueue: !config_GetInt(VLCIntf, "macosx-autoplay")];
1040
1041     return;
1042 }
1043
1044 /* When user click in the Dock icon our double click in the finder */
1045 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1046 {
1047     if (!hasVisibleWindows)
1048         [o_mainwindow makeKeyAndOrderFront:self];
1049
1050     return YES;
1051 }
1052
1053 #pragma mark -
1054 #pragma mark Apple Remote Control
1055
1056 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1057    increase/decrease as long as the user holds the left/right, plus/minus button */
1058 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1059 {
1060     if (b_remote_button_hold) {
1061         switch([buttonIdentifierNumber intValue]) {
1062             case kRemoteButtonRight_Hold:
1063                 [[VLCCoreInteraction sharedInstance] forward];
1064                 break;
1065             case kRemoteButtonLeft_Hold:
1066                 [[VLCCoreInteraction sharedInstance] backward];
1067                 break;
1068             case kRemoteButtonVolume_Plus_Hold:
1069                 if (p_intf)
1070                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1071                 break;
1072             case kRemoteButtonVolume_Minus_Hold:
1073                 if (p_intf)
1074                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1075                 break;
1076         }
1077         if (b_remote_button_hold) {
1078             /* trigger event */
1079             [self performSelector:@selector(executeHoldActionForRemoteButton:)
1080                          withObject:buttonIdentifierNumber
1081                          afterDelay:0.25];
1082         }
1083     }
1084 }
1085
1086 /* Apple Remote callback */
1087 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1088                pressedDown: (BOOL) pressedDown
1089                 clickCount: (unsigned int) count
1090 {
1091     switch(buttonIdentifier) {
1092         case k2009RemoteButtonFullscreen:
1093             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1094             break;
1095         case k2009RemoteButtonPlay:
1096             [[VLCCoreInteraction sharedInstance] playOrPause];
1097             break;
1098         case kRemoteButtonPlay:
1099             if (count >= 2)
1100                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1101             else
1102                 [[VLCCoreInteraction sharedInstance] playOrPause];
1103             break;
1104         case kRemoteButtonVolume_Plus:
1105             if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1106                 [NSSound increaseSystemVolume];
1107             else
1108                 if (p_intf)
1109                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1110             break;
1111         case kRemoteButtonVolume_Minus:
1112             if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1113                 [NSSound decreaseSystemVolume];
1114             else
1115                 if (p_intf)
1116                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1117             break;
1118         case kRemoteButtonRight:
1119             if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1120                 [[VLCCoreInteraction sharedInstance] forward];
1121             else
1122                 [[VLCCoreInteraction sharedInstance] next];
1123             break;
1124         case kRemoteButtonLeft:
1125             if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1126                 [[VLCCoreInteraction sharedInstance] backward];
1127             else
1128                 [[VLCCoreInteraction sharedInstance] previous];
1129             break;
1130         case kRemoteButtonRight_Hold:
1131         case kRemoteButtonLeft_Hold:
1132         case kRemoteButtonVolume_Plus_Hold:
1133         case kRemoteButtonVolume_Minus_Hold:
1134             /* simulate an event as long as the user holds the button */
1135             b_remote_button_hold = pressedDown;
1136             if (pressedDown) {
1137                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt:buttonIdentifier];
1138                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1139                            withObject:buttonIdentifierNumber];
1140             }
1141             break;
1142         case kRemoteButtonMenu:
1143             [o_controls showPosition: self]; //FIXME
1144             break;
1145         case kRemoteButtonPlay_Sleep:
1146         {
1147             NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1148             [script executeAndReturnError:nil];
1149             [script release];
1150             break;
1151         }
1152         default:
1153             /* Add here whatever you want other buttons to do */
1154             break;
1155     }
1156 }
1157
1158 #pragma mark -
1159 #pragma mark Key Shortcuts
1160
1161 /*****************************************************************************
1162  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1163  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1164  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1165  *****************************************************************************/
1166 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1167 {
1168     unichar key = 0;
1169     vlc_value_t val;
1170     unsigned int i_pressed_modifiers = 0;
1171
1172     val.i_int = 0;
1173     i_pressed_modifiers = [o_event modifierFlags];
1174
1175     if (i_pressed_modifiers & NSControlKeyMask)
1176         val.i_int |= KEY_MODIFIER_CTRL;
1177
1178     if (i_pressed_modifiers & NSAlternateKeyMask)
1179         val.i_int |= KEY_MODIFIER_ALT;
1180
1181     if (i_pressed_modifiers & NSShiftKeyMask)
1182         val.i_int |= KEY_MODIFIER_SHIFT;
1183
1184     if (i_pressed_modifiers & NSCommandKeyMask)
1185         val.i_int |= KEY_MODIFIER_COMMAND;
1186
1187     NSString * characters = [o_event charactersIgnoringModifiers];
1188     if ([characters length] > 0) {
1189         key = [[characters lowercaseString] characterAtIndex: 0];
1190
1191         /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1192         if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1193             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1194             return YES;
1195         }
1196
1197         if (!b_force) {
1198             switch(key) {
1199                 case NSDeleteCharacter:
1200                 case NSDeleteFunctionKey:
1201                 case NSDeleteCharFunctionKey:
1202                 case NSBackspaceCharacter:
1203                 case NSUpArrowFunctionKey:
1204                 case NSDownArrowFunctionKey:
1205                 case NSEnterCharacter:
1206                 case NSCarriageReturnCharacter:
1207                     return NO;
1208             }
1209         }
1210
1211         val.i_int |= CocoaKeyToVLC(key);
1212
1213         BOOL b_found_key = NO;
1214         for (NSUInteger i = 0; i < [o_usedHotkeys count]; i++) {
1215             NSString *str = [o_usedHotkeys objectAtIndex:i];
1216             unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1217
1218             if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1219                (i_keyModifiers & NSShiftKeyMask)     == (i_pressed_modifiers & NSShiftKeyMask) &&
1220                (i_keyModifiers & NSControlKeyMask)   == (i_pressed_modifiers & NSControlKeyMask) &&
1221                (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1222                (i_keyModifiers & NSCommandKeyMask)   == (i_pressed_modifiers & NSCommandKeyMask)) {
1223                 b_found_key = YES;
1224                 break;
1225             }
1226         }
1227
1228         if (b_found_key) {
1229             var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1230             return YES;
1231         }
1232     }
1233
1234     return NO;
1235 }
1236
1237 - (void)updateCurrentlyUsedHotkeys
1238 {
1239     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1240     /* Get the main Module */
1241     module_t *p_main = module_get_main();
1242     assert(p_main);
1243     unsigned confsize;
1244     module_config_t *p_config;
1245
1246     p_config = module_config_get (p_main, &confsize);
1247
1248     for (size_t i = 0; i < confsize; i++) {
1249         module_config_t *p_item = p_config + i;
1250
1251         if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1252            && !strncmp(p_item->psz_name , "key-", 4)
1253            && !EMPTY_STR(p_item->psz_text)) {
1254             if (p_item->value.psz)
1255                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1256         }
1257     }
1258     module_config_free (p_config);
1259
1260     if (o_usedHotkeys)
1261         [o_usedHotkeys release];
1262     o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1263     [o_tempArray release];
1264 }
1265
1266 #pragma mark -
1267 #pragma mark Interface updaters
1268 // This must be called on main thread
1269 - (void)PlaylistItemChanged
1270 {
1271     if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1272         var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1273         p_input_changed = p_current_input;
1274         p_current_input = NULL;
1275
1276         [o_mainmenu setRateControlsEnabled: NO];
1277     }
1278     else if (!p_current_input) {
1279         // object is hold here and released then it is dead
1280         p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1281         if (p_current_input) {
1282             var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1283             [self playbackStatusUpdated];
1284             [o_mainmenu setRateControlsEnabled: YES];
1285
1286             if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden]) {
1287                 [o_mainwindow changePlaylistState: psPlaylistItemChangedEvent];
1288             }
1289
1290             p_input_changed = vlc_object_hold(p_current_input);
1291         }
1292     }
1293
1294     [o_playlist updateRowSelection];
1295     [o_mainwindow updateWindow];
1296     [self updateDelays];
1297     [self updateMainMenu];
1298 }
1299
1300 - (void)informInputChanged
1301 {
1302     if (p_input_changed) {
1303         [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1304         vlc_object_release(p_input_changed);
1305         p_input_changed = NULL;
1306     }
1307 }
1308
1309 - (void)updateMainMenu
1310 {
1311     [o_mainmenu setupMenus];
1312     [o_mainmenu updatePlaybackRate];
1313     [[VLCCoreInteraction sharedInstance] resetAtoB];
1314 }
1315
1316 - (void)updateMainWindow
1317 {
1318     [o_mainwindow updateWindow];
1319 }
1320
1321 - (void)showMainWindow
1322 {
1323     [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1324 }
1325
1326 - (void)showFullscreenController
1327 {
1328     // defer selector here (possibly another time) to ensure that keyWindow is set properly
1329     // (needed for NSApplicationDidBecomeActiveNotification)
1330     [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1331 }
1332
1333 - (void)updateDelays
1334 {
1335     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1336 }
1337
1338 - (void)updateName
1339 {
1340     [o_mainwindow updateName];
1341 }
1342
1343 - (void)updatePlaybackPosition
1344 {
1345     [o_mainwindow updateTimeSlider];
1346     [[VLCCoreInteraction sharedInstance] updateAtoB];
1347 }
1348
1349 - (void)updateVolume
1350 {
1351     [o_mainwindow updateVolumeSlider];
1352 }
1353
1354 - (void)playlistUpdated
1355 {
1356     @synchronized(self) {
1357         b_playlist_updated_selector_in_queue = NO;
1358     }
1359
1360     [self playbackStatusUpdated];
1361     [o_playlist playlistUpdated];
1362     [o_mainwindow updateWindow];
1363     [o_mainwindow updateName];
1364
1365     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1366                                                         object: nil
1367                                                       userInfo: nil];
1368 }
1369
1370 - (void)updateRecordState: (BOOL)b_value
1371 {
1372     [o_mainmenu updateRecordState:b_value];
1373 }
1374
1375 - (void)updateInfoandMetaPanel
1376 {
1377     [o_playlist outlineViewSelectionDidChange:nil];
1378 }
1379
1380 - (void)resumeItunesPlayback:(id)sender
1381 {
1382     if (var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1383         if (b_has_itunes_paused) {
1384             iTunesApplication *iTunesApp = (iTunesApplication *) [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1385             if (iTunesApp && [iTunesApp isRunning]) {
1386                 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1387                     msg_Dbg(p_intf, "Unpause iTunes...");
1388                     [iTunesApp playpause];
1389                 }
1390             }
1391         }
1392
1393         if (b_has_spotify_paused) {
1394             SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1395             if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePaused) {
1396                 msg_Dbg(p_intf, "Unpause Spotify...");
1397                 [spotifyApp play];
1398             }
1399         }
1400     }
1401
1402     b_has_itunes_paused = NO;
1403     b_has_spotify_paused = NO;
1404     o_itunes_play_timer = nil;
1405 }
1406
1407 - (void)playbackStatusUpdated
1408 {
1409     int state = -1;
1410     if (p_current_input) {
1411         state = var_GetInteger(p_current_input, "state");
1412     }
1413
1414     int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1415     // cancel itunes timer if next item starts playing
1416     if (state > -1 && state != END_S && i_control_itunes > 0) {
1417         if (o_itunes_play_timer) {
1418             [o_itunes_play_timer invalidate];
1419             o_itunes_play_timer = nil;
1420         }
1421     }
1422
1423     if (state == PLAYING_S) {
1424         if (i_control_itunes > 0) {
1425             // pause iTunes
1426             if (!b_has_itunes_paused) {
1427                 iTunesApplication *iTunesApp = (iTunesApplication *) [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1428                 if (iTunesApp && [iTunesApp isRunning]) {
1429                     if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1430                         msg_Dbg(p_intf, "Pause iTunes...");
1431                         [iTunesApp pause];
1432                         b_has_itunes_paused = YES;
1433                     }
1434                 }
1435             }
1436
1437             // pause Spotify
1438             if (!b_has_spotify_paused) {
1439                 SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1440                 if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePlaying) {
1441                     msg_Dbg(p_intf, "Pause Spotify...");
1442                     [spotifyApp pause];
1443                     b_has_spotify_paused = YES;
1444                 }
1445             }
1446         }
1447
1448         /* Declare user activity.
1449          This wakes the display if it is off, and postpones display sleep according to the users system preferences
1450          Available from 10.7.3 */
1451 #ifdef MAC_OS_X_VERSION_10_7
1452         if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1453         {
1454             CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1455             IOPMAssertionDeclareUserActivity(reasonForActivity,
1456                                              kIOPMUserActiveLocal,
1457                                              &userActivityAssertionID);
1458             CFRelease(reasonForActivity);
1459         }
1460 #endif
1461
1462         /* prevent the system from sleeping */
1463         if (systemSleepAssertionID > 0) {
1464             msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1465             IOPMAssertionRelease(systemSleepAssertionID);
1466         }
1467
1468         IOReturn success;
1469         /* work-around a bug in 10.7.4 and 10.7.5, so check for 10.7.x < 10.7.4, 10.8 and 10.6 */
1470         if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_MAVERICKS || OSX_SNOW_LEOPARD) {
1471             CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1472             if ([self activeVideoPlayback])
1473                 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1474             else
1475                 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1476             CFRelease(reasonForActivity);
1477         } else {
1478             /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1479             if ([self activeVideoPlayback])
1480                 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1481             else
1482                 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1483         }
1484
1485         if (success == kIOReturnSuccess)
1486             msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1487         else
1488             msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1489
1490         [[self mainMenu] setPause];
1491         [o_mainwindow setPause];
1492     } else {
1493         [o_mainmenu setSubmenusEnabled: FALSE];
1494         [[self mainMenu] setPlay];
1495         [o_mainwindow setPlay];
1496
1497         /* allow the system to sleep again */
1498         if (systemSleepAssertionID > 0) {
1499             msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1500             IOPMAssertionRelease(systemSleepAssertionID);
1501         }
1502
1503         if (state == END_S || state == -1) {
1504             if (i_control_itunes > 0) {
1505                 if (o_itunes_play_timer) {
1506                     [o_itunes_play_timer invalidate];
1507                 }
1508                 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1509                                                                        target: self
1510                                                                      selector: @selector(resumeItunesPlayback:)
1511                                                                      userInfo: nil
1512                                                                       repeats: NO];
1513             }
1514         }
1515     }
1516
1517     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1518     [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1519 }
1520
1521 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1522 {
1523     [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1524                                                                    object:nil
1525                                                                  userInfo:nil
1526                                                        deliverImmediately:YES];
1527 }
1528
1529 - (void)playbackModeUpdated
1530 {
1531     playlist_t * p_playlist = pl_Get(VLCIntf);
1532
1533     bool loop = var_GetBool(p_playlist, "loop");
1534     bool repeat = var_GetBool(p_playlist, "repeat");
1535     if (repeat) {
1536         [[o_mainwindow controlsBar] setRepeatOne];
1537         [o_mainmenu setRepeatOne];
1538     } else if (loop) {
1539         [[o_mainwindow controlsBar] setRepeatAll];
1540         [o_mainmenu setRepeatAll];
1541     } else {
1542         [[o_mainwindow controlsBar] setRepeatOff];
1543         [o_mainmenu setRepeatOff];
1544     }
1545
1546     [[o_mainwindow controlsBar] setShuffle];
1547     [o_mainmenu setShuffle];
1548 }
1549
1550 #pragma mark -
1551 #pragma mark Window updater
1552
1553 - (void)setActiveVideoPlayback:(BOOL)b_value
1554 {
1555     b_active_videoplayback = b_value;
1556     if (o_mainwindow) {
1557         [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1558     }
1559
1560     // update sleep blockers
1561     [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1562 }
1563
1564 #pragma mark -
1565 #pragma mark Other objects getters
1566
1567 - (id)mainMenu
1568 {
1569     return o_mainmenu;
1570 }
1571
1572 - (VLCMainWindow *)mainWindow
1573 {
1574     return o_mainwindow;
1575 }
1576
1577 - (id)controls
1578 {
1579     if (o_controls)
1580         return o_controls;
1581
1582     return nil;
1583 }
1584
1585 - (id)bookmarks
1586 {
1587     if (!o_bookmarks)
1588         o_bookmarks = [[VLCBookmarks alloc] init];
1589
1590     if (!nib_bookmarks_loaded)
1591         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1592
1593     return o_bookmarks;
1594 }
1595
1596 - (id)open
1597 {
1598     if (!o_open)
1599         return nil;
1600
1601     if (!nib_open_loaded)
1602         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1603
1604     return o_open;
1605 }
1606
1607 - (id)simplePreferences
1608 {
1609     if (!o_sprefs)
1610         o_sprefs = [[VLCSimplePrefs alloc] init];
1611
1612     if (!nib_prefs_loaded)
1613         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1614
1615     return o_sprefs;
1616 }
1617
1618 - (id)preferences
1619 {
1620     if (!o_prefs)
1621         o_prefs = [[VLCPrefs alloc] init];
1622
1623     if (!nib_prefs_loaded)
1624         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1625
1626     return o_prefs;
1627 }
1628
1629 - (id)playlist
1630 {
1631     if (o_playlist)
1632         return o_playlist;
1633
1634     return nil;
1635 }
1636
1637 - (id)info
1638 {
1639     if (! nib_info_loaded)
1640         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1641
1642     if (o_info)
1643         return o_info;
1644
1645     return nil;
1646 }
1647
1648 - (id)wizard
1649 {
1650     if (!o_wizard)
1651         o_wizard = [[VLCWizard alloc] init];
1652
1653     if (!nib_wizard_loaded) {
1654         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1655         [o_wizard initStrings];
1656     }
1657     return o_wizard;
1658 }
1659
1660 - (id)coreDialogProvider
1661 {
1662     if (o_coredialogs)
1663         return o_coredialogs;
1664
1665     return nil;
1666 }
1667
1668 - (id)eyeTVController
1669 {
1670     if (o_eyetv)
1671         return o_eyetv;
1672
1673     return nil;
1674 }
1675
1676 - (id)appleRemoteController
1677 {
1678     return o_remote;
1679 }
1680
1681 - (BOOL)activeVideoPlayback
1682 {
1683     return b_active_videoplayback;
1684 }
1685
1686 #pragma mark -
1687 #pragma mark Remove old prefs
1688
1689
1690 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1691 static const int kCurrentPreferencesVersion = 3;
1692
1693 - (void)resetAndReinitializeUserDefaults
1694 {
1695     // note that [NSUserDefaults resetStandardUserDefaults] will NOT correctly reset to the defaults
1696
1697     NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
1698     [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
1699
1700     // set correct version to avoid question about outdated config
1701     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1702     [[NSUserDefaults standardUserDefaults] synchronize];
1703 }
1704
1705 - (void)removeOldPreferences
1706 {
1707     NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1708     int version = [defaults integerForKey:kVLCPreferencesVersion];
1709     if (version >= kCurrentPreferencesVersion)
1710         return;
1711
1712     if (version == 1) {
1713         [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1714         [defaults synchronize];
1715
1716         if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1717             return;
1718         else
1719             config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1720     } else if (version == 2) {
1721         /* version 2 (used by VLC 2.0.x and early versions of 2.1) can lead to exceptions within 2.1 or later
1722          * so we reset the OS X specific prefs here - in practice, no user will notice */
1723         [self resetAndReinitializeUserDefaults];
1724
1725     } else {
1726         NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1727             NSUserDomainMask, YES);
1728         if (!libraries || [libraries count] == 0) return;
1729         NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1730
1731         /* File not found, don't attempt anything */
1732         if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1733            ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1734             [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1735             return;
1736         }
1737
1738         int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1739                     _NS("We just found an older version of VLC's preferences files."),
1740                     _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1741         if (res != NSOKButton) {
1742             [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1743             return;
1744         }
1745
1746         // Do NOT add the current plist file here as this would conflict with caching.
1747         // Instead, just reset below.
1748         NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc", @"VLC", nil];
1749
1750         /* Move the file to trash one by one. Using above array the method would stop after first file
1751            not found. */
1752         for (NSString *file in ourPreferences) {
1753             [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:@"" files:[NSArray arrayWithObject:file] tag:nil];
1754         }
1755
1756         [self resetAndReinitializeUserDefaults];
1757     }
1758
1759     /* Relaunch now */
1760     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1761
1762     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1763     if (fork() != 0) {
1764         exit(0);
1765     }
1766     execl(path, path, NULL);
1767 }
1768
1769 #pragma mark -
1770 #pragma mark Playlist toggling
1771
1772 - (void)updateTogglePlaylistState
1773 {
1774     [[self playlist] outlineViewSelectionDidChange: NULL];
1775 }
1776
1777 #pragma mark -
1778
1779 @end
1780
1781 @implementation VLCMain (Internal)
1782
1783 - (void)resetMediaKeyJump
1784 {
1785     b_mediakeyJustJumped = NO;
1786 }
1787
1788 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1789 {
1790     b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1791     if (b_mediaKeySupport) {
1792         if (!o_mediaKeyController)
1793             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1794
1795         if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot]->i_children > 0 ||
1796             p_current_input)
1797             [o_mediaKeyController startWatchingMediaKeys];
1798         else
1799             [o_mediaKeyController stopWatchingMediaKeys];
1800     }
1801     else if (!b_mediaKeySupport && o_mediaKeyController)
1802         [o_mediaKeyController stopWatchingMediaKeys];
1803 }
1804
1805 @end
1806
1807 /*****************************************************************************
1808  * VLCApplication interface
1809  *****************************************************************************/
1810
1811 @implementation VLCApplication
1812 // when user selects the quit menu from dock it sends a terminate:
1813 // but we need to send a stop: to properly exits libvlc.
1814 // However, we are not able to change the action-method sent by this standard menu item.
1815 // thus we override terminate: to send a stop:
1816 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1817 - (void)terminate:(id)sender
1818 {
1819     [self activateIgnoringOtherApps:YES];
1820     [self stop:sender];
1821 }
1822
1823 @end