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:
1064 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1066 case kRemoteButtonVolume_Minus_Hold:
1068 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1071 if (b_remote_button_hold) {
1073 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1074 withObject:buttonIdentifierNumber
1080 /* Apple Remote callback */
1081 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1082 pressedDown: (BOOL) pressedDown
1083 clickCount: (unsigned int) count
1085 switch(buttonIdentifier) {
1086 case k2009RemoteButtonFullscreen:
1087 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1089 case k2009RemoteButtonPlay:
1090 [[VLCCoreInteraction sharedInstance] playOrPause];
1092 case kRemoteButtonPlay:
1094 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1096 [[VLCCoreInteraction sharedInstance] playOrPause];
1098 case kRemoteButtonVolume_Plus:
1099 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1100 [NSSound increaseSystemVolume];
1103 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1105 case kRemoteButtonVolume_Minus:
1106 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1107 [NSSound decreaseSystemVolume];
1110 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1112 case kRemoteButtonRight:
1113 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1114 [[VLCCoreInteraction sharedInstance] forward];
1116 [[VLCCoreInteraction sharedInstance] next];
1118 case kRemoteButtonLeft:
1119 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1120 [[VLCCoreInteraction sharedInstance] backward];
1122 [[VLCCoreInteraction sharedInstance] previous];
1124 case kRemoteButtonRight_Hold:
1125 case kRemoteButtonLeft_Hold:
1126 case kRemoteButtonVolume_Plus_Hold:
1127 case kRemoteButtonVolume_Minus_Hold:
1128 /* simulate an event as long as the user holds the button */
1129 b_remote_button_hold = pressedDown;
1131 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1132 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1133 withObject:buttonIdentifierNumber];
1136 case kRemoteButtonMenu:
1137 [o_controls showPosition: self]; //FIXME
1139 case kRemoteButtonPlay_Sleep:
1141 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1142 [script executeAndReturnError:nil];
1147 /* Add here whatever you want other buttons to do */
1153 #pragma mark Key Shortcuts
1155 /*****************************************************************************
1156 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1157 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1158 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1159 *****************************************************************************/
1160 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1164 unsigned int i_pressed_modifiers = 0;
1167 i_pressed_modifiers = [o_event modifierFlags];
1169 if (i_pressed_modifiers & NSControlKeyMask)
1170 val.i_int |= KEY_MODIFIER_CTRL;
1172 if (i_pressed_modifiers & NSAlternateKeyMask)
1173 val.i_int |= KEY_MODIFIER_ALT;
1175 if (i_pressed_modifiers & NSShiftKeyMask)
1176 val.i_int |= KEY_MODIFIER_SHIFT;
1178 if (i_pressed_modifiers & NSCommandKeyMask)
1179 val.i_int |= KEY_MODIFIER_COMMAND;
1181 NSString * characters = [o_event charactersIgnoringModifiers];
1182 if ([characters length] > 0) {
1183 key = [[characters lowercaseString] characterAtIndex: 0];
1185 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1186 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1187 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1193 case NSDeleteCharacter:
1194 case NSDeleteFunctionKey:
1195 case NSDeleteCharFunctionKey:
1196 case NSBackspaceCharacter:
1197 case NSUpArrowFunctionKey:
1198 case NSDownArrowFunctionKey:
1199 case NSEnterCharacter:
1200 case NSCarriageReturnCharacter:
1205 val.i_int |= CocoaKeyToVLC(key);
1207 BOOL b_found_key = NO;
1208 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1209 NSString *str = [o_usedHotkeys objectAtIndex: i];
1210 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1212 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1213 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1214 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1215 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1216 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1223 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1231 - (void)updateCurrentlyUsedHotkeys
1233 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1234 /* Get the main Module */
1235 module_t *p_main = module_get_main();
1238 module_config_t *p_config;
1240 p_config = module_config_get (p_main, &confsize);
1242 for (size_t i = 0; i < confsize; i++) {
1243 module_config_t *p_item = p_config + i;
1245 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1246 && !strncmp(p_item->psz_name , "key-", 4)
1247 && !EMPTY_STR(p_item->psz_text)) {
1248 if (p_item->value.psz)
1249 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1252 module_config_free (p_config);
1255 [o_usedHotkeys release];
1256 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1257 [o_tempArray release];
1261 #pragma mark Interface updaters
1263 - (void)PlaylistItemChanged
1265 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1266 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1267 p_input_changed = p_current_input;
1268 p_current_input = NULL;
1270 [o_mainmenu setRateControlsEnabled: NO];
1272 else if (!p_current_input) {
1273 // object is hold here and released then it is dead
1274 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1275 if (p_current_input) {
1276 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1277 [self playbackStatusUpdated];
1278 [o_mainmenu setRateControlsEnabled: YES];
1279 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1280 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1281 p_input_changed = vlc_object_hold(p_current_input);
1285 [o_playlist updateRowSelection];
1286 [o_mainwindow updateWindow];
1287 [self updateDelays];
1288 [self updateMainMenu];
1291 - (void)informInputChanged
1293 if (p_input_changed) {
1294 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1295 vlc_object_release(p_input_changed);
1296 p_input_changed = NULL;
1300 - (void)updateMainMenu
1302 [o_mainmenu setupMenus];
1303 [o_mainmenu updatePlaybackRate];
1304 [[VLCCoreInteraction sharedInstance] resetAtoB];
1307 - (void)updateMainWindow
1309 [o_mainwindow updateWindow];
1312 - (void)showMainWindow
1314 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1317 - (void)showFullscreenController
1319 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1322 - (void)updateDelays
1324 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1329 [o_mainwindow updateName];
1332 - (void)updatePlaybackPosition
1334 [o_mainwindow updateTimeSlider];
1335 [[VLCCoreInteraction sharedInstance] updateAtoB];
1338 - (void)updateVolume
1340 [o_mainwindow updateVolumeSlider];
1343 - (void)playlistUpdated
1345 [self playbackStatusUpdated];
1346 [o_playlist playlistUpdated];
1347 [o_mainwindow updateWindow];
1348 [o_mainwindow updateName];
1351 - (void)updateRecordState: (BOOL)b_value
1353 [o_mainmenu updateRecordState:b_value];
1356 - (void)updateInfoandMetaPanel
1358 [o_playlist outlineViewSelectionDidChange:nil];
1361 - (void)resumeItunesPlayback:(id)sender
1363 if (b_has_itunes_paused && var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1364 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1365 if (iTunesApp && [iTunesApp isRunning]) {
1366 if ([iTunesApp playerState] == iTunesEPlSPaused) {
1367 msg_Dbg(p_intf, "Unpause iTunes...");
1368 [iTunesApp playpause];
1374 b_has_itunes_paused = NO;
1375 o_itunes_play_timer = nil;
1378 - (void)playbackStatusUpdated
1381 if (p_current_input) {
1382 state = var_GetInteger(p_current_input, "state");
1385 int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1386 // cancel itunes timer if next item starts playing
1387 if (state > -1 && state != END_S && i_control_itunes > 0) {
1388 if (o_itunes_play_timer) {
1389 [o_itunes_play_timer invalidate];
1390 o_itunes_play_timer = nil;
1394 if (state == PLAYING_S) {
1396 if (i_control_itunes > 0 && !b_has_itunes_paused) {
1397 iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1398 if (iTunesApp && [iTunesApp isRunning]) {
1399 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1400 msg_Dbg(p_intf, "Pause iTunes...");
1402 b_has_itunes_paused = YES;
1408 /* Declare user activity.
1409 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1410 Available from 10.7.3 */
1411 #ifdef MAC_OS_X_VERSION_10_7
1412 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1414 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1415 IOPMAssertionDeclareUserActivity(reasonForActivity,
1416 kIOPMUserActiveLocal,
1417 &userActivityAssertionID);
1418 CFRelease(reasonForActivity);
1422 /* prevent the system from sleeping */
1423 if (systemSleepAssertionID > 0) {
1424 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1425 IOPMAssertionRelease(systemSleepAssertionID);
1429 /* work-around a bug in 10.7.4 and 10.7.5, so check for 10.7.x < 10.7.4, 10.8 and 10.6 */
1430 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1431 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1432 if ([self activeVideoPlayback])
1433 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1435 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1436 CFRelease(reasonForActivity);
1438 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1439 if ([self activeVideoPlayback])
1440 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1442 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1445 if (success == kIOReturnSuccess)
1446 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1448 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1450 [[self mainMenu] setPause];
1451 [o_mainwindow setPause];
1453 [o_mainmenu setSubmenusEnabled: FALSE];
1454 [[self mainMenu] setPlay];
1455 [o_mainwindow setPlay];
1457 /* allow the system to sleep again */
1458 if (systemSleepAssertionID > 0) {
1459 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1460 IOPMAssertionRelease(systemSleepAssertionID);
1463 if (state == END_S || state == -1) {
1464 if (i_control_itunes > 0) {
1465 if (o_itunes_play_timer) {
1466 [o_itunes_play_timer invalidate];
1468 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1470 selector: @selector(resumeItunesPlayback:)
1477 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1478 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1481 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1483 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1486 deliverImmediately:YES];
1489 - (void)playbackModeUpdated
1491 vlc_value_t looping,repeating;
1492 playlist_t * p_playlist = pl_Get(VLCIntf);
1494 bool loop = var_GetBool(p_playlist, "loop");
1495 bool repeat = var_GetBool(p_playlist, "repeat");
1497 [[o_mainwindow controlsBar] setRepeatOne];
1498 [o_mainmenu setRepeatOne];
1500 [[o_mainwindow controlsBar] setRepeatAll];
1501 [o_mainmenu setRepeatAll];
1503 [[o_mainwindow controlsBar] setRepeatOff];
1504 [o_mainmenu setRepeatOff];
1507 [[o_mainwindow controlsBar] setShuffle];
1508 [o_mainmenu setShuffle];
1513 #pragma mark Window updater
1517 - (void)setActiveVideoPlayback:(BOOL)b_value
1519 b_active_videoplayback = b_value;
1521 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1522 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1525 // update sleep blockers
1526 [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1530 #pragma mark Other objects getters
1537 - (VLCMainWindow *)mainWindow
1539 return o_mainwindow;
1553 o_bookmarks = [[VLCBookmarks alloc] init];
1555 if (!nib_bookmarks_loaded)
1556 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1566 if (!nib_open_loaded)
1567 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1572 - (id)simplePreferences
1575 o_sprefs = [[VLCSimplePrefs alloc] init];
1577 if (!nib_prefs_loaded)
1578 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1586 o_prefs = [[VLCPrefs alloc] init];
1588 if (!nib_prefs_loaded)
1589 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1604 if (! nib_info_loaded)
1605 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1616 o_wizard = [[VLCWizard alloc] init];
1618 if (!nib_wizard_loaded) {
1619 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1620 [o_wizard initStrings];
1625 - (id)coreDialogProvider
1628 return o_coredialogs;
1633 - (id)eyeTVController
1641 - (id)appleRemoteController
1646 - (BOOL)activeVideoPlayback
1648 return b_active_videoplayback;
1652 #pragma mark Crash Log
1653 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1655 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1656 NSURL *url = [NSURL URLWithString:urlStr];
1658 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1659 [req setHTTPMethod:@"POST"];
1662 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1663 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1664 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1665 email = [emails valueAtIndex:[emails indexForIdentifier:
1666 [emails primaryIdentifier]]];
1669 email = [NSString string];
1672 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1673 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1674 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1675 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1677 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1679 /* Released from delegate */
1680 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1683 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1685 msg_Dbg(p_intf, "crash report successfully sent");
1686 [crashLogURLConnection release];
1687 crashLogURLConnection = nil;
1690 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1692 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1693 [crashLogURLConnection release];
1694 crashLogURLConnection = nil;
1697 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1699 NSString * crashReporter;
1700 if (OSX_MOUNTAIN_LION)
1701 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1703 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1704 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1706 NSString * latestLog = nil;
1707 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1708 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1709 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1710 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1711 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1713 while (fname = [direnum nextObject]) {
1714 [direnum skipDescendents];
1715 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1716 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1717 if ([compo count] < 3)
1719 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1720 if ([compo count] < 4)
1724 if (year < [[compo objectAtIndex:0] intValue] ||
1725 (year ==[[compo objectAtIndex:0] intValue] &&
1726 (month < [[compo objectAtIndex:1] intValue] ||
1727 (month ==[[compo objectAtIndex:1] intValue] &&
1728 (day < [[compo objectAtIndex:2] intValue] ||
1729 (day ==[[compo objectAtIndex:2] intValue] &&
1730 hours < [[compo objectAtIndex:3] intValue])))))) {
1731 year = [[compo objectAtIndex:0] intValue];
1732 month = [[compo objectAtIndex:1] intValue];
1733 day = [[compo objectAtIndex:2] intValue];
1734 hours = [[compo objectAtIndex:3] intValue];
1735 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1740 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1743 if (!previouslySeen) {
1744 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1745 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1746 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1747 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1752 - (NSString *)latestCrashLogPath
1754 return [self latestCrashLogPathPreviouslySeen:YES];
1757 - (void)lookForCrashLog
1759 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1760 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1761 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1762 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1763 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1764 if (latestLog && !areCrashLogsTooOld) {
1765 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1766 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1767 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1768 [NSApp runModalForWindow: o_crashrep_win];
1769 // bail out, the user doesn't want us to send reports
1775 - (IBAction)crashReporterAction:(id)sender
1777 if (sender == o_crashrep_send_btn) {
1778 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1779 if ([o_crashrep_dontaskagain_ckb state])
1780 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1782 if ([o_crashrep_dontaskagain_ckb state])
1783 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1787 [o_crashrep_win orderOut: sender];
1790 - (IBAction)openCrashLog:(id)sender
1792 NSString * latestLog = [self latestCrashLogPath];
1794 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1796 NSBeginInformationalAlertSheet(_NS("No CrashLog found"), _NS("Continue"), nil, nil, o_msgs_panel, self, NULL, NULL, nil, @"%@", _NS("Couldn't find any trace of a previous crash."));
1801 #pragma mark Remove old prefs
1803 - (void)removeOldPreferences
1805 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1806 static const int kCurrentPreferencesVersion = 2;
1807 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1808 int version = [defaults integerForKey:kVLCPreferencesVersion];
1809 if (version >= kCurrentPreferencesVersion)
1813 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1814 [defaults synchronize];
1816 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1819 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1821 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1822 NSUserDomainMask, YES);
1823 if (!libraries || [libraries count] == 0) return;
1824 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1826 /* File not found, don't attempt anything */
1827 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1828 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1829 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1833 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1834 _NS("We just found an older version of VLC's preferences files."),
1835 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1836 if (res != NSOKButton) {
1837 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1841 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1843 /* Move the file to trash so that user can find them later */
1844 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1846 /* really reset the defaults from now on */
1847 [NSUserDefaults resetStandardUserDefaults];
1849 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1850 [defaults synchronize];
1854 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1856 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1861 execl(path, path, NULL);
1865 #pragma mark Errors, warnings and messages
1866 - (IBAction)updateMessagesPanel:(id)sender
1868 [self windowDidBecomeKey:nil];
1871 - (IBAction)showMessagesPanel:(id)sender
1873 [o_msgs_panel makeKeyAndOrderFront: sender];
1876 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1878 [o_msgs_table reloadData];
1879 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1882 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1884 if (aTableView == o_msgs_table)
1885 return [o_msg_arr count];
1889 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1891 NSMutableAttributedString *result = NULL;
1894 if (rowIndex < [o_msg_arr count])
1895 result = [o_msg_arr objectAtIndex: rowIndex];
1896 [o_msg_lock unlock];
1904 - (void)processReceivedlibvlcMessage:(const vlc_log_t *) item ofType: (int)i_type withStr: (char *)str
1907 NSColor *o_white = [NSColor whiteColor];
1908 NSColor *o_red = [NSColor redColor];
1909 NSColor *o_yellow = [NSColor yellowColor];
1910 NSColor *o_gray = [NSColor grayColor];
1911 NSString * firstString, * secondString;
1913 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1914 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1916 NSDictionary *o_attr;
1917 NSMutableAttributedString *o_msg_color;
1921 if ([o_msg_arr count] > 600) {
1922 [o_msg_arr removeObjectAtIndex: 0];
1923 [o_msg_arr removeObjectAtIndex: 1];
1925 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1926 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1928 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1929 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1930 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1931 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1932 [o_msg_arr addObject: [o_msg_color autorelease]];
1934 b_msg_arr_changed = YES;
1935 [o_msg_lock unlock];
1939 - (IBAction)saveDebugLog:(id)sender
1941 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1943 [saveFolderPanel setCanSelectHiddenExtension: NO];
1944 [saveFolderPanel setCanCreateDirectories: YES];
1945 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1946 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1947 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1948 if (returnCode == NSOKButton) {
1949 NSUInteger count = [o_msg_arr count];
1950 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1951 for (NSUInteger i = 0; i < count; i++)
1952 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1954 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1955 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1957 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1958 msg_Warn(p_intf, "Error while saving the debug log");
1963 [saveFolderPanel release];
1967 #pragma mark Playlist toggling
1969 - (void)updateTogglePlaylistState
1971 [[self playlist] outlineViewSelectionDidChange: NULL];
1978 @implementation VLCMain (Internal)
1980 - (void)handlePortMessage:(NSPortMessage *)o_msg
1985 NSInvocation * o_inv;
1986 NSConditionLock * o_lock;
1988 o_data = [[o_msg components] lastObject];
1989 o_inv = *((NSInvocation **)[o_data bytes]);
1990 [o_inv getArgument: &o_value atIndex: 2];
1991 val = (id **)[o_value pointerValue];
1992 [o_inv setArgument: val[1] atIndex: 2];
1997 [o_lock unlockWithCondition: 1];
2000 - (void)resetMediaKeyJump
2002 b_mediakeyJustJumped = NO;
2005 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2007 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
2008 if (b_mediaKeySupport) {
2009 if (!o_mediaKeyController)
2010 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2011 [o_mediaKeyController startWatchingMediaKeys];
2013 else if (!b_mediaKeySupport && o_mediaKeyController)
2014 [o_mediaKeyController stopWatchingMediaKeys];
2019 /*****************************************************************************
2020 * VLCApplication interface
2021 *****************************************************************************/
2023 @implementation VLCApplication
2024 // when user selects the quit menu from dock it sends a terminate:
2025 // but we need to send a stop: to properly exits libvlc.
2026 // However, we are not able to change the action-method sent by this standard menu item.
2027 // thus we override terminate: to send a stop:
2028 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2029 - (void)terminate:(id)sender
2031 [self activateIgnoringOtherApps:YES];