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