1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2012 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>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
34 #include <stdlib.h> /* malloc(), free() */
35 #include <sys/param.h> /* for MAXPATHLEN */
37 #include <vlc_common.h>
39 #include <vlc_dialog.h>
41 #include <vlc_modules.h>
42 #include <vlc_plugin.h>
43 #include <vlc_aout_intf.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"
67 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
68 #import <Sparkle/Sparkle.h> /* we're the update delegate */
70 /*****************************************************************************
72 *****************************************************************************/
73 static void Run (intf_thread_t *p_intf);
75 static void updateProgressPanel (void *, const char *, float);
76 static bool checkProgressPanel (void *);
77 static void destroyProgressPanel (void *);
79 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap);
81 static int InputEvent(vlc_object_t *, const char *,
82 vlc_value_t, vlc_value_t, void *);
83 static int PLItemChanged(vlc_object_t *, const char *,
84 vlc_value_t, vlc_value_t, void *);
85 static int PlaylistUpdated(vlc_object_t *, const char *,
86 vlc_value_t, vlc_value_t, void *);
87 static int PlaybackModeUpdated(vlc_object_t *, const char *,
88 vlc_value_t, vlc_value_t, void *);
89 static int VolumeUpdated(vlc_object_t *, const char *,
90 vlc_value_t, vlc_value_t, void *);
93 #pragma mark VLC Interface Object Callbacks
95 /*****************************************************************************
96 * OpenIntf: initialize interface
97 *****************************************************************************/
98 int OpenIntf (vlc_object_t *p_this)
100 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
101 [VLCApplication sharedApplication];
103 intf_thread_t *p_intf = (intf_thread_t*) p_this;
105 p_intf->p_sys = malloc(sizeof(intf_sys_t));
106 if (p_intf->p_sys == NULL)
109 memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
111 /* subscribe to LibVLCCore's messages */
112 vlc_Subscribe(&p_intf->p_sys->sub, MsgCallback, NULL);
120 /*****************************************************************************
121 * CloseIntf: destroy interface
122 *****************************************************************************/
123 void CloseIntf (vlc_object_t *p_this)
125 intf_thread_t *p_intf = (intf_thread_t*) p_this;
130 static int WindowControl(vout_window_t *, int i_query, va_list);
132 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
134 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
135 intf_thread_t *p_intf = VLCIntf;
137 msg_Err(p_wnd, "Mac OS X interface not found");
143 unsigned i_width = cfg->width;
144 unsigned i_height = cfg->height;
145 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height forWindow: p_wnd];
147 if (!p_wnd->handle.nsobject) {
148 msg_Err(p_wnd, "got no video view from the interface");
153 // TODO: this seems to be strange. Why not just allocating in the right size?
154 // This could avoid strange resize-animations...
155 NSSize newSize = NSMakeSize(cfg->width, cfg->height);
156 SEL sel = @selector(setNativeVideoSize:forWindow:);
157 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
158 [inv setTarget:[[VLCMain sharedInstance] voutController]];
159 [inv setSelector:sel];
160 [inv setArgument:&newSize atIndex:2]; // starting at 2!
161 [inv setArgument:&p_wnd atIndex:3];
162 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
165 // TODO: find a cleaner way for "start in fullscreen"
166 if (var_GetBool(pl_Get(VLCIntf), "fullscreen")) {
169 SEL sel = @selector(setFullscreen:forWindow:);
170 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
171 [inv setTarget:[VLCMain sharedInstance]];
172 [inv setSelector:sel];
173 [inv setArgument:&i_full atIndex:2];
174 [inv setArgument:&p_wnd atIndex:3];
175 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
179 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
180 p_wnd->control = WindowControl;
181 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
186 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
189 case VOUT_WINDOW_SET_STATE:
191 unsigned i_state = va_arg(args, unsigned);
192 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:i_state] waitUntilDone:NO];
195 case VOUT_WINDOW_SET_SIZE:
197 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
199 unsigned int i_width = va_arg(args, unsigned int);
200 unsigned int i_height = va_arg(args, unsigned int);
202 NSSize newSize = NSMakeSize(i_width, i_height);
203 SEL sel = @selector(setNativeVideoSize:forWindow:);
204 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
205 [inv setTarget:[[VLCMain sharedInstance] voutController]];
206 [inv setSelector:sel];
207 [inv setArgument:&newSize atIndex:2]; // starting at 2!
208 [inv setArgument:&p_wnd atIndex:3];
209 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
215 case VOUT_WINDOW_SET_FULLSCREEN:
217 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
218 int i_full = va_arg(args, int);
220 SEL sel = @selector(setFullscreen:forWindow:);
221 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
222 [inv setTarget:[VLCMain sharedInstance]];
223 [inv setSelector:sel];
224 [inv setArgument:&i_full atIndex:2]; // starting at 2!
225 [inv setArgument:&p_wnd atIndex:3];
226 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
230 //[[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
235 msg_Warn(p_wnd, "unsupported control query");
240 void WindowClose(vout_window_t *p_wnd)
242 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
243 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
245 [[[VLCMain sharedInstance] voutController] performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
250 /*****************************************************************************
252 *****************************************************************************/
253 static NSLock * o_appLock = nil; // controls access to f_appExit
255 static void Run(intf_thread_t *p_intf)
257 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
258 [VLCApplication sharedApplication];
260 o_appLock = [[NSLock alloc] init];
262 [[VLCMain sharedInstance] setIntf: p_intf];
263 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
266 [[VLCMain sharedInstance] applicationWillTerminate:nil];
274 #pragma mark Variables Callback
276 /*****************************************************************************
277 * MsgCallback: Callback triggered by the core once a new debug message is
278 * ready to be displayed. We store everything in a NSArray in our Cocoa part
280 *****************************************************************************/
281 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap)
283 int canc = vlc_savecancel();
286 if (vasprintf(&str, format, ap) == -1) {
287 vlc_restorecancel(canc);
291 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
292 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
295 vlc_restorecancel(canc);
299 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
300 vlc_value_t oldval, vlc_value_t new_val, void *param)
302 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
303 switch (new_val.i_int) {
304 case INPUT_EVENT_STATE:
305 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
307 case INPUT_EVENT_RATE:
308 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
310 case INPUT_EVENT_POSITION:
311 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
313 case INPUT_EVENT_TITLE:
314 case INPUT_EVENT_CHAPTER:
315 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
317 case INPUT_EVENT_CACHE:
318 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
320 case INPUT_EVENT_STATISTICS:
321 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
325 case INPUT_EVENT_TELETEXT:
327 case INPUT_EVENT_AOUT:
329 case INPUT_EVENT_VOUT:
331 case INPUT_EVENT_ITEM_META:
332 case INPUT_EVENT_ITEM_INFO:
333 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
335 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
337 case INPUT_EVENT_BOOKMARK:
339 case INPUT_EVENT_RECORD:
340 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
342 case INPUT_EVENT_PROGRAM:
343 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
345 case INPUT_EVENT_ITEM_EPG:
347 case INPUT_EVENT_SIGNAL:
350 case INPUT_EVENT_ITEM_NAME:
351 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
352 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
355 case INPUT_EVENT_AUDIO_DELAY:
356 case INPUT_EVENT_SUBTITLE_DELAY:
357 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
360 case INPUT_EVENT_DEAD:
361 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
362 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
365 case INPUT_EVENT_ABORT:
366 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
367 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
371 //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
379 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
380 vlc_value_t oldval, vlc_value_t new_val, void *param)
382 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
383 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
389 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
390 vlc_value_t oldval, vlc_value_t new_val, void *param)
392 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
393 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
399 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
400 vlc_value_t oldval, vlc_value_t new_val, void *param)
402 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
403 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
409 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
410 vlc_value_t oldval, vlc_value_t new_val, void *param)
412 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
413 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
419 /*****************************************************************************
420 * ShowController: Callback triggered by the show-intf playlist variable
421 * through the ShowIntf-control-intf, to let us show the controller-win;
422 * usually when in fullscreen-mode
423 *****************************************************************************/
424 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
425 vlc_value_t old_val, vlc_value_t new_val, void *param)
427 intf_thread_t * p_intf = VLCIntf;
428 if (p_intf && p_intf->p_sys) {
429 playlist_t * p_playlist = pl_Get(p_intf);
430 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
431 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
432 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
434 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
439 /*****************************************************************************
440 * DialogCallback: Callback triggered by the "dialog-*" variables
441 * to let the intf display error and interaction dialogs
442 *****************************************************************************/
443 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
445 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
446 VLCMain *interface = (VLCMain *)data;
448 if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
449 /* the progress panel needs to update itself and therefore wants special treatment within this context */
450 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
452 p_dialog->pf_update = updateProgressPanel;
453 p_dialog->pf_check = checkProgressPanel;
454 p_dialog->pf_destroy = destroyProgressPanel;
455 p_dialog->p_sys = VLCIntf->p_libvlc;
458 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
459 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
465 void updateProgressPanel (void *priv, const char *text, float value)
467 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
471 o_txt = [NSString stringWithUTF8String: text];
475 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
480 void destroyProgressPanel (void *priv)
482 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
483 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
487 bool checkProgressPanel (void *priv)
489 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
490 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
497 input_thread_t *getInput(void)
499 intf_thread_t *p_intf = VLCIntf;
502 return pl_CurrentInput(p_intf);
505 vout_thread_t *getVout(void)
507 input_thread_t *p_input = getInput();
510 vout_thread_t *p_vout = input_GetVout(p_input);
511 vlc_object_release(p_input);
515 vout_thread_t *getVoutForActiveWindow(void)
517 vout_thread_t *p_vout = nil;
519 id currentWindow = [NSApp keyWindow];
520 if ([currentWindow respondsToSelector:@selector(videoView)]) {
521 VLCVoutView *videoView = [currentWindow videoView];
523 p_vout = [videoView voutThread];
533 audio_output_t *getAout(void)
535 input_thread_t *p_input = getInput();
538 audio_output_t *p_aout = input_GetAout(p_input);
539 vlc_object_release(p_input);
546 @interface VLCMain ()
547 - (void)_removeOldPreferences;
550 /*****************************************************************************
551 * VLCMain implementation
552 *****************************************************************************/
553 @implementation VLCMain
555 @synthesize voutController=o_vout_controller;
556 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
559 #pragma mark Initialization
561 static VLCMain *_o_sharedMainInstance = nil;
563 + (VLCMain *)sharedInstance
565 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
570 if (_o_sharedMainInstance) {
572 return _o_sharedMainInstance;
574 _o_sharedMainInstance = [super init];
577 p_current_input = NULL;
579 o_msg_lock = [[NSLock alloc] init];
580 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
582 o_open = [[VLCOpen alloc] init];
583 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
584 o_info = [[VLCInfo alloc] init];
585 o_mainmenu = [[VLCMainMenu alloc] init];
586 o_coreinteraction = [[VLCCoreInteraction alloc] init];
587 o_eyetv = [[VLCEyeTVController alloc] init];
588 o_mainwindow = [[VLCMainWindow alloc] init];
590 /* announce our launch to a potential eyetv plugin */
591 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
592 object: @"VLCEyeTVSupport"
594 deliverImmediately: YES];
596 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
597 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
598 [defaults registerDefaults:appDefaults];
600 o_vout_controller = [[VLCVoutWindowController alloc] init];
602 return _o_sharedMainInstance;
605 - (void)setIntf: (intf_thread_t *)p_mainintf
610 - (intf_thread_t *)intf
617 playlist_t *p_playlist;
620 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
622 /* Check if we already did this once. Opening the other nibs calls it too,
623 because VLCMain is the owner */
627 [o_msgs_panel setExcludedFromWindowsMenu: YES];
628 [o_msgs_panel setDelegate: self];
630 p_playlist = pl_Get(p_intf);
634 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
635 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
636 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
637 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
638 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
639 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
640 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
641 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
642 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
643 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
644 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
645 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
646 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
648 if (!OSX_SNOW_LEOPARD) {
649 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
650 var_SetBool(p_playlist, "fullscreen", YES);
653 /* load our Core and Shared Dialogs nibs */
654 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
655 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
657 /* subscribe to various interactive dialogues */
658 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
659 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
660 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
661 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
662 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
663 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
664 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
665 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
666 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
667 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
668 dialog_Register(p_intf);
670 /* init Apple Remote support */
671 o_remote = [[AppleRemote alloc] init];
672 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
673 [o_remote setDelegate: _o_sharedMainInstance];
675 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
677 /* yeah, we are done */
678 b_nativeFullscreenMode = NO;
679 #ifdef MAC_OS_X_VERSION_10_7
680 if (!OSX_SNOW_LEOPARD)
681 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
684 /* recover stored audio device, if set
685 * in case it was unplugged in the meantime, auhal will fall back on the default */
686 int i_value = config_GetInt(p_intf, "macosx-audio-device");
688 var_SetInteger(pl_Get(VLCIntf), "audio-device", i_value);
690 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
691 /* After day 354 of the year, the usual VLC cone is replaced by another cone
692 * wearing a Father Xmas hat.
693 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
695 NSCalendar *gregorian =
696 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
697 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
700 if (dayOfYear >= 354)
701 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
706 nib_main_loaded = TRUE;
709 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
714 [self updateCurrentlyUsedHotkeys];
716 /* init media key support */
717 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
718 if (b_mediaKeySupport) {
719 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
720 [o_mediaKeyController startWatchingMediaKeys];
721 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
722 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
725 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
727 [self _removeOldPreferences];
729 /* Handle sleep notification */
730 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
731 name:NSWorkspaceWillSleepNotification object:nil];
733 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
735 /* we will need this, so let's load it here so the interface appears to be more responsive */
736 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
738 /* update the main window */
739 [o_mainwindow updateWindow];
740 [o_mainwindow updateTimeSlider];
741 [o_mainwindow updateVolumeSlider];
750 [o_msgs_panel setTitle: _NS("Messages")];
751 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
752 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
754 /* crash reporter panel */
755 [o_crashrep_send_btn setTitle: _NS("Send")];
756 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
757 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
758 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
759 [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, ...")];
760 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
761 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
762 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
766 #pragma mark Termination
768 - (void)applicationWillTerminate:(NSNotification *)notification
770 /* don't allow a double termination call. If the user has
771 * already invoked the quit then simply return this time. */
772 static bool f_appExit = false;
776 isTerminating = f_appExit;
783 if (notification == nil)
784 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
786 playlist_t * p_playlist = pl_Get(p_intf);
787 int returnedValue = 0;
789 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
790 if (b_nativeFullscreenMode) {
791 [o_mainwindow toggleFullScreen: self];
792 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
795 /* Save some interface state in configuration, at module quit */
796 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
797 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
798 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
800 msg_Dbg(p_intf, "Terminating");
802 /* unsubscribe from the interactive dialogues */
803 dialog_Unregister(p_intf);
804 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
805 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
806 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
807 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
808 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
809 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
810 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
811 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
812 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
813 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
814 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
815 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
816 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
817 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
818 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
819 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
820 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
821 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
823 if (p_current_input) {
824 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
825 vlc_object_release(p_current_input);
826 p_current_input = NULL;
829 /* remove global observer watching for vout device changes correctly */
830 [[NSNotificationCenter defaultCenter] removeObserver: self];
832 /* release some other objects here, because it isn't sure whether dealloc
833 * will be called later on */
848 [crashLogURLConnection cancel];
849 [crashLogURLConnection release];
851 [o_coredialogs release];
854 /* unsubscribe from libvlc's debug messages */
855 vlc_Unsubscribe(&p_intf->p_sys->sub);
857 [o_msg_arr removeAllObjects];
860 [o_usedHotkeys release];
861 o_usedHotkeys = NULL;
863 [o_msg_lock release];
865 /* write cached user defaults to disk */
866 [[NSUserDefaults standardUserDefaults] synchronize];
868 [o_mainmenu release];
870 [o_vout_controller release];
871 o_vout_controller = nil;
873 libvlc_Quit(p_intf->p_libvlc);
875 [o_mainwindow release];
882 #pragma mark Sparkle delegate
883 /* received directly before the update gets installed, so let's shut down a bit */
884 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
886 [NSApp activateIgnoringOtherApps:YES];
887 [o_remote stopListening: self];
888 [[VLCCoreInteraction sharedInstance] stop];
892 #pragma mark Media Key support
894 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
896 if (b_mediaKeySupport) {
897 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
899 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
900 int keyFlags = ([event data1] & 0x0000FFFF);
901 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
902 int keyRepeat = (keyFlags & 0x1);
904 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
905 [[VLCCoreInteraction sharedInstance] play];
907 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
908 if (keyState == 0 && keyRepeat == 0)
909 [[VLCCoreInteraction sharedInstance] next];
910 else if (keyRepeat == 1) {
911 [[VLCCoreInteraction sharedInstance] forwardShort];
912 b_mediakeyJustJumped = YES;
913 [self performSelector:@selector(resetMediaKeyJump)
919 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
920 if (keyState == 0 && keyRepeat == 0)
921 [[VLCCoreInteraction sharedInstance] previous];
922 else if (keyRepeat == 1) {
923 [[VLCCoreInteraction sharedInstance] backwardShort];
924 b_mediakeyJustJumped = YES;
925 [self performSelector:@selector(resetMediaKeyJump)
934 #pragma mark Other notification
936 /* Listen to the remote in exclusive mode, only when VLC is the active
938 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
942 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
943 [o_remote startListening: self];
945 - (void)applicationDidResignActive:(NSNotification *)aNotification
949 [o_remote stopListening: self];
952 /* Triggered when the computer goes to sleep */
953 - (void)computerWillSleep: (NSNotification *)notification
955 [[VLCCoreInteraction sharedInstance] pause];
959 #pragma mark File opening over dock icon
961 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
963 BOOL b_autoplay = config_GetInt(VLCIntf, "macosx-autoplay");
964 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
966 // try to add file as subtitle
967 if ([o_names count] == 1 && psz_uri) {
968 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
970 BOOL b_returned = NO;
971 b_returned = input_AddSubtitle(p_input, psz_uri, true);
972 vlc_object_release(p_input);
981 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
982 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
983 for (int i = 0; i < [o_sorted_names count]; i++) {
984 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file");
988 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
990 [o_result addObject: o_dic];
994 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
996 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
1001 /* When user click in the Dock icon our double click in the finder */
1002 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1004 if (!hasVisibleWindows)
1005 [o_mainwindow makeKeyAndOrderFront:self];
1011 #pragma mark Apple Remote Control
1013 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1014 increase/decrease as long as the user holds the left/right, plus/minus button */
1015 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1017 if (b_remote_button_hold) {
1018 switch([buttonIdentifierNumber intValue]) {
1019 case kRemoteButtonRight_Hold:
1020 [[VLCCoreInteraction sharedInstance] forward];
1022 case kRemoteButtonLeft_Hold:
1023 [[VLCCoreInteraction sharedInstance] backward];
1025 case kRemoteButtonVolume_Plus_Hold:
1027 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1029 case kRemoteButtonVolume_Minus_Hold:
1031 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1034 if (b_remote_button_hold) {
1036 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1037 withObject:buttonIdentifierNumber
1043 /* Apple Remote callback */
1044 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1045 pressedDown: (BOOL) pressedDown
1046 clickCount: (unsigned int) count
1048 switch(buttonIdentifier) {
1049 case k2009RemoteButtonFullscreen:
1050 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1052 case k2009RemoteButtonPlay:
1053 [[VLCCoreInteraction sharedInstance] play];
1055 case kRemoteButtonPlay:
1057 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1059 [[VLCCoreInteraction sharedInstance] play];
1061 case kRemoteButtonVolume_Plus:
1062 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1063 [NSSound increaseSystemVolume];
1065 [[VLCCoreInteraction sharedInstance] volumeUp];
1067 case kRemoteButtonVolume_Minus:
1068 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1069 [NSSound decreaseSystemVolume];
1071 [[VLCCoreInteraction sharedInstance] volumeDown];
1073 case kRemoteButtonRight:
1074 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1075 [[VLCCoreInteraction sharedInstance] forward];
1077 [[VLCCoreInteraction sharedInstance] next];
1079 case kRemoteButtonLeft:
1080 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1081 [[VLCCoreInteraction sharedInstance] backward];
1083 [[VLCCoreInteraction sharedInstance] previous];
1085 case kRemoteButtonRight_Hold:
1086 case kRemoteButtonLeft_Hold:
1087 case kRemoteButtonVolume_Plus_Hold:
1088 case kRemoteButtonVolume_Minus_Hold:
1089 /* simulate an event as long as the user holds the button */
1090 b_remote_button_hold = pressedDown;
1092 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1093 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1094 withObject:buttonIdentifierNumber];
1097 case kRemoteButtonMenu:
1098 [o_controls showPosition: self]; //FIXME
1100 case kRemoteButtonPlay_Sleep:
1102 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1103 [script executeAndReturnError:nil];
1108 /* Add here whatever you want other buttons to do */
1114 #pragma mark Key Shortcuts
1116 /*****************************************************************************
1117 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1118 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1119 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1120 *****************************************************************************/
1121 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1125 unsigned int i_pressed_modifiers = 0;
1128 i_pressed_modifiers = [o_event modifierFlags];
1130 if (i_pressed_modifiers & NSControlKeyMask)
1131 val.i_int |= KEY_MODIFIER_CTRL;
1133 if (i_pressed_modifiers & NSAlternateKeyMask)
1134 val.i_int |= KEY_MODIFIER_ALT;
1136 if (i_pressed_modifiers & NSShiftKeyMask)
1137 val.i_int |= KEY_MODIFIER_SHIFT;
1139 if (i_pressed_modifiers & NSCommandKeyMask)
1140 val.i_int |= KEY_MODIFIER_COMMAND;
1142 NSString * characters = [o_event charactersIgnoringModifiers];
1143 if ([characters length] > 0) {
1144 key = [[characters lowercaseString] characterAtIndex: 0];
1146 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1147 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1148 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1154 case NSDeleteCharacter:
1155 case NSDeleteFunctionKey:
1156 case NSDeleteCharFunctionKey:
1157 case NSBackspaceCharacter:
1158 case NSUpArrowFunctionKey:
1159 case NSDownArrowFunctionKey:
1160 case NSRightArrowFunctionKey:
1161 case NSLeftArrowFunctionKey:
1162 case NSEnterCharacter:
1163 case NSCarriageReturnCharacter:
1168 if (key == 0x0020) { // space key
1169 [[VLCCoreInteraction sharedInstance] play];
1173 val.i_int |= CocoaKeyToVLC(key);
1175 BOOL b_found_key = NO;
1176 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1177 NSString *str = [o_usedHotkeys objectAtIndex: i];
1178 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1180 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1181 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1182 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1183 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1184 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1191 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1199 - (void)updateCurrentlyUsedHotkeys
1201 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1202 /* Get the main Module */
1203 module_t *p_main = module_get_main();
1206 module_config_t *p_config;
1208 p_config = module_config_get (p_main, &confsize);
1210 for (size_t i = 0; i < confsize; i++) {
1211 module_config_t *p_item = p_config + i;
1213 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1214 && !strncmp(p_item->psz_name , "key-", 4)
1215 && !EMPTY_STR(p_item->psz_text)) {
1216 if (p_item->value.psz)
1217 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1220 module_config_free (p_config);
1223 [o_usedHotkeys release];
1224 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1225 [o_tempArray release];
1229 #pragma mark Interface updaters
1230 - (void)setFullscreen:(int)i_full forWindow:(vout_window_t *)p_wnd
1232 if (!p_intf || (!b_nativeFullscreenMode && !p_wnd))
1234 playlist_t * p_playlist = pl_Get(p_intf);
1235 BOOL b_fullscreen = i_full;
1237 if (!var_GetBool(p_playlist, "fullscreen") != !b_fullscreen) {
1238 var_SetBool(p_playlist, "fullscreen", b_fullscreen);
1241 if (b_nativeFullscreenMode) {
1242 // this is called twice in certain situations, so only toogle if we really need to
1243 if ((b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)) ||
1244 (!b_fullscreen && ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)))
1245 [o_mainwindow toggleFullScreen: self];
1248 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1250 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1255 input_thread_t * p_input = pl_CurrentInput(p_intf);
1256 if (p_input != NULL && [self activeVideoPlayback]) {
1257 // activate app, as method can also be triggered from outside the app (prevents nasty window layout)
1258 [NSApp activateIgnoringOtherApps:YES];
1259 [o_vout_controller updateWindow:p_wnd withSelector:@selector(enterFullscreen)];
1263 vlc_object_release(p_input);
1265 // leaving fullscreen is always allowed
1266 [o_vout_controller updateWindow:p_wnd withSelector:@selector(leaveFullscreen)];
1271 - (void)PlaylistItemChanged
1273 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1274 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1275 vlc_object_release(p_current_input);
1276 p_current_input = NULL;
1278 [o_mainmenu setRateControlsEnabled: NO];
1280 else if (!p_current_input) {
1281 // object is hold here and released then it is dead
1282 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1283 if (p_current_input) {
1284 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1285 [self playbackStatusUpdated];
1286 [o_mainmenu setRateControlsEnabled: YES];
1287 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1288 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1292 [o_playlist updateRowSelection];
1293 [o_mainwindow updateWindow];
1294 [self updateDelays];
1295 [self updateMainMenu];
1298 - (void)updateMainMenu
1300 [o_mainmenu setupMenus];
1301 [o_mainmenu updatePlaybackRate];
1304 - (void)updateMainWindow
1306 [o_mainwindow updateWindow];
1309 - (void)showMainWindow
1311 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1314 - (void)showFullscreenController
1316 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1319 - (void)updateDelays
1321 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1326 [o_mainwindow updateName];
1329 - (void)updatePlaybackPosition
1331 [o_mainwindow updateTimeSlider];
1334 - (void)updateVolume
1336 [o_mainwindow updateVolumeSlider];
1339 - (void)playlistUpdated
1341 [self playbackStatusUpdated];
1342 [o_playlist playlistUpdated];
1343 [o_mainwindow updateWindow];
1344 [o_mainwindow updateName];
1347 - (void)updateRecordState: (BOOL)b_value
1349 [o_mainmenu updateRecordState:b_value];
1352 - (void)updateInfoandMetaPanel
1354 [o_playlist outlineViewSelectionDidChange:nil];
1357 - (void)playbackStatusUpdated
1359 input_thread_t * p_input;
1361 p_input = pl_CurrentInput(p_intf);
1363 int state = var_GetInteger(p_input, "state");
1364 if (state == PLAYING_S) {
1365 /* prevent the system from sleeping */
1367 /* 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 */
1368 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1369 CFStringRef reasonForActivity= CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1370 if ([self activeVideoPlayback])
1371 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1373 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1374 CFRelease(reasonForActivity);
1376 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1377 if ([self activeVideoPlayback])
1378 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1380 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1383 if (success == kIOReturnSuccess)
1384 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1386 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1388 [[self mainMenu] setPause];
1389 [o_mainwindow setPause];
1392 [o_mainmenu setSubmenusEnabled: FALSE];
1393 [[self mainMenu] setPlay];
1394 [o_mainwindow setPlay];
1396 /* allow the system to sleep again */
1397 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1398 IOPMAssertionRelease(systemSleepAssertionID);
1400 vlc_object_release(p_input);
1403 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1404 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1407 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1409 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1412 deliverImmediately:YES];
1415 - (void)playbackModeUpdated
1417 vlc_value_t looping,repeating;
1418 playlist_t * p_playlist = pl_Get(VLCIntf);
1420 bool loop = var_GetBool(p_playlist, "loop");
1421 bool repeat = var_GetBool(p_playlist, "repeat");
1423 [[o_mainwindow controlsBar] setRepeatOne];
1424 [o_mainmenu setRepeatOne];
1426 [[o_mainwindow controlsBar] setRepeatAll];
1427 [o_mainmenu setRepeatAll];
1429 [[o_mainwindow controlsBar] setRepeatOff];
1430 [o_mainmenu setRepeatOff];
1433 [[o_mainwindow controlsBar] setShuffle];
1434 [o_mainmenu setShuffle];
1439 #pragma mark Window updater
1441 - (void)setWindowLevel:(NSNumber*)state
1443 if (var_InheritBool(p_intf, "video-wallpaper") || [[[[VLCMainWindow sharedInstance] videoView] window] level] < NSNormalWindowLevel)
1446 if ([state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE)
1447 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSStatusWindowLevel];
1449 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSNormalWindowLevel];
1452 - (void)setActiveVideoPlayback:(BOOL)b_value
1454 b_active_videoplayback = b_value;
1456 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1457 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1462 #pragma mark Other objects getters
1469 - (VLCMainWindow *)mainWindow
1471 return o_mainwindow;
1485 o_bookmarks = [[VLCBookmarks alloc] init];
1487 if (!nib_bookmarks_loaded)
1488 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1498 if (!nib_open_loaded)
1499 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1504 - (id)simplePreferences
1507 o_sprefs = [[VLCSimplePrefs alloc] init];
1509 if (!nib_prefs_loaded)
1510 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1518 o_prefs = [[VLCPrefs alloc] init];
1520 if (!nib_prefs_loaded)
1521 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1536 if (! nib_info_loaded)
1537 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1548 o_wizard = [[VLCWizard alloc] init];
1550 if (!nib_wizard_loaded) {
1551 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1552 [o_wizard initStrings];
1557 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height forWindow:(vout_window_t *)p_wnd
1559 SEL sel = @selector(setupVout:);
1560 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
1561 [inv setTarget:o_vout_controller];
1562 [inv setSelector:sel];
1563 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
1565 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
1568 VLCVoutView *videoView;
1569 [inv getReturnValue:&videoView];
1571 NSRect videoRect = [videoView frame];
1572 int i_x = (int)videoRect.origin.x;
1573 int i_y = (int)videoRect.origin.y;
1574 unsigned int i_width = (int)videoRect.size.width;
1575 unsigned int i_height = (int)videoRect.size.height;
1578 pi_width = &i_width;
1579 pi_height = &i_height;
1580 msg_Dbg(VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height);
1584 - (id)coreDialogProvider
1587 return o_coredialogs;
1592 - (id)eyeTVController
1600 - (id)appleRemoteController
1605 - (BOOL)activeVideoPlayback
1607 return b_active_videoplayback;
1611 #pragma mark Crash Log
1612 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1614 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1615 NSURL *url = [NSURL URLWithString:urlStr];
1617 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1618 [req setHTTPMethod:@"POST"];
1621 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1622 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1623 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1624 email = [emails valueAtIndex:[emails indexForIdentifier:
1625 [emails primaryIdentifier]]];
1628 email = [NSString string];
1631 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1632 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1633 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1634 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1636 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1638 /* Released from delegate */
1639 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1642 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1644 msg_Dbg(p_intf, "crash report successfully sent");
1645 [crashLogURLConnection release];
1646 crashLogURLConnection = nil;
1649 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1651 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1652 [crashLogURLConnection release];
1653 crashLogURLConnection = nil;
1656 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1658 NSString * crashReporter;
1659 if (OSX_MOUNTAIN_LION)
1660 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1662 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1663 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1665 NSString * latestLog = nil;
1666 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1667 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1668 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1669 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1670 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1672 while (fname = [direnum nextObject]) {
1673 [direnum skipDescendents];
1674 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1675 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1676 if ([compo count] < 3)
1678 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1679 if ([compo count] < 4)
1683 if (year < [[compo objectAtIndex:0] intValue] ||
1684 (year ==[[compo objectAtIndex:0] intValue] &&
1685 (month < [[compo objectAtIndex:1] intValue] ||
1686 (month ==[[compo objectAtIndex:1] intValue] &&
1687 (day < [[compo objectAtIndex:2] intValue] ||
1688 (day ==[[compo objectAtIndex:2] intValue] &&
1689 hours < [[compo objectAtIndex:3] intValue])))))) {
1690 year = [[compo objectAtIndex:0] intValue];
1691 month = [[compo objectAtIndex:1] intValue];
1692 day = [[compo objectAtIndex:2] intValue];
1693 hours = [[compo objectAtIndex:3] intValue];
1694 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1699 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1702 if (!previouslySeen) {
1703 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1704 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1705 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1706 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1711 - (NSString *)latestCrashLogPath
1713 return [self latestCrashLogPathPreviouslySeen:YES];
1716 - (void)lookForCrashLog
1718 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1719 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1720 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1721 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1722 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1723 if (latestLog && !areCrashLogsTooOld) {
1724 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1725 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1726 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1727 [NSApp runModalForWindow: o_crashrep_win];
1728 // bail out, the user doesn't want us to send reports
1734 - (IBAction)crashReporterAction:(id)sender
1736 if (sender == o_crashrep_send_btn) {
1737 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1738 if ([o_crashrep_dontaskagain_ckb state])
1739 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1741 if ([o_crashrep_dontaskagain_ckb state])
1742 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1746 [o_crashrep_win orderOut: sender];
1749 - (IBAction)openCrashLog:(id)sender
1751 NSString * latestLog = [self latestCrashLogPath];
1753 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1755 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."));
1760 #pragma mark Remove old prefs
1762 - (void)_removeOldPreferences
1764 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1765 static const int kCurrentPreferencesVersion = 2;
1766 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1767 int version = [defaults integerForKey:kVLCPreferencesVersion];
1768 if (version >= kCurrentPreferencesVersion)
1772 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1773 [defaults synchronize];
1775 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1778 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1780 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1781 NSUserDomainMask, YES);
1782 if (!libraries || [libraries count] == 0) return;
1783 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1785 /* File not found, don't attempt anything */
1786 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1787 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1788 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1792 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1793 _NS("We just found an older version of VLC's preferences files."),
1794 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1795 if (res != NSOKButton) {
1796 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1800 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1802 /* Move the file to trash so that user can find them later */
1803 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1805 /* really reset the defaults from now on */
1806 [NSUserDefaults resetStandardUserDefaults];
1808 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1809 [defaults synchronize];
1813 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1815 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1820 execl(path, path, NULL);
1824 #pragma mark Errors, warnings and messages
1825 - (IBAction)updateMessagesPanel:(id)sender
1827 [self windowDidBecomeKey:nil];
1830 - (IBAction)showMessagesPanel:(id)sender
1832 [o_msgs_panel makeKeyAndOrderFront: sender];
1835 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1837 [o_msgs_table reloadData];
1838 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1841 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1843 if (aTableView == o_msgs_table)
1844 return [o_msg_arr count];
1848 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1850 NSMutableAttributedString *result = NULL;
1853 if (rowIndex < [o_msg_arr count])
1854 result = [o_msg_arr objectAtIndex: rowIndex];
1855 [o_msg_lock unlock];
1863 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1866 NSColor *o_white = [NSColor whiteColor];
1867 NSColor *o_red = [NSColor redColor];
1868 NSColor *o_yellow = [NSColor yellowColor];
1869 NSColor *o_gray = [NSColor grayColor];
1870 NSString * firstString, * secondString;
1872 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1873 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1875 NSDictionary *o_attr;
1876 NSMutableAttributedString *o_msg_color;
1880 if ([o_msg_arr count] > 600) {
1881 [o_msg_arr removeObjectAtIndex: 0];
1882 [o_msg_arr removeObjectAtIndex: 1];
1884 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1885 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1887 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1888 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1889 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1890 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1891 [o_msg_arr addObject: [o_msg_color autorelease]];
1893 b_msg_arr_changed = YES;
1894 [o_msg_lock unlock];
1898 - (IBAction)saveDebugLog:(id)sender
1900 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1902 [saveFolderPanel setCanSelectHiddenExtension: NO];
1903 [saveFolderPanel setCanCreateDirectories: YES];
1904 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1905 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1906 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1907 if (returnCode == NSOKButton) {
1908 NSUInteger count = [o_msg_arr count];
1909 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1910 for (NSUInteger i = 0; i < count; i++)
1911 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1913 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1914 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1916 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1917 msg_Warn(p_intf, "Error while saving the debug log");
1922 [saveFolderPanel release];
1926 #pragma mark Playlist toggling
1928 - (void)updateTogglePlaylistState
1930 [[self playlist] outlineViewSelectionDidChange: NULL];
1937 @implementation VLCMain (Internal)
1939 - (void)handlePortMessage:(NSPortMessage *)o_msg
1944 NSInvocation * o_inv;
1945 NSConditionLock * o_lock;
1947 o_data = [[o_msg components] lastObject];
1948 o_inv = *((NSInvocation **)[o_data bytes]);
1949 [o_inv getArgument: &o_value atIndex: 2];
1950 val = (id **)[o_value pointerValue];
1951 [o_inv setArgument: val[1] atIndex: 2];
1956 [o_lock unlockWithCondition: 1];
1959 - (void)resetMediaKeyJump
1961 b_mediakeyJustJumped = NO;
1964 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1966 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1967 if (b_mediaKeySupport) {
1968 if (!o_mediaKeyController)
1969 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1970 [o_mediaKeyController startWatchingMediaKeys];
1972 else if (!b_mediaKeySupport && o_mediaKeyController)
1973 [o_mediaKeyController stopWatchingMediaKeys];
1978 /*****************************************************************************
1979 * VLCApplication interface
1980 *****************************************************************************/
1982 @implementation VLCApplication
1983 // when user selects the quit menu from dock it sends a terminate:
1984 // but we need to send a stop: to properly exits libvlc.
1985 // However, we are not able to change the action-method sent by this standard menu item.
1986 // thus we override terminate: to send a stop:
1987 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1988 - (void)terminate:(id)sender
1990 [self activateIgnoringOtherApps:YES];