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