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 vlc_log_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));
123 /*****************************************************************************
124 * CloseIntf: destroy interface
125 *****************************************************************************/
126 void CloseIntf (vlc_object_t *p_this)
128 intf_thread_t *p_intf = (intf_thread_t*) p_this;
133 static int WindowControl(vout_window_t *, int i_query, va_list);
135 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
137 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
138 intf_thread_t *p_intf = VLCIntf;
140 msg_Err(p_wnd, "Mac OS X interface not found");
143 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
145 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
146 SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
147 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
148 [inv setTarget:o_vout_controller];
149 [inv setSelector:sel];
150 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
151 [inv setArgument:&proposedVideoViewPosition atIndex:3];
153 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
156 VLCVoutView *videoView = nil;
157 [inv getReturnValue:&videoView];
160 msg_Err(p_wnd, "got no video view from the interface");
165 msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
166 p_wnd->handle.nsobject = videoView;
169 // TODO: find a cleaner way for "start in fullscreen"
170 if (var_GetBool(pl_Get(VLCIntf), "fullscreen")) {
173 SEL sel = @selector(setFullscreen:forWindow:);
174 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
175 [inv setTarget:[[VLCMain sharedInstance] voutController]];
176 [inv setSelector:sel];
177 [inv setArgument:&i_full atIndex:2];
178 [inv setArgument:&p_wnd atIndex:3];
179 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
183 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
184 p_wnd->control = WindowControl;
190 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
193 case VOUT_WINDOW_SET_STATE:
195 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
196 unsigned i_state = va_arg(args, unsigned);
198 NSInteger i_cooca_level = NSNormalWindowLevel;
199 if (i_state & VOUT_WINDOW_STATE_ABOVE)
200 i_cooca_level = NSStatusWindowLevel;
202 SEL sel = @selector(setWindowLevel:forWindow:);
203 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
204 [inv setTarget:[[VLCMain sharedInstance] voutController]];
205 [inv setSelector:sel];
206 [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
207 [inv setArgument:&p_wnd atIndex:3];
208 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
214 case VOUT_WINDOW_SET_SIZE:
216 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
218 unsigned int i_width = va_arg(args, unsigned int);
219 unsigned int i_height = va_arg(args, unsigned int);
221 NSSize newSize = NSMakeSize(i_width, i_height);
222 SEL sel = @selector(setNativeVideoSize:forWindow:);
223 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
224 [inv setTarget:[[VLCMain sharedInstance] voutController]];
225 [inv setSelector:sel];
226 [inv setArgument:&newSize atIndex:2]; // starting at 2!
227 [inv setArgument:&p_wnd atIndex:3];
228 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
234 case VOUT_WINDOW_SET_FULLSCREEN:
236 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
237 int i_full = va_arg(args, int);
239 SEL sel = @selector(setFullscreen:forWindow:);
240 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
241 [inv setTarget:[[VLCMain sharedInstance] voutController]];
242 [inv setSelector:sel];
243 [inv setArgument:&i_full atIndex:2]; // starting at 2!
244 [inv setArgument:&p_wnd atIndex:3];
245 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
252 msg_Warn(p_wnd, "unsupported control query");
257 void WindowClose(vout_window_t *p_wnd)
259 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
261 [[[VLCMain sharedInstance] voutController] performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
266 /*****************************************************************************
268 *****************************************************************************/
269 static NSLock * o_appLock = nil; // controls access to f_appExit
270 static NSLock * o_plItemChangedLock = nil;
272 static void Run(intf_thread_t *p_intf)
274 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
275 [VLCApplication sharedApplication];
277 o_appLock = [[NSLock alloc] init];
278 o_plItemChangedLock = [[NSLock alloc] init];
280 [[VLCMain sharedInstance] setIntf: p_intf];
282 /* subscribe to LibVLCCore's messages */
283 vlc_LogSet(p_intf->p_libvlc, MsgCallback, NULL);
285 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
288 [[VLCMain sharedInstance] applicationWillTerminate:nil];
289 [o_plItemChangedLock release];
297 #pragma mark Variables Callback
299 /*****************************************************************************
300 * MsgCallback: Callback triggered by the core once a new debug message is
301 * ready to be displayed. We store everything in a NSArray in our Cocoa part
303 *****************************************************************************/
304 static void MsgCallback(void *data, int type, const vlc_log_t *item, const char *format, va_list ap)
306 int canc = vlc_savecancel();
309 if (vasprintf(&str, format, ap) == -1) {
310 vlc_restorecancel(canc);
314 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
315 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
318 vlc_restorecancel(canc);
322 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
323 vlc_value_t oldval, vlc_value_t new_val, void *param)
325 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
326 switch (new_val.i_int) {
327 case INPUT_EVENT_STATE:
328 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
330 case INPUT_EVENT_RATE:
331 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
333 case INPUT_EVENT_POSITION:
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
336 case INPUT_EVENT_TITLE:
337 case INPUT_EVENT_CHAPTER:
338 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
340 case INPUT_EVENT_CACHE:
341 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
343 case INPUT_EVENT_STATISTICS:
344 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
348 case INPUT_EVENT_TELETEXT:
350 case INPUT_EVENT_AOUT:
352 case INPUT_EVENT_VOUT:
354 case INPUT_EVENT_ITEM_META:
355 case INPUT_EVENT_ITEM_INFO:
356 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
357 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
358 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
360 case INPUT_EVENT_BOOKMARK:
362 case INPUT_EVENT_RECORD:
363 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
365 case INPUT_EVENT_PROGRAM:
366 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
368 case INPUT_EVENT_ITEM_EPG:
370 case INPUT_EVENT_SIGNAL:
373 case INPUT_EVENT_ITEM_NAME:
374 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
375 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
378 case INPUT_EVENT_AUDIO_DELAY:
379 case INPUT_EVENT_SUBTITLE_DELAY:
380 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
383 case INPUT_EVENT_DEAD:
384 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
385 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
388 case INPUT_EVENT_ABORT:
389 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
390 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
394 //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
402 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
403 vlc_value_t oldval, vlc_value_t new_val, void *param)
405 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
407 /* Due to constraints within NSAttributedString's main loop runtime handling
408 * and other issues, we need to wait for -PlaylistItemChanged to finish and
409 * then -informInputChanged on this non-main thread. */
410 [o_plItemChangedLock lock];
411 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES];
412 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(informInputChanged) withObject:nil waitUntilDone:YES];
413 [o_plItemChangedLock unlock];
419 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
420 vlc_value_t oldval, vlc_value_t new_val, void *param)
422 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
423 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
429 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
430 vlc_value_t oldval, vlc_value_t new_val, void *param)
432 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
433 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
439 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
440 vlc_value_t oldval, vlc_value_t new_val, void *param)
442 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
443 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
449 /*****************************************************************************
450 * ShowController: Callback triggered by the show-intf playlist variable
451 * through the ShowIntf-control-intf, to let us show the controller-win;
452 * usually when in fullscreen-mode
453 *****************************************************************************/
454 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
455 vlc_value_t old_val, vlc_value_t new_val, void *param)
457 intf_thread_t * p_intf = VLCIntf;
458 if (p_intf && p_intf->p_sys) {
459 playlist_t * p_playlist = pl_Get(p_intf);
460 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
461 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
462 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
464 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
469 /*****************************************************************************
470 * DialogCallback: Callback triggered by the "dialog-*" variables
471 * to let the intf display error and interaction dialogs
472 *****************************************************************************/
473 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
475 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
476 VLCMain *interface = (VLCMain *)data;
478 if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
479 /* the progress panel needs to update itself and therefore wants special treatment within this context */
480 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
482 p_dialog->pf_update = updateProgressPanel;
483 p_dialog->pf_check = checkProgressPanel;
484 p_dialog->pf_destroy = destroyProgressPanel;
485 p_dialog->p_sys = VLCIntf->p_libvlc;
488 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
489 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
495 void updateProgressPanel (void *priv, const char *text, float value)
497 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
501 o_txt = [NSString stringWithUTF8String: text];
505 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
510 void destroyProgressPanel (void *priv)
512 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
514 if ([[NSApplication sharedApplication] isRunning])
515 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
520 bool checkProgressPanel (void *priv)
522 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
523 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
530 input_thread_t *getInput(void)
532 intf_thread_t *p_intf = VLCIntf;
535 return pl_CurrentInput(p_intf);
538 vout_thread_t *getVout(void)
540 input_thread_t *p_input = getInput();
543 vout_thread_t *p_vout = input_GetVout(p_input);
544 vlc_object_release(p_input);
548 vout_thread_t *getVoutForActiveWindow(void)
550 vout_thread_t *p_vout = nil;
552 id currentWindow = [NSApp keyWindow];
553 if ([currentWindow respondsToSelector:@selector(videoView)]) {
554 VLCVoutView *videoView = [currentWindow videoView];
556 p_vout = [videoView voutThread];
566 audio_output_t *getAout(void)
568 intf_thread_t *p_intf = VLCIntf;
571 return playlist_GetAout(pl_Get(p_intf));
577 @interface VLCMain ()
578 - (void)removeOldPreferences;
581 @interface VLCMain (Internal)
582 - (void)handlePortMessage:(NSPortMessage *)o_msg;
583 - (void)resetMediaKeyJump;
584 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
587 /*****************************************************************************
588 * VLCMain implementation
589 *****************************************************************************/
590 @implementation VLCMain
592 @synthesize voutController=o_vout_controller;
593 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
596 #pragma mark Initialization
598 static VLCMain *_o_sharedMainInstance = nil;
600 + (VLCMain *)sharedInstance
602 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
607 if (_o_sharedMainInstance) {
609 return _o_sharedMainInstance;
611 _o_sharedMainInstance = [super init];
614 p_current_input = p_input_changed = NULL;
616 o_msg_lock = [[NSLock alloc] init];
617 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
619 o_open = [[VLCOpen alloc] init];
620 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
621 o_info = [[VLCInfo alloc] init];
622 o_mainmenu = [[VLCMainMenu alloc] init];
623 o_coreinteraction = [[VLCCoreInteraction alloc] init];
624 o_eyetv = [[VLCEyeTVController alloc] init];
625 o_mainwindow = [[VLCMainWindow alloc] init];
627 /* announce our launch to a potential eyetv plugin */
628 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
629 object: @"VLCEyeTVSupport"
631 deliverImmediately: YES];
633 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
634 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
635 [defaults registerDefaults:appDefaults];
637 o_vout_controller = [[VLCVoutWindowController alloc] init];
639 return _o_sharedMainInstance;
642 - (void)setIntf: (intf_thread_t *)p_mainintf
647 - (intf_thread_t *)intf
654 playlist_t *p_playlist;
657 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
659 /* Check if we already did this once. Opening the other nibs calls it too,
660 because VLCMain is the owner */
664 [o_msgs_panel setExcludedFromWindowsMenu: YES];
665 [o_msgs_panel setDelegate: self];
667 p_playlist = pl_Get(p_intf);
671 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
672 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
673 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
674 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
675 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
676 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
677 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
678 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
679 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
680 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
681 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
682 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
684 if (!OSX_SNOW_LEOPARD) {
685 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
686 var_SetBool(p_playlist, "fullscreen", YES);
689 /* load our Core and Shared Dialogs nibs */
690 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
691 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
693 /* subscribe to various interactive dialogues */
694 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
695 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
696 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
697 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
698 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
699 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
700 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
701 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
702 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
703 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
704 dialog_Register(p_intf);
706 /* init Apple Remote support */
707 o_remote = [[AppleRemote alloc] init];
708 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
709 [o_remote setDelegate: _o_sharedMainInstance];
711 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
713 /* yeah, we are done */
714 b_nativeFullscreenMode = NO;
715 #ifdef MAC_OS_X_VERSION_10_7
716 if (!OSX_SNOW_LEOPARD)
717 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
720 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
721 /* After day 354 of the year, the usual VLC cone is replaced by another cone
722 * wearing a Father Xmas hat.
723 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
725 NSCalendar *gregorian =
726 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
727 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
730 if (dayOfYear >= 354)
731 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
736 nib_main_loaded = TRUE;
739 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
744 [self updateCurrentlyUsedHotkeys];
746 /* init media key support */
747 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
748 if (b_mediaKeySupport) {
749 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
750 [o_mediaKeyController startWatchingMediaKeys];
751 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
752 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
755 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
757 [self removeOldPreferences];
759 /* Handle sleep notification */
760 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
761 name:NSWorkspaceWillSleepNotification object:nil];
763 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
765 /* we will need this, so let's load it here so the interface appears to be more responsive */
766 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
768 /* update the main window */
769 [o_mainwindow updateWindow];
770 [o_mainwindow updateTimeSlider];
771 [o_mainwindow updateVolumeSlider];
780 [o_msgs_panel setTitle: _NS("Messages")];
781 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
782 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
784 /* crash reporter panel */
785 [o_crashrep_send_btn setTitle: _NS("Send")];
786 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
787 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
788 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
789 [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, ...")];
790 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
791 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
792 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
796 #pragma mark Termination
798 - (void)applicationWillTerminate:(NSNotification *)notification
800 /* don't allow a double termination call. If the user has
801 * already invoked the quit then simply return this time. */
802 static bool f_appExit = false;
806 isTerminating = f_appExit;
813 [self resumeItunesPlayback:nil];
815 if (notification == nil)
816 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
818 playlist_t * p_playlist = pl_Get(p_intf);
819 int returnedValue = 0;
821 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
822 if (b_nativeFullscreenMode) {
823 [o_mainwindow toggleFullScreen: self];
824 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
827 /* save current video and audio profiles */
828 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
829 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
831 /* Save some interface state in configuration, at module quit */
832 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
833 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
834 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
836 msg_Dbg(p_intf, "Terminating");
838 /* unsubscribe from the interactive dialogues */
839 dialog_Unregister(p_intf);
840 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
841 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
842 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
843 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
844 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
845 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
846 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
847 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
848 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
849 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
850 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
851 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
852 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
853 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
854 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
855 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
856 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
858 if (p_current_input) {
859 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
860 vlc_object_release(p_current_input);
861 p_current_input = NULL;
864 /* remove global observer watching for vout device changes correctly */
865 [[NSNotificationCenter defaultCenter] removeObserver: self];
867 // release before o_info!
868 [o_vout_controller release];
869 o_vout_controller = nil;
871 /* release some other objects here, because it isn't sure whether dealloc
872 * will be called later on */
887 [crashLogURLConnection cancel];
888 [crashLogURLConnection release];
890 [o_coredialogs release];
893 /* unsubscribe from libvlc's debug messages */
894 vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
896 [o_msg_arr removeAllObjects];
899 [o_usedHotkeys release];
900 o_usedHotkeys = NULL;
902 [o_msg_lock release];
904 /* write cached user defaults to disk */
905 [[NSUserDefaults standardUserDefaults] synchronize];
908 [o_mainmenu release];
910 libvlc_Quit(p_intf->p_libvlc);
912 [o_mainwindow release];
919 #pragma mark Sparkle delegate
920 /* received directly before the update gets installed, so let's shut down a bit */
921 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
923 [NSApp activateIgnoringOtherApps:YES];
924 [o_remote stopListening: self];
925 [[VLCCoreInteraction sharedInstance] stop];
929 #pragma mark Media Key support
931 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
933 if (b_mediaKeySupport) {
934 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
936 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
937 int keyFlags = ([event data1] & 0x0000FFFF);
938 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
939 int keyRepeat = (keyFlags & 0x1);
941 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
942 [[VLCCoreInteraction sharedInstance] playOrPause];
944 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
945 if (keyState == 0 && keyRepeat == 0)
946 [[VLCCoreInteraction sharedInstance] next];
947 else if (keyRepeat == 1) {
948 [[VLCCoreInteraction sharedInstance] forwardShort];
949 b_mediakeyJustJumped = YES;
950 [self performSelector:@selector(resetMediaKeyJump)
956 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
957 if (keyState == 0 && keyRepeat == 0)
958 [[VLCCoreInteraction sharedInstance] previous];
959 else if (keyRepeat == 1) {
960 [[VLCCoreInteraction sharedInstance] backwardShort];
961 b_mediakeyJustJumped = YES;
962 [self performSelector:@selector(resetMediaKeyJump)
971 #pragma mark Other notification
973 /* Listen to the remote in exclusive mode, only when VLC is the active
975 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
979 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
980 [o_remote startListening: self];
982 - (void)applicationDidResignActive:(NSNotification *)aNotification
986 [o_remote stopListening: self];
989 /* Triggered when the computer goes to sleep */
990 - (void)computerWillSleep: (NSNotification *)notification
992 [[VLCCoreInteraction sharedInstance] pause];
996 #pragma mark File opening over dock icon
998 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
1000 BOOL b_autoplay = config_GetInt(VLCIntf, "macosx-autoplay");
1001 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
1003 // try to add file as subtitle
1004 if ([o_names count] == 1 && psz_uri) {
1005 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1007 BOOL b_returned = NO;
1008 b_returned = input_AddSubtitle(p_input, psz_uri, true);
1009 vlc_object_release(p_input);
1018 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1019 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1020 for (int i = 0; i < [o_sorted_names count]; i++) {
1021 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file");
1025 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1027 [o_result addObject: o_dic];
1031 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
1033 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
1038 /* When user click in the Dock icon our double click in the finder */
1039 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1041 if (!hasVisibleWindows)
1042 [o_mainwindow makeKeyAndOrderFront:self];
1048 #pragma mark Apple Remote Control
1050 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1051 increase/decrease as long as the user holds the left/right, plus/minus button */
1052 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1054 if (b_remote_button_hold) {
1055 switch([buttonIdentifierNumber intValue]) {
1056 case kRemoteButtonRight_Hold:
1057 [[VLCCoreInteraction sharedInstance] forward];
1059 case kRemoteButtonLeft_Hold:
1060 [[VLCCoreInteraction sharedInstance] backward];
1062 case kRemoteButtonVolume_Plus_Hold:
1063 [[VLCCoreInteraction sharedInstance] volumeUp];
1065 case kRemoteButtonVolume_Minus_Hold:
1066 [[VLCCoreInteraction sharedInstance] volumeDown];
1069 if (b_remote_button_hold) {
1071 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1072 withObject:buttonIdentifierNumber
1078 /* Apple Remote callback */
1079 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1080 pressedDown: (BOOL) pressedDown
1081 clickCount: (unsigned int) count
1083 switch(buttonIdentifier) {
1084 case k2009RemoteButtonFullscreen:
1085 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1087 case k2009RemoteButtonPlay:
1088 [[VLCCoreInteraction sharedInstance] playOrPause];
1090 case kRemoteButtonPlay:
1092 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1094 [[VLCCoreInteraction sharedInstance] playOrPause];
1096 case kRemoteButtonVolume_Plus:
1097 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1098 [NSSound increaseSystemVolume];
1100 [[VLCCoreInteraction sharedInstance] volumeUp];
1102 case kRemoteButtonVolume_Minus:
1103 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1104 [NSSound decreaseSystemVolume];
1106 [[VLCCoreInteraction sharedInstance] volumeDown];
1108 case kRemoteButtonRight:
1109 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1110 [[VLCCoreInteraction sharedInstance] forward];
1112 [[VLCCoreInteraction sharedInstance] next];
1114 case kRemoteButtonLeft:
1115 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1116 [[VLCCoreInteraction sharedInstance] backward];
1118 [[VLCCoreInteraction sharedInstance] previous];
1120 case kRemoteButtonRight_Hold:
1121 case kRemoteButtonLeft_Hold:
1122 case kRemoteButtonVolume_Plus_Hold:
1123 case kRemoteButtonVolume_Minus_Hold:
1124 /* simulate an event as long as the user holds the button */
1125 b_remote_button_hold = pressedDown;
1127 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1128 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1129 withObject:buttonIdentifierNumber];
1132 case kRemoteButtonMenu:
1133 [o_controls showPosition: self]; //FIXME
1135 case kRemoteButtonPlay_Sleep:
1137 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1138 [script executeAndReturnError:nil];
1143 /* Add here whatever you want other buttons to do */
1149 #pragma mark Key Shortcuts
1151 /*****************************************************************************
1152 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1153 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1154 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1155 *****************************************************************************/
1156 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1160 unsigned int i_pressed_modifiers = 0;
1163 i_pressed_modifiers = [o_event modifierFlags];
1165 if (i_pressed_modifiers & NSControlKeyMask)
1166 val.i_int |= KEY_MODIFIER_CTRL;
1168 if (i_pressed_modifiers & NSAlternateKeyMask)
1169 val.i_int |= KEY_MODIFIER_ALT;
1171 if (i_pressed_modifiers & NSShiftKeyMask)
1172 val.i_int |= KEY_MODIFIER_SHIFT;
1174 if (i_pressed_modifiers & NSCommandKeyMask)
1175 val.i_int |= KEY_MODIFIER_COMMAND;
1177 NSString * characters = [o_event charactersIgnoringModifiers];
1178 if ([characters length] > 0) {
1179 key = [[characters lowercaseString] characterAtIndex: 0];
1181 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1182 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1183 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1189 case NSDeleteCharacter:
1190 case NSDeleteFunctionKey:
1191 case NSDeleteCharFunctionKey:
1192 case NSBackspaceCharacter:
1193 case NSUpArrowFunctionKey:
1194 case NSDownArrowFunctionKey:
1195 case NSEnterCharacter:
1196 case NSCarriageReturnCharacter:
1201 if (key == 0x0020) { // space key
1202 [[VLCCoreInteraction sharedInstance] playOrPause];
1206 val.i_int |= CocoaKeyToVLC(key);
1208 BOOL b_found_key = NO;
1209 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1210 NSString *str = [o_usedHotkeys objectAtIndex: i];
1211 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1213 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1214 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1215 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1216 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1217 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1224 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1232 - (void)updateCurrentlyUsedHotkeys
1234 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1235 /* Get the main Module */
1236 module_t *p_main = module_get_main();
1239 module_config_t *p_config;
1241 p_config = module_config_get (p_main, &confsize);
1243 for (size_t i = 0; i < confsize; i++) {
1244 module_config_t *p_item = p_config + i;
1246 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1247 && !strncmp(p_item->psz_name , "key-", 4)
1248 && !EMPTY_STR(p_item->psz_text)) {
1249 if (p_item->value.psz)
1250 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1253 module_config_free (p_config);
1256 [o_usedHotkeys release];
1257 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1258 [o_tempArray release];
1262 #pragma mark Interface updaters
1264 - (void)PlaylistItemChanged
1266 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1267 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1268 p_input_changed = p_current_input;
1269 p_current_input = NULL;
1271 [o_mainmenu setRateControlsEnabled: NO];
1273 else if (!p_current_input) {
1274 // object is hold here and released then it is dead
1275 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1276 if (p_current_input) {
1277 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1278 [self playbackStatusUpdated];
1279 [o_mainmenu setRateControlsEnabled: YES];
1280 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1281 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1282 p_input_changed = vlc_object_hold(p_current_input);
1286 [o_playlist updateRowSelection];
1287 [o_mainwindow updateWindow];
1288 [self updateDelays];
1289 [self updateMainMenu];
1292 - (void)informInputChanged
1294 if (p_input_changed) {
1295 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1296 vlc_object_release(p_input_changed);
1297 p_input_changed = NULL;
1301 - (void)updateMainMenu
1303 [o_mainmenu setupMenus];
1304 [o_mainmenu updatePlaybackRate];
1305 [[VLCCoreInteraction sharedInstance] resetAtoB];
1308 - (void)updateMainWindow
1310 [o_mainwindow updateWindow];
1313 - (void)showMainWindow
1315 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1318 - (void)showFullscreenController
1320 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1323 - (void)updateDelays
1325 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1330 [o_mainwindow updateName];
1333 - (void)updatePlaybackPosition
1335 [o_mainwindow updateTimeSlider];
1336 [[VLCCoreInteraction sharedInstance] updateAtoB];
1339 - (void)updateVolume
1341 [o_mainwindow updateVolumeSlider];
1344 - (void)playlistUpdated
1346 [self playbackStatusUpdated];
1347 [o_playlist playlistUpdated];
1348 [o_mainwindow updateWindow];
1349 [o_mainwindow updateName];
1352 - (void)updateRecordState: (BOOL)b_value
1354 [o_mainmenu updateRecordState:b_value];
1357 - (void)updateInfoandMetaPanel
1359 [o_playlist outlineViewSelectionDidChange:nil];
1362 - (void)resumeItunesPlayback:(id)sender
1364 if (b_has_itunes_paused && var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1365 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1366 if (iTunesApp && [iTunesApp isRunning]) {
1367 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1368 msg_Dbg(p_intf, "Unpause iTunes...");
1369 [iTunesApp playpause];
1375 b_has_itunes_paused = NO;
1376 o_itunes_play_timer = nil;
1379 - (void)playbackStatusUpdated
1382 if (p_current_input) {
1383 state = var_GetInteger(p_current_input, "state");
1386 int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1387 // cancel itunes timer if next item starts playing
1388 if (state > -1 && state != END_S && i_control_itunes > 0) {
1389 if (o_itunes_play_timer) {
1390 [o_itunes_play_timer invalidate];
1391 o_itunes_play_timer = nil;
1395 if (state == PLAYING_S) {
1397 if (i_control_itunes > 0 && !b_has_itunes_paused) {
1398 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1399 if (iTunesApp && [iTunesApp isRunning]) {
1400 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1401 msg_Dbg(p_intf, "Pause iTunes...");
1403 b_has_itunes_paused = YES;
1409 /* Declare user activity.
1410 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1411 Available from 10.7.3 */
1412 #ifdef MAC_OS_X_VERSION_10_7
1413 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1415 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1416 IOPMAssertionDeclareUserActivity(reasonForActivity,
1417 kIOPMUserActiveLocal,
1418 &userActivityAssertionID);
1419 CFRelease(reasonForActivity);
1423 /* prevent the system from sleeping */
1424 if (systemSleepAssertionID > 0) {
1425 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1426 IOPMAssertionRelease(systemSleepAssertionID);
1430 /* 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 */
1431 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1432 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1433 if ([self activeVideoPlayback])
1434 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1436 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1437 CFRelease(reasonForActivity);
1439 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1440 if ([self activeVideoPlayback])
1441 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1443 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1446 if (success == kIOReturnSuccess)
1447 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1449 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1451 [[self mainMenu] setPause];
1452 [o_mainwindow setPause];
1454 [o_mainmenu setSubmenusEnabled: FALSE];
1455 [[self mainMenu] setPlay];
1456 [o_mainwindow setPlay];
1458 /* allow the system to sleep again */
1459 if (systemSleepAssertionID > 0) {
1460 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1461 IOPMAssertionRelease(systemSleepAssertionID);
1464 if (state == END_S || state == -1) {
1465 if (i_control_itunes > 0) {
1466 if (o_itunes_play_timer) {
1467 [o_itunes_play_timer invalidate];
1469 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1471 selector: @selector(resumeItunesPlayback:)
1478 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1479 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1482 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1484 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1487 deliverImmediately:YES];
1490 - (void)playbackModeUpdated
1492 vlc_value_t looping,repeating;
1493 playlist_t * p_playlist = pl_Get(VLCIntf);
1495 bool loop = var_GetBool(p_playlist, "loop");
1496 bool repeat = var_GetBool(p_playlist, "repeat");
1498 [[o_mainwindow controlsBar] setRepeatOne];
1499 [o_mainmenu setRepeatOne];
1501 [[o_mainwindow controlsBar] setRepeatAll];
1502 [o_mainmenu setRepeatAll];
1504 [[o_mainwindow controlsBar] setRepeatOff];
1505 [o_mainmenu setRepeatOff];
1508 [[o_mainwindow controlsBar] setShuffle];
1509 [o_mainmenu setShuffle];
1514 #pragma mark Window updater
1518 - (void)setActiveVideoPlayback:(BOOL)b_value
1520 b_active_videoplayback = b_value;
1522 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1523 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1526 // update sleep blockers
1527 [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1531 #pragma mark Other objects getters
1538 - (VLCMainWindow *)mainWindow
1540 return o_mainwindow;
1554 o_bookmarks = [[VLCBookmarks alloc] init];
1556 if (!nib_bookmarks_loaded)
1557 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1567 if (!nib_open_loaded)
1568 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1573 - (id)simplePreferences
1576 o_sprefs = [[VLCSimplePrefs alloc] init];
1578 if (!nib_prefs_loaded)
1579 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1587 o_prefs = [[VLCPrefs alloc] init];
1589 if (!nib_prefs_loaded)
1590 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1605 if (! nib_info_loaded)
1606 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1617 o_wizard = [[VLCWizard alloc] init];
1619 if (!nib_wizard_loaded) {
1620 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1621 [o_wizard initStrings];
1626 - (id)coreDialogProvider
1629 return o_coredialogs;
1634 - (id)eyeTVController
1642 - (id)appleRemoteController
1647 - (BOOL)activeVideoPlayback
1649 return b_active_videoplayback;
1653 #pragma mark Crash Log
1654 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1656 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1657 NSURL *url = [NSURL URLWithString:urlStr];
1659 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1660 [req setHTTPMethod:@"POST"];
1663 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1664 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1665 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1666 email = [emails valueAtIndex:[emails indexForIdentifier:
1667 [emails primaryIdentifier]]];
1670 email = [NSString string];
1673 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1674 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1675 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1676 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1678 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1680 /* Released from delegate */
1681 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1684 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1686 msg_Dbg(p_intf, "crash report successfully sent");
1687 [crashLogURLConnection release];
1688 crashLogURLConnection = nil;
1691 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1693 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1694 [crashLogURLConnection release];
1695 crashLogURLConnection = nil;
1698 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1700 NSString * crashReporter;
1701 if (OSX_MOUNTAIN_LION)
1702 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1704 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1705 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1707 NSString * latestLog = nil;
1708 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1709 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1710 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1711 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1712 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1714 while (fname = [direnum nextObject]) {
1715 [direnum skipDescendents];
1716 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1717 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1718 if ([compo count] < 3)
1720 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1721 if ([compo count] < 4)
1725 if (year < [[compo objectAtIndex:0] intValue] ||
1726 (year ==[[compo objectAtIndex:0] intValue] &&
1727 (month < [[compo objectAtIndex:1] intValue] ||
1728 (month ==[[compo objectAtIndex:1] intValue] &&
1729 (day < [[compo objectAtIndex:2] intValue] ||
1730 (day ==[[compo objectAtIndex:2] intValue] &&
1731 hours < [[compo objectAtIndex:3] intValue])))))) {
1732 year = [[compo objectAtIndex:0] intValue];
1733 month = [[compo objectAtIndex:1] intValue];
1734 day = [[compo objectAtIndex:2] intValue];
1735 hours = [[compo objectAtIndex:3] intValue];
1736 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1741 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1744 if (!previouslySeen) {
1745 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1746 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1747 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1748 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1753 - (NSString *)latestCrashLogPath
1755 return [self latestCrashLogPathPreviouslySeen:YES];
1758 - (void)lookForCrashLog
1760 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1761 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1762 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1763 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1764 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1765 if (latestLog && !areCrashLogsTooOld) {
1766 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1767 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1768 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1769 [NSApp runModalForWindow: o_crashrep_win];
1770 // bail out, the user doesn't want us to send reports
1776 - (IBAction)crashReporterAction:(id)sender
1778 if (sender == o_crashrep_send_btn) {
1779 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1780 if ([o_crashrep_dontaskagain_ckb state])
1781 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1783 if ([o_crashrep_dontaskagain_ckb state])
1784 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1788 [o_crashrep_win orderOut: sender];
1791 - (IBAction)openCrashLog:(id)sender
1793 NSString * latestLog = [self latestCrashLogPath];
1795 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1797 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."));
1802 #pragma mark Remove old prefs
1804 - (void)removeOldPreferences
1806 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1807 static const int kCurrentPreferencesVersion = 2;
1808 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1809 int version = [defaults integerForKey:kVLCPreferencesVersion];
1810 if (version >= kCurrentPreferencesVersion)
1814 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1815 [defaults synchronize];
1817 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1820 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1822 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1823 NSUserDomainMask, YES);
1824 if (!libraries || [libraries count] == 0) return;
1825 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1827 /* File not found, don't attempt anything */
1828 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1829 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1830 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1834 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1835 _NS("We just found an older version of VLC's preferences files."),
1836 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1837 if (res != NSOKButton) {
1838 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1842 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1844 /* Move the file to trash so that user can find them later */
1845 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1847 /* really reset the defaults from now on */
1848 [NSUserDefaults resetStandardUserDefaults];
1850 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1851 [defaults synchronize];
1855 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1857 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1862 execl(path, path, NULL);
1866 #pragma mark Errors, warnings and messages
1867 - (IBAction)updateMessagesPanel:(id)sender
1869 [self windowDidBecomeKey:nil];
1872 - (IBAction)showMessagesPanel:(id)sender
1874 [o_msgs_panel makeKeyAndOrderFront: sender];
1877 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1879 [o_msgs_table reloadData];
1880 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1883 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1885 if (aTableView == o_msgs_table)
1886 return [o_msg_arr count];
1890 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1892 NSMutableAttributedString *result = NULL;
1895 if (rowIndex < [o_msg_arr count])
1896 result = [o_msg_arr objectAtIndex: rowIndex];
1897 [o_msg_lock unlock];
1905 - (void)processReceivedlibvlcMessage:(const vlc_log_t *) item ofType: (int)i_type withStr: (char *)str
1908 NSColor *o_white = [NSColor whiteColor];
1909 NSColor *o_red = [NSColor redColor];
1910 NSColor *o_yellow = [NSColor yellowColor];
1911 NSColor *o_gray = [NSColor grayColor];
1912 NSString * firstString, * secondString;
1914 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1915 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1917 NSDictionary *o_attr;
1918 NSMutableAttributedString *o_msg_color;
1922 if ([o_msg_arr count] > 600) {
1923 [o_msg_arr removeObjectAtIndex: 0];
1924 [o_msg_arr removeObjectAtIndex: 1];
1926 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1927 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1929 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1930 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1931 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1932 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1933 [o_msg_arr addObject: [o_msg_color autorelease]];
1935 b_msg_arr_changed = YES;
1936 [o_msg_lock unlock];
1940 - (IBAction)saveDebugLog:(id)sender
1942 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1944 [saveFolderPanel setCanSelectHiddenExtension: NO];
1945 [saveFolderPanel setCanCreateDirectories: YES];
1946 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1947 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1948 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1949 if (returnCode == NSOKButton) {
1950 NSUInteger count = [o_msg_arr count];
1951 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1952 for (NSUInteger i = 0; i < count; i++)
1953 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1955 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1956 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1958 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1959 msg_Warn(p_intf, "Error while saving the debug log");
1964 [saveFolderPanel release];
1968 #pragma mark Playlist toggling
1970 - (void)updateTogglePlaylistState
1972 [[self playlist] outlineViewSelectionDidChange: NULL];
1979 @implementation VLCMain (Internal)
1981 - (void)handlePortMessage:(NSPortMessage *)o_msg
1986 NSInvocation * o_inv;
1987 NSConditionLock * o_lock;
1989 o_data = [[o_msg components] lastObject];
1990 o_inv = *((NSInvocation **)[o_data bytes]);
1991 [o_inv getArgument: &o_value atIndex: 2];
1992 val = (id **)[o_value pointerValue];
1993 [o_inv setArgument: val[1] atIndex: 2];
1998 [o_lock unlockWithCondition: 1];
2001 - (void)resetMediaKeyJump
2003 b_mediakeyJustJumped = NO;
2006 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2008 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
2009 if (b_mediaKeySupport) {
2010 if (!o_mediaKeyController)
2011 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2012 [o_mediaKeyController startWatchingMediaKeys];
2014 else if (!b_mediaKeySupport && o_mediaKeyController)
2015 [o_mediaKeyController stopWatchingMediaKeys];
2020 /*****************************************************************************
2021 * VLCApplication interface
2022 *****************************************************************************/
2024 @implementation VLCApplication
2025 // when user selects the quit menu from dock it sends a terminate:
2026 // but we need to send a stop: to properly exits libvlc.
2027 // However, we are not able to change the action-method sent by this standard menu item.
2028 // thus we override terminate: to send a stop:
2029 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2030 - (void)terminate:(id)sender
2032 [self activateIgnoringOtherApps:YES];