1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2013 VLC authors and VideoLAN
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>
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.
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.
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 *****************************************************************************/
28 /*****************************************************************************
30 *****************************************************************************/
35 #include <stdlib.h> /* malloc(), free() */
37 #include <vlc_common.h>
39 #include <vlc_dialog.h>
41 #include <vlc_modules.h>
42 #include <vlc_plugin.h>
43 #include <vlc_vout_display.h>
44 #include <unistd.h> /* execl() */
46 #import "CompatibilityFixes.h"
52 #import "playlistinfo.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.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"
67 #import "VideoEffects.h"
68 #import "AudioEffects.h"
71 #import <Sparkle/Sparkle.h> /* we're the update delegate */
77 /*****************************************************************************
79 *****************************************************************************/
81 static void updateProgressPanel (void *, const char *, float);
82 static bool checkProgressPanel (void *);
83 static void destroyProgressPanel (void *);
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 *);
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 *);
100 #pragma mark VLC Interface Object Callbacks
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;
106 static NSLock * o_appLock = nil; // controls access to f_appExit
107 static NSLock * o_vout_provider_lock = nil;
110 /*****************************************************************************
111 * OpenIntf: initialize interface
112 *****************************************************************************/
113 int OpenIntf (vlc_object_t *p_this)
115 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
116 [VLCApplication sharedApplication];
118 intf_thread_t *p_intf = (intf_thread_t*) p_this;
119 msg_Dbg(p_intf, "Starting macosx interface");
121 [VLCApplication sharedApplication];
123 o_appLock = [[NSLock alloc] init];
124 o_vout_provider_lock = [[NSLock alloc] init];
126 [[VLCMain sharedInstance] setIntf: p_intf];
128 vlc_mutex_lock(&start_mutex);
129 b_intf_starting = true;
130 vlc_cond_signal(&start_cond);
131 vlc_mutex_unlock(&start_mutex);
133 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
139 void CloseIntf (vlc_object_t *p_this)
141 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
143 msg_Dbg(p_this, "Closing macosx interface");
144 [[VLCMain sharedInstance] applicationWillTerminate:nil];
146 [o_vout_provider_lock release];
147 o_vout_provider_lock = nil;
151 static int WindowControl(vout_window_t *, int i_query, va_list);
153 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
155 if (cfg->type != VOUT_WINDOW_TYPE_INVALID
156 && cfg->type != VOUT_WINDOW_TYPE_NSOBJECT)
159 msg_Dbg(p_wnd, "Opening video window");
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).
168 * Timeout is needed as the mac intf is not always started at all.
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)) {
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);
183 vlc_mutex_unlock(&start_mutex);
185 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
187 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
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];
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];
204 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
207 VLCVoutView *videoView = nil;
208 [inv getReturnValue:&videoView];
210 // this method is not supposed to fail
211 assert(videoView != nil);
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;
216 [o_vout_provider_lock unlock];
218 p_wnd->type = VOUT_WINDOW_TYPE_NSOBJECT;
219 p_wnd->control = WindowControl;
225 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
227 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
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];
238 case VOUT_WINDOW_SET_STATE:
240 unsigned i_state = va_arg(args, unsigned);
242 if (i_state & VOUT_WINDOW_STATE_BELOW)
244 msg_Dbg(p_wnd, "Ignore change to VOUT_WINDOW_STATE_BELOW");
248 NSInteger i_cooca_level = NSNormalWindowLevel;
249 if (i_state & VOUT_WINDOW_STATE_ABOVE)
250 i_cooca_level = NSStatusWindowLevel;
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
263 case VOUT_WINDOW_SET_SIZE:
265 unsigned int i_width = va_arg(args, unsigned int);
266 unsigned int i_height = va_arg(args, unsigned int);
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
280 case VOUT_WINDOW_SET_FULLSCREEN:
282 if (var_InheritBool(VLCIntf, "video-wallpaper")) {
283 msg_Dbg(p_wnd, "Ignore fullscreen event as video-wallpaper is on");
287 int i_full = va_arg(args, int);
288 BOOL b_animation = YES;
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
304 msg_Warn(p_wnd, "unsupported control query");
305 [o_vout_provider_lock unlock];
312 [o_vout_provider_lock unlock];
317 void WindowClose(vout_window_t *p_wnd)
319 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
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];
329 [o_vout_controller performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
330 [o_vout_provider_lock unlock];
336 #pragma mark Variables Callback
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)
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];
346 case INPUT_EVENT_RATE:
347 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
349 case INPUT_EVENT_POSITION:
350 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
352 case INPUT_EVENT_TITLE:
353 case INPUT_EVENT_CHAPTER:
354 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
356 case INPUT_EVENT_CACHE:
357 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
359 case INPUT_EVENT_STATISTICS:
360 dispatch_async(dispatch_get_main_queue(), ^{
361 [[[VLCMain sharedInstance] info] updateStatistics];
366 case INPUT_EVENT_TELETEXT:
368 case INPUT_EVENT_AOUT:
370 case INPUT_EVENT_VOUT:
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];
378 case INPUT_EVENT_BOOKMARK:
380 case INPUT_EVENT_RECORD:
381 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
383 case INPUT_EVENT_PROGRAM:
384 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
386 case INPUT_EVENT_ITEM_EPG:
388 case INPUT_EVENT_SIGNAL:
391 case INPUT_EVENT_ITEM_NAME:
392 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
395 case INPUT_EVENT_AUDIO_DELAY:
396 case INPUT_EVENT_SUBTITLE_DELAY:
397 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
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];
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)
416 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
418 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
425 * Callback for item-change variable. Is triggered after update of duration or metadata.
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)
430 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
432 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(plItemUpdated) withObject:nil waitUntilDone:NO];
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)
441 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
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];
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)
454 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
456 NSNumber *o_val = [NSNumber numberWithInt:new_val.i_int];
457 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(plItemRemoved:) withObject:o_val waitUntilDone:NO];
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)
466 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
467 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
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)
476 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
477 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
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)
486 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
488 [[VLCCoreInteraction sharedInstance] performSelectorOnMainThread:@selector(pause) withObject:nil waitUntilDone:NO];
489 [[VLCApplication sharedApplication] hide:nil];
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)
503 intf_thread_t * p_intf = VLCIntf;
505 playlist_t * p_playlist = pl_Get(p_intf);
506 BOOL b_fullscreen = var_GetBool(p_playlist, "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];
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)
522 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
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;
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;
534 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
535 [[[VLCMain sharedInstance] coreDialogProvider] performEventWithObject: o_value ofType: type];
541 void updateProgressPanel (void *priv, const char *text, float value)
543 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
545 NSString *o_txt = toNSStr(text);
546 dispatch_async(dispatch_get_main_queue(), ^{
547 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
553 void destroyProgressPanel (void *priv)
555 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
557 if ([[NSApplication sharedApplication] isRunning])
558 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
563 bool checkProgressPanel (void *priv)
565 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
571 input_thread_t *getInput(void)
573 intf_thread_t *p_intf = VLCIntf;
576 return pl_CurrentInput(p_intf);
579 vout_thread_t *getVout(void)
581 input_thread_t *p_input = getInput();
584 vout_thread_t *p_vout = input_GetVout(p_input);
585 vlc_object_release(p_input);
589 vout_thread_t *getVoutForActiveWindow(void)
591 vout_thread_t *p_vout = nil;
593 id currentWindow = [NSApp keyWindow];
594 if ([currentWindow respondsToSelector:@selector(videoView)]) {
595 VLCVoutView *videoView = [currentWindow videoView];
597 p_vout = [videoView voutThread];
607 audio_output_t *getAout(void)
609 intf_thread_t *p_intf = VLCIntf;
612 return playlist_GetAout(pl_Get(p_intf));
618 @interface VLCMain () <BWQuincyManagerDelegate>
619 - (void)removeOldPreferences;
622 @interface VLCMain (Internal)
623 - (void)resetMediaKeyJump;
624 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
627 /*****************************************************************************
628 * VLCMain implementation
629 *****************************************************************************/
630 @implementation VLCMain
632 @synthesize voutController=o_vout_controller;
633 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
636 #pragma mark Initialization
638 static VLCMain *_o_sharedMainInstance = nil;
640 + (VLCMain *)sharedInstance
642 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
647 if (_o_sharedMainInstance) {
649 return _o_sharedMainInstance;
651 _o_sharedMainInstance = [super init];
654 p_current_input = NULL;
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];
662 /* announce our launch to a potential eyetv plugin */
663 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
664 object: @"VLCEyeTVSupport"
666 deliverImmediately: YES];
668 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
669 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
670 [defaults registerDefaults:appDefaults];
672 o_vout_controller = [[VLCVoutWindowController alloc] init];
674 informInputChangedQueue = dispatch_queue_create("org.videolan.vlc.inputChangedQueue", DISPATCH_QUEUE_SERIAL);
676 return _o_sharedMainInstance;
679 - (void)setIntf: (intf_thread_t *)p_mainintf
684 - (intf_thread_t *)intf
691 playlist_t *p_playlist;
693 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
695 /* Check if we already did this once. Opening the other nibs calls it too,
696 because VLCMain is the owner */
700 p_playlist = pl_Get(p_intf);
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);
715 if (!OSX_SNOW_LEOPARD) {
716 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
717 var_SetBool(p_playlist, "fullscreen", YES);
720 /* load our Shared Dialogs nib */
721 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
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);
736 /* init Apple Remote support */
737 o_remote = [[AppleRemote alloc] init];
738 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
739 [o_remote setDelegate: _o_sharedMainInstance];
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");
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.
753 NSCalendar *gregorian =
754 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
755 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
758 if (dayOfYear >= 354)
759 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
762 nib_main_loaded = TRUE;
765 - (void)applicationWillFinishLaunching:(NSNotification *)aNotification
767 playlist_t * p_playlist = pl_Get(VLCIntf);
769 items_at_launch = p_playlist->p_local_category->i_children;
772 [NSBundle loadNibNamed:@"MainWindow" owner: self];
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];
779 [[SUUpdater sharedUpdater] setDelegate:self];
783 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
790 NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey: @"CFBundleVersion"];
791 NSRange endRande = [appVersion rangeOfString:@"-"];
792 if (endRande.location != NSNotFound)
793 appVersion = [appVersion substringToIndex:endRande.location];
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"];
801 [self updateCurrentlyUsedHotkeys];
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,
811 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
813 [self removeOldPreferences];
815 /* Handle sleep notification */
816 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
817 name:NSWorkspaceWillSleepNotification object:nil];
819 /* update the main window */
820 [o_mainwindow updateWindow];
821 [o_mainwindow updateTimeSlider];
822 [o_mainwindow updateVolumeSlider];
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.
828 [self PlaylistItemChanged];
829 [self playbackModeUpdated];
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);
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);
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;
846 #pragma mark Termination
848 - (BOOL)isTerminating
853 - (void)applicationWillTerminate:(NSNotification *)notification
858 isTerminating = f_appExit;
865 [self resumeItunesPlayback:nil];
867 if (notification == nil)
868 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
870 playlist_t * p_playlist = pl_Get(p_intf);
872 /* save current video and audio profiles */
873 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
874 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
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"));
881 msg_Dbg(p_intf, "Terminating");
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);
903 if (p_current_input) {
904 /* continue playback where you left off */
905 [[self playlist] storePlaybackPositionForItem:p_current_input];
907 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
908 vlc_object_release(p_current_input);
909 p_current_input = NULL;
912 /* remove global observer watching for vout device changes correctly */
913 [[NSNotificationCenter defaultCenter] removeObserver: self];
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];
922 /* release some other objects here, because it isn't sure whether dealloc
923 * will be called later on */
939 [o_bookmarks release];
941 [o_coredialogs release];
945 /* unsubscribe from libvlc's debug messages */
946 vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
948 [o_usedHotkeys release];
949 o_usedHotkeys = NULL;
951 [o_mediaKeyController release];
953 /* write cached user defaults to disk */
954 [[NSUserDefaults standardUserDefaults] synchronize];
956 [o_mainmenu release];
957 [o_coreinteraction release];
965 #pragma mark Sparkle delegate
968 /* received directly before the update gets installed, so let's shut down a bit */
969 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
971 [NSApp activateIgnoringOtherApps:YES];
972 [o_remote stopListening: self];
973 [[VLCCoreInteraction sharedInstance] stop];
976 /* don't be enthusiastic about an update if we currently play a video */
977 - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle
979 if ([self activeVideoPlayback])
987 #pragma mark Media Key support
989 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
991 if (b_mediaKeySupport) {
992 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
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);
999 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
1000 [[VLCCoreInteraction sharedInstance] playOrPause];
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)
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)
1029 #pragma mark Other notification
1031 /* Listen to the remote in exclusive mode, only when VLC is the active
1033 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1037 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
1038 [o_remote startListening: self];
1040 - (void)applicationDidResignActive:(NSNotification *)aNotification
1044 [o_remote stopListening: self];
1047 /* Triggered when the computer goes to sleep */
1048 - (void)computerWillSleep: (NSNotification *)notification
1050 [[VLCCoreInteraction sharedInstance] pause];
1054 #pragma mark File opening over dock icon
1056 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
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;
1068 items_at_launch -= items;
1073 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], NULL);
1075 // try to add file as subtitle
1076 if ([o_names count] == 1 && psz_uri) {
1077 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
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) {
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");
1096 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1098 [o_result addObject: o_dic];
1101 [[[VLCMain sharedInstance] playlist] addPlaylistItems:o_result];
1104 /* When user click in the Dock icon our double click in the finder */
1105 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1107 if (!hasVisibleWindows)
1108 [o_mainwindow makeKeyAndOrderFront:self];
1114 #pragma mark Apple Remote Control
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
1120 if (b_remote_button_hold) {
1121 switch([buttonIdentifierNumber intValue]) {
1122 case kRemoteButtonRight_Hold:
1123 [[VLCCoreInteraction sharedInstance] forward];
1125 case kRemoteButtonLeft_Hold:
1126 [[VLCCoreInteraction sharedInstance] backward];
1128 case kRemoteButtonVolume_Plus_Hold:
1130 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1132 case kRemoteButtonVolume_Minus_Hold:
1134 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1137 if (b_remote_button_hold) {
1139 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1140 withObject:buttonIdentifierNumber
1146 /* Apple Remote callback */
1147 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1148 pressedDown: (BOOL) pressedDown
1149 clickCount: (unsigned int) count
1151 switch(buttonIdentifier) {
1152 case k2009RemoteButtonFullscreen:
1153 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1155 case k2009RemoteButtonPlay:
1156 [[VLCCoreInteraction sharedInstance] playOrPause];
1158 case kRemoteButtonPlay:
1160 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1162 [[VLCCoreInteraction sharedInstance] playOrPause];
1164 case kRemoteButtonVolume_Plus:
1165 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1166 [NSSound increaseSystemVolume];
1169 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1171 case kRemoteButtonVolume_Minus:
1172 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1173 [NSSound decreaseSystemVolume];
1176 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1178 case kRemoteButtonRight:
1179 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1180 [[VLCCoreInteraction sharedInstance] forward];
1182 [[VLCCoreInteraction sharedInstance] next];
1184 case kRemoteButtonLeft:
1185 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1186 [[VLCCoreInteraction sharedInstance] backward];
1188 [[VLCCoreInteraction sharedInstance] previous];
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;
1197 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt:buttonIdentifier];
1198 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1199 withObject:buttonIdentifierNumber];
1202 case kRemoteButtonMenu:
1203 [o_controls showPosition: self]; //FIXME
1205 case kRemoteButtonPlay_Sleep:
1207 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1208 [script executeAndReturnError:nil];
1213 /* Add here whatever you want other buttons to do */
1219 #pragma mark Key Shortcuts
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
1230 unsigned int i_pressed_modifiers = 0;
1233 i_pressed_modifiers = [o_event modifierFlags];
1235 if (i_pressed_modifiers & NSControlKeyMask)
1236 val.i_int |= KEY_MODIFIER_CTRL;
1238 if (i_pressed_modifiers & NSAlternateKeyMask)
1239 val.i_int |= KEY_MODIFIER_ALT;
1241 if (i_pressed_modifiers & NSShiftKeyMask)
1242 val.i_int |= KEY_MODIFIER_SHIFT;
1244 if (i_pressed_modifiers & NSCommandKeyMask)
1245 val.i_int |= KEY_MODIFIER_COMMAND;
1247 NSString * characters = [o_event charactersIgnoringModifiers];
1248 if ([characters length] > 0) {
1249 key = [[characters lowercaseString] characterAtIndex: 0];
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];
1259 case NSDeleteCharacter:
1260 case NSDeleteFunctionKey:
1261 case NSDeleteCharFunctionKey:
1262 case NSBackspaceCharacter:
1263 case NSUpArrowFunctionKey:
1264 case NSDownArrowFunctionKey:
1265 case NSEnterCharacter:
1266 case NSCarriageReturnCharacter:
1271 val.i_int |= CocoaKeyToVLC(key);
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];
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)) {
1289 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1297 - (void)updateCurrentlyUsedHotkeys
1299 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1300 /* Get the main Module */
1301 module_t *p_main = module_get_main();
1304 module_config_t *p_config;
1306 p_config = module_config_get (p_main, &confsize);
1308 for (size_t i = 0; i < confsize; i++) {
1309 module_config_t *p_item = p_config + i;
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]];
1318 module_config_free (p_config);
1321 [o_usedHotkeys release];
1322 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1323 [o_tempArray release];
1327 #pragma mark Interface updaters
1329 - (void)plItemAppended:(NSArray *)o_val
1331 int i_node = [[o_val objectAtIndex:0] intValue];
1332 int i_item = [[o_val objectAtIndex:1] intValue];
1334 [[[self playlist] model] addItem:i_item withParentNode:i_node];
1336 // update badge in sidebar
1337 [o_mainwindow updateWindow];
1339 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1344 - (void)plItemRemoved:(NSNumber *)o_val
1346 int i_item = [o_val intValue];
1348 [[[self playlist] model] removeItem:i_item];
1349 [[self playlist] deletionCompleted];
1351 // update badge in sidebar
1352 [o_mainwindow updateWindow];
1354 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1359 // This must be called on main thread
1360 - (void)PlaylistItemChanged
1362 input_thread_t *p_input_changed = NULL;
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;
1369 [o_mainmenu setRateControlsEnabled: NO];
1371 [[NSNotificationCenter defaultCenter] postNotificationName:VLCInputChangedNotification
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];
1382 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden]) {
1383 [o_mainwindow changePlaylistState: psPlaylistItemChangedEvent];
1386 p_input_changed = vlc_object_hold(p_current_input);
1388 [[self playlist] currentlyPlayingItemChanged];
1390 [[self playlist] continuePlaybackWhereYouLeftOff:p_current_input];
1392 [[NSNotificationCenter defaultCenter] postNotificationName:VLCInputChangedNotification
1397 [self updateMetaAndInfo];
1399 [o_mainwindow updateWindow];
1400 [self updateDelays];
1401 [self updateMainMenu];
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.
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);
1415 - (void)plItemUpdated
1417 [o_mainwindow updateName];
1420 [o_info updateMetadata];
1423 - (void)updateMainMenu
1425 [o_mainmenu setupMenus];
1426 [o_mainmenu updatePlaybackRate];
1427 [[VLCCoreInteraction sharedInstance] resetAtoB];
1430 - (void)updateMainWindow
1432 [o_mainwindow updateWindow];
1435 - (void)showMainWindow
1437 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1440 - (void)showFullscreenController
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];
1447 - (void)updateDelays
1449 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1454 [o_mainwindow updateName];
1457 - (void)updatePlaybackPosition
1459 [o_mainwindow updateTimeSlider];
1460 [[VLCCoreInteraction sharedInstance] updateAtoB];
1463 - (void)updateVolume
1465 [o_mainwindow updateVolumeSlider];
1468 - (void)updateRecordState: (BOOL)b_value
1470 [o_mainmenu updateRecordState:b_value];
1473 - (void)updateMetaAndInfo
1475 if (!p_current_input) {
1476 [[self info] updatePanelWithItem:nil];
1480 input_item_t *p_input_item = input_GetItem(p_current_input);
1482 [[[self playlist] model] updateItem:p_input_item];
1483 [[self info] updatePanelWithItem:p_input_item];
1486 - (void)resumeItunesPlayback:(id)sender
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];
1499 if (b_has_spotify_paused) {
1500 SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1502 if ([spotifyApp respondsToSelector:@selector(isRunning)] && [spotifyApp respondsToSelector:@selector(playerState)]) {
1503 if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePaused) {
1504 msg_Dbg(p_intf, "unpausing Spotify");
1512 b_has_itunes_paused = NO;
1513 b_has_spotify_paused = NO;
1514 o_itunes_play_timer = nil;
1517 - (void)playbackStatusUpdated
1520 if (p_current_input) {
1521 state = var_GetInteger(p_current_input, "state");
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;
1533 if (state == PLAYING_S) {
1534 if (i_control_itunes > 0) {
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");
1542 b_has_itunes_paused = YES;
1548 if (!b_has_spotify_paused) {
1549 SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1552 if ([spotifyApp respondsToSelector:@selector(isRunning)] && [spotifyApp respondsToSelector:@selector(playerState)]) {
1553 if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePlaying) {
1554 msg_Dbg(p_intf, "pausing Spotify");
1556 b_has_spotify_paused = YES;
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)
1569 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1570 IOPMAssertionDeclareUserActivity(reasonForActivity,
1571 kIOPMUserActiveLocal,
1572 &userActivityAssertionID);
1573 CFRelease(reasonForActivity);
1577 /* prevent the system from sleeping */
1578 if (systemSleepAssertionID > 0) {
1579 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1580 IOPMAssertionRelease(systemSleepAssertionID);
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);
1590 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1591 CFRelease(reasonForActivity);
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);
1597 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1600 if (success == kIOReturnSuccess)
1601 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1603 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1605 [[self mainMenu] setPause];
1606 [o_mainwindow setPause];
1608 [o_mainmenu setSubmenusEnabled: FALSE];
1609 [[self mainMenu] setPlay];
1610 [o_mainwindow setPlay];
1612 /* allow the system to sleep again */
1613 if (systemSleepAssertionID > 0) {
1614 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1615 IOPMAssertionRelease(systemSleepAssertionID);
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];
1623 if (i_control_itunes > 0) {
1624 if (o_itunes_play_timer) {
1625 [o_itunes_play_timer invalidate];
1627 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1629 selector: @selector(resumeItunesPlayback:)
1636 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1637 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1640 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1642 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1645 deliverImmediately:YES];
1648 - (void)playbackModeUpdated
1650 playlist_t * p_playlist = pl_Get(VLCIntf);
1652 bool loop = var_GetBool(p_playlist, "loop");
1653 bool repeat = var_GetBool(p_playlist, "repeat");
1655 [[o_mainwindow controlsBar] setRepeatOne];
1656 [o_mainmenu setRepeatOne];
1658 [[o_mainwindow controlsBar] setRepeatAll];
1659 [o_mainmenu setRepeatAll];
1661 [[o_mainwindow controlsBar] setRepeatOff];
1662 [o_mainmenu setRepeatOff];
1665 [[o_mainwindow controlsBar] setShuffle];
1666 [o_mainmenu setShuffle];
1670 #pragma mark Window updater
1672 - (void)setActiveVideoPlayback:(BOOL)b_value
1674 assert([NSThread isMainThread]);
1676 b_active_videoplayback = b_value;
1678 [o_mainwindow setVideoplayEnabled];
1681 // update sleep blockers
1682 [self playbackStatusUpdated];
1686 #pragma mark Other objects getters
1693 - (VLCMainWindow *)mainWindow
1695 return o_mainwindow;
1706 o_bookmarks = [[VLCBookmarks alloc] init];
1708 if (!nib_bookmarks_loaded)
1709 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1716 if (!nib_open_loaded)
1717 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1722 - (id)simplePreferences
1725 o_sprefs = [[VLCSimplePrefs alloc] init];
1727 if (!nib_prefs_loaded)
1728 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1736 o_prefs = [[VLCPrefs alloc] init];
1738 if (!nib_prefs_loaded)
1739 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1752 o_info = [[VLCInfo alloc] init];
1754 if (! nib_info_loaded)
1755 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1763 o_wizard = [[VLCWizard alloc] init];
1765 if (!nib_wizard_loaded) {
1766 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1767 [o_wizard initStrings];
1773 - (id)coreDialogProvider
1775 if (!nib_coredialogs_loaded) {
1776 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
1779 return o_coredialogs;
1782 - (id)eyeTVController
1787 - (id)appleRemoteController
1792 - (BOOL)activeVideoPlayback
1794 return b_active_videoplayback;
1798 #pragma mark Remove old prefs
1801 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1802 static const int kCurrentPreferencesVersion = 3;
1806 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCurrentPreferencesVersion]
1807 forKey:kVLCPreferencesVersion];
1809 [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
1812 - (void)resetAndReinitializeUserDefaults
1814 // note that [NSUserDefaults resetStandardUserDefaults] will NOT correctly reset to the defaults
1816 NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
1817 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
1819 // set correct version to avoid question about outdated config
1820 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1821 [[NSUserDefaults standardUserDefaults] synchronize];
1824 - (void)removeOldPreferences
1826 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1827 int version = [defaults integerForKey:kVLCPreferencesVersion];
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.
1834 [defaults setInteger:version forKey:kVLCPreferencesVersion];
1835 if (version >= kCurrentPreferencesVersion)
1839 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1840 [defaults synchronize];
1842 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
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];
1852 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1853 NSUserDomainMask, YES);
1854 if (!libraries || [libraries count] == 0) return;
1855 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
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];
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];
1869 /* Move the file to trash one by one. Using above array the method would stop after first file
1871 for (NSString *file in ourPreferences) {
1872 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:@"" files:[NSArray arrayWithObject:file] tag:nil];
1875 [self resetAndReinitializeUserDefaults];
1879 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1881 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1885 execl(path, path, NULL);
1889 #pragma mark Playlist toggling
1891 - (void)updateTogglePlaylistState
1893 [[self playlist] outlineViewSelectionDidChange: NULL];
1900 @implementation VLCMain (Internal)
1902 - (void)resetMediaKeyJump
1904 b_mediakeyJustJumped = NO;
1907 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1909 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1910 if (b_mediaKeySupport && !o_mediaKeyController)
1911 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1913 if (b_mediaKeySupport && ([[[[VLCMain sharedInstance] playlist] model] hasChildren] ||
1915 if (!b_mediaKeyTrapEnabled) {
1916 b_mediaKeyTrapEnabled = YES;
1917 msg_Dbg(p_intf, "Enable media key support");
1918 [o_mediaKeyController startWatchingMediaKeys];
1921 if (b_mediaKeyTrapEnabled) {
1922 b_mediaKeyTrapEnabled = NO;
1923 msg_Dbg(p_intf, "Disable media key support");
1924 [o_mediaKeyController stopWatchingMediaKeys];
1931 /*****************************************************************************
1932 * VLCApplication interface
1933 *****************************************************************************/
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
1943 [self activateIgnoringOtherApps:YES];