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