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