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