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 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot 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"
68 #import "VideoEffects.h"
69 #import "AudioEffects.h"
71 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
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 void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap);
87 static int InputEvent(vlc_object_t *, const char *,
88 vlc_value_t, vlc_value_t, void *);
89 static int PLItemChanged(vlc_object_t *, const char *,
90 vlc_value_t, vlc_value_t, void *);
91 static int PlaylistUpdated(vlc_object_t *, const char *,
92 vlc_value_t, vlc_value_t, void *);
93 static int PlaybackModeUpdated(vlc_object_t *, const char *,
94 vlc_value_t, vlc_value_t, void *);
95 static int VolumeUpdated(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));
117 /* subscribe to LibVLCCore's messages */
118 vlc_LogSet(p_this->p_libvlc, MsgCallback, NULL);
126 /*****************************************************************************
127 * CloseIntf: destroy interface
128 *****************************************************************************/
129 void CloseIntf (vlc_object_t *p_this)
131 intf_thread_t *p_intf = (intf_thread_t*) p_this;
136 static int WindowControl(vout_window_t *, int i_query, va_list);
138 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
140 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
141 intf_thread_t *p_intf = VLCIntf;
143 msg_Err(p_wnd, "Mac OS X interface not found");
146 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
148 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
149 SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
150 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
151 [inv setTarget:o_vout_controller];
152 [inv setSelector:sel];
153 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
154 [inv setArgument:&proposedVideoViewPosition atIndex:3];
156 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
159 VLCVoutView *videoView = nil;
160 [inv getReturnValue:&videoView];
163 msg_Err(p_wnd, "got no video view from the interface");
168 msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
169 p_wnd->handle.nsobject = videoView;
172 // TODO: find a cleaner way for "start in fullscreen"
173 if (var_GetBool(pl_Get(VLCIntf), "fullscreen")) {
176 SEL sel = @selector(setFullscreen:forWindow:);
177 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
178 [inv setTarget:[[VLCMain sharedInstance] voutController]];
179 [inv setSelector:sel];
180 [inv setArgument:&i_full atIndex:2];
181 [inv setArgument:&p_wnd atIndex:3];
182 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
186 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
187 p_wnd->control = WindowControl;
193 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
196 case VOUT_WINDOW_SET_STATE:
198 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
199 unsigned i_state = va_arg(args, unsigned);
201 NSInteger i_cooca_level = NSNormalWindowLevel;
202 if (i_state & VOUT_WINDOW_STATE_ABOVE)
203 i_cooca_level = NSStatusWindowLevel;
205 SEL sel = @selector(setWindowLevel:forWindow:);
206 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
207 [inv setTarget:[[VLCMain sharedInstance] voutController]];
208 [inv setSelector:sel];
209 [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
210 [inv setArgument:&p_wnd atIndex:3];
211 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
217 case VOUT_WINDOW_SET_SIZE:
219 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
221 unsigned int i_width = va_arg(args, unsigned int);
222 unsigned int i_height = va_arg(args, unsigned int);
224 NSSize newSize = NSMakeSize(i_width, i_height);
225 SEL sel = @selector(setNativeVideoSize:forWindow:);
226 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
227 [inv setTarget:[[VLCMain sharedInstance] voutController]];
228 [inv setSelector:sel];
229 [inv setArgument:&newSize atIndex:2]; // starting at 2!
230 [inv setArgument:&p_wnd atIndex:3];
231 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
237 case VOUT_WINDOW_SET_FULLSCREEN:
239 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
240 int i_full = va_arg(args, int);
242 SEL sel = @selector(setFullscreen:forWindow:);
243 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
244 [inv setTarget:[[VLCMain sharedInstance] voutController]];
245 [inv setSelector:sel];
246 [inv setArgument:&i_full atIndex:2]; // starting at 2!
247 [inv setArgument:&p_wnd atIndex:3];
248 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
255 msg_Warn(p_wnd, "unsupported control query");
260 void WindowClose(vout_window_t *p_wnd)
262 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
264 [[[VLCMain sharedInstance] voutController] performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
269 /*****************************************************************************
271 *****************************************************************************/
272 static NSLock * o_appLock = nil; // controls access to f_appExit
273 static NSLock * o_plItemChangedLock = nil;
275 static void Run(intf_thread_t *p_intf)
277 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
278 [VLCApplication sharedApplication];
280 o_appLock = [[NSLock alloc] init];
281 o_plItemChangedLock = [[NSLock alloc] init];
283 [[VLCMain sharedInstance] setIntf: p_intf];
284 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
287 [[VLCMain sharedInstance] applicationWillTerminate:nil];
288 [o_plItemChangedLock release];
296 #pragma mark Variables Callback
298 /*****************************************************************************
299 * MsgCallback: Callback triggered by the core once a new debug message is
300 * ready to be displayed. We store everything in a NSArray in our Cocoa part
302 *****************************************************************************/
303 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap)
305 int canc = vlc_savecancel();
308 if (vasprintf(&str, format, ap) == -1) {
309 vlc_restorecancel(canc);
313 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
314 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
317 vlc_restorecancel(canc);
321 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
322 vlc_value_t oldval, vlc_value_t new_val, void *param)
324 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
325 switch (new_val.i_int) {
326 case INPUT_EVENT_STATE:
327 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
329 case INPUT_EVENT_RATE:
330 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
332 case INPUT_EVENT_POSITION:
333 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
335 case INPUT_EVENT_TITLE:
336 case INPUT_EVENT_CHAPTER:
337 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
339 case INPUT_EVENT_CACHE:
340 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
342 case INPUT_EVENT_STATISTICS:
343 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
347 case INPUT_EVENT_TELETEXT:
349 case INPUT_EVENT_AOUT:
351 case INPUT_EVENT_VOUT:
353 case INPUT_EVENT_ITEM_META:
354 case INPUT_EVENT_ITEM_INFO:
355 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
356 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
357 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
359 case INPUT_EVENT_BOOKMARK:
361 case INPUT_EVENT_RECORD:
362 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
364 case INPUT_EVENT_PROGRAM:
365 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
367 case INPUT_EVENT_ITEM_EPG:
369 case INPUT_EVENT_SIGNAL:
372 case INPUT_EVENT_ITEM_NAME:
373 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
374 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) 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];
387 case INPUT_EVENT_ABORT:
388 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
389 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
393 //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
401 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
402 vlc_value_t oldval, vlc_value_t new_val, void *param)
404 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
406 /* Due to constraints within NSAttributedString's main loop runtime handling
407 * and other issues, we need to wait for -PlaylistItemChanged to finish and
408 * then -informInputChanged on this non-main thread. */
409 [o_plItemChangedLock lock];
410 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES];
411 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(informInputChanged) withObject:nil waitUntilDone:YES];
412 [o_plItemChangedLock unlock];
418 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
419 vlc_value_t oldval, vlc_value_t new_val, void *param)
421 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
422 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
428 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
429 vlc_value_t oldval, vlc_value_t new_val, void *param)
431 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
432 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
438 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
439 vlc_value_t oldval, vlc_value_t new_val, void *param)
441 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
442 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
448 /*****************************************************************************
449 * ShowController: Callback triggered by the show-intf playlist variable
450 * through the ShowIntf-control-intf, to let us show the controller-win;
451 * usually when in fullscreen-mode
452 *****************************************************************************/
453 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
454 vlc_value_t old_val, vlc_value_t new_val, void *param)
456 intf_thread_t * p_intf = VLCIntf;
457 if (p_intf && p_intf->p_sys) {
458 playlist_t * p_playlist = pl_Get(p_intf);
459 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
460 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
461 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
463 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
468 /*****************************************************************************
469 * DialogCallback: Callback triggered by the "dialog-*" variables
470 * to let the intf display error and interaction dialogs
471 *****************************************************************************/
472 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
474 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
475 VLCMain *interface = (VLCMain *)data;
477 if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
478 /* the progress panel needs to update itself and therefore wants special treatment within this context */
479 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
481 p_dialog->pf_update = updateProgressPanel;
482 p_dialog->pf_check = checkProgressPanel;
483 p_dialog->pf_destroy = destroyProgressPanel;
484 p_dialog->p_sys = VLCIntf->p_libvlc;
487 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
488 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
494 void updateProgressPanel (void *priv, const char *text, float value)
496 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
500 o_txt = [NSString stringWithUTF8String: text];
504 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
509 void destroyProgressPanel (void *priv)
511 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
513 if ([[NSApplication sharedApplication] isRunning])
514 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
519 bool checkProgressPanel (void *priv)
521 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
522 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
529 input_thread_t *getInput(void)
531 intf_thread_t *p_intf = VLCIntf;
534 return pl_CurrentInput(p_intf);
537 vout_thread_t *getVout(void)
539 input_thread_t *p_input = getInput();
542 vout_thread_t *p_vout = input_GetVout(p_input);
543 vlc_object_release(p_input);
547 vout_thread_t *getVoutForActiveWindow(void)
549 vout_thread_t *p_vout = nil;
551 id currentWindow = [NSApp keyWindow];
552 if ([currentWindow respondsToSelector:@selector(videoView)]) {
553 VLCVoutView *videoView = [currentWindow videoView];
555 p_vout = [videoView voutThread];
565 audio_output_t *getAout(void)
567 intf_thread_t *p_intf = VLCIntf;
570 return playlist_GetAout(pl_Get(p_intf));
576 @interface VLCMain ()
577 - (void)removeOldPreferences;
580 @interface VLCMain (Internal)
581 - (void)handlePortMessage:(NSPortMessage *)o_msg;
582 - (void)resetMediaKeyJump;
583 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
586 /*****************************************************************************
587 * VLCMain implementation
588 *****************************************************************************/
589 @implementation VLCMain
591 @synthesize voutController=o_vout_controller;
592 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
595 #pragma mark Initialization
597 static VLCMain *_o_sharedMainInstance = nil;
599 + (VLCMain *)sharedInstance
601 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
606 if (_o_sharedMainInstance) {
608 return _o_sharedMainInstance;
610 _o_sharedMainInstance = [super init];
613 p_current_input = p_input_changed = NULL;
615 o_msg_lock = [[NSLock alloc] init];
616 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
618 o_open = [[VLCOpen alloc] init];
619 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
620 o_info = [[VLCInfo alloc] init];
621 o_mainmenu = [[VLCMainMenu alloc] init];
622 o_coreinteraction = [[VLCCoreInteraction alloc] init];
623 o_eyetv = [[VLCEyeTVController alloc] init];
624 o_mainwindow = [[VLCMainWindow alloc] init];
626 /* announce our launch to a potential eyetv plugin */
627 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
628 object: @"VLCEyeTVSupport"
630 deliverImmediately: YES];
632 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
633 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
634 [defaults registerDefaults:appDefaults];
636 o_vout_controller = [[VLCVoutWindowController alloc] init];
638 return _o_sharedMainInstance;
641 - (void)setIntf: (intf_thread_t *)p_mainintf
646 - (intf_thread_t *)intf
653 playlist_t *p_playlist;
656 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
658 /* Check if we already did this once. Opening the other nibs calls it too,
659 because VLCMain is the owner */
663 [o_msgs_panel setExcludedFromWindowsMenu: YES];
664 [o_msgs_panel setDelegate: self];
666 p_playlist = pl_Get(p_intf);
670 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
671 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
672 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
673 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
674 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
675 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
676 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
677 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
678 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
679 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
680 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
681 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
683 if (!OSX_SNOW_LEOPARD) {
684 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
685 var_SetBool(p_playlist, "fullscreen", YES);
688 /* load our Core and Shared Dialogs nibs */
689 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
690 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
692 /* subscribe to various interactive dialogues */
693 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
694 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
695 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
696 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
697 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
698 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
699 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
700 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
701 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
702 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
703 dialog_Register(p_intf);
705 /* init Apple Remote support */
706 o_remote = [[AppleRemote alloc] init];
707 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
708 [o_remote setDelegate: _o_sharedMainInstance];
710 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
712 /* yeah, we are done */
713 b_nativeFullscreenMode = NO;
714 #ifdef MAC_OS_X_VERSION_10_7
715 if (!OSX_SNOW_LEOPARD)
716 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
719 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
720 /* After day 354 of the year, the usual VLC cone is replaced by another cone
721 * wearing a Father Xmas hat.
722 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
724 NSCalendar *gregorian =
725 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
726 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
729 if (dayOfYear >= 354)
730 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
735 nib_main_loaded = TRUE;
738 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
743 [self updateCurrentlyUsedHotkeys];
745 /* init media key support */
746 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
747 if (b_mediaKeySupport) {
748 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
749 [o_mediaKeyController startWatchingMediaKeys];
750 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
751 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
754 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
756 [self removeOldPreferences];
758 /* Handle sleep notification */
759 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
760 name:NSWorkspaceWillSleepNotification object:nil];
762 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
764 /* we will need this, so let's load it here so the interface appears to be more responsive */
765 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
767 /* update the main window */
768 [o_mainwindow updateWindow];
769 [o_mainwindow updateTimeSlider];
770 [o_mainwindow updateVolumeSlider];
779 [o_msgs_panel setTitle: _NS("Messages")];
780 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
781 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
783 /* crash reporter panel */
784 [o_crashrep_send_btn setTitle: _NS("Send")];
785 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
786 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
787 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
788 [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
789 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
790 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
791 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
795 #pragma mark Termination
797 - (void)applicationWillTerminate:(NSNotification *)notification
799 /* don't allow a double termination call. If the user has
800 * already invoked the quit then simply return this time. */
801 static bool f_appExit = false;
805 isTerminating = f_appExit;
812 [self resumeItunesPlayback:nil];
814 if (notification == nil)
815 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
817 playlist_t * p_playlist = pl_Get(p_intf);
818 int returnedValue = 0;
820 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
821 if (b_nativeFullscreenMode) {
822 [o_mainwindow toggleFullScreen: self];
823 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
826 /* save current video and audio profiles */
827 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
828 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
830 /* Save some interface state in configuration, at module quit */
831 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
832 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
833 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
835 msg_Dbg(p_intf, "Terminating");
837 /* unsubscribe from the interactive dialogues */
838 dialog_Unregister(p_intf);
839 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
840 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
841 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
842 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
843 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
844 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
845 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
846 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
847 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
848 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
849 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
850 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
851 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
852 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
853 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
854 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
855 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
857 if (p_current_input) {
858 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
859 vlc_object_release(p_current_input);
860 p_current_input = NULL;
863 /* remove global observer watching for vout device changes correctly */
864 [[NSNotificationCenter defaultCenter] removeObserver: self];
866 // release before o_info!
867 [o_vout_controller release];
868 o_vout_controller = nil;
870 /* release some other objects here, because it isn't sure whether dealloc
871 * will be called later on */
886 [crashLogURLConnection cancel];
887 [crashLogURLConnection release];
889 [o_coredialogs release];
892 /* unsubscribe from libvlc's debug messages */
893 vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
895 [o_msg_arr removeAllObjects];
898 [o_usedHotkeys release];
899 o_usedHotkeys = NULL;
901 [o_msg_lock release];
903 /* write cached user defaults to disk */
904 [[NSUserDefaults standardUserDefaults] synchronize];
907 [o_mainmenu release];
909 libvlc_Quit(p_intf->p_libvlc);
911 [o_mainwindow release];
918 #pragma mark Sparkle delegate
919 /* received directly before the update gets installed, so let's shut down a bit */
920 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
922 [NSApp activateIgnoringOtherApps:YES];
923 [o_remote stopListening: self];
924 [[VLCCoreInteraction sharedInstance] stop];
928 #pragma mark Media Key support
930 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
932 if (b_mediaKeySupport) {
933 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
935 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
936 int keyFlags = ([event data1] & 0x0000FFFF);
937 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
938 int keyRepeat = (keyFlags & 0x1);
940 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
941 [[VLCCoreInteraction sharedInstance] playOrPause];
943 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
944 if (keyState == 0 && keyRepeat == 0)
945 [[VLCCoreInteraction sharedInstance] next];
946 else if (keyRepeat == 1) {
947 [[VLCCoreInteraction sharedInstance] forwardShort];
948 b_mediakeyJustJumped = YES;
949 [self performSelector:@selector(resetMediaKeyJump)
955 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
956 if (keyState == 0 && keyRepeat == 0)
957 [[VLCCoreInteraction sharedInstance] previous];
958 else if (keyRepeat == 1) {
959 [[VLCCoreInteraction sharedInstance] backwardShort];
960 b_mediakeyJustJumped = YES;
961 [self performSelector:@selector(resetMediaKeyJump)
970 #pragma mark Other notification
972 /* Listen to the remote in exclusive mode, only when VLC is the active
974 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
978 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
979 [o_remote startListening: self];
981 - (void)applicationDidResignActive:(NSNotification *)aNotification
985 [o_remote stopListening: self];
988 /* Triggered when the computer goes to sleep */
989 - (void)computerWillSleep: (NSNotification *)notification
991 [[VLCCoreInteraction sharedInstance] pause];
995 #pragma mark File opening over dock icon
997 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
999 BOOL b_autoplay = config_GetInt(VLCIntf, "macosx-autoplay");
1000 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
1002 // try to add file as subtitle
1003 if ([o_names count] == 1 && psz_uri) {
1004 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1006 BOOL b_returned = NO;
1007 b_returned = input_AddSubtitle(p_input, psz_uri, true);
1008 vlc_object_release(p_input);
1017 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1018 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1019 for (int i = 0; i < [o_sorted_names count]; i++) {
1020 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file");
1024 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1026 [o_result addObject: o_dic];
1030 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
1032 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
1037 /* When user click in the Dock icon our double click in the finder */
1038 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1040 if (!hasVisibleWindows)
1041 [o_mainwindow makeKeyAndOrderFront:self];
1047 #pragma mark Apple Remote Control
1049 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1050 increase/decrease as long as the user holds the left/right, plus/minus button */
1051 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1053 if (b_remote_button_hold) {
1054 switch([buttonIdentifierNumber intValue]) {
1055 case kRemoteButtonRight_Hold:
1056 [[VLCCoreInteraction sharedInstance] forward];
1058 case kRemoteButtonLeft_Hold:
1059 [[VLCCoreInteraction sharedInstance] backward];
1061 case kRemoteButtonVolume_Plus_Hold:
1062 [[VLCCoreInteraction sharedInstance] volumeUp];
1064 case kRemoteButtonVolume_Minus_Hold:
1065 [[VLCCoreInteraction sharedInstance] volumeDown];
1068 if (b_remote_button_hold) {
1070 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1071 withObject:buttonIdentifierNumber
1077 /* Apple Remote callback */
1078 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1079 pressedDown: (BOOL) pressedDown
1080 clickCount: (unsigned int) count
1082 switch(buttonIdentifier) {
1083 case k2009RemoteButtonFullscreen:
1084 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1086 case k2009RemoteButtonPlay:
1087 [[VLCCoreInteraction sharedInstance] playOrPause];
1089 case kRemoteButtonPlay:
1091 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1093 [[VLCCoreInteraction sharedInstance] playOrPause];
1095 case kRemoteButtonVolume_Plus:
1096 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1097 [NSSound increaseSystemVolume];
1099 [[VLCCoreInteraction sharedInstance] volumeUp];
1101 case kRemoteButtonVolume_Minus:
1102 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1103 [NSSound decreaseSystemVolume];
1105 [[VLCCoreInteraction sharedInstance] volumeDown];
1107 case kRemoteButtonRight:
1108 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1109 [[VLCCoreInteraction sharedInstance] forward];
1111 [[VLCCoreInteraction sharedInstance] next];
1113 case kRemoteButtonLeft:
1114 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1115 [[VLCCoreInteraction sharedInstance] backward];
1117 [[VLCCoreInteraction sharedInstance] previous];
1119 case kRemoteButtonRight_Hold:
1120 case kRemoteButtonLeft_Hold:
1121 case kRemoteButtonVolume_Plus_Hold:
1122 case kRemoteButtonVolume_Minus_Hold:
1123 /* simulate an event as long as the user holds the button */
1124 b_remote_button_hold = pressedDown;
1126 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1127 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1128 withObject:buttonIdentifierNumber];
1131 case kRemoteButtonMenu:
1132 [o_controls showPosition: self]; //FIXME
1134 case kRemoteButtonPlay_Sleep:
1136 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1137 [script executeAndReturnError:nil];
1142 /* Add here whatever you want other buttons to do */
1148 #pragma mark Key Shortcuts
1150 /*****************************************************************************
1151 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1152 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1153 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1154 *****************************************************************************/
1155 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1159 unsigned int i_pressed_modifiers = 0;
1162 i_pressed_modifiers = [o_event modifierFlags];
1164 if (i_pressed_modifiers & NSControlKeyMask)
1165 val.i_int |= KEY_MODIFIER_CTRL;
1167 if (i_pressed_modifiers & NSAlternateKeyMask)
1168 val.i_int |= KEY_MODIFIER_ALT;
1170 if (i_pressed_modifiers & NSShiftKeyMask)
1171 val.i_int |= KEY_MODIFIER_SHIFT;
1173 if (i_pressed_modifiers & NSCommandKeyMask)
1174 val.i_int |= KEY_MODIFIER_COMMAND;
1176 NSString * characters = [o_event charactersIgnoringModifiers];
1177 if ([characters length] > 0) {
1178 key = [[characters lowercaseString] characterAtIndex: 0];
1180 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1181 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1182 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1188 case NSDeleteCharacter:
1189 case NSDeleteFunctionKey:
1190 case NSDeleteCharFunctionKey:
1191 case NSBackspaceCharacter:
1192 case NSUpArrowFunctionKey:
1193 case NSDownArrowFunctionKey:
1194 case NSEnterCharacter:
1195 case NSCarriageReturnCharacter:
1200 if (key == 0x0020) { // space key
1201 [[VLCCoreInteraction sharedInstance] playOrPause];
1205 val.i_int |= CocoaKeyToVLC(key);
1207 BOOL b_found_key = NO;
1208 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1209 NSString *str = [o_usedHotkeys objectAtIndex: i];
1210 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1212 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1213 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1214 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1215 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1216 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1223 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1231 - (void)updateCurrentlyUsedHotkeys
1233 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1234 /* Get the main Module */
1235 module_t *p_main = module_get_main();
1238 module_config_t *p_config;
1240 p_config = module_config_get (p_main, &confsize);
1242 for (size_t i = 0; i < confsize; i++) {
1243 module_config_t *p_item = p_config + i;
1245 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1246 && !strncmp(p_item->psz_name , "key-", 4)
1247 && !EMPTY_STR(p_item->psz_text)) {
1248 if (p_item->value.psz)
1249 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1252 module_config_free (p_config);
1255 [o_usedHotkeys release];
1256 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1257 [o_tempArray release];
1261 #pragma mark Interface updaters
1263 - (void)PlaylistItemChanged
1265 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1266 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1267 p_input_changed = p_current_input;
1268 p_current_input = NULL;
1270 [o_mainmenu setRateControlsEnabled: NO];
1272 else if (!p_current_input) {
1273 // object is hold here and released then it is dead
1274 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1275 if (p_current_input) {
1276 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1277 [self playbackStatusUpdated];
1278 [o_mainmenu setRateControlsEnabled: YES];
1279 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1280 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1281 p_input_changed = vlc_object_hold(p_current_input);
1285 [o_playlist updateRowSelection];
1286 [o_mainwindow updateWindow];
1287 [self updateDelays];
1288 [self updateMainMenu];
1291 - (void)informInputChanged
1293 if (p_input_changed) {
1294 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1295 vlc_object_release(p_input_changed);
1296 p_input_changed = NULL;
1300 - (void)updateMainMenu
1302 [o_mainmenu setupMenus];
1303 [o_mainmenu updatePlaybackRate];
1304 [[VLCCoreInteraction sharedInstance] resetAtoB];
1307 - (void)updateMainWindow
1309 [o_mainwindow updateWindow];
1312 - (void)showMainWindow
1314 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1317 - (void)showFullscreenController
1319 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1322 - (void)updateDelays
1324 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1329 [o_mainwindow updateName];
1332 - (void)updatePlaybackPosition
1334 [o_mainwindow updateTimeSlider];
1335 [[VLCCoreInteraction sharedInstance] updateAtoB];
1338 - (void)updateVolume
1340 [o_mainwindow updateVolumeSlider];
1343 - (void)playlistUpdated
1345 [self playbackStatusUpdated];
1346 [o_playlist playlistUpdated];
1347 [o_mainwindow updateWindow];
1348 [o_mainwindow updateName];
1351 - (void)updateRecordState: (BOOL)b_value
1353 [o_mainmenu updateRecordState:b_value];
1356 - (void)updateInfoandMetaPanel
1358 [o_playlist outlineViewSelectionDidChange:nil];
1361 - (void)resumeItunesPlayback:(id)sender
1363 if (b_has_itunes_paused && var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1364 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1365 if (iTunesApp && [iTunesApp isRunning]) {
1366 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1367 msg_Dbg(p_intf, "Unpause iTunes...");
1368 [iTunesApp playpause];
1374 b_has_itunes_paused = NO;
1375 o_itunes_play_timer = nil;
1378 - (void)playbackStatusUpdated
1381 if (p_current_input) {
1382 state = var_GetInteger(p_current_input, "state");
1385 int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1386 // cancel itunes timer if next item starts playing
1387 if (state > -1 && state != END_S && i_control_itunes > 0) {
1388 if (o_itunes_play_timer) {
1389 [o_itunes_play_timer invalidate];
1390 o_itunes_play_timer = nil;
1394 if (state == PLAYING_S) {
1396 if (i_control_itunes > 0 && !b_has_itunes_paused) {
1397 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1398 if (iTunesApp && [iTunesApp isRunning]) {
1399 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1400 msg_Dbg(p_intf, "Pause iTunes...");
1402 b_has_itunes_paused = YES;
1408 /* Declare user activity.
1409 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1410 Available from 10.7.3 */
1411 #ifdef MAC_OS_X_VERSION_10_7
1412 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1414 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1415 IOPMAssertionDeclareUserActivity(reasonForActivity,
1416 kIOPMUserActiveLocal,
1417 &userActivityAssertionID);
1418 CFRelease(reasonForActivity);
1422 /* prevent the system from sleeping */
1423 if (systemSleepAssertionID > 0) {
1424 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1425 IOPMAssertionRelease(systemSleepAssertionID);
1429 /* 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 */
1430 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1431 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1432 if ([self activeVideoPlayback])
1433 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1435 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1436 CFRelease(reasonForActivity);
1438 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1439 if ([self activeVideoPlayback])
1440 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1442 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1445 if (success == kIOReturnSuccess)
1446 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1448 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1450 [[self mainMenu] setPause];
1451 [o_mainwindow setPause];
1453 [o_mainmenu setSubmenusEnabled: FALSE];
1454 [[self mainMenu] setPlay];
1455 [o_mainwindow setPlay];
1457 /* allow the system to sleep again */
1458 if (systemSleepAssertionID > 0) {
1459 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1460 IOPMAssertionRelease(systemSleepAssertionID);
1463 if (state == END_S || state == -1) {
1464 if (i_control_itunes > 0) {
1465 if (o_itunes_play_timer) {
1466 [o_itunes_play_timer invalidate];
1468 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1470 selector: @selector(resumeItunesPlayback:)
1477 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1478 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1481 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1483 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1486 deliverImmediately:YES];
1489 - (void)playbackModeUpdated
1491 vlc_value_t looping,repeating;
1492 playlist_t * p_playlist = pl_Get(VLCIntf);
1494 bool loop = var_GetBool(p_playlist, "loop");
1495 bool repeat = var_GetBool(p_playlist, "repeat");
1497 [[o_mainwindow controlsBar] setRepeatOne];
1498 [o_mainmenu setRepeatOne];
1500 [[o_mainwindow controlsBar] setRepeatAll];
1501 [o_mainmenu setRepeatAll];
1503 [[o_mainwindow controlsBar] setRepeatOff];
1504 [o_mainmenu setRepeatOff];
1507 [[o_mainwindow controlsBar] setShuffle];
1508 [o_mainmenu setShuffle];
1513 #pragma mark Window updater
1517 - (void)setActiveVideoPlayback:(BOOL)b_value
1519 b_active_videoplayback = b_value;
1521 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1522 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1525 // update sleep blockers
1526 [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1530 #pragma mark Other objects getters
1537 - (VLCMainWindow *)mainWindow
1539 return o_mainwindow;
1553 o_bookmarks = [[VLCBookmarks alloc] init];
1555 if (!nib_bookmarks_loaded)
1556 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1566 if (!nib_open_loaded)
1567 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1572 - (id)simplePreferences
1575 o_sprefs = [[VLCSimplePrefs alloc] init];
1577 if (!nib_prefs_loaded)
1578 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1586 o_prefs = [[VLCPrefs alloc] init];
1588 if (!nib_prefs_loaded)
1589 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1604 if (! nib_info_loaded)
1605 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1616 o_wizard = [[VLCWizard alloc] init];
1618 if (!nib_wizard_loaded) {
1619 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1620 [o_wizard initStrings];
1625 - (id)coreDialogProvider
1628 return o_coredialogs;
1633 - (id)eyeTVController
1641 - (id)appleRemoteController
1646 - (BOOL)activeVideoPlayback
1648 return b_active_videoplayback;
1652 #pragma mark Crash Log
1653 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1655 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1656 NSURL *url = [NSURL URLWithString:urlStr];
1658 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1659 [req setHTTPMethod:@"POST"];
1662 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1663 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1664 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1665 email = [emails valueAtIndex:[emails indexForIdentifier:
1666 [emails primaryIdentifier]]];
1669 email = [NSString string];
1672 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1673 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1674 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1675 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1677 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1679 /* Released from delegate */
1680 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1683 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1685 msg_Dbg(p_intf, "crash report successfully sent");
1686 [crashLogURLConnection release];
1687 crashLogURLConnection = nil;
1690 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1692 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1693 [crashLogURLConnection release];
1694 crashLogURLConnection = nil;
1697 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1699 NSString * crashReporter;
1700 if (OSX_MOUNTAIN_LION)
1701 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1703 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1704 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1706 NSString * latestLog = nil;
1707 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1708 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1709 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1710 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1711 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1713 while (fname = [direnum nextObject]) {
1714 [direnum skipDescendents];
1715 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1716 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1717 if ([compo count] < 3)
1719 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1720 if ([compo count] < 4)
1724 if (year < [[compo objectAtIndex:0] intValue] ||
1725 (year ==[[compo objectAtIndex:0] intValue] &&
1726 (month < [[compo objectAtIndex:1] intValue] ||
1727 (month ==[[compo objectAtIndex:1] intValue] &&
1728 (day < [[compo objectAtIndex:2] intValue] ||
1729 (day ==[[compo objectAtIndex:2] intValue] &&
1730 hours < [[compo objectAtIndex:3] intValue])))))) {
1731 year = [[compo objectAtIndex:0] intValue];
1732 month = [[compo objectAtIndex:1] intValue];
1733 day = [[compo objectAtIndex:2] intValue];
1734 hours = [[compo objectAtIndex:3] intValue];
1735 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1740 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1743 if (!previouslySeen) {
1744 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1745 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1746 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1747 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1752 - (NSString *)latestCrashLogPath
1754 return [self latestCrashLogPathPreviouslySeen:YES];
1757 - (void)lookForCrashLog
1759 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1760 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1761 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1762 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1763 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1764 if (latestLog && !areCrashLogsTooOld) {
1765 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1766 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1767 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1768 [NSApp runModalForWindow: o_crashrep_win];
1769 // bail out, the user doesn't want us to send reports
1775 - (IBAction)crashReporterAction:(id)sender
1777 if (sender == o_crashrep_send_btn) {
1778 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1779 if ([o_crashrep_dontaskagain_ckb state])
1780 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1782 if ([o_crashrep_dontaskagain_ckb state])
1783 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1787 [o_crashrep_win orderOut: sender];
1790 - (IBAction)openCrashLog:(id)sender
1792 NSString * latestLog = [self latestCrashLogPath];
1794 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1796 NSBeginInformationalAlertSheet(_NS("No CrashLog found"), _NS("Continue"), nil, nil, o_msgs_panel, self, NULL, NULL, nil, @"%@", _NS("Couldn't find any trace of a previous crash."));
1801 #pragma mark Remove old prefs
1803 - (void)removeOldPreferences
1805 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1806 static const int kCurrentPreferencesVersion = 2;
1807 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1808 int version = [defaults integerForKey:kVLCPreferencesVersion];
1809 if (version >= kCurrentPreferencesVersion)
1813 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1814 [defaults synchronize];
1816 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1819 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1821 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1822 NSUserDomainMask, YES);
1823 if (!libraries || [libraries count] == 0) return;
1824 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1826 /* File not found, don't attempt anything */
1827 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1828 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1829 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1833 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1834 _NS("We just found an older version of VLC's preferences files."),
1835 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1836 if (res != NSOKButton) {
1837 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1841 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1843 /* Move the file to trash so that user can find them later */
1844 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1846 /* really reset the defaults from now on */
1847 [NSUserDefaults resetStandardUserDefaults];
1849 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1850 [defaults synchronize];
1854 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1856 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1861 execl(path, path, NULL);
1865 #pragma mark Errors, warnings and messages
1866 - (IBAction)updateMessagesPanel:(id)sender
1868 [self windowDidBecomeKey:nil];
1871 - (IBAction)showMessagesPanel:(id)sender
1873 [o_msgs_panel makeKeyAndOrderFront: sender];
1876 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1878 [o_msgs_table reloadData];
1879 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1882 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1884 if (aTableView == o_msgs_table)
1885 return [o_msg_arr count];
1889 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1891 NSMutableAttributedString *result = NULL;
1894 if (rowIndex < [o_msg_arr count])
1895 result = [o_msg_arr objectAtIndex: rowIndex];
1896 [o_msg_lock unlock];
1904 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1907 NSColor *o_white = [NSColor whiteColor];
1908 NSColor *o_red = [NSColor redColor];
1909 NSColor *o_yellow = [NSColor yellowColor];
1910 NSColor *o_gray = [NSColor grayColor];
1911 NSString * firstString, * secondString;
1913 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1914 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1916 NSDictionary *o_attr;
1917 NSMutableAttributedString *o_msg_color;
1921 if ([o_msg_arr count] > 600) {
1922 [o_msg_arr removeObjectAtIndex: 0];
1923 [o_msg_arr removeObjectAtIndex: 1];
1925 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1926 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1928 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1929 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1930 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1931 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1932 [o_msg_arr addObject: [o_msg_color autorelease]];
1934 b_msg_arr_changed = YES;
1935 [o_msg_lock unlock];
1939 - (IBAction)saveDebugLog:(id)sender
1941 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1943 [saveFolderPanel setCanSelectHiddenExtension: NO];
1944 [saveFolderPanel setCanCreateDirectories: YES];
1945 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1946 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1947 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1948 if (returnCode == NSOKButton) {
1949 NSUInteger count = [o_msg_arr count];
1950 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1951 for (NSUInteger i = 0; i < count; i++)
1952 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1954 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1955 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1957 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1958 msg_Warn(p_intf, "Error while saving the debug log");
1963 [saveFolderPanel release];
1967 #pragma mark Playlist toggling
1969 - (void)updateTogglePlaylistState
1971 [[self playlist] outlineViewSelectionDidChange: NULL];
1978 @implementation VLCMain (Internal)
1980 - (void)handlePortMessage:(NSPortMessage *)o_msg
1985 NSInvocation * o_inv;
1986 NSConditionLock * o_lock;
1988 o_data = [[o_msg components] lastObject];
1989 o_inv = *((NSInvocation **)[o_data bytes]);
1990 [o_inv getArgument: &o_value atIndex: 2];
1991 val = (id **)[o_value pointerValue];
1992 [o_inv setArgument: val[1] atIndex: 2];
1997 [o_lock unlockWithCondition: 1];
2000 - (void)resetMediaKeyJump
2002 b_mediakeyJustJumped = NO;
2005 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2007 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
2008 if (b_mediaKeySupport) {
2009 if (!o_mediaKeyController)
2010 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2011 [o_mediaKeyController startWatchingMediaKeys];
2013 else if (!b_mediaKeySupport && o_mediaKeyController)
2014 [o_mediaKeyController stopWatchingMediaKeys];
2019 /*****************************************************************************
2020 * VLCApplication interface
2021 *****************************************************************************/
2023 @implementation VLCApplication
2024 // when user selects the quit menu from dock it sends a terminate:
2025 // but we need to send a stop: to properly exits libvlc.
2026 // However, we are not able to change the action-method sent by this standard menu item.
2027 // thus we override terminate: to send a stop:
2028 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2029 - (void)terminate:(id)sender
2031 [self activateIgnoringOtherApps:YES];