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"
70 #import <Sparkle/Sparkle.h> /* we're the update delegate */
75 /*****************************************************************************
77 *****************************************************************************/
78 static void Run (intf_thread_t *p_intf);
80 static void updateProgressPanel (void *, const char *, float);
81 static bool checkProgressPanel (void *);
82 static void destroyProgressPanel (void *);
84 static int InputEvent(vlc_object_t *, const char *,
85 vlc_value_t, vlc_value_t, void *);
86 static int PLItemChanged(vlc_object_t *, const char *,
87 vlc_value_t, vlc_value_t, void *);
88 static int PLItemUpdated(vlc_object_t *, const char *,
89 vlc_value_t, vlc_value_t, void *);
91 static int PlaybackModeUpdated(vlc_object_t *, const char *,
92 vlc_value_t, vlc_value_t, void *);
93 static int VolumeUpdated(vlc_object_t *, const char *,
94 vlc_value_t, vlc_value_t, void *);
95 static int BossCallback(vlc_object_t *, const char *,
96 vlc_value_t, vlc_value_t, void *);
99 #pragma mark VLC Interface Object Callbacks
101 /*****************************************************************************
102 * OpenIntf: initialize interface
103 *****************************************************************************/
104 int OpenIntf (vlc_object_t *p_this)
106 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
107 [VLCApplication sharedApplication];
109 intf_thread_t *p_intf = (intf_thread_t*) p_this;
116 static NSLock * o_vout_provider_lock = nil;
118 static int WindowControl(vout_window_t *, int i_query, va_list);
120 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
122 if (cfg->type != VOUT_WINDOW_TYPE_INVALID
123 && cfg->type != VOUT_WINDOW_TYPE_NSOBJECT)
126 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
127 intf_thread_t *p_intf = VLCIntf;
129 msg_Err(p_wnd, "Mac OS X interface not found");
133 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
135 [o_vout_provider_lock lock];
136 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
137 if (!o_vout_controller) {
138 [o_vout_provider_lock unlock];
143 SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
144 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
145 [inv setTarget:o_vout_controller];
146 [inv setSelector:sel];
147 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
148 [inv setArgument:&proposedVideoViewPosition atIndex:3];
150 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
153 VLCVoutView *videoView = nil;
154 [inv getReturnValue:&videoView];
156 // this method is not supposed to fail
157 assert(videoView != nil);
159 msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
160 p_wnd->handle.nsobject = videoView;
162 [o_vout_provider_lock unlock];
164 p_wnd->type = VOUT_WINDOW_TYPE_NSOBJECT;
165 p_wnd->control = WindowControl;
171 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
173 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
175 [o_vout_provider_lock lock];
176 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
177 if (!o_vout_controller) {
178 [o_vout_provider_lock unlock];
184 case VOUT_WINDOW_SET_STATE:
186 unsigned i_state = va_arg(args, unsigned);
188 if (i_state & VOUT_WINDOW_STATE_BELOW)
190 msg_Dbg(p_wnd, "Ignore change to VOUT_WINDOW_STATE_BELOW");
194 NSInteger i_cooca_level = NSNormalWindowLevel;
195 if (i_state & VOUT_WINDOW_STATE_ABOVE)
196 i_cooca_level = NSStatusWindowLevel;
198 SEL sel = @selector(setWindowLevel:forWindow:);
199 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
200 [inv setTarget:o_vout_controller];
201 [inv setSelector:sel];
202 [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
203 [inv setArgument:&p_wnd atIndex:3];
204 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
209 case VOUT_WINDOW_SET_SIZE:
211 unsigned int i_width = va_arg(args, unsigned int);
212 unsigned int i_height = va_arg(args, unsigned int);
214 NSSize newSize = NSMakeSize(i_width, i_height);
215 SEL sel = @selector(setNativeVideoSize:forWindow:);
216 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
217 [inv setTarget:o_vout_controller];
218 [inv setSelector:sel];
219 [inv setArgument:&newSize atIndex:2]; // starting at 2!
220 [inv setArgument:&p_wnd atIndex:3];
221 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
226 case VOUT_WINDOW_SET_FULLSCREEN:
228 if (var_InheritBool(VLCIntf, "video-wallpaper")) {
229 msg_Dbg(p_wnd, "Ignore fullscreen event as video-wallpaper is on");
233 int i_full = va_arg(args, int);
234 BOOL b_animation = YES;
236 SEL sel = @selector(setFullscreen:forWindow:withAnimation:);
237 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
238 [inv setTarget:o_vout_controller];
239 [inv setSelector:sel];
240 [inv setArgument:&i_full atIndex:2]; // starting at 2!
241 [inv setArgument:&p_wnd atIndex:3];
242 [inv setArgument:&b_animation atIndex:4];
243 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
250 msg_Warn(p_wnd, "unsupported control query");
251 [o_vout_provider_lock unlock];
258 [o_vout_provider_lock unlock];
263 void WindowClose(vout_window_t *p_wnd)
265 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
267 [o_vout_provider_lock lock];
268 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
269 if (!o_vout_controller) {
270 [o_vout_provider_lock unlock];
275 [o_vout_controller performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
276 [o_vout_provider_lock unlock];
281 /* Used to abort the app.exec() on OSX after libvlc_Quit is called */
282 #include "../../../lib/libvlc_internal.h" /* libvlc_SetExitHandler */
284 static void QuitVLC( void *obj )
286 [[VLCApplication sharedApplication] performSelectorOnMainThread:@selector(terminate:) withObject:nil waitUntilDone:NO];
289 /*****************************************************************************
291 *****************************************************************************/
292 static NSLock * o_appLock = nil; // controls access to f_appExit
294 static void Run(intf_thread_t *p_intf)
296 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
297 [VLCApplication sharedApplication];
299 o_appLock = [[NSLock alloc] init];
300 o_vout_provider_lock = [[NSLock alloc] init];
302 libvlc_SetExitHandler(p_intf->p_libvlc, QuitVLC, p_intf);
304 [[VLCMain sharedInstance] setIntf: p_intf];
306 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
309 msg_Dbg(p_intf, "Run loop has been stopped");
310 [[VLCMain sharedInstance] applicationWillTerminate:nil];
312 [o_vout_provider_lock release];
313 o_vout_provider_lock = nil;
320 #pragma mark Variables Callback
322 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
323 vlc_value_t oldval, vlc_value_t new_val, void *param)
325 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
326 switch (new_val.i_int) {
327 case INPUT_EVENT_STATE:
328 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
330 case INPUT_EVENT_RATE:
331 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
333 case INPUT_EVENT_POSITION:
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
336 case INPUT_EVENT_TITLE:
337 case INPUT_EVENT_CHAPTER:
338 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
340 case INPUT_EVENT_CACHE:
341 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
343 case INPUT_EVENT_STATISTICS:
344 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
348 case INPUT_EVENT_TELETEXT:
350 case INPUT_EVENT_AOUT:
352 case INPUT_EVENT_VOUT:
354 case INPUT_EVENT_ITEM_META:
355 case INPUT_EVENT_ITEM_INFO:
356 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
357 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
358 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMetaAndInfo) withObject: nil waitUntilDone:NO];
360 case INPUT_EVENT_BOOKMARK:
362 case INPUT_EVENT_RECORD:
363 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
365 case INPUT_EVENT_PROGRAM:
366 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
368 case INPUT_EVENT_ITEM_EPG:
370 case INPUT_EVENT_SIGNAL:
373 case INPUT_EVENT_ITEM_NAME:
374 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
377 case INPUT_EVENT_AUDIO_DELAY:
378 case INPUT_EVENT_SUBTITLE_DELAY:
379 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
382 case INPUT_EVENT_DEAD:
383 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
384 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
395 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
396 vlc_value_t oldval, vlc_value_t new_val, void *param)
398 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
400 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
407 * Callback for item-change variable. Is triggered after update of duration or metadata.
409 static int PLItemUpdated(vlc_object_t *p_this, const char *psz_var,
410 vlc_value_t oldval, vlc_value_t new_val, void *param)
412 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
414 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(plItemUpdated) withObject:nil waitUntilDone:NO];
420 static int PLItemAppended(vlc_object_t *p_this, const char *psz_var,
421 vlc_value_t oldval, vlc_value_t new_val, void *param)
423 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
425 playlist_add_t *p_add = new_val.p_address;
426 NSArray *o_val = [NSArray arrayWithObjects:[NSNumber numberWithInt:p_add->i_node], [NSNumber numberWithInt:p_add->i_item], nil];
427 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(plItemAppended:) withObject:o_val waitUntilDone:NO];
433 static int PLItemRemoved(vlc_object_t *p_this, const char *psz_var,
434 vlc_value_t oldval, vlc_value_t new_val, void *param)
436 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
438 NSNumber *o_val = [NSNumber numberWithInt:new_val.i_int];
439 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(plItemRemoved:) withObject:o_val waitUntilDone:NO];
445 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
446 vlc_value_t oldval, vlc_value_t new_val, void *param)
448 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
449 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
455 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
456 vlc_value_t oldval, vlc_value_t new_val, void *param)
458 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
459 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
465 static int BossCallback(vlc_object_t *p_this, const char *psz_var,
466 vlc_value_t oldval, vlc_value_t new_val, void *param)
468 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
470 [[VLCCoreInteraction sharedInstance] performSelectorOnMainThread:@selector(pause) withObject:nil waitUntilDone:NO];
471 [[VLCApplication sharedApplication] hide:nil];
477 /*****************************************************************************
478 * ShowController: Callback triggered by the show-intf playlist variable
479 * through the ShowIntf-control-intf, to let us show the controller-win;
480 * usually when in fullscreen-mode
481 *****************************************************************************/
482 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
483 vlc_value_t old_val, vlc_value_t new_val, void *param)
485 intf_thread_t * p_intf = VLCIntf;
487 playlist_t * p_playlist = pl_Get(p_intf);
488 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
490 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
491 else if (!strcmp(psz_variable, "intf-show"))
492 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
498 /*****************************************************************************
499 * DialogCallback: Callback triggered by the "dialog-*" variables
500 * to let the intf display error and interaction dialogs
501 *****************************************************************************/
502 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
504 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
506 if ([[NSString stringWithUTF8String:type] isEqualToString: @"dialog-progress-bar"]) {
507 /* the progress panel needs to update itself and therefore wants special treatment within this context */
508 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
510 p_dialog->pf_update = updateProgressPanel;
511 p_dialog->pf_check = checkProgressPanel;
512 p_dialog->pf_destroy = destroyProgressPanel;
513 p_dialog->p_sys = VLCIntf->p_libvlc;
516 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
517 [[[VLCMain sharedInstance] coreDialogProvider] performEventWithObject: o_value ofType: type];
523 void updateProgressPanel (void *priv, const char *text, float value)
525 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
529 o_txt = [NSString stringWithUTF8String:text];
533 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
538 void destroyProgressPanel (void *priv)
540 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
542 if ([[NSApplication sharedApplication] isRunning])
543 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
548 bool checkProgressPanel (void *priv)
550 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
556 input_thread_t *getInput(void)
558 intf_thread_t *p_intf = VLCIntf;
561 return pl_CurrentInput(p_intf);
564 vout_thread_t *getVout(void)
566 input_thread_t *p_input = getInput();
569 vout_thread_t *p_vout = input_GetVout(p_input);
570 vlc_object_release(p_input);
574 vout_thread_t *getVoutForActiveWindow(void)
576 vout_thread_t *p_vout = nil;
578 id currentWindow = [NSApp keyWindow];
579 if ([currentWindow respondsToSelector:@selector(videoView)]) {
580 VLCVoutView *videoView = [currentWindow videoView];
582 p_vout = [videoView voutThread];
592 audio_output_t *getAout(void)
594 intf_thread_t *p_intf = VLCIntf;
597 return playlist_GetAout(pl_Get(p_intf));
603 @interface VLCMain () <BWQuincyManagerDelegate>
604 - (void)removeOldPreferences;
607 @interface VLCMain (Internal)
608 - (void)resetMediaKeyJump;
609 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
612 /*****************************************************************************
613 * VLCMain implementation
614 *****************************************************************************/
615 @implementation VLCMain
617 @synthesize voutController=o_vout_controller;
618 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
621 #pragma mark Initialization
623 static VLCMain *_o_sharedMainInstance = nil;
625 + (VLCMain *)sharedInstance
627 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
632 if (_o_sharedMainInstance) {
634 return _o_sharedMainInstance;
636 _o_sharedMainInstance = [super init];
639 p_current_input = NULL;
641 o_open = [[VLCOpen alloc] init];
642 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
643 o_mainmenu = [[VLCMainMenu alloc] init];
644 o_coreinteraction = [[VLCCoreInteraction alloc] init];
645 o_eyetv = [[VLCEyeTVController alloc] init];
647 /* announce our launch to a potential eyetv plugin */
648 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
649 object: @"VLCEyeTVSupport"
651 deliverImmediately: YES];
653 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
654 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
655 [defaults registerDefaults:appDefaults];
657 o_vout_controller = [[VLCVoutWindowController alloc] init];
659 informInputChangedQueue = dispatch_queue_create("org.videolan.vlc.inputChangedQueue", DISPATCH_QUEUE_SERIAL);
661 return _o_sharedMainInstance;
664 - (void)setIntf: (intf_thread_t *)p_mainintf
669 - (intf_thread_t *)intf
676 playlist_t *p_playlist;
678 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
680 /* Check if we already did this once. Opening the other nibs calls it too,
681 because VLCMain is the owner */
685 p_playlist = pl_Get(p_intf);
687 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
688 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
689 var_AddCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
690 var_AddCallback(p_playlist, "item-change", PLItemUpdated, self);
691 var_AddCallback(p_playlist, "input-current", PLItemChanged, self);
692 var_AddCallback(p_playlist, "playlist-item-append", PLItemAppended, self);
693 var_AddCallback(p_playlist, "playlist-item-deleted", PLItemRemoved, self);
694 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
695 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
696 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
697 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
698 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
700 if (!OSX_SNOW_LEOPARD) {
701 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
702 var_SetBool(p_playlist, "fullscreen", YES);
705 /* load our Shared Dialogs nib */
706 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
708 /* subscribe to various interactive dialogues */
709 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
710 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
711 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
712 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
713 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
714 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
715 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
716 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
717 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
718 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
719 dialog_Register(p_intf);
721 /* init Apple Remote support */
722 o_remote = [[AppleRemote alloc] init];
723 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
724 [o_remote setDelegate: _o_sharedMainInstance];
726 /* yeah, we are done */
727 b_nativeFullscreenMode = NO;
728 #ifdef MAC_OS_X_VERSION_10_7
729 if (!OSX_SNOW_LEOPARD)
730 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
733 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
734 /* After day 354 of the year, the usual VLC cone is replaced by another cone
735 * wearing a Father Xmas hat.
736 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
738 NSCalendar *gregorian =
739 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
740 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
743 if (dayOfYear >= 354)
744 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
747 nib_main_loaded = TRUE;
750 - (void)applicationWillFinishLaunching:(NSNotification *)aNotification
752 playlist_t * p_playlist = pl_Get(VLCIntf);
754 items_at_launch = p_playlist->p_local_category->i_children;
757 [NSBundle loadNibNamed:@"MainWindow" owner: self];
758 [o_mainwindow makeKeyAndOrderFront:nil];
760 [[SUUpdater sharedUpdater] setDelegate:self];
763 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
770 NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey: @"CFBundleVersion"];
771 NSRange endRande = [appVersion rangeOfString:@"-"];
772 if (endRande.location != NSNotFound)
773 appVersion = [appVersion substringToIndex:endRande.location];
775 BWQuincyManager *quincyManager = [BWQuincyManager sharedQuincyManager];
776 [quincyManager setApplicationVersion:appVersion];
777 [quincyManager setSubmissionURL:@"http://crash.videolan.org/crash_v200.php"];
778 [quincyManager setDelegate:self];
779 [quincyManager setCompanyName:@"VideoLAN"];
781 [self updateCurrentlyUsedHotkeys];
783 /* init media key support */
784 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
785 if (b_mediaKeySupport) {
786 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
787 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
788 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
791 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
793 [self removeOldPreferences];
795 /* Handle sleep notification */
796 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
797 name:NSWorkspaceWillSleepNotification object:nil];
799 /* update the main window */
800 [o_mainwindow updateWindow];
801 [o_mainwindow updateTimeSlider];
802 [o_mainwindow updateVolumeSlider];
804 // respect playlist-autostart
805 // note that PLAYLIST_PLAY will not stop any playback if already started
806 playlist_t * p_playlist = pl_Get(VLCIntf);
808 BOOL kidsAround = p_playlist->p_local_category->i_children != 0;
809 if (kidsAround && var_GetBool(p_playlist, "playlist-autostart"))
810 playlist_Control(p_playlist, PLAYLIST_PLAY, true);
814 /* don't allow a double termination call. If the user has
815 * already invoked the quit then simply return this time. */
816 static bool f_appExit = false;
819 #pragma mark Termination
821 - (BOOL)isTerminating
826 - (void)applicationWillTerminate:(NSNotification *)notification
831 isTerminating = f_appExit;
838 [self resumeItunesPlayback:nil];
840 if (notification == nil)
841 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
843 playlist_t * p_playlist = pl_Get(p_intf);
845 /* save current video and audio profiles */
846 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
847 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
849 /* Save some interface state in configuration, at module quit */
850 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
851 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
852 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
854 msg_Dbg(p_intf, "Terminating");
856 /* unsubscribe from the interactive dialogues */
857 dialog_Unregister(p_intf);
858 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
859 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
860 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
861 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
862 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
863 var_DelCallback(p_playlist, "item-change", PLItemUpdated, self);
864 var_DelCallback(p_playlist, "input-current", PLItemChanged, self);
865 var_DelCallback(p_playlist, "playlist-item-append", PLItemAppended, self);
866 var_DelCallback(p_playlist, "playlist-item-deleted", PLItemRemoved, self);
867 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
868 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
869 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
870 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
871 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
872 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
873 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
874 var_DelCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
876 if (p_current_input) {
877 /* continue playback where you left off */
878 [[self playlist] storePlaybackPositionForItem:p_current_input];
880 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
881 vlc_object_release(p_current_input);
882 p_current_input = NULL;
885 /* remove global observer watching for vout device changes correctly */
886 [[NSNotificationCenter defaultCenter] removeObserver: self];
888 [o_vout_provider_lock lock];
889 // release before o_info!
890 // closes all open vouts
891 [o_vout_controller release];
892 o_vout_controller = nil;
893 [o_vout_provider_lock unlock];
895 /* release some other objects here, because it isn't sure whether dealloc
896 * will be called later on */
912 [o_bookmarks release];
914 [o_coredialogs release];
918 /* unsubscribe from libvlc's debug messages */
919 vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
921 [o_usedHotkeys release];
922 o_usedHotkeys = NULL;
924 [o_mediaKeyController release];
926 /* write cached user defaults to disk */
927 [[NSUserDefaults standardUserDefaults] synchronize];
929 [o_mainmenu release];
930 [o_coreinteraction release];
938 #pragma mark Sparkle delegate
939 /* received directly before the update gets installed, so let's shut down a bit */
940 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
942 [NSApp activateIgnoringOtherApps:YES];
943 [o_remote stopListening: self];
944 [[VLCCoreInteraction sharedInstance] stop];
947 /* don't be enthusiastic about an update if we currently play a video */
948 - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle
950 if ([self activeVideoPlayback])
957 #pragma mark Media Key support
959 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
961 if (b_mediaKeySupport) {
962 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
964 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
965 int keyFlags = ([event data1] & 0x0000FFFF);
966 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
967 int keyRepeat = (keyFlags & 0x1);
969 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
970 [[VLCCoreInteraction sharedInstance] playOrPause];
972 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
973 if (keyState == 0 && keyRepeat == 0)
974 [[VLCCoreInteraction sharedInstance] next];
975 else if (keyRepeat == 1) {
976 [[VLCCoreInteraction sharedInstance] forwardShort];
977 b_mediakeyJustJumped = YES;
978 [self performSelector:@selector(resetMediaKeyJump)
984 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
985 if (keyState == 0 && keyRepeat == 0)
986 [[VLCCoreInteraction sharedInstance] previous];
987 else if (keyRepeat == 1) {
988 [[VLCCoreInteraction sharedInstance] backwardShort];
989 b_mediakeyJustJumped = YES;
990 [self performSelector:@selector(resetMediaKeyJump)
999 #pragma mark Other notification
1001 /* Listen to the remote in exclusive mode, only when VLC is the active
1003 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1007 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
1008 [o_remote startListening: self];
1010 - (void)applicationDidResignActive:(NSNotification *)aNotification
1014 [o_remote stopListening: self];
1017 /* Triggered when the computer goes to sleep */
1018 - (void)computerWillSleep: (NSNotification *)notification
1020 [[VLCCoreInteraction sharedInstance] pause];
1024 #pragma mark File opening over dock icon
1026 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
1028 // Only add items here which are getting dropped to to the application icon
1029 // or are given at startup. If a file is passed via command line, libvlccore
1030 // will add the item, but cocoa also calls this function. In this case, the
1031 // invocation is ignored here.
1032 if (launched == NO) {
1033 if (items_at_launch) {
1034 int items = [o_names count];
1035 if (items > items_at_launch)
1036 items_at_launch = 0;
1038 items_at_launch -= items;
1043 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], NULL);
1045 // try to add file as subtitle
1046 if ([o_names count] == 1 && psz_uri) {
1047 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1049 int i_result = input_AddSubtitleOSD(p_input, [[o_names objectAtIndex:0] UTF8String], true, true);
1050 vlc_object_release(p_input);
1051 if (i_result == VLC_SUCCESS) {
1059 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1060 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1061 for (NSUInteger i = 0; i < [o_sorted_names count]; i++) {
1062 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex:i] UTF8String], "file");
1066 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1068 [o_result addObject: o_dic];
1071 [[[VLCMain sharedInstance] playlist] addPlaylistItems:o_result];
1074 /* When user click in the Dock icon our double click in the finder */
1075 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1077 if (!hasVisibleWindows)
1078 [o_mainwindow makeKeyAndOrderFront:self];
1084 #pragma mark Apple Remote Control
1086 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1087 increase/decrease as long as the user holds the left/right, plus/minus button */
1088 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1090 if (b_remote_button_hold) {
1091 switch([buttonIdentifierNumber intValue]) {
1092 case kRemoteButtonRight_Hold:
1093 [[VLCCoreInteraction sharedInstance] forward];
1095 case kRemoteButtonLeft_Hold:
1096 [[VLCCoreInteraction sharedInstance] backward];
1098 case kRemoteButtonVolume_Plus_Hold:
1100 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1102 case kRemoteButtonVolume_Minus_Hold:
1104 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1107 if (b_remote_button_hold) {
1109 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1110 withObject:buttonIdentifierNumber
1116 /* Apple Remote callback */
1117 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1118 pressedDown: (BOOL) pressedDown
1119 clickCount: (unsigned int) count
1121 switch(buttonIdentifier) {
1122 case k2009RemoteButtonFullscreen:
1123 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1125 case k2009RemoteButtonPlay:
1126 [[VLCCoreInteraction sharedInstance] playOrPause];
1128 case kRemoteButtonPlay:
1130 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1132 [[VLCCoreInteraction sharedInstance] playOrPause];
1134 case kRemoteButtonVolume_Plus:
1135 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1136 [NSSound increaseSystemVolume];
1139 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1141 case kRemoteButtonVolume_Minus:
1142 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1143 [NSSound decreaseSystemVolume];
1146 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1148 case kRemoteButtonRight:
1149 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1150 [[VLCCoreInteraction sharedInstance] forward];
1152 [[VLCCoreInteraction sharedInstance] next];
1154 case kRemoteButtonLeft:
1155 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1156 [[VLCCoreInteraction sharedInstance] backward];
1158 [[VLCCoreInteraction sharedInstance] previous];
1160 case kRemoteButtonRight_Hold:
1161 case kRemoteButtonLeft_Hold:
1162 case kRemoteButtonVolume_Plus_Hold:
1163 case kRemoteButtonVolume_Minus_Hold:
1164 /* simulate an event as long as the user holds the button */
1165 b_remote_button_hold = pressedDown;
1167 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt:buttonIdentifier];
1168 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1169 withObject:buttonIdentifierNumber];
1172 case kRemoteButtonMenu:
1173 [o_controls showPosition: self]; //FIXME
1175 case kRemoteButtonPlay_Sleep:
1177 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1178 [script executeAndReturnError:nil];
1183 /* Add here whatever you want other buttons to do */
1189 #pragma mark Key Shortcuts
1191 /*****************************************************************************
1192 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1193 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1194 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1195 *****************************************************************************/
1196 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1200 unsigned int i_pressed_modifiers = 0;
1203 i_pressed_modifiers = [o_event modifierFlags];
1205 if (i_pressed_modifiers & NSControlKeyMask)
1206 val.i_int |= KEY_MODIFIER_CTRL;
1208 if (i_pressed_modifiers & NSAlternateKeyMask)
1209 val.i_int |= KEY_MODIFIER_ALT;
1211 if (i_pressed_modifiers & NSShiftKeyMask)
1212 val.i_int |= KEY_MODIFIER_SHIFT;
1214 if (i_pressed_modifiers & NSCommandKeyMask)
1215 val.i_int |= KEY_MODIFIER_COMMAND;
1217 NSString * characters = [o_event charactersIgnoringModifiers];
1218 if ([characters length] > 0) {
1219 key = [[characters lowercaseString] characterAtIndex: 0];
1221 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1222 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1223 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1229 case NSDeleteCharacter:
1230 case NSDeleteFunctionKey:
1231 case NSDeleteCharFunctionKey:
1232 case NSBackspaceCharacter:
1233 case NSUpArrowFunctionKey:
1234 case NSDownArrowFunctionKey:
1235 case NSEnterCharacter:
1236 case NSCarriageReturnCharacter:
1241 val.i_int |= CocoaKeyToVLC(key);
1243 BOOL b_found_key = NO;
1244 for (NSUInteger i = 0; i < [o_usedHotkeys count]; i++) {
1245 NSString *str = [o_usedHotkeys objectAtIndex:i];
1246 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1248 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1249 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1250 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1251 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1252 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1259 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1267 - (void)updateCurrentlyUsedHotkeys
1269 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1270 /* Get the main Module */
1271 module_t *p_main = module_get_main();
1274 module_config_t *p_config;
1276 p_config = module_config_get (p_main, &confsize);
1278 for (size_t i = 0; i < confsize; i++) {
1279 module_config_t *p_item = p_config + i;
1281 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1282 && !strncmp(p_item->psz_name , "key-", 4)
1283 && !EMPTY_STR(p_item->psz_text)) {
1284 if (p_item->value.psz)
1285 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1288 module_config_free (p_config);
1291 [o_usedHotkeys release];
1292 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1293 [o_tempArray release];
1297 #pragma mark Interface updaters
1299 - (void)plItemAppended:(NSArray *)o_val
1301 int i_node = [[o_val objectAtIndex:0] intValue];
1302 int i_item = [[o_val objectAtIndex:1] intValue];
1304 [[[self playlist] model] addItem:i_item withParentNode:i_node];
1306 // update badge in sidebar
1307 [o_mainwindow updateWindow];
1309 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1314 - (void)plItemRemoved:(NSNumber *)o_val
1316 int i_item = [o_val intValue];
1318 [[[self playlist] model] removeItem:i_item];
1319 [[self playlist] deletionCompleted];
1321 // update badge in sidebar
1322 [o_mainwindow updateWindow];
1324 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1329 // This must be called on main thread
1330 - (void)PlaylistItemChanged
1332 input_thread_t *p_input_changed = NULL;
1334 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1335 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1336 vlc_object_release(p_current_input);
1337 p_current_input = NULL;
1339 [o_mainmenu setRateControlsEnabled: NO];
1341 [[NSNotificationCenter defaultCenter] postNotificationName:VLCInputChangedNotification
1344 else if (!p_current_input) {
1345 // object is hold here and released then it is dead
1346 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1347 if (p_current_input) {
1348 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1349 [self playbackStatusUpdated];
1350 [o_mainmenu setRateControlsEnabled: YES];
1352 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden]) {
1353 [o_mainwindow changePlaylistState: psPlaylistItemChangedEvent];
1356 p_input_changed = vlc_object_hold(p_current_input);
1358 [[self playlist] currentlyPlayingItemChanged];
1360 [[self playlist] continuePlaybackWhereYouLeftOff:p_current_input];
1362 [[NSNotificationCenter defaultCenter] postNotificationName:VLCInputChangedNotification
1367 [self updateMetaAndInfo];
1369 [o_mainwindow updateWindow];
1370 [self updateDelays];
1371 [self updateMainMenu];
1374 * Due to constraints within NSAttributedString's main loop runtime handling
1375 * and other issues, we need to inform the extension manager on a separate thread.
1376 * The serial queue ensures that changed inputs are propagated in the same order as they arrive.
1378 dispatch_async(informInputChangedQueue, ^{
1379 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1380 if (p_input_changed)
1381 vlc_object_release(p_input_changed);
1385 - (void)plItemUpdated
1387 [o_mainwindow updateName];
1390 [o_info updateMetadata];
1393 - (void)updateMainMenu
1395 [o_mainmenu setupMenus];
1396 [o_mainmenu updatePlaybackRate];
1397 [[VLCCoreInteraction sharedInstance] resetAtoB];
1400 - (void)updateMainWindow
1402 [o_mainwindow updateWindow];
1405 - (void)showMainWindow
1407 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1410 - (void)showFullscreenController
1412 // defer selector here (possibly another time) to ensure that keyWindow is set properly
1413 // (needed for NSApplicationDidBecomeActiveNotification)
1414 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1417 - (void)updateDelays
1419 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1424 [o_mainwindow updateName];
1427 - (void)updatePlaybackPosition
1429 [o_mainwindow updateTimeSlider];
1430 [[VLCCoreInteraction sharedInstance] updateAtoB];
1433 - (void)updateVolume
1435 [o_mainwindow updateVolumeSlider];
1438 - (void)updateRecordState: (BOOL)b_value
1440 [o_mainmenu updateRecordState:b_value];
1443 - (void)updateMetaAndInfo
1445 if (!p_current_input) {
1446 [[self info] updatePanelWithItem:nil];
1450 input_item_t *p_input_item = input_GetItem(p_current_input);
1452 [[[self playlist] model] updateItem:p_input_item];
1453 [[self info] updatePanelWithItem:p_input_item];
1456 - (void)resumeItunesPlayback:(id)sender
1458 if (var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1459 if (b_has_itunes_paused) {
1460 iTunesApplication *iTunesApp = (iTunesApplication *) [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1461 if (iTunesApp && [iTunesApp isRunning]) {
1462 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1463 msg_Dbg(p_intf, "unpausing iTunes");
1464 [iTunesApp playpause];
1469 if (b_has_spotify_paused) {
1470 SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1472 if ([spotifyApp respondsToSelector:@selector(isRunning)] && [spotifyApp respondsToSelector:@selector(playerState)]) {
1473 if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePaused) {
1474 msg_Dbg(p_intf, "unpausing Spotify");
1482 b_has_itunes_paused = NO;
1483 b_has_spotify_paused = NO;
1484 o_itunes_play_timer = nil;
1487 - (void)playbackStatusUpdated
1490 if (p_current_input) {
1491 state = var_GetInteger(p_current_input, "state");
1494 int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1495 // cancel itunes timer if next item starts playing
1496 if (state > -1 && state != END_S && i_control_itunes > 0) {
1497 if (o_itunes_play_timer) {
1498 [o_itunes_play_timer invalidate];
1499 o_itunes_play_timer = nil;
1503 if (state == PLAYING_S) {
1504 if (i_control_itunes > 0) {
1506 if (!b_has_itunes_paused) {
1507 iTunesApplication *iTunesApp = (iTunesApplication *) [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1508 if (iTunesApp && [iTunesApp isRunning]) {
1509 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1510 msg_Dbg(p_intf, "pausing iTunes");
1512 b_has_itunes_paused = YES;
1518 if (!b_has_spotify_paused) {
1519 SpotifyApplication *spotifyApp = (SpotifyApplication *) [SBApplication applicationWithBundleIdentifier:@"com.spotify.client"];
1522 if ([spotifyApp respondsToSelector:@selector(isRunning)] && [spotifyApp respondsToSelector:@selector(playerState)]) {
1523 if ([spotifyApp isRunning] && [spotifyApp playerState] == kSpotifyPlayerStatePlaying) {
1524 msg_Dbg(p_intf, "pausing Spotify");
1526 b_has_spotify_paused = YES;
1533 /* Declare user activity.
1534 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1535 Available from 10.7.3 */
1536 #ifdef MAC_OS_X_VERSION_10_7
1537 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1539 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1540 IOPMAssertionDeclareUserActivity(reasonForActivity,
1541 kIOPMUserActiveLocal,
1542 &userActivityAssertionID);
1543 CFRelease(reasonForActivity);
1547 /* prevent the system from sleeping */
1548 if (systemSleepAssertionID > 0) {
1549 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1550 IOPMAssertionRelease(systemSleepAssertionID);
1554 /* work-around a bug in 10.7.4 and 10.7.5, so check for 10.7.x < 10.7.4, 10.8 and 10.6 */
1555 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_MAVERICKS || OSX_YOSEMITE || OSX_SNOW_LEOPARD) {
1556 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1557 if ([self activeVideoPlayback])
1558 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1560 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1561 CFRelease(reasonForActivity);
1563 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1564 if ([self activeVideoPlayback])
1565 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1567 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1570 if (success == kIOReturnSuccess)
1571 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1573 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1575 [[self mainMenu] setPause];
1576 [o_mainwindow setPause];
1578 [o_mainmenu setSubmenusEnabled: FALSE];
1579 [[self mainMenu] setPlay];
1580 [o_mainwindow setPlay];
1582 /* allow the system to sleep again */
1583 if (systemSleepAssertionID > 0) {
1584 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1585 IOPMAssertionRelease(systemSleepAssertionID);
1588 if (state == END_S || state == -1) {
1589 /* continue playback where you left off */
1590 if (p_current_input)
1591 [[self playlist] storePlaybackPositionForItem:p_current_input];
1593 if (i_control_itunes > 0) {
1594 if (o_itunes_play_timer) {
1595 [o_itunes_play_timer invalidate];
1597 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1599 selector: @selector(resumeItunesPlayback:)
1606 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1607 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1610 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1612 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1615 deliverImmediately:YES];
1618 - (void)playbackModeUpdated
1620 playlist_t * p_playlist = pl_Get(VLCIntf);
1622 bool loop = var_GetBool(p_playlist, "loop");
1623 bool repeat = var_GetBool(p_playlist, "repeat");
1625 [[o_mainwindow controlsBar] setRepeatOne];
1626 [o_mainmenu setRepeatOne];
1628 [[o_mainwindow controlsBar] setRepeatAll];
1629 [o_mainmenu setRepeatAll];
1631 [[o_mainwindow controlsBar] setRepeatOff];
1632 [o_mainmenu setRepeatOff];
1635 [[o_mainwindow controlsBar] setShuffle];
1636 [o_mainmenu setShuffle];
1640 #pragma mark Window updater
1642 - (void)setActiveVideoPlayback:(BOOL)b_value
1644 assert([NSThread isMainThread]);
1646 b_active_videoplayback = b_value;
1648 [o_mainwindow setVideoplayEnabled];
1651 // update sleep blockers
1652 [self playbackStatusUpdated];
1656 #pragma mark Other objects getters
1663 - (VLCMainWindow *)mainWindow
1665 return o_mainwindow;
1676 o_bookmarks = [[VLCBookmarks alloc] init];
1678 if (!nib_bookmarks_loaded)
1679 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1686 if (!nib_open_loaded)
1687 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1692 - (id)simplePreferences
1695 o_sprefs = [[VLCSimplePrefs alloc] init];
1697 if (!nib_prefs_loaded)
1698 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1706 o_prefs = [[VLCPrefs alloc] init];
1708 if (!nib_prefs_loaded)
1709 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1722 o_info = [[VLCInfo alloc] init];
1724 if (! nib_info_loaded)
1725 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1733 o_wizard = [[VLCWizard alloc] init];
1735 if (!nib_wizard_loaded) {
1736 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1737 [o_wizard initStrings];
1743 - (id)coreDialogProvider
1745 if (!nib_coredialogs_loaded) {
1746 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
1749 return o_coredialogs;
1752 - (id)eyeTVController
1757 - (id)appleRemoteController
1762 - (BOOL)activeVideoPlayback
1764 return b_active_videoplayback;
1768 #pragma mark Remove old prefs
1771 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1772 static const int kCurrentPreferencesVersion = 3;
1776 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCurrentPreferencesVersion]
1777 forKey:kVLCPreferencesVersion];
1779 [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
1782 - (void)resetAndReinitializeUserDefaults
1784 // note that [NSUserDefaults resetStandardUserDefaults] will NOT correctly reset to the defaults
1786 NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
1787 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
1789 // set correct version to avoid question about outdated config
1790 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1791 [[NSUserDefaults standardUserDefaults] synchronize];
1794 - (void)removeOldPreferences
1796 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1797 int version = [defaults integerForKey:kVLCPreferencesVersion];
1800 * Store version explicitely in file, for ease of debugging.
1801 * Otherwise, the value will be just defined at app startup,
1802 * as initialized above.
1804 [defaults setInteger:version forKey:kVLCPreferencesVersion];
1805 if (version >= kCurrentPreferencesVersion)
1809 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1810 [defaults synchronize];
1812 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1815 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1816 } else if (version == 2) {
1817 /* version 2 (used by VLC 2.0.x and early versions of 2.1) can lead to exceptions within 2.1 or later
1818 * so we reset the OS X specific prefs here - in practice, no user will notice */
1819 [self resetAndReinitializeUserDefaults];
1822 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1823 NSUserDomainMask, YES);
1824 if (!libraries || [libraries count] == 0) return;
1825 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1827 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1828 _NS("We just found an older version of VLC's preferences files."),
1829 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1830 if (res != NSOKButton) {
1831 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1835 // Do NOT add the current plist file here as this would conflict with caching.
1836 // Instead, just reset below.
1837 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc", @"VLC", nil];
1839 /* Move the file to trash one by one. Using above array the method would stop after first file
1841 for (NSString *file in ourPreferences) {
1842 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:@"" files:[NSArray arrayWithObject:file] tag:nil];
1845 [self resetAndReinitializeUserDefaults];
1849 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1851 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1855 execl(path, path, NULL);
1859 #pragma mark Playlist toggling
1861 - (void)updateTogglePlaylistState
1863 [[self playlist] outlineViewSelectionDidChange: NULL];
1870 @implementation VLCMain (Internal)
1872 - (void)resetMediaKeyJump
1874 b_mediakeyJustJumped = NO;
1877 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1879 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1880 if (b_mediaKeySupport && !o_mediaKeyController)
1881 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1883 if (b_mediaKeySupport && ([[[[VLCMain sharedInstance] playlist] model] hasChildren] ||
1885 if (!b_mediaKeyTrapEnabled) {
1886 b_mediaKeyTrapEnabled = YES;
1887 msg_Dbg(p_intf, "Enable media key support");
1888 [o_mediaKeyController startWatchingMediaKeys];
1891 if (b_mediaKeyTrapEnabled) {
1892 b_mediaKeyTrapEnabled = NO;
1893 msg_Dbg(p_intf, "Disable media key support");
1894 [o_mediaKeyController stopWatchingMediaKeys];
1901 /*****************************************************************************
1902 * VLCApplication interface
1903 *****************************************************************************/
1905 @implementation VLCApplication
1906 // when user selects the quit menu from dock it sends a terminate:
1907 // but we need to send a stop: to properly exits libvlc.
1908 // However, we are not able to change the action-method sent by this standard menu item.
1909 // thus we override terminate: to send a stop:
1910 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1911 - (void)terminate:(id)sender
1913 [self activateIgnoringOtherApps:YES];