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 */
74 /*****************************************************************************
76 *****************************************************************************/
77 static void Run (intf_thread_t *p_intf);
79 static void updateProgressPanel (void *, const char *, float);
80 static bool checkProgressPanel (void *);
81 static void destroyProgressPanel (void *);
83 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap);
85 static int InputEvent(vlc_object_t *, const char *,
86 vlc_value_t, vlc_value_t, void *);
87 static int PLItemChanged(vlc_object_t *, const char *,
88 vlc_value_t, vlc_value_t, void *);
89 static int PlaylistUpdated(vlc_object_t *, const char *,
90 vlc_value_t, vlc_value_t, void *);
91 static int PlaybackModeUpdated(vlc_object_t *, const char *,
92 vlc_value_t, vlc_value_t, void *);
93 static int VolumeUpdated(vlc_object_t *, const char *,
94 vlc_value_t, vlc_value_t, void *);
97 #pragma mark VLC Interface Object Callbacks
99 /*****************************************************************************
100 * OpenIntf: initialize interface
101 *****************************************************************************/
102 int OpenIntf (vlc_object_t *p_this)
104 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
105 [VLCApplication sharedApplication];
107 intf_thread_t *p_intf = (intf_thread_t*) p_this;
109 p_intf->p_sys = malloc(sizeof(intf_sys_t));
110 if (p_intf->p_sys == NULL)
113 memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
115 /* subscribe to LibVLCCore's messages */
116 vlc_Subscribe(&p_intf->p_sys->sub, MsgCallback, NULL);
124 /*****************************************************************************
125 * CloseIntf: destroy interface
126 *****************************************************************************/
127 void CloseIntf (vlc_object_t *p_this)
129 intf_thread_t *p_intf = (intf_thread_t*) p_this;
134 static int WindowControl(vout_window_t *, int i_query, va_list);
136 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
138 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
139 intf_thread_t *p_intf = VLCIntf;
141 msg_Err(p_wnd, "Mac OS X interface not found");
144 NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
146 VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
147 SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
148 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
149 [inv setTarget:o_vout_controller];
150 [inv setSelector:sel];
151 [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
152 [inv setArgument:&proposedVideoViewPosition atIndex:3];
154 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
157 VLCVoutView *videoView = nil;
158 [inv getReturnValue:&videoView];
161 msg_Err(p_wnd, "got no video view from the interface");
166 msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
167 p_wnd->handle.nsobject = videoView;
170 // TODO: find a cleaner way for "start in fullscreen"
171 if (var_GetBool(pl_Get(VLCIntf), "fullscreen")) {
174 SEL sel = @selector(setFullscreen:forWindow:);
175 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
176 [inv setTarget:[VLCMain sharedInstance]];
177 [inv setSelector:sel];
178 [inv setArgument:&i_full atIndex:2];
179 [inv setArgument:&p_wnd atIndex:3];
180 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
184 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
185 p_wnd->control = WindowControl;
191 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
194 case VOUT_WINDOW_SET_STATE:
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
213 case VOUT_WINDOW_SET_SIZE:
215 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
217 unsigned int i_width = va_arg(args, unsigned int);
218 unsigned int i_height = va_arg(args, unsigned int);
220 NSSize newSize = NSMakeSize(i_width, i_height);
221 SEL sel = @selector(setNativeVideoSize:forWindow:);
222 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
223 [inv setTarget:[[VLCMain sharedInstance] voutController]];
224 [inv setSelector:sel];
225 [inv setArgument:&newSize atIndex:2]; // starting at 2!
226 [inv setArgument:&p_wnd atIndex:3];
227 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
233 case VOUT_WINDOW_SET_FULLSCREEN:
235 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
236 int i_full = va_arg(args, int);
238 SEL sel = @selector(setFullscreen:forWindow:);
239 NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
240 [inv setTarget:[VLCMain sharedInstance]];
241 [inv setSelector:sel];
242 [inv setArgument:&i_full atIndex:2]; // starting at 2!
243 [inv setArgument:&p_wnd atIndex:3];
244 [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
251 msg_Warn(p_wnd, "unsupported control query");
256 void WindowClose(vout_window_t *p_wnd)
258 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
260 [[[VLCMain sharedInstance] voutController] performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
265 /*****************************************************************************
267 *****************************************************************************/
268 static NSLock * o_appLock = nil; // controls access to f_appExit
269 static NSLock * o_plItemChangedLock = nil;
271 static void Run(intf_thread_t *p_intf)
273 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
274 [VLCApplication sharedApplication];
276 o_appLock = [[NSLock alloc] init];
277 o_plItemChangedLock = [[NSLock alloc] init];
279 [[VLCMain sharedInstance] setIntf: p_intf];
280 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
283 [[VLCMain sharedInstance] applicationWillTerminate:nil];
284 [o_plItemChangedLock release];
292 #pragma mark Variables Callback
294 /*****************************************************************************
295 * MsgCallback: Callback triggered by the core once a new debug message is
296 * ready to be displayed. We store everything in a NSArray in our Cocoa part
298 *****************************************************************************/
299 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap)
301 int canc = vlc_savecancel();
304 if (vasprintf(&str, format, ap) == -1) {
305 vlc_restorecancel(canc);
309 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
310 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
313 vlc_restorecancel(canc);
317 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
318 vlc_value_t oldval, vlc_value_t new_val, void *param)
320 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
321 switch (new_val.i_int) {
322 case INPUT_EVENT_STATE:
323 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
325 case INPUT_EVENT_RATE:
326 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
328 case INPUT_EVENT_POSITION:
329 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
331 case INPUT_EVENT_TITLE:
332 case INPUT_EVENT_CHAPTER:
333 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
335 case INPUT_EVENT_CACHE:
336 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
338 case INPUT_EVENT_STATISTICS:
339 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
343 case INPUT_EVENT_TELETEXT:
345 case INPUT_EVENT_AOUT:
347 case INPUT_EVENT_VOUT:
349 case INPUT_EVENT_ITEM_META:
350 case INPUT_EVENT_ITEM_INFO:
351 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
352 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
353 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
355 case INPUT_EVENT_BOOKMARK:
357 case INPUT_EVENT_RECORD:
358 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
360 case INPUT_EVENT_PROGRAM:
361 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
363 case INPUT_EVENT_ITEM_EPG:
365 case INPUT_EVENT_SIGNAL:
368 case INPUT_EVENT_ITEM_NAME:
369 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
370 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
373 case INPUT_EVENT_AUDIO_DELAY:
374 case INPUT_EVENT_SUBTITLE_DELAY:
375 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
378 case INPUT_EVENT_DEAD:
379 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
380 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
383 case INPUT_EVENT_ABORT:
384 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
385 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
389 //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
397 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
398 vlc_value_t oldval, vlc_value_t new_val, void *param)
400 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
402 /* Due to constraints within NSAttributedString's main loop runtime handling
403 * and other issues, we need to wait for -PlaylistItemChanged to finish and
404 * then -informInputChanged on this non-main thread. */
405 [o_plItemChangedLock lock];
406 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES];
407 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(informInputChanged) withObject:nil waitUntilDone:YES];
408 [o_plItemChangedLock unlock];
414 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
415 vlc_value_t oldval, vlc_value_t new_val, void *param)
417 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
418 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
424 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
425 vlc_value_t oldval, vlc_value_t new_val, void *param)
427 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
428 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
434 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
435 vlc_value_t oldval, vlc_value_t new_val, void *param)
437 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
438 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
444 /*****************************************************************************
445 * ShowController: Callback triggered by the show-intf playlist variable
446 * through the ShowIntf-control-intf, to let us show the controller-win;
447 * usually when in fullscreen-mode
448 *****************************************************************************/
449 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
450 vlc_value_t old_val, vlc_value_t new_val, void *param)
452 intf_thread_t * p_intf = VLCIntf;
453 if (p_intf && p_intf->p_sys) {
454 playlist_t * p_playlist = pl_Get(p_intf);
455 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
456 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
457 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
459 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
464 /*****************************************************************************
465 * DialogCallback: Callback triggered by the "dialog-*" variables
466 * to let the intf display error and interaction dialogs
467 *****************************************************************************/
468 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
470 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
471 VLCMain *interface = (VLCMain *)data;
473 if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
474 /* the progress panel needs to update itself and therefore wants special treatment within this context */
475 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
477 p_dialog->pf_update = updateProgressPanel;
478 p_dialog->pf_check = checkProgressPanel;
479 p_dialog->pf_destroy = destroyProgressPanel;
480 p_dialog->p_sys = VLCIntf->p_libvlc;
483 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
484 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
490 void updateProgressPanel (void *priv, const char *text, float value)
492 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
496 o_txt = [NSString stringWithUTF8String: text];
500 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
505 void destroyProgressPanel (void *priv)
507 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
509 if ([[NSApplication sharedApplication] isRunning])
510 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
515 bool checkProgressPanel (void *priv)
517 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
518 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
525 input_thread_t *getInput(void)
527 intf_thread_t *p_intf = VLCIntf;
530 return pl_CurrentInput(p_intf);
533 vout_thread_t *getVout(void)
535 input_thread_t *p_input = getInput();
538 vout_thread_t *p_vout = input_GetVout(p_input);
539 vlc_object_release(p_input);
543 vout_thread_t *getVoutForActiveWindow(void)
545 vout_thread_t *p_vout = nil;
547 id currentWindow = [NSApp keyWindow];
548 if ([currentWindow respondsToSelector:@selector(videoView)]) {
549 VLCVoutView *videoView = [currentWindow videoView];
551 p_vout = [videoView voutThread];
561 audio_output_t *getAout(void)
563 intf_thread_t *p_intf = VLCIntf;
566 return playlist_GetAout(pl_Get(p_intf));
572 @interface VLCMain ()
573 - (void)removeOldPreferences;
576 @interface VLCMain (Internal)
577 - (void)handlePortMessage:(NSPortMessage *)o_msg;
578 - (void)resetMediaKeyJump;
579 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
582 /*****************************************************************************
583 * VLCMain implementation
584 *****************************************************************************/
585 @implementation VLCMain
587 @synthesize voutController=o_vout_controller;
588 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
591 #pragma mark Initialization
593 static VLCMain *_o_sharedMainInstance = nil;
595 + (VLCMain *)sharedInstance
597 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
602 if (_o_sharedMainInstance) {
604 return _o_sharedMainInstance;
606 _o_sharedMainInstance = [super init];
609 p_current_input = p_input_changed = NULL;
611 o_msg_lock = [[NSLock alloc] init];
612 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
614 o_open = [[VLCOpen alloc] init];
615 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
616 o_info = [[VLCInfo alloc] init];
617 o_mainmenu = [[VLCMainMenu alloc] init];
618 o_coreinteraction = [[VLCCoreInteraction alloc] init];
619 o_eyetv = [[VLCEyeTVController alloc] init];
620 o_mainwindow = [[VLCMainWindow alloc] init];
622 /* announce our launch to a potential eyetv plugin */
623 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
624 object: @"VLCEyeTVSupport"
626 deliverImmediately: YES];
628 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
629 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
630 [defaults registerDefaults:appDefaults];
632 o_vout_controller = [[VLCVoutWindowController alloc] init];
634 return _o_sharedMainInstance;
637 - (void)setIntf: (intf_thread_t *)p_mainintf
642 - (intf_thread_t *)intf
649 playlist_t *p_playlist;
652 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
654 /* Check if we already did this once. Opening the other nibs calls it too,
655 because VLCMain is the owner */
659 [o_msgs_panel setExcludedFromWindowsMenu: YES];
660 [o_msgs_panel setDelegate: self];
662 p_playlist = pl_Get(p_intf);
666 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
667 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
668 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
669 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
670 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
671 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
672 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
673 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
674 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
675 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
676 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
677 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
679 if (!OSX_SNOW_LEOPARD) {
680 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
681 var_SetBool(p_playlist, "fullscreen", YES);
684 /* load our Core and Shared Dialogs nibs */
685 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
686 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
688 /* subscribe to various interactive dialogues */
689 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
690 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
691 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
692 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
693 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
694 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
695 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
696 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
697 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
698 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
699 dialog_Register(p_intf);
701 /* init Apple Remote support */
702 o_remote = [[AppleRemote alloc] init];
703 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
704 [o_remote setDelegate: _o_sharedMainInstance];
706 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
708 /* yeah, we are done */
709 b_nativeFullscreenMode = NO;
710 #ifdef MAC_OS_X_VERSION_10_7
711 if (!OSX_SNOW_LEOPARD)
712 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
715 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
716 /* After day 354 of the year, the usual VLC cone is replaced by another cone
717 * wearing a Father Xmas hat.
718 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
720 NSCalendar *gregorian =
721 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
722 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
725 if (dayOfYear >= 354)
726 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
731 nib_main_loaded = TRUE;
734 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
739 [self updateCurrentlyUsedHotkeys];
741 /* init media key support */
742 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
743 if (b_mediaKeySupport) {
744 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
745 [o_mediaKeyController startWatchingMediaKeys];
746 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
747 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
750 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
752 [self removeOldPreferences];
754 /* Handle sleep notification */
755 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
756 name:NSWorkspaceWillSleepNotification object:nil];
758 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
760 /* we will need this, so let's load it here so the interface appears to be more responsive */
761 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
763 /* update the main window */
764 [o_mainwindow updateWindow];
765 [o_mainwindow updateTimeSlider];
766 [o_mainwindow updateVolumeSlider];
775 [o_msgs_panel setTitle: _NS("Messages")];
776 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
777 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
779 /* crash reporter panel */
780 [o_crashrep_send_btn setTitle: _NS("Send")];
781 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
782 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
783 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
784 [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, ...")];
785 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
786 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
787 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
791 #pragma mark Termination
793 - (void)applicationWillTerminate:(NSNotification *)notification
795 /* don't allow a double termination call. If the user has
796 * already invoked the quit then simply return this time. */
797 static bool f_appExit = false;
801 isTerminating = f_appExit;
808 if (notification == nil)
809 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
811 playlist_t * p_playlist = pl_Get(p_intf);
812 int returnedValue = 0;
814 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
815 if (b_nativeFullscreenMode) {
816 [o_mainwindow toggleFullScreen: self];
817 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
820 /* save current video and audio profiles */
821 [[VLCVideoEffects sharedInstance] saveCurrentProfile];
822 [[VLCAudioEffects sharedInstance] saveCurrentProfile];
824 /* Save some interface state in configuration, at module quit */
825 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
826 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
827 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
829 msg_Dbg(p_intf, "Terminating");
831 /* unsubscribe from the interactive dialogues */
832 dialog_Unregister(p_intf);
833 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
834 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
835 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
836 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
837 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
838 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
839 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
840 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
841 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
842 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
843 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
844 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
845 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
846 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
847 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
848 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
849 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
851 if (p_current_input) {
852 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
853 vlc_object_release(p_current_input);
854 p_current_input = NULL;
857 /* remove global observer watching for vout device changes correctly */
858 [[NSNotificationCenter defaultCenter] removeObserver: self];
860 // release before o_info!
861 [o_vout_controller release];
862 o_vout_controller = nil;
864 /* release some other objects here, because it isn't sure whether dealloc
865 * will be called later on */
880 [crashLogURLConnection cancel];
881 [crashLogURLConnection release];
883 [o_coredialogs release];
886 /* unsubscribe from libvlc's debug messages */
887 vlc_Unsubscribe(&p_intf->p_sys->sub);
889 [o_msg_arr removeAllObjects];
892 [o_usedHotkeys release];
893 o_usedHotkeys = NULL;
895 [o_msg_lock release];
897 /* write cached user defaults to disk */
898 [[NSUserDefaults standardUserDefaults] synchronize];
901 [o_mainmenu release];
903 libvlc_Quit(p_intf->p_libvlc);
905 [o_mainwindow release];
912 #pragma mark Sparkle delegate
913 /* received directly before the update gets installed, so let's shut down a bit */
914 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
916 [NSApp activateIgnoringOtherApps:YES];
917 [o_remote stopListening: self];
918 [[VLCCoreInteraction sharedInstance] stop];
922 #pragma mark Media Key support
924 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
926 if (b_mediaKeySupport) {
927 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
929 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
930 int keyFlags = ([event data1] & 0x0000FFFF);
931 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
932 int keyRepeat = (keyFlags & 0x1);
934 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
935 [[VLCCoreInteraction sharedInstance] play];
937 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
938 if (keyState == 0 && keyRepeat == 0)
939 [[VLCCoreInteraction sharedInstance] next];
940 else if (keyRepeat == 1) {
941 [[VLCCoreInteraction sharedInstance] forwardShort];
942 b_mediakeyJustJumped = YES;
943 [self performSelector:@selector(resetMediaKeyJump)
949 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
950 if (keyState == 0 && keyRepeat == 0)
951 [[VLCCoreInteraction sharedInstance] previous];
952 else if (keyRepeat == 1) {
953 [[VLCCoreInteraction sharedInstance] backwardShort];
954 b_mediakeyJustJumped = YES;
955 [self performSelector:@selector(resetMediaKeyJump)
964 #pragma mark Other notification
966 /* Listen to the remote in exclusive mode, only when VLC is the active
968 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
972 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
973 [o_remote startListening: self];
975 - (void)applicationDidResignActive:(NSNotification *)aNotification
979 [o_remote stopListening: self];
982 /* Triggered when the computer goes to sleep */
983 - (void)computerWillSleep: (NSNotification *)notification
985 [[VLCCoreInteraction sharedInstance] pause];
989 #pragma mark File opening over dock icon
991 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
993 BOOL b_autoplay = config_GetInt(VLCIntf, "macosx-autoplay");
994 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
996 // try to add file as subtitle
997 if ([o_names count] == 1 && psz_uri) {
998 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1000 BOOL b_returned = NO;
1001 b_returned = input_AddSubtitle(p_input, psz_uri, true);
1002 vlc_object_release(p_input);
1011 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1012 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1013 for (int i = 0; i < [o_sorted_names count]; i++) {
1014 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file");
1018 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1020 [o_result addObject: o_dic];
1024 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
1026 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
1031 /* When user click in the Dock icon our double click in the finder */
1032 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1034 if (!hasVisibleWindows)
1035 [o_mainwindow makeKeyAndOrderFront:self];
1041 #pragma mark Apple Remote Control
1043 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1044 increase/decrease as long as the user holds the left/right, plus/minus button */
1045 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1047 if (b_remote_button_hold) {
1048 switch([buttonIdentifierNumber intValue]) {
1049 case kRemoteButtonRight_Hold:
1050 [[VLCCoreInteraction sharedInstance] forward];
1052 case kRemoteButtonLeft_Hold:
1053 [[VLCCoreInteraction sharedInstance] backward];
1055 case kRemoteButtonVolume_Plus_Hold:
1056 [[VLCCoreInteraction sharedInstance] volumeUp];
1058 case kRemoteButtonVolume_Minus_Hold:
1059 [[VLCCoreInteraction sharedInstance] volumeDown];
1062 if (b_remote_button_hold) {
1064 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1065 withObject:buttonIdentifierNumber
1071 /* Apple Remote callback */
1072 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1073 pressedDown: (BOOL) pressedDown
1074 clickCount: (unsigned int) count
1076 switch(buttonIdentifier) {
1077 case k2009RemoteButtonFullscreen:
1078 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1080 case k2009RemoteButtonPlay:
1081 [[VLCCoreInteraction sharedInstance] play];
1083 case kRemoteButtonPlay:
1085 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1087 [[VLCCoreInteraction sharedInstance] play];
1089 case kRemoteButtonVolume_Plus:
1090 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1091 [NSSound increaseSystemVolume];
1093 [[VLCCoreInteraction sharedInstance] volumeUp];
1095 case kRemoteButtonVolume_Minus:
1096 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1097 [NSSound decreaseSystemVolume];
1099 [[VLCCoreInteraction sharedInstance] volumeDown];
1101 case kRemoteButtonRight:
1102 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1103 [[VLCCoreInteraction sharedInstance] forward];
1105 [[VLCCoreInteraction sharedInstance] next];
1107 case kRemoteButtonLeft:
1108 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1109 [[VLCCoreInteraction sharedInstance] backward];
1111 [[VLCCoreInteraction sharedInstance] previous];
1113 case kRemoteButtonRight_Hold:
1114 case kRemoteButtonLeft_Hold:
1115 case kRemoteButtonVolume_Plus_Hold:
1116 case kRemoteButtonVolume_Minus_Hold:
1117 /* simulate an event as long as the user holds the button */
1118 b_remote_button_hold = pressedDown;
1120 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1121 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1122 withObject:buttonIdentifierNumber];
1125 case kRemoteButtonMenu:
1126 [o_controls showPosition: self]; //FIXME
1128 case kRemoteButtonPlay_Sleep:
1130 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1131 [script executeAndReturnError:nil];
1136 /* Add here whatever you want other buttons to do */
1142 #pragma mark Key Shortcuts
1144 /*****************************************************************************
1145 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1146 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1147 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1148 *****************************************************************************/
1149 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1153 unsigned int i_pressed_modifiers = 0;
1156 i_pressed_modifiers = [o_event modifierFlags];
1158 if (i_pressed_modifiers & NSControlKeyMask)
1159 val.i_int |= KEY_MODIFIER_CTRL;
1161 if (i_pressed_modifiers & NSAlternateKeyMask)
1162 val.i_int |= KEY_MODIFIER_ALT;
1164 if (i_pressed_modifiers & NSShiftKeyMask)
1165 val.i_int |= KEY_MODIFIER_SHIFT;
1167 if (i_pressed_modifiers & NSCommandKeyMask)
1168 val.i_int |= KEY_MODIFIER_COMMAND;
1170 NSString * characters = [o_event charactersIgnoringModifiers];
1171 if ([characters length] > 0) {
1172 key = [[characters lowercaseString] characterAtIndex: 0];
1174 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1175 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1176 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1182 case NSDeleteCharacter:
1183 case NSDeleteFunctionKey:
1184 case NSDeleteCharFunctionKey:
1185 case NSBackspaceCharacter:
1186 case NSUpArrowFunctionKey:
1187 case NSDownArrowFunctionKey:
1188 case NSEnterCharacter:
1189 case NSCarriageReturnCharacter:
1194 if (key == 0x0020) { // space key
1195 [[VLCCoreInteraction sharedInstance] play];
1199 val.i_int |= CocoaKeyToVLC(key);
1201 BOOL b_found_key = NO;
1202 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1203 NSString *str = [o_usedHotkeys objectAtIndex: i];
1204 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1206 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1207 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1208 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1209 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1210 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1217 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1225 - (void)updateCurrentlyUsedHotkeys
1227 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1228 /* Get the main Module */
1229 module_t *p_main = module_get_main();
1232 module_config_t *p_config;
1234 p_config = module_config_get (p_main, &confsize);
1236 for (size_t i = 0; i < confsize; i++) {
1237 module_config_t *p_item = p_config + i;
1239 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1240 && !strncmp(p_item->psz_name , "key-", 4)
1241 && !EMPTY_STR(p_item->psz_text)) {
1242 if (p_item->value.psz)
1243 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1246 module_config_free (p_config);
1249 [o_usedHotkeys release];
1250 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1251 [o_tempArray release];
1255 #pragma mark Interface updaters
1256 - (void)setFullscreen:(int)i_full forWindow:(vout_window_t *)p_wnd
1258 if (!p_intf || (!b_nativeFullscreenMode && !p_wnd))
1260 playlist_t * p_playlist = pl_Get(p_intf);
1261 BOOL b_fullscreen = i_full;
1263 if (!var_GetBool(p_playlist, "fullscreen") != !b_fullscreen)
1264 var_SetBool(p_playlist, "fullscreen", b_fullscreen);
1266 if (b_nativeFullscreenMode) {
1267 // this is called twice in certain situations, so only toogle if we really need to
1268 if ((b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)) ||
1269 (!b_fullscreen && ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)))
1270 [o_mainwindow toggleFullScreen: self];
1273 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1275 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1280 input_thread_t * p_input = pl_CurrentInput(p_intf);
1281 if (p_input != NULL && [self activeVideoPlayback]) {
1282 // activate app, as method can also be triggered from outside the app (prevents nasty window layout)
1283 [NSApp activateIgnoringOtherApps:YES];
1284 [o_vout_controller updateWindow:p_wnd withSelector:@selector(enterFullscreen)];
1288 vlc_object_release(p_input);
1290 // leaving fullscreen is always allowed
1291 [o_vout_controller updateWindow:p_wnd withSelector:@selector(leaveFullscreen)];
1296 - (void)PlaylistItemChanged
1298 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1299 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1300 p_input_changed = p_current_input;
1301 p_current_input = NULL;
1303 [o_mainmenu setRateControlsEnabled: NO];
1305 else if (!p_current_input) {
1306 // object is hold here and released then it is dead
1307 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1308 if (p_current_input) {
1309 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1310 [self playbackStatusUpdated];
1311 [o_mainmenu setRateControlsEnabled: YES];
1312 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1313 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1314 p_input_changed = vlc_object_hold(p_current_input);
1318 [o_playlist updateRowSelection];
1319 [o_mainwindow updateWindow];
1320 [self updateDelays];
1321 [self updateMainMenu];
1324 - (void)informInputChanged
1326 if (p_input_changed) {
1327 [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1328 vlc_object_release(p_input_changed);
1329 p_input_changed = NULL;
1333 - (void)updateMainMenu
1335 [o_mainmenu setupMenus];
1336 [o_mainmenu updatePlaybackRate];
1337 [[VLCCoreInteraction sharedInstance] resetAtoB];
1340 - (void)updateMainWindow
1342 [o_mainwindow updateWindow];
1345 - (void)showMainWindow
1347 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1350 - (void)showFullscreenController
1352 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1355 - (void)updateDelays
1357 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1362 [o_mainwindow updateName];
1365 - (void)updatePlaybackPosition
1367 [o_mainwindow updateTimeSlider];
1368 [[VLCCoreInteraction sharedInstance] updateAtoB];
1371 - (void)updateVolume
1373 [o_mainwindow updateVolumeSlider];
1376 - (void)playlistUpdated
1378 [self playbackStatusUpdated];
1379 [o_playlist playlistUpdated];
1380 [o_mainwindow updateWindow];
1381 [o_mainwindow updateName];
1384 - (void)updateRecordState: (BOOL)b_value
1386 [o_mainmenu updateRecordState:b_value];
1389 - (void)updateInfoandMetaPanel
1391 [o_playlist outlineViewSelectionDidChange:nil];
1394 - (void)playbackStatusUpdated
1396 input_thread_t * p_input;
1398 p_input = pl_CurrentInput(p_intf);
1400 int state = var_GetInteger(p_input, "state");
1401 if (state == PLAYING_S) {
1402 /* Declare user activity.
1403 This wakes the display if it is off, and postpones display sleep according to the users system preferences
1404 Available from 10.7.3 */
1405 #ifdef MAC_OS_X_VERSION_10_7
1406 if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1408 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1409 IOPMAssertionDeclareUserActivity(reasonForActivity,
1410 kIOPMUserActiveLocal,
1411 &userActivityAssertionID);
1412 CFRelease(reasonForActivity);
1416 /* prevent the system from sleeping */
1417 if (systemSleepAssertionID > 0) {
1418 msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1419 IOPMAssertionRelease(systemSleepAssertionID);
1423 /* 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 */
1424 if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1425 CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1426 if ([self activeVideoPlayback])
1427 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1429 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1430 CFRelease(reasonForActivity);
1432 /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1433 if ([self activeVideoPlayback])
1434 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1436 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1439 if (success == kIOReturnSuccess)
1440 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1442 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1444 [[self mainMenu] setPause];
1445 [o_mainwindow setPause];
1448 [o_mainmenu setSubmenusEnabled: FALSE];
1449 [[self mainMenu] setPlay];
1450 [o_mainwindow setPlay];
1452 /* allow the system to sleep again */
1453 if (systemSleepAssertionID > 0) {
1454 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1455 IOPMAssertionRelease(systemSleepAssertionID);
1458 vlc_object_release(p_input);
1461 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1462 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1465 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1467 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1470 deliverImmediately:YES];
1473 - (void)playbackModeUpdated
1475 vlc_value_t looping,repeating;
1476 playlist_t * p_playlist = pl_Get(VLCIntf);
1478 bool loop = var_GetBool(p_playlist, "loop");
1479 bool repeat = var_GetBool(p_playlist, "repeat");
1481 [[o_mainwindow controlsBar] setRepeatOne];
1482 [o_mainmenu setRepeatOne];
1484 [[o_mainwindow controlsBar] setRepeatAll];
1485 [o_mainmenu setRepeatAll];
1487 [[o_mainwindow controlsBar] setRepeatOff];
1488 [o_mainmenu setRepeatOff];
1491 [[o_mainwindow controlsBar] setShuffle];
1492 [o_mainmenu setShuffle];
1497 #pragma mark Window updater
1501 - (void)setActiveVideoPlayback:(BOOL)b_value
1503 b_active_videoplayback = b_value;
1505 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1506 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1509 // update sleep blockers
1510 [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1514 #pragma mark Other objects getters
1521 - (VLCMainWindow *)mainWindow
1523 return o_mainwindow;
1537 o_bookmarks = [[VLCBookmarks alloc] init];
1539 if (!nib_bookmarks_loaded)
1540 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1550 if (!nib_open_loaded)
1551 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1556 - (id)simplePreferences
1559 o_sprefs = [[VLCSimplePrefs alloc] init];
1561 if (!nib_prefs_loaded)
1562 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1570 o_prefs = [[VLCPrefs alloc] init];
1572 if (!nib_prefs_loaded)
1573 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1588 if (! nib_info_loaded)
1589 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1600 o_wizard = [[VLCWizard alloc] init];
1602 if (!nib_wizard_loaded) {
1603 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1604 [o_wizard initStrings];
1609 - (id)coreDialogProvider
1612 return o_coredialogs;
1617 - (id)eyeTVController
1625 - (id)appleRemoteController
1630 - (BOOL)activeVideoPlayback
1632 return b_active_videoplayback;
1636 #pragma mark Crash Log
1637 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1639 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1640 NSURL *url = [NSURL URLWithString:urlStr];
1642 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1643 [req setHTTPMethod:@"POST"];
1646 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1647 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1648 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1649 email = [emails valueAtIndex:[emails indexForIdentifier:
1650 [emails primaryIdentifier]]];
1653 email = [NSString string];
1656 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1657 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1658 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1659 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1661 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1663 /* Released from delegate */
1664 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1667 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1669 msg_Dbg(p_intf, "crash report successfully sent");
1670 [crashLogURLConnection release];
1671 crashLogURLConnection = nil;
1674 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1676 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1677 [crashLogURLConnection release];
1678 crashLogURLConnection = nil;
1681 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1683 NSString * crashReporter;
1684 if (OSX_MOUNTAIN_LION)
1685 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1687 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1688 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1690 NSString * latestLog = nil;
1691 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1692 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1693 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1694 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1695 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1697 while (fname = [direnum nextObject]) {
1698 [direnum skipDescendents];
1699 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1700 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1701 if ([compo count] < 3)
1703 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1704 if ([compo count] < 4)
1708 if (year < [[compo objectAtIndex:0] intValue] ||
1709 (year ==[[compo objectAtIndex:0] intValue] &&
1710 (month < [[compo objectAtIndex:1] intValue] ||
1711 (month ==[[compo objectAtIndex:1] intValue] &&
1712 (day < [[compo objectAtIndex:2] intValue] ||
1713 (day ==[[compo objectAtIndex:2] intValue] &&
1714 hours < [[compo objectAtIndex:3] intValue])))))) {
1715 year = [[compo objectAtIndex:0] intValue];
1716 month = [[compo objectAtIndex:1] intValue];
1717 day = [[compo objectAtIndex:2] intValue];
1718 hours = [[compo objectAtIndex:3] intValue];
1719 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1724 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1727 if (!previouslySeen) {
1728 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1729 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1730 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1731 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1736 - (NSString *)latestCrashLogPath
1738 return [self latestCrashLogPathPreviouslySeen:YES];
1741 - (void)lookForCrashLog
1743 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1744 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1745 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1746 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1747 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1748 if (latestLog && !areCrashLogsTooOld) {
1749 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1750 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1751 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1752 [NSApp runModalForWindow: o_crashrep_win];
1753 // bail out, the user doesn't want us to send reports
1759 - (IBAction)crashReporterAction:(id)sender
1761 if (sender == o_crashrep_send_btn) {
1762 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1763 if ([o_crashrep_dontaskagain_ckb state])
1764 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1766 if ([o_crashrep_dontaskagain_ckb state])
1767 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1771 [o_crashrep_win orderOut: sender];
1774 - (IBAction)openCrashLog:(id)sender
1776 NSString * latestLog = [self latestCrashLogPath];
1778 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1780 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."));
1785 #pragma mark Remove old prefs
1787 - (void)removeOldPreferences
1789 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1790 static const int kCurrentPreferencesVersion = 2;
1791 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1792 int version = [defaults integerForKey:kVLCPreferencesVersion];
1793 if (version >= kCurrentPreferencesVersion)
1797 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1798 [defaults synchronize];
1800 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1803 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1805 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1806 NSUserDomainMask, YES);
1807 if (!libraries || [libraries count] == 0) return;
1808 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1810 /* File not found, don't attempt anything */
1811 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1812 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1813 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1817 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1818 _NS("We just found an older version of VLC's preferences files."),
1819 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1820 if (res != NSOKButton) {
1821 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1825 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1827 /* Move the file to trash so that user can find them later */
1828 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1830 /* really reset the defaults from now on */
1831 [NSUserDefaults resetStandardUserDefaults];
1833 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1834 [defaults synchronize];
1838 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1840 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1845 execl(path, path, NULL);
1849 #pragma mark Errors, warnings and messages
1850 - (IBAction)updateMessagesPanel:(id)sender
1852 [self windowDidBecomeKey:nil];
1855 - (IBAction)showMessagesPanel:(id)sender
1857 [o_msgs_panel makeKeyAndOrderFront: sender];
1860 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1862 [o_msgs_table reloadData];
1863 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1866 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1868 if (aTableView == o_msgs_table)
1869 return [o_msg_arr count];
1873 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1875 NSMutableAttributedString *result = NULL;
1878 if (rowIndex < [o_msg_arr count])
1879 result = [o_msg_arr objectAtIndex: rowIndex];
1880 [o_msg_lock unlock];
1888 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1891 NSColor *o_white = [NSColor whiteColor];
1892 NSColor *o_red = [NSColor redColor];
1893 NSColor *o_yellow = [NSColor yellowColor];
1894 NSColor *o_gray = [NSColor grayColor];
1895 NSString * firstString, * secondString;
1897 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1898 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1900 NSDictionary *o_attr;
1901 NSMutableAttributedString *o_msg_color;
1905 if ([o_msg_arr count] > 600) {
1906 [o_msg_arr removeObjectAtIndex: 0];
1907 [o_msg_arr removeObjectAtIndex: 1];
1909 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1910 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1912 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1913 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1914 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1915 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1916 [o_msg_arr addObject: [o_msg_color autorelease]];
1918 b_msg_arr_changed = YES;
1919 [o_msg_lock unlock];
1923 - (IBAction)saveDebugLog:(id)sender
1925 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1927 [saveFolderPanel setCanSelectHiddenExtension: NO];
1928 [saveFolderPanel setCanCreateDirectories: YES];
1929 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1930 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1931 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1932 if (returnCode == NSOKButton) {
1933 NSUInteger count = [o_msg_arr count];
1934 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1935 for (NSUInteger i = 0; i < count; i++)
1936 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1938 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1939 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1941 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1942 msg_Warn(p_intf, "Error while saving the debug log");
1947 [saveFolderPanel release];
1951 #pragma mark Playlist toggling
1953 - (void)updateTogglePlaylistState
1955 [[self playlist] outlineViewSelectionDidChange: NULL];
1962 @implementation VLCMain (Internal)
1964 - (void)handlePortMessage:(NSPortMessage *)o_msg
1969 NSInvocation * o_inv;
1970 NSConditionLock * o_lock;
1972 o_data = [[o_msg components] lastObject];
1973 o_inv = *((NSInvocation **)[o_data bytes]);
1974 [o_inv getArgument: &o_value atIndex: 2];
1975 val = (id **)[o_value pointerValue];
1976 [o_inv setArgument: val[1] atIndex: 2];
1981 [o_lock unlockWithCondition: 1];
1984 - (void)resetMediaKeyJump
1986 b_mediakeyJustJumped = NO;
1989 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1991 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1992 if (b_mediaKeySupport) {
1993 if (!o_mediaKeyController)
1994 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1995 [o_mediaKeyController startWatchingMediaKeys];
1997 else if (!b_mediaKeySupport && o_mediaKeyController)
1998 [o_mediaKeyController stopWatchingMediaKeys];
2003 /*****************************************************************************
2004 * VLCApplication interface
2005 *****************************************************************************/
2007 @implementation VLCApplication
2008 // when user selects the quit menu from dock it sends a terminate:
2009 // but we need to send a stop: to properly exits libvlc.
2010 // However, we are not able to change the action-method sent by this standard menu item.
2011 // thus we override terminate: to send a stop:
2012 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2013 - (void)terminate:(id)sender
2015 [self activateIgnoringOtherApps:YES];