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() */
36 #include <sys/param.h> /* for MAXPATHLEN */
38 #include <vlc_common.h>
40 #include <vlc_dialog.h>
42 #include <vlc_modules.h>
43 #include <vlc_plugin.h>
44 #include <vlc_vout_display.h>
45 #include <unistd.h> /* execl() */
47 #import "CompatibilityFixes.h"
49 #import "StringUtility.h"
54 #import "playlistinfo.h"
59 #import "coredialogs.h"
60 #import "AppleRemote.h"
62 #import "simple_prefs.h"
63 #import "CoreInteraction.h"
64 #import "TrackSynchronization.h"
65 #import "VLCVoutWindowController.h"
66 #import "ExtensionsManager.h"
67 #import "CrashReporter.h"
69 #import "VideoEffects.h"
70 #import "AudioEffects.h"
72 #import <Sparkle/Sparkle.h> /* we're the update delegate */
76 /*****************************************************************************
78 *****************************************************************************/
79 static void Run (intf_thread_t *p_intf);
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 PlaylistUpdated(vlc_object_t *, const char *,
90 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;
111 p_intf->p_sys = malloc(sizeof(intf_sys_t));
112 if (p_intf->p_sys == NULL)
115 memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
123 /*****************************************************************************
124 * CloseIntf: destroy interface
125 *****************************************************************************/
126 void CloseIntf (vlc_object_t *p_this)
128 intf_thread_t *p_intf = (intf_thread_t*) p_this;
133 static NSLock * o_vout_provider_lock = nil;
135 static int WindowControl(vout_window_t *, int i_query, va_list);
137 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
139 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
140 intf_thread_t *p_intf = VLCIntf;
142 msg_Err(p_wnd, "Mac OS X interface not found");
146 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
148 [o_vout_provider_lock lock];
149 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
150 if (!o_vout_controller) {
151 [o_vout_provider_lock unlock];
156 SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
157 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
158 [inv setTarget:o_vout_controller];
159 [inv setSelector:sel];
160 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
161 [inv setArgument:&proposedVideoViewPosition atIndex:3];
163 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
166 VLCVoutView *videoView = nil;
167 [inv getReturnValue:&videoView];
170 msg_Err(p_wnd, "got no video view from the interface");
171 [o_vout_provider_lock unlock];
176 msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
177 p_wnd->handle.nsobject = videoView;
179 [o_vout_provider_lock unlock];
181 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
182 p_wnd->control = WindowControl;
188 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
190 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
192 [o_vout_provider_lock lock];
193 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
194 if (!o_vout_controller) {
195 [o_vout_provider_lock unlock];
201 case VOUT_WINDOW_SET_STATE:
203 unsigned i_state = va_arg(args, unsigned);
205 NSInteger i_cooca_level = NSNormalWindowLevel;
206 if (i_state & VOUT_WINDOW_STATE_ABOVE)
207 i_cooca_level = NSStatusWindowLevel;
209 SEL sel = @selector(setWindowLevel:forWindow:);
210 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
211 [inv setTarget:o_vout_controller];
212 [inv setSelector:sel];
213 [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
214 [inv setArgument:&p_wnd atIndex:3];
215 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
220 case VOUT_WINDOW_SET_SIZE:
223 unsigned int i_width = va_arg(args, unsigned int);
224 unsigned int i_height = va_arg(args, unsigned int);
226 NSSize newSize = NSMakeSize(i_width, i_height);
227 SEL sel = @selector(setNativeVideoSize:forWindow:);
228 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
229 [inv setTarget:o_vout_controller];
230 [inv setSelector:sel];
231 [inv setArgument:&newSize atIndex:2]; // starting at 2!
232 [inv setArgument:&p_wnd atIndex:3];
233 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
238 case VOUT_WINDOW_SET_FULLSCREEN:
240 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
241 int i_full = va_arg(args, int);
243 SEL sel = @selector(setFullscreen:forWindow:);
244 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
245 [inv setTarget:o_vout_controller];
246 [inv setSelector:sel];
247 [inv setArgument:&i_full atIndex:2]; // starting at 2!
248 [inv setArgument:&p_wnd atIndex:3];
249 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
256 msg_Warn(p_wnd, "unsupported control query");
257 [o_vout_provider_lock unlock];
263 [o_vout_provider_lock unlock];
268 void WindowClose(vout_window_t *p_wnd)
270 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
272 [o_vout_provider_lock lock];
273 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
274 if (!o_vout_controller) {
275 [o_vout_provider_lock unlock];
280 [o_vout_controller performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
281 [o_vout_provider_lock unlock];
286 /*****************************************************************************
288 *****************************************************************************/
289 static NSLock * o_appLock = nil; // controls access to f_appExit
290 static NSLock * o_plItemChangedLock = nil;
292 static void Run(intf_thread_t *p_intf)
294 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
295 [VLCApplication sharedApplication];
297 o_appLock = [[NSLock alloc] init];
298 o_plItemChangedLock = [[NSLock alloc] init];
299 o_vout_provider_lock = [[NSLock alloc] init];
301 [[VLCMain sharedInstance] setIntf: p_intf];
303 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
306 [[VLCMain sharedInstance] applicationWillTerminate:nil];
307 [o_plItemChangedLock release];
309 [o_vout_provider_lock release];
310 o_vout_provider_lock = nil;
317 #pragma mark Variables Callback
319 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
320 vlc_value_t oldval, vlc_value_t new_val, void *param)
322 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
323 switch (new_val.i_int) {
324 case INPUT_EVENT_STATE:
325 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
327 case INPUT_EVENT_RATE:
328 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
330 case INPUT_EVENT_POSITION:
331 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
333 case INPUT_EVENT_TITLE:
334 case INPUT_EVENT_CHAPTER:
335 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
337 case INPUT_EVENT_CACHE:
338 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
340 case INPUT_EVENT_STATISTICS:
341 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
345 case INPUT_EVENT_TELETEXT:
347 case INPUT_EVENT_AOUT:
349 case INPUT_EVENT_VOUT:
351 case INPUT_EVENT_ITEM_META:
352 case INPUT_EVENT_ITEM_INFO:
353 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
354 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
355 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
357 case INPUT_EVENT_BOOKMARK:
359 case INPUT_EVENT_RECORD:
360 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
362 case INPUT_EVENT_PROGRAM:
363 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
365 case INPUT_EVENT_ITEM_EPG:
367 case INPUT_EVENT_SIGNAL:
370 case INPUT_EVENT_ITEM_NAME:
371 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
372 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
375 case INPUT_EVENT_AUDIO_DELAY:
376 case INPUT_EVENT_SUBTITLE_DELAY:
377 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
380 case INPUT_EVENT_DEAD:
381 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
382 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
385 case INPUT_EVENT_ABORT:
386 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
387 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
398 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
399 vlc_value_t oldval, vlc_value_t new_val, void *param)
401 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
403 /* Due to constraints within NSAttributedString's main loop runtime handling
404 * and other issues, we need to wait for -PlaylistItemChanged to finish and
405 * then -informInputChanged on this non-main thread. */
406 [o_plItemChangedLock lock];
407 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES]; // MUST BE ON MAIN THREAD
408 [[VLCMain sharedInstance] informInputChanged]; // DO NOT MOVE TO MAIN THREAD
409 [o_plItemChangedLock unlock];
415 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
416 vlc_value_t oldval, vlc_value_t new_val, void *param)
418 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
420 /* Avoid event queue flooding with playlistUpdated selectors, leading to UI freezes.
421 * Therefore, only enqueue if no selector already enqueued.
423 VLCMain *o_main = [VLCMain sharedInstance];
424 @synchronized(o_main) {
425 if(![o_main playlistUpdatedSelectorInQueue]) {
426 [o_main setPlaylistUpdatedSelectorInQueue:YES];
427 [o_main performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
435 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
436 vlc_value_t oldval, vlc_value_t new_val, void *param)
438 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
439 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
445 static int VolumeUpdated(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(updateVolume) withObject:nil waitUntilDone:NO];
455 static int BossCallback(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];
460 [[VLCCoreInteraction sharedInstance] performSelectorOnMainThread:@selector(pause) withObject:nil waitUntilDone:NO];
461 [[VLCApplication sharedApplication] hide:nil];
467 /*****************************************************************************
468 * ShowController: Callback triggered by the show-intf playlist variable
469 * through the ShowIntf-control-intf, to let us show the controller-win;
470 * usually when in fullscreen-mode
471 *****************************************************************************/
472 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
473 vlc_value_t old_val, vlc_value_t new_val, void *param)
475 intf_thread_t * p_intf = VLCIntf;
476 if (p_intf && p_intf->p_sys) {
477 playlist_t * p_playlist = pl_Get(p_intf);
478 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
479 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
480 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
482 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
487 /*****************************************************************************
488 * DialogCallback: Callback triggered by the "dialog-*" variables
489 * to let the intf display error and interaction dialogs
490 *****************************************************************************/
491 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
493 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
494 VLCMain *interface = (VLCMain *)data;
496 if ([[NSString stringWithUTF8String:type] isEqualToString: @"dialog-progress-bar"]) {
497 /* the progress panel needs to update itself and therefore wants special treatment within this context */
498 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
500 p_dialog->pf_update = updateProgressPanel;
501 p_dialog->pf_check = checkProgressPanel;
502 p_dialog->pf_destroy = destroyProgressPanel;
503 p_dialog->p_sys = VLCIntf->p_libvlc;
506 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
507 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
513 void updateProgressPanel (void *priv, const char *text, float value)
515 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
519 o_txt = [NSString stringWithUTF8String:text];
523 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
528 void destroyProgressPanel (void *priv)
530 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
532 if ([[NSApplication sharedApplication] isRunning])
533 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
538 bool checkProgressPanel (void *priv)
540 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
541 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
548 input_thread_t *getInput(void)
550 intf_thread_t *p_intf = VLCIntf;
553 return pl_CurrentInput(p_intf);
556 vout_thread_t *getVout(void)
558 input_thread_t *p_input = getInput();
561 vout_thread_t *p_vout = input_GetVout(p_input);
562 vlc_object_release(p_input);
566 vout_thread_t *getVoutForActiveWindow(void)
568 vout_thread_t *p_vout = nil;
570 id currentWindow = [NSApp keyWindow];
571 if ([currentWindow respondsToSelector:@selector(videoView)]) {
572 VLCVoutView *videoView = [currentWindow videoView];
574 p_vout = [videoView voutThread];
584 audio_output_t *getAout(void)
586 intf_thread_t *p_intf = VLCIntf;
589 return playlist_GetAout(pl_Get(p_intf));
595 @interface VLCMain () <VLCCrashReporterDelegate>
596 - (void)removeOldPreferences;
599 @interface VLCMain (Internal)
600 - (void)handlePortMessage:(NSPortMessage *)o_msg;
601 - (void)resetMediaKeyJump;
602 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
605 /*****************************************************************************
606 * VLCMain implementation
607 *****************************************************************************/
608 @implementation VLCMain
610 @synthesize voutController=o_vout_controller;
611 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
612 @synthesize playlistUpdatedSelectorInQueue=b_playlist_updated_selector_in_queue;
615 #pragma mark Initialization
617 static VLCMain *_o_sharedMainInstance = nil;
619 + (VLCMain *)sharedInstance
621 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
626 if (_o_sharedMainInstance) {
628 return _o_sharedMainInstance;
630 _o_sharedMainInstance = [super init];
633 p_current_input = p_input_changed = NULL;
635 o_open = [[VLCOpen alloc] init];
636 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
637 o_info = [[VLCInfo alloc] init];
638 o_mainmenu = [[VLCMainMenu alloc] init];
639 o_coreinteraction = [[VLCCoreInteraction alloc] init];
640 o_eyetv = [[VLCEyeTVController alloc] init];
642 /* announce our launch to a potential eyetv plugin */
643 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
644 object: @"VLCEyeTVSupport"
646 deliverImmediately: YES];
648 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
649 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
650 [defaults registerDefaults:appDefaults];
652 o_vout_controller = [[VLCVoutWindowController alloc] init];
654 return _o_sharedMainInstance;
657 - (void)setIntf: (intf_thread_t *)p_mainintf
662 - (intf_thread_t *)intf
669 playlist_t *p_playlist;
672 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
674 /* Check if we already did this once. Opening the other nibs calls it too,
675 because VLCMain is the owner */
679 p_playlist = pl_Get(p_intf);
683 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
684 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
685 var_AddCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
686 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
687 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
688 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
689 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
690 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
691 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
692 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
693 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
694 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
695 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
697 if (!OSX_SNOW_LEOPARD) {
698 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
699 var_SetBool(p_playlist, "fullscreen", YES);
702 /* load our Core and Shared Dialogs nibs */
703 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
704 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
706 /* subscribe to various interactive dialogues */
707 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
708 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
709 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
710 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
711 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
712 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
713 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
714 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
715 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
716 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
717 dialog_Register(p_intf);
719 /* init Apple Remote support */
720 o_remote = [[AppleRemote alloc] init];
721 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
722 [o_remote setDelegate: _o_sharedMainInstance];
724 /* yeah, we are done */
725 b_nativeFullscreenMode = NO;
726 #ifdef MAC_OS_X_VERSION_10_7
727 if (!OSX_SNOW_LEOPARD)
728 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
731 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
732 /* After day 354 of the year, the usual VLC cone is replaced by another cone
733 * wearing a Father Xmas hat.
734 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
736 NSCalendar *gregorian =
737 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
738 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
741 if (dayOfYear >= 354)
742 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
745 nib_main_loaded = TRUE;
748 - (void)applicationWillFinishLaunching:(NSNotification *)aNotification
750 playlist_t * p_playlist = pl_Get(VLCIntf);
752 items_at_launch = p_playlist->p_local_category->i_children;
755 [NSBundle loadNibNamed:@"MainWindow" owner: NSApp];
756 o_playlist = [[VLCPlaylist alloc] init];
757 o_mainwindow = [[VLCMainWindow alloc] init];
758 [o_mainwindow makeKeyAndOrderFront:nil];
761 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
768 [self updateCurrentlyUsedHotkeys];
770 /* init media key support */
771 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
772 if (b_mediaKeySupport) {
773 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
774 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
775 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
778 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
780 [self removeOldPreferences];
782 /* Handle sleep notification */
783 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
784 name:NSWorkspaceWillSleepNotification object:nil];
786 [self performSelector:@selector(lookForCrashLog) withObject:nil afterDelay:1.5];
788 /* we will need this, so let's load it here so the interface appears to be more responsive */
789 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
791 /* update the main window */
792 [o_mainwindow updateWindow];
793 [o_mainwindow updateTimeSlider];
794 [o_mainwindow updateVolumeSlider];
796 playlist_t * p_playlist = pl_Get(VLCIntf);
798 BOOL kidsAround = p_playlist->p_local_category->i_children;
800 if (kidsAround && var_GetBool(p_playlist, "playlist-autostart"))
801 [[self playlist] playItem:nil];
805 #pragma mark Termination
807 - (void)applicationWillTerminate:(NSNotification *)notification
809 /* don't allow a double termination call. If the user has
810 * already invoked the quit then simply return this time. */
811 static bool f_appExit = false;
815 isTerminating = f_appExit;
822 [self resumeItunesPlayback:nil];
824 if (notification == nil)
825 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
827 playlist_t * p_playlist = pl_Get(p_intf);
828 int returnedValue = 0;
830 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
831 if (b_nativeFullscreenMode && [o_mainwindow fullscreen]) {
832 [o_mainwindow toggleFullScreen: self];
833 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
836 /* save current video and audio profiles */
837 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
838 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
840 /* Save some interface state in configuration, at module quit */
841 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
842 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
843 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
845 msg_Dbg(p_intf, "Terminating");
847 /* unsubscribe from the interactive dialogues */
848 dialog_Unregister(p_intf);
849 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
850 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
851 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
852 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
853 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
854 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
855 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
856 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
857 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
858 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
859 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
860 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
861 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
862 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
863 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
864 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
865 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
866 var_DelCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
868 if (p_current_input) {
869 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
870 vlc_object_release(p_current_input);
871 p_current_input = NULL;
874 /* remove global observer watching for vout device changes correctly */
875 [[NSNotificationCenter defaultCenter] removeObserver: self];
877 [o_vout_provider_lock lock];
878 // release before o_info!
879 [o_vout_controller release];
880 o_vout_controller = nil;
881 [o_vout_provider_lock unlock];
883 /* release some other objects here, because it isn't sure whether dealloc
884 * will be called later on */
899 [o_coredialogs release];
902 /* unsubscribe from libvlc's debug messages */
903 vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
905 [o_usedHotkeys release];
906 o_usedHotkeys = NULL;
908 [o_mediaKeyController release];
910 /* write cached user defaults to disk */
911 [[NSUserDefaults standardUserDefaults] synchronize];
913 [o_mainmenu release];
915 libvlc_Quit(p_intf->p_libvlc);
917 [o_mainwindow release];
924 #pragma mark Sparkle delegate
925 /* received directly before the update gets installed, so let's shut down a bit */
926 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
928 [NSApp activateIgnoringOtherApps:YES];
929 [o_remote stopListening: self];
930 [[VLCCoreInteraction sharedInstance] stop];
934 #pragma mark Media Key support
936 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
938 if (b_mediaKeySupport) {
939 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
941 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
942 int keyFlags = ([event data1] & 0x0000FFFF);
943 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
944 int keyRepeat = (keyFlags & 0x1);
946 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
947 [[VLCCoreInteraction sharedInstance] playOrPause];
949 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
950 if (keyState == 0 && keyRepeat == 0)
951 [[VLCCoreInteraction sharedInstance] next];
952 else if (keyRepeat == 1) {
953 [[VLCCoreInteraction sharedInstance] forwardShort];
954 b_mediakeyJustJumped = YES;
955 [self performSelector:@selector(resetMediaKeyJump)
961 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
962 if (keyState == 0 && keyRepeat == 0)
963 [[VLCCoreInteraction sharedInstance] previous];
964 else if (keyRepeat == 1) {
965 [[VLCCoreInteraction sharedInstance] backwardShort];
966 b_mediakeyJustJumped = YES;
967 [self performSelector:@selector(resetMediaKeyJump)
976 #pragma mark Other notification
978 /* Listen to the remote in exclusive mode, only when VLC is the active
980 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
984 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
985 [o_remote startListening: self];
987 - (void)applicationDidResignActive:(NSNotification *)aNotification
991 [o_remote stopListening: self];
994 /* Triggered when the computer goes to sleep */
995 - (void)computerWillSleep: (NSNotification *)notification
997 [[VLCCoreInteraction sharedInstance] pause];
1001 #pragma mark File opening over dock icon
1003 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
1005 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
1007 if (launched == NO) {
1008 if (items_at_launch) {
1009 int items = [o_names count];
1010 if (items > items_at_launch)
1011 items_at_launch = 0;
1013 items_at_launch -= items;
1018 // try to add file as subtitle
1019 if ([o_names count] == 1 && psz_uri) {
1020 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1022 BOOL b_returned = NO;
1023 b_returned = input_AddSubtitle(p_input, psz_uri, true);
1024 vlc_object_release(p_input);
1033 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1034 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1035 for (int i = 0; i < [o_sorted_names count]; i++) {
1036 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex:i] UTF8String], "file");
1040 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1042 [o_result addObject: o_dic];
1045 [o_playlist appendArray: o_result atPos: -1 enqueue: !config_GetInt(VLCIntf, "macosx-autoplay")];
1050 /* When user click in the Dock icon our double click in the finder */
1051 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1053 if (!hasVisibleWindows)
1054 [o_mainwindow makeKeyAndOrderFront:self];
1060 #pragma mark Apple Remote Control
1062 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1063 increase/decrease as long as the user holds the left/right, plus/minus button */
1064 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1066 if (b_remote_button_hold) {
1067 switch([buttonIdentifierNumber intValue]) {
1068 case kRemoteButtonRight_Hold:
1069 [[VLCCoreInteraction sharedInstance] forward];
1071 case kRemoteButtonLeft_Hold:
1072 [[VLCCoreInteraction sharedInstance] backward];
1074 case kRemoteButtonVolume_Plus_Hold:
1076 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1078 case kRemoteButtonVolume_Minus_Hold:
1080 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1083 if (b_remote_button_hold) {
1085 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1086 withObject:buttonIdentifierNumber
1092 /* Apple Remote callback */
1093 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1094 pressedDown: (BOOL) pressedDown
1095 clickCount: (unsigned int) count
1097 switch(buttonIdentifier) {
1098 case k2009RemoteButtonFullscreen:
1099 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1101 case k2009RemoteButtonPlay:
1102 [[VLCCoreInteraction sharedInstance] playOrPause];
1104 case kRemoteButtonPlay:
1106 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1108 [[VLCCoreInteraction sharedInstance] playOrPause];
1110 case kRemoteButtonVolume_Plus:
1111 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1112 [NSSound increaseSystemVolume];
1115 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1117 case kRemoteButtonVolume_Minus:
1118 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1119 [NSSound decreaseSystemVolume];
1122 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1124 case kRemoteButtonRight:
1125 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1126 [[VLCCoreInteraction sharedInstance] forward];
1128 [[VLCCoreInteraction sharedInstance] next];
1130 case kRemoteButtonLeft:
1131 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1132 [[VLCCoreInteraction sharedInstance] backward];
1134 [[VLCCoreInteraction sharedInstance] previous];
1136 case kRemoteButtonRight_Hold:
1137 case kRemoteButtonLeft_Hold:
1138 case kRemoteButtonVolume_Plus_Hold:
1139 case kRemoteButtonVolume_Minus_Hold:
1140 /* simulate an event as long as the user holds the button */
1141 b_remote_button_hold = pressedDown;
1143 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt:buttonIdentifier];
1144 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1145 withObject:buttonIdentifierNumber];
1148 case kRemoteButtonMenu:
1149 [o_controls showPosition: self]; //FIXME
1151 case kRemoteButtonPlay_Sleep:
1153 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1154 [script executeAndReturnError:nil];
1159 /* Add here whatever you want other buttons to do */
1165 #pragma mark Key Shortcuts
1167 /*****************************************************************************
1168 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1169 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1170 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1171 *****************************************************************************/
1172 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1176 unsigned int i_pressed_modifiers = 0;
1179 i_pressed_modifiers = [o_event modifierFlags];
1181 if (i_pressed_modifiers & NSControlKeyMask)
1182 val.i_int |= KEY_MODIFIER_CTRL;
1184 if (i_pressed_modifiers & NSAlternateKeyMask)
1185 val.i_int |= KEY_MODIFIER_ALT;
1187 if (i_pressed_modifiers & NSShiftKeyMask)
1188 val.i_int |= KEY_MODIFIER_SHIFT;
1190 if (i_pressed_modifiers & NSCommandKeyMask)
1191 val.i_int |= KEY_MODIFIER_COMMAND;
1193 NSString * characters = [o_event charactersIgnoringModifiers];
1194 if ([characters length] > 0) {
1195 key = [[characters lowercaseString] characterAtIndex: 0];
1197 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1198 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1199 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1205 case NSDeleteCharacter:
1206 case NSDeleteFunctionKey:
1207 case NSDeleteCharFunctionKey:
1208 case NSBackspaceCharacter:
1209 case NSUpArrowFunctionKey:
1210 case NSDownArrowFunctionKey:
1211 case NSEnterCharacter:
1212 case NSCarriageReturnCharacter:
1217 val.i_int |= CocoaKeyToVLC(key);
1219 BOOL b_found_key = NO;
1220 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1221 NSString *str = [o_usedHotkeys objectAtIndex:i];
1222 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1224 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1225 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1226 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1227 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1228 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1235 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1243 - (void)updateCurrentlyUsedHotkeys
1245 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1246 /* Get the main Module */
1247 module_t *p_main = module_get_main();
1250 module_config_t *p_config;
1252 p_config = module_config_get (p_main, &confsize);
1254 for (size_t i = 0; i < confsize; i++) {
1255 module_config_t *p_item = p_config + i;
1257 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1258 && !strncmp(p_item->psz_name , "key-", 4)
1259 && !EMPTY_STR(p_item->psz_text)) {
1260 if (p_item->value.psz)
1261 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1264 module_config_free (p_config);
1267 [o_usedHotkeys release];
1268 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1269 [o_tempArray release];
1273 #pragma mark Interface updaters
1275 - (void)PlaylistItemChanged
1277 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1278 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1279 p_input_changed = p_current_input;
1280 p_current_input = NULL;
1282 [o_mainmenu setRateControlsEnabled: NO];
1284 else if (!p_current_input) {
1285 // object is hold here and released then it is dead
1286 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1287 if (p_current_input) {
1288 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1289 [self playbackStatusUpdated];
1290 [o_mainmenu setRateControlsEnabled: YES];
1292 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden]) {
1293 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: [NSNumber numberWithInt:1] waitUntilDone:NO];
1296 p_input_changed = vlc_object_hold(p_current_input);
1300 [o_playlist updateRowSelection];
1301 [o_mainwindow updateWindow];
1302 [self updateDelays];
1303 [self updateMainMenu];
1306 - (void)informInputChanged
1308 if (p_input_changed) {
1309 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1310 vlc_object_release(p_input_changed);
1311 p_input_changed = NULL;
1315 - (void)updateMainMenu
1317 [o_mainmenu setupMenus];
1318 [o_mainmenu updatePlaybackRate];
1319 [[VLCCoreInteraction sharedInstance] resetAtoB];
1322 - (void)updateMainWindow
1324 [o_mainwindow updateWindow];
1327 - (void)showMainWindow
1329 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1332 - (void)showFullscreenController
1334 // defer selector here (possibly another time) to ensure that keyWindow is set properly
1335 // (needed for NSApplicationDidBecomeActiveNotification)
1336 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1339 - (void)updateDelays
1341 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1346 [o_mainwindow updateName];
1349 - (void)updatePlaybackPosition
1351 [o_mainwindow updateTimeSlider];
1352 [[VLCCoreInteraction sharedInstance] updateAtoB];
1355 - (void)updateVolume
1357 [o_mainwindow updateVolumeSlider];
1360 - (void)playlistUpdated
1362 @synchronized(self) {
1363 b_playlist_updated_selector_in_queue = NO;
1366 [self playbackStatusUpdated];
1367 [o_playlist playlistUpdated];
1368 [o_mainwindow updateWindow];
1369 [o_mainwindow updateName];
1371 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1376 - (void)updateRecordState: (BOOL)b_value
1378 [o_mainmenu updateRecordState:b_value];
1381 - (void)updateInfoandMetaPanel
1383 [o_playlist outlineViewSelectionDidChange:nil];
1386 - (void)resumeItunesPlayback:(id)sender
1388 if (b_has_itunes_paused && var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1389 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1390 if (iTunesApp && [iTunesApp isRunning]) {
1391 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1392 msg_Dbg(p_intf, "Unpause iTunes...");
1393 [iTunesApp playpause];
1399 b_has_itunes_paused = NO;
1400 o_itunes_play_timer = nil;
1403 - (void)playbackStatusUpdated
1406 if (p_current_input) {
1407 state = var_GetInteger(p_current_input, "state");
1410 int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1411 // cancel itunes timer if next item starts playing
1412 if (state > -1 && state != END_S && i_control_itunes > 0) {
1413 if (o_itunes_play_timer) {
1414 [o_itunes_play_timer invalidate];
1415 o_itunes_play_timer = nil;
1419 if (state == PLAYING_S) {
1421 if (i_control_itunes > 0 && !b_has_itunes_paused) {
1422 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1423 if (iTunesApp && [iTunesApp isRunning]) {
1424 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1425 msg_Dbg(p_intf, "Pause iTunes...");
1427 b_has_itunes_paused = YES;
1433 /* Declare user activity.
1434 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1435 Available from 10.7.3 */
1436 #ifdef MAC_OS_X_VERSION_10_7
1437 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1439 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1440 IOPMAssertionDeclareUserActivity(reasonForActivity,
1441 kIOPMUserActiveLocal,
1442 &userActivityAssertionID);
1443 CFRelease(reasonForActivity);
1447 /* prevent the system from sleeping */
1448 if (systemSleepAssertionID > 0) {
1449 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1450 IOPMAssertionRelease(systemSleepAssertionID);
1454 /* 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 */
1455 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_MAVERICKS || OSX_SNOW_LEOPARD) {
1456 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1457 if ([self activeVideoPlayback])
1458 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1460 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1461 CFRelease(reasonForActivity);
1463 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1464 if ([self activeVideoPlayback])
1465 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1467 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1470 if (success == kIOReturnSuccess)
1471 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1473 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1475 [[self mainMenu] setPause];
1476 [o_mainwindow setPause];
1478 [o_mainmenu setSubmenusEnabled: FALSE];
1479 [[self mainMenu] setPlay];
1480 [o_mainwindow setPlay];
1482 /* allow the system to sleep again */
1483 if (systemSleepAssertionID > 0) {
1484 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1485 IOPMAssertionRelease(systemSleepAssertionID);
1488 if (state == END_S || state == -1) {
1489 if (i_control_itunes > 0) {
1490 if (o_itunes_play_timer) {
1491 [o_itunes_play_timer invalidate];
1493 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1495 selector: @selector(resumeItunesPlayback:)
1502 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1503 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1506 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1508 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1511 deliverImmediately:YES];
1514 - (void)playbackModeUpdated
1516 vlc_value_t looping,repeating;
1517 playlist_t * p_playlist = pl_Get(VLCIntf);
1519 bool loop = var_GetBool(p_playlist, "loop");
1520 bool repeat = var_GetBool(p_playlist, "repeat");
1522 [[o_mainwindow controlsBar] setRepeatOne];
1523 [o_mainmenu setRepeatOne];
1525 [[o_mainwindow controlsBar] setRepeatAll];
1526 [o_mainmenu setRepeatAll];
1528 [[o_mainwindow controlsBar] setRepeatOff];
1529 [o_mainmenu setRepeatOff];
1532 [[o_mainwindow controlsBar] setShuffle];
1533 [o_mainmenu setShuffle];
1537 #pragma mark Window updater
1539 - (void)setActiveVideoPlayback:(BOOL)b_value
1541 b_active_videoplayback = b_value;
1543 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1544 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1547 // update sleep blockers
1548 [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1552 #pragma mark Other objects getters
1559 - (VLCMainWindow *)mainWindow
1561 return o_mainwindow;
1575 o_bookmarks = [[VLCBookmarks alloc] init];
1577 if (!nib_bookmarks_loaded)
1578 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1588 if (!nib_open_loaded)
1589 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1594 - (id)simplePreferences
1597 o_sprefs = [[VLCSimplePrefs alloc] init];
1599 if (!nib_prefs_loaded)
1600 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1608 o_prefs = [[VLCPrefs alloc] init];
1610 if (!nib_prefs_loaded)
1611 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1626 if (! nib_info_loaded)
1627 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1638 o_wizard = [[VLCWizard alloc] init];
1640 if (!nib_wizard_loaded) {
1641 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1642 [o_wizard initStrings];
1647 - (id)coreDialogProvider
1650 return o_coredialogs;
1655 - (id)eyeTVController
1663 - (id)appleRemoteController
1668 - (BOOL)activeVideoPlayback
1670 return b_active_videoplayback;
1674 #pragma mark Crash Log handling
1676 - (void)lookForCrashLog
1678 VLCCrashReporter *reporter = [[VLCCrashReporter alloc] init];
1679 reporter.delegate = self;
1680 [reporter showDialogAndSendLogIfDesired];
1683 - (void)reporterFinishedAction:(VLCCrashReporter *)reporter
1689 #pragma mark Remove old prefs
1691 - (void)removeOldPreferences
1693 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1694 static const int kCurrentPreferencesVersion = 3;
1695 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1696 int version = [defaults integerForKey:kVLCPreferencesVersion];
1697 if (version >= kCurrentPreferencesVersion)
1701 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1702 [defaults synchronize];
1704 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1707 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1708 } else if (version == 2) {
1709 /* version 2 (used by VLC 2.0.x and early versions of 2.1) can lead to exceptions within 2.1 or later
1710 * so we reset the OS X specific prefs here - in practice, no user will notice */
1711 [NSUserDefaults resetStandardUserDefaults];
1713 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1714 [defaults synchronize];
1716 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1717 NSUserDomainMask, YES);
1718 if (!libraries || [libraries count] == 0) return;
1719 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1721 /* File not found, don't attempt anything */
1722 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1723 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1724 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1728 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1729 _NS("We just found an older version of VLC's preferences files."),
1730 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1731 if (res != NSOKButton) {
1732 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1736 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1738 /* Move the file to trash so that user can find them later */
1739 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1741 /* really reset the defaults from now on */
1742 [NSUserDefaults resetStandardUserDefaults];
1744 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1745 [defaults synchronize];
1749 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1751 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1756 execl(path, path, NULL);
1760 #pragma mark Playlist toggling
1762 - (void)updateTogglePlaylistState
1764 [[self playlist] outlineViewSelectionDidChange: NULL];
1771 @implementation VLCMain (Internal)
1773 - (void)handlePortMessage:(NSPortMessage *)o_msg
1778 NSInvocation * o_inv;
1779 NSConditionLock * o_lock;
1781 o_data = [[o_msg components] lastObject];
1782 o_inv = *((NSInvocation **)[o_data bytes]);
1783 [o_inv getArgument: &o_value atIndex: 2];
1784 val = (id **)[o_value pointerValue];
1785 [o_inv setArgument: val[1] atIndex: 2];
1790 [o_lock unlockWithCondition: 1];
1793 - (void)resetMediaKeyJump
1795 b_mediakeyJustJumped = NO;
1798 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1800 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1801 if (b_mediaKeySupport) {
1802 if (!o_mediaKeyController)
1803 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1805 if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot]->i_children > 0 ||
1807 [o_mediaKeyController startWatchingMediaKeys];
1809 [o_mediaKeyController stopWatchingMediaKeys];
1811 else if (!b_mediaKeySupport && o_mediaKeyController)
1812 [o_mediaKeyController stopWatchingMediaKeys];
1817 /*****************************************************************************
1818 * VLCApplication interface
1819 *****************************************************************************/
1821 @implementation VLCApplication
1822 // when user selects the quit menu from dock it sends a terminate:
1823 // but we need to send a stop: to properly exits libvlc.
1824 // However, we are not able to change the action-method sent by this standard menu item.
1825 // thus we override terminate: to send a stop:
1826 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1827 - (void)terminate:(id)sender
1829 [self activateIgnoringOtherApps:YES];