1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2012 VLC authors and VideoLAN
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
34 #include <stdlib.h> /* malloc(), free() */
35 #include <sys/param.h> /* for MAXPATHLEN */
37 #include <vlc_common.h>
39 #include <vlc_dialog.h>
41 #include <vlc_modules.h>
42 #include <vlc_plugin.h>
43 #include <vlc_aout_intf.h>
44 #include <vlc_vout_window.h>
45 #include <vlc_vout_display.h>
46 #include <unistd.h> /* execl() */
48 #import "CompatibilityFixes.h"
50 #import "StringUtility.h"
55 #import "playlistinfo.h"
60 #import "coredialogs.h"
61 #import "AppleRemote.h"
63 #import "simple_prefs.h"
64 #import "CoreInteraction.h"
65 #import "TrackSynchronization.h"
67 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
68 #import <Sparkle/Sparkle.h> /* we're the update delegate */
70 /*****************************************************************************
72 *****************************************************************************/
73 static void Run (intf_thread_t *p_intf);
75 static void updateProgressPanel (void *, const char *, float);
76 static bool checkProgressPanel (void *);
77 static void destroyProgressPanel (void *);
79 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap);
81 static int InputEvent(vlc_object_t *, const char *,
82 vlc_value_t, vlc_value_t, void *);
83 static int PLItemChanged(vlc_object_t *, const char *,
84 vlc_value_t, vlc_value_t, void *);
85 static int PlaylistUpdated(vlc_object_t *, const char *,
86 vlc_value_t, vlc_value_t, void *);
87 static int PlaybackModeUpdated(vlc_object_t *, const char *,
88 vlc_value_t, vlc_value_t, void *);
89 static int VolumeUpdated(vlc_object_t *, const char *,
90 vlc_value_t, vlc_value_t, void *);
93 #pragma mark VLC Interface Object Callbacks
95 /*****************************************************************************
96 * OpenIntf: initialize interface
97 *****************************************************************************/
98 int OpenIntf (vlc_object_t *p_this)
100 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
101 [VLCApplication sharedApplication];
103 intf_thread_t *p_intf = (intf_thread_t*) p_this;
105 p_intf->p_sys = malloc(sizeof(intf_sys_t));
106 if (p_intf->p_sys == NULL)
109 memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
111 /* subscribe to LibVLCCore's messages */
112 vlc_Subscribe(&p_intf->p_sys->sub, MsgCallback, NULL);
120 /*****************************************************************************
121 * CloseIntf: destroy interface
122 *****************************************************************************/
123 void CloseIntf (vlc_object_t *p_this)
125 intf_thread_t *p_intf = (intf_thread_t*) p_this;
130 static int WindowControl(vout_window_t *, int i_query, va_list);
132 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
134 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
135 intf_thread_t *p_intf = VLCIntf;
137 msg_Err(p_wnd, "Mac OS X interface not found");
143 unsigned i_width = cfg->width;
144 unsigned i_height = cfg->height;
145 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
147 if (!p_wnd->handle.nsobject) {
148 msg_Err(p_wnd, "got no video view from the interface");
153 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize(cfg->width, cfg->height)];
154 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
155 p_wnd->control = WindowControl;
156 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
161 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
164 case VOUT_WINDOW_SET_STATE:
166 unsigned i_state = va_arg(args, unsigned);
167 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:i_state] waitUntilDone:NO];
170 case VOUT_WINDOW_SET_SIZE:
172 unsigned int i_width = va_arg(args, unsigned int);
173 unsigned int i_height = va_arg(args, unsigned int);
174 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize(i_width, i_height)];
177 case VOUT_WINDOW_SET_FULLSCREEN:
179 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
180 int i_full = va_arg(args, int);
181 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(checkFullscreenChange:) withObject:[NSNumber numberWithInt: i_full] waitUntilDone:NO];
186 msg_Warn(p_wnd, "unsupported control query");
191 void WindowClose(vout_window_t *p_wnd)
193 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
194 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
199 /*****************************************************************************
201 *****************************************************************************/
202 static NSLock * o_appLock = nil; // controls access to f_appExit
204 static void Run(intf_thread_t *p_intf)
206 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
207 [VLCApplication sharedApplication];
209 o_appLock = [[NSLock alloc] init];
211 [[VLCMain sharedInstance] setIntf: p_intf];
212 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
215 [[VLCMain sharedInstance] applicationWillTerminate:nil];
223 #pragma mark Variables Callback
225 /*****************************************************************************
226 * MsgCallback: Callback triggered by the core once a new debug message is
227 * ready to be displayed. We store everything in a NSArray in our Cocoa part
229 *****************************************************************************/
230 static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap)
232 int canc = vlc_savecancel();
235 if (vasprintf(&str, format, ap) == -1) {
236 vlc_restorecancel(canc);
240 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
241 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
244 vlc_restorecancel(canc);
248 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
249 vlc_value_t oldval, vlc_value_t new_val, void *param)
251 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
252 switch (new_val.i_int) {
253 case INPUT_EVENT_STATE:
254 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
256 case INPUT_EVENT_RATE:
257 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
259 case INPUT_EVENT_POSITION:
260 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
262 case INPUT_EVENT_TITLE:
263 case INPUT_EVENT_CHAPTER:
264 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
266 case INPUT_EVENT_CACHE:
267 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
269 case INPUT_EVENT_STATISTICS:
270 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
274 case INPUT_EVENT_TELETEXT:
276 case INPUT_EVENT_AOUT:
278 case INPUT_EVENT_VOUT:
280 case INPUT_EVENT_ITEM_META:
281 case INPUT_EVENT_ITEM_INFO:
282 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
283 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
284 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
286 case INPUT_EVENT_BOOKMARK:
288 case INPUT_EVENT_RECORD:
289 [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
291 case INPUT_EVENT_PROGRAM:
292 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
294 case INPUT_EVENT_ITEM_EPG:
296 case INPUT_EVENT_SIGNAL:
299 case INPUT_EVENT_ITEM_NAME:
300 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
301 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
304 case INPUT_EVENT_AUDIO_DELAY:
305 case INPUT_EVENT_SUBTITLE_DELAY:
306 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
309 case INPUT_EVENT_DEAD:
310 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
311 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
314 case INPUT_EVENT_ABORT:
315 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
316 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
320 //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
328 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
329 vlc_value_t oldval, vlc_value_t new_val, void *param)
331 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
332 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
338 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
339 vlc_value_t oldval, vlc_value_t new_val, void *param)
341 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
342 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
348 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
349 vlc_value_t oldval, vlc_value_t new_val, void *param)
351 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
352 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
358 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
359 vlc_value_t oldval, vlc_value_t new_val, void *param)
361 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
362 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
368 /*****************************************************************************
369 * ShowController: Callback triggered by the show-intf playlist variable
370 * through the ShowIntf-control-intf, to let us show the controller-win;
371 * usually when in fullscreen-mode
372 *****************************************************************************/
373 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
374 vlc_value_t old_val, vlc_value_t new_val, void *param)
376 intf_thread_t * p_intf = VLCIntf;
377 if (p_intf && p_intf->p_sys) {
378 playlist_t * p_playlist = pl_Get(p_intf);
379 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
380 if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
381 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
383 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
388 /*****************************************************************************
389 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
390 * variable, to let the intf update the controller.
391 *****************************************************************************/
392 static int FullscreenChanged(vlc_object_t *p_this, const char *psz_variable,
393 vlc_value_t old_val, vlc_value_t new_val, void *param)
395 intf_thread_t * p_intf = VLCIntf;
397 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
398 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
404 /*****************************************************************************
405 * DialogCallback: Callback triggered by the "dialog-*" variables
406 * to let the intf display error and interaction dialogs
407 *****************************************************************************/
408 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
410 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
411 VLCMain *interface = (VLCMain *)data;
413 if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
414 /* the progress panel needs to update itself and therefore wants special treatment within this context */
415 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
417 p_dialog->pf_update = updateProgressPanel;
418 p_dialog->pf_check = checkProgressPanel;
419 p_dialog->pf_destroy = destroyProgressPanel;
420 p_dialog->p_sys = VLCIntf->p_libvlc;
423 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
424 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
430 void updateProgressPanel (void *priv, const char *text, float value)
432 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
436 o_txt = [NSString stringWithUTF8String: text];
440 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
445 void destroyProgressPanel (void *priv)
447 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
448 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
452 bool checkProgressPanel (void *priv)
454 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
455 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
462 input_thread_t *getInput(void)
464 intf_thread_t *p_intf = VLCIntf;
467 return pl_CurrentInput(p_intf);
470 vout_thread_t *getVout(void)
472 input_thread_t *p_input = getInput();
475 vout_thread_t *p_vout = input_GetVout(p_input);
476 vlc_object_release(p_input);
480 audio_output_t *getAout(void)
482 input_thread_t *p_input = getInput();
485 audio_output_t *p_aout = input_GetAout(p_input);
486 vlc_object_release(p_input);
493 @interface VLCMain ()
494 - (void)_removeOldPreferences;
497 /*****************************************************************************
498 * VLCMain implementation
499 *****************************************************************************/
500 @implementation VLCMain
503 #pragma mark Initialization
505 static VLCMain *_o_sharedMainInstance = nil;
507 + (VLCMain *)sharedInstance
509 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
514 if (_o_sharedMainInstance) {
516 return _o_sharedMainInstance;
518 _o_sharedMainInstance = [super init];
521 p_current_input = NULL;
523 o_msg_lock = [[NSLock alloc] init];
524 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
526 o_open = [[VLCOpen alloc] init];
527 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
528 o_info = [[VLCInfo alloc] init];
529 o_mainmenu = [[VLCMainMenu alloc] init];
530 o_coreinteraction = [[VLCCoreInteraction alloc] init];
531 o_eyetv = [[VLCEyeTVController alloc] init];
532 o_mainwindow = [[VLCMainWindow alloc] init];
534 /* announce our launch to a potential eyetv plugin */
535 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
536 object: @"VLCEyeTVSupport"
538 deliverImmediately: YES];
540 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
541 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
542 [defaults registerDefaults:appDefaults];
544 return _o_sharedMainInstance;
547 - (void)setIntf: (intf_thread_t *)p_mainintf
552 - (intf_thread_t *)intf
559 playlist_t *p_playlist;
562 var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
564 /* Check if we already did this once. Opening the other nibs calls it too,
565 because VLCMain is the owner */
569 [o_msgs_panel setExcludedFromWindowsMenu: YES];
570 [o_msgs_panel setDelegate: self];
572 p_playlist = pl_Get(p_intf);
576 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
577 var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
578 var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
579 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
580 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
581 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
582 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
583 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
584 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
585 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
586 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
587 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
588 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
589 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
591 if (!OSX_SNOW_LEOPARD) {
592 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
593 var_SetBool(p_playlist, "fullscreen", YES);
596 /* load our Core and Shared Dialogs nibs */
597 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
598 [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
600 /* subscribe to various interactive dialogues */
601 var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
602 var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
603 var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
604 var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
605 var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
606 var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
607 var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
608 var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
609 var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
610 var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
611 dialog_Register(p_intf);
613 /* init Apple Remote support */
614 o_remote = [[AppleRemote alloc] init];
615 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
616 [o_remote setDelegate: _o_sharedMainInstance];
618 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
620 /* yeah, we are done */
621 b_nativeFullscreenMode = NO;
622 #ifdef MAC_OS_X_VERSION_10_7
623 if (!OSX_SNOW_LEOPARD)
624 b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
627 /* recover stored audio device, if set
628 * in case it was unplugged in the meantime, auhal will fall back on the default */
629 int i_value = config_GetInt(p_intf, "macosx-audio-device");
631 var_SetInteger(pl_Get(VLCIntf), "audio-device", i_value);
633 if (config_GetInt(VLCIntf, "macosx-icon-change")) {
634 /* After day 354 of the year, the usual VLC cone is replaced by another cone
635 * wearing a Father Xmas hat.
636 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
638 NSCalendar *gregorian =
639 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
640 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
643 if (dayOfYear >= 354)
644 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
649 nib_main_loaded = TRUE;
652 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
657 [self updateCurrentlyUsedHotkeys];
659 /* init media key support */
660 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
661 if (b_mediaKeySupport) {
662 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
663 [o_mediaKeyController startWatchingMediaKeys];
664 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
665 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
668 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
670 [self _removeOldPreferences];
672 /* Handle sleep notification */
673 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
674 name:NSWorkspaceWillSleepNotification object:nil];
676 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
678 /* we will need this, so let's load it here so the interface appears to be more responsive */
679 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
681 /* update the main window */
682 [o_mainwindow updateWindow];
683 [o_mainwindow updateTimeSlider];
684 [o_mainwindow updateVolumeSlider];
693 [o_msgs_panel setTitle: _NS("Messages")];
694 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
695 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
697 /* crash reporter panel */
698 [o_crashrep_send_btn setTitle: _NS("Send")];
699 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
700 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
701 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
702 [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, ...")];
703 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
704 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
705 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
709 #pragma mark Termination
711 - (void)applicationWillTerminate:(NSNotification *)notification
713 /* don't allow a double termination call. If the user has
714 * already invoked the quit then simply return this time. */
715 static bool f_appExit = false;
719 isTerminating = f_appExit;
726 if (notification == nil)
727 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
729 playlist_t * p_playlist = pl_Get(p_intf);
730 int returnedValue = 0;
732 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
733 if (b_nativeFullscreenMode) {
734 [o_mainwindow toggleFullScreen: self];
735 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
738 /* Save some interface state in configuration, at module quit */
739 config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
740 config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
741 config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
743 msg_Dbg(p_intf, "Terminating");
745 /* unsubscribe from the interactive dialogues */
746 dialog_Unregister(p_intf);
747 var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
748 var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
749 var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
750 var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
751 var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
752 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
753 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
754 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
755 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
756 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
757 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
758 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
759 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
760 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
761 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
762 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
763 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
764 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
765 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
767 if (p_current_input) {
768 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
769 vlc_object_release(p_current_input);
770 p_current_input = NULL;
773 /* remove global observer watching for vout device changes correctly */
774 [[NSNotificationCenter defaultCenter] removeObserver: self];
776 /* release some other objects here, because it isn't sure whether dealloc
777 * will be called later on */
792 [crashLogURLConnection cancel];
793 [crashLogURLConnection release];
795 [o_coredialogs release];
798 /* unsubscribe from libvlc's debug messages */
799 vlc_Unsubscribe(&p_intf->p_sys->sub);
801 [o_msg_arr removeAllObjects];
804 [o_usedHotkeys release];
805 o_usedHotkeys = NULL;
807 [o_msg_lock release];
809 /* write cached user defaults to disk */
810 [[NSUserDefaults standardUserDefaults] synchronize];
812 [o_mainmenu release];
814 libvlc_Quit(p_intf->p_libvlc);
816 [o_mainwindow release];
823 #pragma mark Sparkle delegate
824 /* received directly before the update gets installed, so let's shut down a bit */
825 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
827 [NSApp activateIgnoringOtherApps:YES];
828 [o_remote stopListening: self];
829 [[VLCCoreInteraction sharedInstance] stop];
833 #pragma mark Media Key support
835 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
837 if (b_mediaKeySupport) {
838 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
840 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
841 int keyFlags = ([event data1] & 0x0000FFFF);
842 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
843 int keyRepeat = (keyFlags & 0x1);
845 if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
846 [[VLCCoreInteraction sharedInstance] play];
848 if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
849 if (keyState == 0 && keyRepeat == 0)
850 [[VLCCoreInteraction sharedInstance] next];
851 else if (keyRepeat == 1) {
852 [[VLCCoreInteraction sharedInstance] forwardShort];
853 b_mediakeyJustJumped = YES;
854 [self performSelector:@selector(resetMediaKeyJump)
860 if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
861 if (keyState == 0 && keyRepeat == 0)
862 [[VLCCoreInteraction sharedInstance] previous];
863 else if (keyRepeat == 1) {
864 [[VLCCoreInteraction sharedInstance] backwardShort];
865 b_mediakeyJustJumped = YES;
866 [self performSelector:@selector(resetMediaKeyJump)
875 #pragma mark Other notification
877 /* Listen to the remote in exclusive mode, only when VLC is the active
879 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
883 if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
884 [o_remote startListening: self];
886 - (void)applicationDidResignActive:(NSNotification *)aNotification
890 [o_remote stopListening: self];
893 /* Triggered when the computer goes to sleep */
894 - (void)computerWillSleep: (NSNotification *)notification
896 [[VLCCoreInteraction sharedInstance] pause];
900 #pragma mark File opening over dock icon
902 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
904 BOOL b_autoplay = config_GetInt(VLCIntf, "macosx-autoplay");
905 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
907 // try to add file as subtitle
908 if ([o_names count] == 1 && psz_uri) {
909 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
911 BOOL b_returned = NO;
912 b_returned = input_AddSubtitle(p_input, psz_uri, true);
913 vlc_object_release(p_input);
922 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
923 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
924 for (int i = 0; i < [o_sorted_names count]; i++) {
925 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file");
929 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
931 [o_result addObject: o_dic];
935 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
937 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
942 /* When user click in the Dock icon our double click in the finder */
943 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
945 if (!hasVisibleWindows)
946 [o_mainwindow makeKeyAndOrderFront:self];
952 #pragma mark Apple Remote Control
954 /* Helper method for the remote control interface in order to trigger forward/backward and volume
955 increase/decrease as long as the user holds the left/right, plus/minus button */
956 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
958 if (b_remote_button_hold) {
959 switch([buttonIdentifierNumber intValue]) {
960 case kRemoteButtonRight_Hold:
961 [[VLCCoreInteraction sharedInstance] forward];
963 case kRemoteButtonLeft_Hold:
964 [[VLCCoreInteraction sharedInstance] backward];
966 case kRemoteButtonVolume_Plus_Hold:
968 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
970 case kRemoteButtonVolume_Minus_Hold:
972 var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
975 if (b_remote_button_hold) {
977 [self performSelector:@selector(executeHoldActionForRemoteButton:)
978 withObject:buttonIdentifierNumber
984 /* Apple Remote callback */
985 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
986 pressedDown: (BOOL) pressedDown
987 clickCount: (unsigned int) count
989 switch(buttonIdentifier) {
990 case k2009RemoteButtonFullscreen:
991 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
993 case k2009RemoteButtonPlay:
994 [[VLCCoreInteraction sharedInstance] play];
996 case kRemoteButtonPlay:
998 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1000 [[VLCCoreInteraction sharedInstance] play];
1002 case kRemoteButtonVolume_Plus:
1003 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1004 [NSSound increaseSystemVolume];
1006 [[VLCCoreInteraction sharedInstance] volumeUp];
1008 case kRemoteButtonVolume_Minus:
1009 if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1010 [NSSound decreaseSystemVolume];
1012 [[VLCCoreInteraction sharedInstance] volumeDown];
1014 case kRemoteButtonRight:
1015 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1016 [[VLCCoreInteraction sharedInstance] forward];
1018 [[VLCCoreInteraction sharedInstance] next];
1020 case kRemoteButtonLeft:
1021 if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1022 [[VLCCoreInteraction sharedInstance] backward];
1024 [[VLCCoreInteraction sharedInstance] previous];
1026 case kRemoteButtonRight_Hold:
1027 case kRemoteButtonLeft_Hold:
1028 case kRemoteButtonVolume_Plus_Hold:
1029 case kRemoteButtonVolume_Minus_Hold:
1030 /* simulate an event as long as the user holds the button */
1031 b_remote_button_hold = pressedDown;
1033 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1034 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1035 withObject:buttonIdentifierNumber];
1038 case kRemoteButtonMenu:
1039 [o_controls showPosition: self]; //FIXME
1041 case kRemoteButtonPlay_Sleep:
1043 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1044 [script executeAndReturnError:nil];
1049 /* Add here whatever you want other buttons to do */
1055 #pragma mark Key Shortcuts
1057 /*****************************************************************************
1058 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1059 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1060 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1061 *****************************************************************************/
1062 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1066 unsigned int i_pressed_modifiers = 0;
1069 i_pressed_modifiers = [o_event modifierFlags];
1071 if (i_pressed_modifiers & NSControlKeyMask)
1072 val.i_int |= KEY_MODIFIER_CTRL;
1074 if (i_pressed_modifiers & NSAlternateKeyMask)
1075 val.i_int |= KEY_MODIFIER_ALT;
1077 if (i_pressed_modifiers & NSShiftKeyMask)
1078 val.i_int |= KEY_MODIFIER_SHIFT;
1080 if (i_pressed_modifiers & NSCommandKeyMask)
1081 val.i_int |= KEY_MODIFIER_COMMAND;
1083 NSString * characters = [o_event charactersIgnoringModifiers];
1084 if ([characters length] > 0) {
1085 key = [[characters lowercaseString] characterAtIndex: 0];
1087 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1088 if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1089 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1095 case NSDeleteCharacter:
1096 case NSDeleteFunctionKey:
1097 case NSDeleteCharFunctionKey:
1098 case NSBackspaceCharacter:
1099 case NSUpArrowFunctionKey:
1100 case NSDownArrowFunctionKey:
1101 case NSRightArrowFunctionKey:
1102 case NSLeftArrowFunctionKey:
1103 case NSEnterCharacter:
1104 case NSCarriageReturnCharacter:
1109 if (key == 0x0020) { // space key
1110 [[VLCCoreInteraction sharedInstance] play];
1114 val.i_int |= CocoaKeyToVLC(key);
1116 BOOL b_found_key = NO;
1117 for (int i = 0; i < [o_usedHotkeys count]; i++) {
1118 NSString *str = [o_usedHotkeys objectAtIndex: i];
1119 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1121 if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1122 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1123 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1124 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1125 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask)) {
1132 var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1140 - (void)updateCurrentlyUsedHotkeys
1142 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1143 /* Get the main Module */
1144 module_t *p_main = module_get_main();
1147 module_config_t *p_config;
1149 p_config = module_config_get (p_main, &confsize);
1151 for (size_t i = 0; i < confsize; i++) {
1152 module_config_t *p_item = p_config + i;
1154 if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1155 && !strncmp(p_item->psz_name , "key-", 4)
1156 && !EMPTY_STR(p_item->psz_text)) {
1157 if (p_item->value.psz)
1158 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1161 module_config_free (p_config);
1164 [o_usedHotkeys release];
1165 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1166 [o_tempArray release];
1170 #pragma mark Interface updaters
1171 - (void)fullscreenChanged
1173 playlist_t * p_playlist = pl_Get(VLCIntf);
1174 BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
1176 if (b_nativeFullscreenMode) {
1177 // this is called twice in certain situations, so only toogle if we really need to
1178 if ((b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)) ||
1179 (!b_fullscreen && ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)))
1180 [o_mainwindow toggleFullScreen: self];
1183 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1185 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1188 input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1189 if (p_input != NULL && [self activeVideoPlayback]) {
1190 // activate app, as method can also be triggered from outside the app (prevents nasty window layout)
1191 [NSApp activateIgnoringOtherApps:YES];
1192 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1195 vlc_object_release(p_input);
1197 // leaving fullscreen is always allowed
1198 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1203 - (void)checkFullscreenChange:(NSNumber *)o_full
1205 BOOL b_full = [o_full boolValue];
1206 if (p_intf && !var_GetBool(pl_Get(p_intf), "fullscreen") != !b_full) {
1207 var_SetBool(pl_Get(p_intf), "fullscreen", b_full);
1211 - (void)PlaylistItemChanged
1213 if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1214 var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1215 vlc_object_release(p_current_input);
1216 p_current_input = NULL;
1218 [o_mainmenu setRateControlsEnabled: NO];
1220 else if (!p_current_input) {
1221 // object is hold here and released then it is dead
1222 p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1223 if (p_current_input) {
1224 var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1225 [self playbackStatusUpdated];
1226 [o_mainmenu setRateControlsEnabled: YES];
1227 if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1228 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1232 [o_playlist updateRowSelection];
1233 [o_mainwindow updateWindow];
1234 [self updateDelays];
1235 [self updateMainMenu];
1238 - (void)updateMainMenu
1240 [o_mainmenu setupMenus];
1241 [o_mainmenu updatePlaybackRate];
1244 - (void)updateMainWindow
1246 [o_mainwindow updateWindow];
1249 - (void)showMainWindow
1251 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1254 - (void)showFullscreenController
1256 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1259 - (void)updateDelays
1261 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1266 [o_mainwindow updateName];
1269 - (void)updatePlaybackPosition
1271 [o_mainwindow updateTimeSlider];
1274 - (void)updateVolume
1276 [o_mainwindow updateVolumeSlider];
1279 - (void)playlistUpdated
1281 [self playbackStatusUpdated];
1282 [o_playlist playlistUpdated];
1283 [o_mainwindow updateWindow];
1284 [o_mainwindow updateName];
1287 - (void)updateRecordState: (BOOL)b_value
1289 [o_mainmenu updateRecordState:b_value];
1292 - (void)updateInfoandMetaPanel
1294 [o_playlist outlineViewSelectionDidChange:nil];
1297 - (void)playbackStatusUpdated
1299 input_thread_t * p_input;
1301 p_input = pl_CurrentInput(p_intf);
1303 int state = var_GetInteger(p_input, "state");
1304 if (state == PLAYING_S) {
1305 /* prevent the system from sleeping */
1307 CFStringRef reasonForActivity= CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1308 if ([self activeVideoPlayback])
1309 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1311 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1312 CFRelease(reasonForActivity);
1314 if (success == kIOReturnSuccess)
1315 msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1317 msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1319 [[self mainMenu] setPause];
1320 [o_mainwindow setPause];
1323 [o_mainmenu setSubmenusEnabled: FALSE];
1324 [[self mainMenu] setPlay];
1325 [o_mainwindow setPlay];
1327 /* allow the system to sleep again */
1328 msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1329 IOPMAssertionRelease(systemSleepAssertionID);
1331 vlc_object_release(p_input);
1334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1335 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1338 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1340 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1343 deliverImmediately:YES];
1346 - (void)playbackModeUpdated
1348 vlc_value_t looping,repeating;
1349 playlist_t * p_playlist = pl_Get(VLCIntf);
1351 bool loop = var_GetBool(p_playlist, "loop");
1352 bool repeat = var_GetBool(p_playlist, "repeat");
1354 [o_mainwindow setRepeatOne];
1355 [o_mainmenu setRepeatOne];
1357 [o_mainwindow setRepeatAll];
1358 [o_mainmenu setRepeatAll];
1360 [o_mainwindow setRepeatOff];
1361 [o_mainmenu setRepeatOff];
1364 [o_mainwindow setShuffle];
1365 [o_mainmenu setShuffle];
1370 #pragma mark Window updater
1372 - (void)setWindowLevel:(NSNumber*)state
1374 if (var_InheritBool(p_intf, "video-wallpaper") || [[[[VLCMainWindow sharedInstance] videoView] window] level] < NSNormalWindowLevel)
1377 if ([state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE)
1378 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSStatusWindowLevel];
1380 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSNormalWindowLevel];
1383 - (void)setActiveVideoPlayback:(BOOL)b_value
1385 b_active_videoplayback = b_value;
1387 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1388 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1392 - (void)setNativeVideoSize:(NSSize)size
1394 [o_mainwindow setNativeVideoSize:size];
1398 #pragma mark Other objects getters
1407 return o_mainwindow;
1421 o_bookmarks = [[VLCBookmarks alloc] init];
1423 if (!nib_bookmarks_loaded)
1424 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1434 if (!nib_open_loaded)
1435 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1440 - (id)simplePreferences
1443 o_sprefs = [[VLCSimplePrefs alloc] init];
1445 if (!nib_prefs_loaded)
1446 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1454 o_prefs = [[VLCPrefs alloc] init];
1456 if (!nib_prefs_loaded)
1457 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1472 if (! nib_info_loaded)
1473 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1484 o_wizard = [[VLCWizard alloc] init];
1486 if (!nib_wizard_loaded) {
1487 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1488 [o_wizard initStrings];
1493 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1495 [o_mainwindow performSelectorOnMainThread:@selector(setupVideoView) withObject:nil waitUntilDone:YES];
1496 id videoView = [o_mainwindow videoView];
1497 NSRect videoRect = [videoView frame];
1498 int i_x = (int)videoRect.origin.x;
1499 int i_y = (int)videoRect.origin.y;
1500 unsigned int i_width = (int)videoRect.size.width;
1501 unsigned int i_height = (int)videoRect.size.height;
1504 pi_width = &i_width;
1505 pi_height = &i_height;
1506 msg_Dbg(VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height);
1510 - (id)coreDialogProvider
1513 return o_coredialogs;
1518 - (id)eyeTVController
1526 - (id)appleRemoteController
1531 - (BOOL)activeVideoPlayback
1533 return b_active_videoplayback;
1537 #pragma mark Crash Log
1538 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1540 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1541 NSURL *url = [NSURL URLWithString:urlStr];
1543 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1544 [req setHTTPMethod:@"POST"];
1547 if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1548 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1549 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1550 email = [emails valueAtIndex:[emails indexForIdentifier:
1551 [emails primaryIdentifier]]];
1554 email = [NSString string];
1557 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1558 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1559 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1560 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1562 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1564 /* Released from delegate */
1565 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1568 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1570 msg_Dbg(p_intf, "crash report successfully sent");
1571 [crashLogURLConnection release];
1572 crashLogURLConnection = nil;
1575 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1577 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1578 [crashLogURLConnection release];
1579 crashLogURLConnection = nil;
1582 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1584 NSString * crashReporter;
1585 if (OSX_MOUNTAIN_LION)
1586 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1588 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1589 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1591 NSString * latestLog = nil;
1592 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1593 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1594 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1595 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1596 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1598 while (fname = [direnum nextObject]) {
1599 [direnum skipDescendents];
1600 if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1601 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1602 if ([compo count] < 3)
1604 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1605 if ([compo count] < 4)
1609 if (year < [[compo objectAtIndex:0] intValue] ||
1610 (year ==[[compo objectAtIndex:0] intValue] &&
1611 (month < [[compo objectAtIndex:1] intValue] ||
1612 (month ==[[compo objectAtIndex:1] intValue] &&
1613 (day < [[compo objectAtIndex:2] intValue] ||
1614 (day ==[[compo objectAtIndex:2] intValue] &&
1615 hours < [[compo objectAtIndex:3] intValue])))))) {
1616 year = [[compo objectAtIndex:0] intValue];
1617 month = [[compo objectAtIndex:1] intValue];
1618 day = [[compo objectAtIndex:2] intValue];
1619 hours = [[compo objectAtIndex:3] intValue];
1620 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1625 if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1628 if (!previouslySeen) {
1629 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1630 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1631 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1632 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1637 - (NSString *)latestCrashLogPath
1639 return [self latestCrashLogPathPreviouslySeen:YES];
1642 - (void)lookForCrashLog
1644 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1645 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1646 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1647 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1648 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1649 if (latestLog && !areCrashLogsTooOld) {
1650 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1651 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1652 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1653 [NSApp runModalForWindow: o_crashrep_win];
1654 // bail out, the user doesn't want us to send reports
1660 - (IBAction)crashReporterAction:(id)sender
1662 if (sender == o_crashrep_send_btn) {
1663 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1664 if ([o_crashrep_dontaskagain_ckb state])
1665 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1667 if ([o_crashrep_dontaskagain_ckb state])
1668 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1672 [o_crashrep_win orderOut: sender];
1675 - (IBAction)openCrashLog:(id)sender
1677 NSString * latestLog = [self latestCrashLogPath];
1679 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1681 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."));
1686 #pragma mark Remove old prefs
1688 - (void)_removeOldPreferences
1690 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1691 static const int kCurrentPreferencesVersion = 2;
1692 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1693 int version = [defaults integerForKey:kVLCPreferencesVersion];
1694 if (version >= kCurrentPreferencesVersion)
1698 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1699 [defaults synchronize];
1701 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1704 config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1706 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1707 NSUserDomainMask, YES);
1708 if (!libraries || [libraries count] == 0) return;
1709 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1711 /* File not found, don't attempt anything */
1712 if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1713 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1714 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1718 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1719 _NS("We just found an older version of VLC's preferences files."),
1720 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1721 if (res != NSOKButton) {
1722 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1726 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1728 /* Move the file to trash so that user can find them later */
1729 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1731 /* really reset the defaults from now on */
1732 [NSUserDefaults resetStandardUserDefaults];
1734 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1735 [defaults synchronize];
1739 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1741 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1746 execl(path, path, NULL);
1750 #pragma mark Errors, warnings and messages
1751 - (IBAction)updateMessagesPanel:(id)sender
1753 [self windowDidBecomeKey:nil];
1756 - (IBAction)showMessagesPanel:(id)sender
1758 [o_msgs_panel makeKeyAndOrderFront: sender];
1761 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1763 [o_msgs_table reloadData];
1764 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1767 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1769 if (aTableView == o_msgs_table)
1770 return [o_msg_arr count];
1774 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1776 NSMutableAttributedString *result = NULL;
1779 if (rowIndex < [o_msg_arr count])
1780 result = [o_msg_arr objectAtIndex: rowIndex];
1781 [o_msg_lock unlock];
1789 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1792 NSColor *o_white = [NSColor whiteColor];
1793 NSColor *o_red = [NSColor redColor];
1794 NSColor *o_yellow = [NSColor yellowColor];
1795 NSColor *o_gray = [NSColor grayColor];
1796 NSString * firstString, * secondString;
1798 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1799 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1801 NSDictionary *o_attr;
1802 NSMutableAttributedString *o_msg_color;
1806 if ([o_msg_arr count] > 600) {
1807 [o_msg_arr removeObjectAtIndex: 0];
1808 [o_msg_arr removeObjectAtIndex: 1];
1810 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1811 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1813 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1814 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1815 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1816 [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
1817 [o_msg_arr addObject: [o_msg_color autorelease]];
1819 b_msg_arr_changed = YES;
1820 [o_msg_lock unlock];
1824 - (IBAction)saveDebugLog:(id)sender
1826 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1828 [saveFolderPanel setCanSelectHiddenExtension: NO];
1829 [saveFolderPanel setCanCreateDirectories: YES];
1830 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1831 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1832 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1833 if (returnCode == NSOKButton) {
1834 NSUInteger count = [o_msg_arr count];
1835 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1836 for (NSUInteger i = 0; i < count; i++)
1837 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1839 NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
1840 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1842 if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
1843 msg_Warn(p_intf, "Error while saving the debug log");
1848 [saveFolderPanel release];
1852 #pragma mark Playlist toggling
1854 - (void)updateTogglePlaylistState
1856 [[self playlist] outlineViewSelectionDidChange: NULL];
1863 @implementation VLCMain (Internal)
1865 - (void)handlePortMessage:(NSPortMessage *)o_msg
1870 NSInvocation * o_inv;
1871 NSConditionLock * o_lock;
1873 o_data = [[o_msg components] lastObject];
1874 o_inv = *((NSInvocation **)[o_data bytes]);
1875 [o_inv getArgument: &o_value atIndex: 2];
1876 val = (id **)[o_value pointerValue];
1877 [o_inv setArgument: val[1] atIndex: 2];
1882 [o_lock unlockWithCondition: 1];
1885 - (void)resetMediaKeyJump
1887 b_mediakeyJustJumped = NO;
1890 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1892 b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
1893 if (b_mediaKeySupport) {
1894 if (!o_mediaKeyController)
1895 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1896 [o_mediaKeyController startWatchingMediaKeys];
1898 else if (!b_mediaKeySupport && o_mediaKeyController)
1899 [o_mediaKeyController stopWatchingMediaKeys];
1904 /*****************************************************************************
1905 * VLCApplication interface
1906 *****************************************************************************/
1908 @implementation VLCApplication
1909 // when user selects the quit menu from dock it sends a terminate:
1910 // but we need to send a stop: to properly exits libvlc.
1911 // However, we are not able to change the action-method sent by this standard menu item.
1912 // thus we override terminate: to send a stop:
1913 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1914 - (void)terminate:(id)sender
1916 [self activateIgnoringOtherApps:YES];