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;
127 free( p_intf->p_sys );
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 )
165 case VOUT_WINDOW_SET_STATE:
167 unsigned i_state = va_arg( args, unsigned );
168 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(setWindowLevel:) withObject:[NSNumber numberWithUnsignedInt:i_state] waitUntilDone:NO];
171 case VOUT_WINDOW_SET_SIZE:
173 unsigned int i_width = va_arg( args, unsigned int );
174 unsigned int i_height = va_arg( args, unsigned int );
175 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
178 case VOUT_WINDOW_SET_FULLSCREEN:
180 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
181 int i_full = va_arg( args, int );
182 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(checkFullscreenChange:) withObject:[NSNumber numberWithInt: i_full] waitUntilDone:NO];
187 msg_Warn( p_wnd, "unsupported control query" );
192 void WindowClose( vout_window_t *p_wnd )
194 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
195 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
200 /*****************************************************************************
202 *****************************************************************************/
203 static NSLock * o_appLock = nil; // controls access to f_appExit
205 static void Run( intf_thread_t *p_intf )
207 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
208 [VLCApplication sharedApplication];
210 o_appLock = [[NSLock alloc] init];
212 [[VLCMain sharedInstance] setIntf: p_intf];
213 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
216 [[VLCMain sharedInstance] applicationWillTerminate:nil];
224 #pragma mark Variables Callback
226 /*****************************************************************************
227 * MsgCallback: Callback triggered by the core once a new debug message is
228 * ready to be displayed. We store everything in a NSArray in our Cocoa part
230 *****************************************************************************/
231 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
233 int canc = vlc_savecancel();
236 if (vasprintf( &str, format, ap ) == -1)
238 vlc_restorecancel( canc );
242 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
243 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
246 vlc_restorecancel( canc );
250 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
251 vlc_value_t oldval, vlc_value_t new_val, void *param )
253 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
254 switch (new_val.i_int) {
255 case INPUT_EVENT_STATE:
256 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
258 case INPUT_EVENT_RATE:
259 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
261 case INPUT_EVENT_POSITION:
262 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
264 case INPUT_EVENT_TITLE:
265 case INPUT_EVENT_CHAPTER:
266 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
268 case INPUT_EVENT_CACHE:
269 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
271 case INPUT_EVENT_STATISTICS:
272 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
276 case INPUT_EVENT_TELETEXT:
278 case INPUT_EVENT_AOUT:
280 case INPUT_EVENT_VOUT:
282 case INPUT_EVENT_ITEM_META:
283 case INPUT_EVENT_ITEM_INFO:
284 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
285 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
286 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
288 case INPUT_EVENT_BOOKMARK:
290 case INPUT_EVENT_RECORD:
291 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
293 case INPUT_EVENT_PROGRAM:
294 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
296 case INPUT_EVENT_ITEM_EPG:
298 case INPUT_EVENT_SIGNAL:
301 case INPUT_EVENT_ITEM_NAME:
302 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
303 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
306 case INPUT_EVENT_AUDIO_DELAY:
307 case INPUT_EVENT_SUBTITLE_DELAY:
308 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
311 case INPUT_EVENT_DEAD:
312 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
313 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
316 case INPUT_EVENT_ABORT:
317 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
318 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
322 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
330 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
331 vlc_value_t oldval, vlc_value_t new_val, void *param )
333 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
340 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
341 vlc_value_t oldval, vlc_value_t new_val, void *param )
343 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
344 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
350 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
351 vlc_value_t oldval, vlc_value_t new_val, void *param )
353 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
354 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
360 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
361 vlc_value_t oldval, vlc_value_t new_val, void *param )
363 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
364 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
370 /*****************************************************************************
371 * ShowController: Callback triggered by the show-intf playlist variable
372 * through the ShowIntf-control-intf, to let us show the controller-win;
373 * usually when in fullscreen-mode
374 *****************************************************************************/
375 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
376 vlc_value_t old_val, vlc_value_t new_val, void *param )
378 intf_thread_t * p_intf = VLCIntf;
379 if( p_intf && p_intf->p_sys )
381 playlist_t * p_playlist = pl_Get( p_intf );
382 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
383 if( strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen )
385 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
389 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
395 /*****************************************************************************
396 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
397 * variable, to let the intf update the controller.
398 *****************************************************************************/
399 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
400 vlc_value_t old_val, vlc_value_t new_val, void *param )
402 intf_thread_t * p_intf = VLCIntf;
405 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
406 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
412 /*****************************************************************************
413 * DialogCallback: Callback triggered by the "dialog-*" variables
414 * to let the intf display error and interaction dialogs
415 *****************************************************************************/
416 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
418 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
419 VLCMain *interface = (VLCMain *)data;
421 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
423 /* the progress panel needs to update itself and therefore wants special treatment within this context */
424 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
426 p_dialog->pf_update = updateProgressPanel;
427 p_dialog->pf_check = checkProgressPanel;
428 p_dialog->pf_destroy = destroyProgressPanel;
429 p_dialog->p_sys = VLCIntf->p_libvlc;
432 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
433 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
439 void updateProgressPanel (void *priv, const char *text, float value)
441 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
445 o_txt = [NSString stringWithUTF8String: text];
449 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
454 void destroyProgressPanel (void *priv)
456 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
457 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
461 bool checkProgressPanel (void *priv)
463 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
464 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
471 input_thread_t *getInput(void)
473 intf_thread_t *p_intf = VLCIntf;
476 return pl_CurrentInput(p_intf);
479 vout_thread_t *getVout(void)
481 input_thread_t *p_input = getInput();
484 vout_thread_t *p_vout = input_GetVout(p_input);
485 vlc_object_release(p_input);
489 audio_output_t *getAout(void)
491 input_thread_t *p_input = getInput();
494 audio_output_t *p_aout = input_GetAout(p_input);
495 vlc_object_release(p_input);
502 @interface VLCMain ()
503 - (void)_removeOldPreferences;
506 /*****************************************************************************
507 * VLCMain implementation
508 *****************************************************************************/
509 @implementation VLCMain
512 #pragma mark Initialization
514 static VLCMain *_o_sharedMainInstance = nil;
516 + (VLCMain *)sharedInstance
518 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
523 if( _o_sharedMainInstance)
526 return _o_sharedMainInstance;
529 _o_sharedMainInstance = [super init];
532 p_current_input = NULL;
534 o_msg_lock = [[NSLock alloc] init];
535 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
537 o_open = [[VLCOpen alloc] init];
538 //o_embedded_list = [[VLCEmbeddedList alloc] init];
539 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
540 o_info = [[VLCInfo alloc] init];
541 o_mainmenu = [[VLCMainMenu alloc] init];
542 o_coreinteraction = [[VLCCoreInteraction alloc] init];
543 o_eyetv = [[VLCEyeTVController alloc] init];
544 o_mainwindow = [[VLCMainWindow alloc] init];
546 /* announce our launch to a potential eyetv plugin */
547 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
548 object: @"VLCEyeTVSupport"
550 deliverImmediately: YES];
552 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
553 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
554 [defaults registerDefaults:appDefaults];
556 return _o_sharedMainInstance;
559 - (void)setIntf: (intf_thread_t *)p_mainintf {
563 - (intf_thread_t *)intf {
569 playlist_t *p_playlist;
571 if( !p_intf ) return;
572 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
574 /* Check if we already did this once. Opening the other nibs calls it too,
575 because VLCMain is the owner */
576 if( nib_main_loaded ) return;
578 [o_msgs_panel setExcludedFromWindowsMenu: YES];
579 [o_msgs_panel setDelegate: self];
581 p_playlist = pl_Get( p_intf );
585 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
586 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
587 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
588 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
589 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
590 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
591 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
592 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
593 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
594 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
595 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
596 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
597 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
598 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
602 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
603 var_SetBool( p_playlist, "fullscreen", YES );
606 /* load our Core Dialogs nib */
607 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
609 /* subscribe to various interactive dialogues */
610 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
611 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
612 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
613 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
614 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
615 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
616 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
617 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
618 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
619 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
620 dialog_Register( p_intf );
622 /* init Apple Remote support */
623 o_remote = [[AppleRemote alloc] init];
624 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
625 [o_remote setDelegate: _o_sharedMainInstance];
627 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
629 BOOL b_video_deco = var_InheritBool( VLCIntf, "video-deco" );
630 /* yeah, we are done */
631 b_nativeFullscreenMode = NO;
632 #ifdef MAC_OS_X_VERSION_10_7
633 if( OSX_LION && b_video_deco )
634 b_nativeFullscreenMode = var_InheritBool( p_intf, "macosx-nativefullscreenmode" );
637 /* recover stored audio device, if set
638 * in case it was unplugged in the meantime, auhal will fall back on the default */
639 int i_value = config_GetInt( p_intf, "macosx-audio-device" );
641 var_SetInteger( pl_Get( VLCIntf ), "audio-device", i_value );
643 if (config_GetInt( VLCIntf, "macosx-icon-change"))
645 /* After day 354 of the year, the usual VLC cone is replaced by another cone
646 * wearing a Father Xmas hat.
647 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
649 NSCalendar *gregorian =
650 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
651 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
654 if (dayOfYear >= 354)
655 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
660 nib_main_loaded = TRUE;
663 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
665 if( !p_intf ) return;
667 [self updateCurrentlyUsedHotkeys];
669 /* init media key support */
670 b_mediaKeySupport = var_InheritBool( VLCIntf, "macosx-mediakeys" );
671 if( b_mediaKeySupport )
673 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
674 [o_mediaKeyController startWatchingMediaKeys];
675 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
676 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
679 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
681 [self _removeOldPreferences];
683 /* Handle sleep notification */
684 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
685 name:NSWorkspaceWillSleepNotification object:nil];
687 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
689 /* we will need this, so let's load it here so the interface appears to be more responsive */
690 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
692 /* update the main window */
693 [o_mainwindow updateWindow];
694 [o_mainwindow updateTimeSlider];
695 [o_mainwindow updateVolumeSlider];
700 if( !p_intf ) return;
703 [o_msgs_panel setTitle: _NS("Messages")];
704 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
705 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
707 /* crash reporter panel */
708 [o_crashrep_send_btn setTitle: _NS("Send")];
709 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
710 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
711 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
712 [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, ...")];
713 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
714 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
715 [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
719 #pragma mark Termination
721 - (void)applicationWillTerminate:(NSNotification *)notification
723 /* don't allow a double termination call. If the user has
724 * already invoked the quit then simply return this time. */
725 static bool f_appExit = false;
729 isTerminating = f_appExit;
736 if (notification == nil)
737 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
739 playlist_t * p_playlist = pl_Get( p_intf );
740 int returnedValue = 0;
742 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
743 if (b_nativeFullscreenMode)
745 [o_mainwindow toggleFullScreen: self];
746 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
749 /* Save some interface state in configuration, at module quit */
750 config_PutInt( p_intf, "random", var_GetBool( p_playlist, "random" ) );
751 config_PutInt( p_intf, "loop", var_GetBool( p_playlist, "loop" ) );
752 config_PutInt( p_intf, "repeat", var_GetBool( p_playlist, "repeat" ) );
754 msg_Dbg( p_intf, "Terminating" );
756 /* unsubscribe from the interactive dialogues */
757 dialog_Unregister( p_intf );
758 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
759 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
760 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
761 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
762 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
763 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
764 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
765 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
766 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
767 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
768 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
769 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
770 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
771 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
772 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
773 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
774 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
775 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
776 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
778 if( p_current_input )
780 var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
781 vlc_object_release( p_current_input );
782 p_current_input = NULL;
785 /* remove global observer watching for vout device changes correctly */
786 [[NSNotificationCenter defaultCenter] removeObserver: self];
788 /* release some other objects here, because it isn't sure whether dealloc
789 * will be called later on */
804 [crashLogURLConnection cancel];
805 [crashLogURLConnection release];
807 [o_embedded_list release];
808 [o_coredialogs release];
811 /* unsubscribe from libvlc's debug messages */
812 vlc_Unsubscribe( &p_intf->p_sys->sub );
814 [o_msg_arr removeAllObjects];
817 [o_usedHotkeys release];
818 o_usedHotkeys = NULL;
820 [o_msg_lock release];
822 /* write cached user defaults to disk */
823 [[NSUserDefaults standardUserDefaults] synchronize];
825 [o_mainmenu release];
827 libvlc_Quit( p_intf->p_libvlc );
829 [o_mainwindow release];
836 #pragma mark Sparkle delegate
837 /* received directly before the update gets installed, so let's shut down a bit */
838 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
840 [NSApp activateIgnoringOtherApps:YES];
841 [o_remote stopListening: self];
842 [[VLCCoreInteraction sharedInstance] stop];
846 #pragma mark Media Key support
848 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
850 if( b_mediaKeySupport )
852 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
854 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
855 int keyFlags = ([event data1] & 0x0000FFFF);
856 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
857 int keyRepeat = (keyFlags & 0x1);
859 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
860 [[VLCCoreInteraction sharedInstance] play];
862 if( (keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped )
864 if( keyState == 0 && keyRepeat == 0 )
865 [[VLCCoreInteraction sharedInstance] next];
866 else if( keyRepeat == 1 )
868 [[VLCCoreInteraction sharedInstance] forwardShort];
869 b_mediakeyJustJumped = YES;
870 [self performSelector:@selector(resetMediaKeyJump)
876 if( (keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped )
878 if( keyState == 0 && keyRepeat == 0 )
879 [[VLCCoreInteraction sharedInstance] previous];
880 else if( keyRepeat == 1 )
882 [[VLCCoreInteraction sharedInstance] backwardShort];
883 b_mediakeyJustJumped = YES;
884 [self performSelector:@selector(resetMediaKeyJump)
893 #pragma mark Other notification
895 /* Listen to the remote in exclusive mode, only when VLC is the active
897 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
899 if( !p_intf ) return;
900 if( var_InheritBool( p_intf, "macosx-appleremote" ) == YES )
901 [o_remote startListening: self];
903 - (void)applicationDidResignActive:(NSNotification *)aNotification
905 if( !p_intf ) return;
906 [o_remote stopListening: self];
909 /* Triggered when the computer goes to sleep */
910 - (void)computerWillSleep: (NSNotification *)notification
912 [[VLCCoreInteraction sharedInstance] pause];
916 #pragma mark File opening over dock icon
918 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
920 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
921 char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file" );
923 // try to add file as subtitle
924 if( [o_names count] == 1 && psz_uri )
926 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
929 BOOL b_returned = NO;
930 b_returned = input_AddSubtitle( p_input, psz_uri, true );
931 vlc_object_release( p_input );
941 NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
942 NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
943 for( int i = 0; i < [o_sorted_names count]; i++ )
945 psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex: i] UTF8String], "file" );
949 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
951 [o_result addObject: o_dic];
955 [o_playlist appendArray: o_result atPos: -1 enqueue: NO];
957 [o_playlist appendArray: o_result atPos: -1 enqueue: YES];
962 /* When user click in the Dock icon our double click in the finder */
963 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
965 if(!hasVisibleWindows)
966 [o_mainwindow makeKeyAndOrderFront:self];
972 #pragma mark Apple Remote Control
974 /* Helper method for the remote control interface in order to trigger forward/backward and volume
975 increase/decrease as long as the user holds the left/right, plus/minus button */
976 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
978 if(b_remote_button_hold)
980 switch([buttonIdentifierNumber intValue])
982 case kRemoteButtonRight_Hold:
983 [[VLCCoreInteraction sharedInstance] forward];
985 case kRemoteButtonLeft_Hold:
986 [[VLCCoreInteraction sharedInstance] backward];
988 case kRemoteButtonVolume_Plus_Hold:
990 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP );
992 case kRemoteButtonVolume_Minus_Hold:
994 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN );
997 if(b_remote_button_hold)
1000 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1001 withObject:buttonIdentifierNumber
1007 /* Apple Remote callback */
1008 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1009 pressedDown: (BOOL) pressedDown
1010 clickCount: (unsigned int) count
1012 switch( buttonIdentifier )
1014 case k2009RemoteButtonFullscreen:
1015 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1017 case k2009RemoteButtonPlay:
1018 [[VLCCoreInteraction sharedInstance] play];
1020 case kRemoteButtonPlay:
1022 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1024 [[VLCCoreInteraction sharedInstance] play];
1027 case kRemoteButtonVolume_Plus:
1028 if (config_GetInt( VLCIntf, "macosx-appleremote-sysvol"))
1029 [NSSound increaseSystemVolume];
1032 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP );
1034 case kRemoteButtonVolume_Minus:
1035 if (config_GetInt( VLCIntf, "macosx-appleremote-sysvol"))
1036 [NSSound decreaseSystemVolume];
1039 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN );
1041 case kRemoteButtonRight:
1042 if (config_GetInt( VLCIntf, "macosx-appleremote-prevnext"))
1043 [[VLCCoreInteraction sharedInstance] forward];
1045 [[VLCCoreInteraction sharedInstance] next];
1047 case kRemoteButtonLeft:
1048 if (config_GetInt( VLCIntf, "macosx-appleremote-prevnext"))
1049 [[VLCCoreInteraction sharedInstance] backward];
1051 [[VLCCoreInteraction sharedInstance] previous];
1053 case kRemoteButtonRight_Hold:
1054 case kRemoteButtonLeft_Hold:
1055 case kRemoteButtonVolume_Plus_Hold:
1056 case kRemoteButtonVolume_Minus_Hold:
1057 /* simulate an event as long as the user holds the button */
1058 b_remote_button_hold = pressedDown;
1061 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1062 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1063 withObject:buttonIdentifierNumber];
1066 case kRemoteButtonMenu:
1067 [o_controls showPosition: self]; //FIXME
1069 case kRemoteButtonPlay_Sleep:
1071 NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1072 [script executeAndReturnError:nil];
1077 /* Add here whatever you want other buttons to do */
1083 #pragma mark Key Shortcuts
1085 /*****************************************************************************
1086 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1087 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1088 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1089 *****************************************************************************/
1090 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1094 unsigned int i_pressed_modifiers = 0;
1097 i_pressed_modifiers = [o_event modifierFlags];
1099 if( i_pressed_modifiers & NSControlKeyMask ) {
1100 val.i_int |= KEY_MODIFIER_CTRL;
1102 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1103 val.i_int |= KEY_MODIFIER_ALT;
1105 if( i_pressed_modifiers & NSShiftKeyMask ) {
1106 val.i_int |= KEY_MODIFIER_SHIFT;
1108 if( i_pressed_modifiers & NSCommandKeyMask ) {
1109 val.i_int |= KEY_MODIFIER_COMMAND;
1112 NSString * characters = [o_event charactersIgnoringModifiers];
1113 if ([characters length] > 0)
1115 key = [[characters lowercaseString] characterAtIndex: 0];
1117 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1118 if( key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask )
1120 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1128 case NSDeleteCharacter:
1129 case NSDeleteFunctionKey:
1130 case NSDeleteCharFunctionKey:
1131 case NSBackspaceCharacter:
1132 case NSUpArrowFunctionKey:
1133 case NSDownArrowFunctionKey:
1134 case NSRightArrowFunctionKey:
1135 case NSLeftArrowFunctionKey:
1136 case NSEnterCharacter:
1137 case NSCarriageReturnCharacter:
1142 if( key == 0x0020 ) // space key
1144 [[VLCCoreInteraction sharedInstance] play];
1148 val.i_int |= CocoaKeyToVLC( key );
1150 BOOL b_found_key = NO;
1151 for( int i = 0; i < [o_usedHotkeys count]; i++ )
1153 NSString *str = [o_usedHotkeys objectAtIndex: i];
1154 unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1156 if( [[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1157 (i_keyModifiers & NSShiftKeyMask) == (i_pressed_modifiers & NSShiftKeyMask) &&
1158 (i_keyModifiers & NSControlKeyMask) == (i_pressed_modifiers & NSControlKeyMask) &&
1159 (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1160 (i_keyModifiers & NSCommandKeyMask) == (i_pressed_modifiers & NSCommandKeyMask) )
1169 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1177 - (void)updateCurrentlyUsedHotkeys
1179 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1180 /* Get the main Module */
1181 module_t *p_main = module_get_main();
1184 module_config_t *p_config;
1186 p_config = module_config_get (p_main, &confsize);
1188 for (size_t i = 0; i < confsize; i++)
1190 module_config_t *p_item = p_config + i;
1192 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1193 && !strncmp( p_item->psz_name , "key-", 4 )
1194 && !EMPTY_STR( p_item->psz_text ) )
1196 if (p_item->value.psz)
1198 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1202 module_config_free (p_config);
1205 [o_usedHotkeys release];
1206 o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1207 [o_tempArray release];
1211 #pragma mark Interface updaters
1212 - (void)fullscreenChanged
1214 playlist_t * p_playlist = pl_Get( VLCIntf );
1215 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1217 if (b_nativeFullscreenMode)
1219 // this is called twice in certain situations, so only toogle if we really need to
1220 if( ( b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) ||
1221 ( !b_fullscreen && ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) )
1222 [o_mainwindow toggleFullScreen: self];
1225 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1227 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1233 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1234 if( p_input != NULL && [self activeVideoPlayback] )
1236 // activate app, as method can also be triggered from outside the app (prevents nasty window layout)
1237 [NSApp activateIgnoringOtherApps:YES];
1238 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1241 vlc_object_release( p_input );
1245 // leaving fullscreen is always allowed
1246 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1251 - (void)checkFullscreenChange:(NSNumber *)o_full
1253 BOOL b_full = [o_full boolValue];
1254 if( p_intf && !var_GetBool( pl_Get( p_intf ), "fullscreen" ) != !b_full )
1256 var_SetBool( pl_Get(p_intf), "fullscreen", b_full );
1260 - (void)PlaylistItemChanged
1262 if( p_current_input && ( p_current_input->b_dead || !vlc_object_alive( p_current_input ) ))
1264 var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1265 vlc_object_release( p_current_input );
1266 p_current_input = NULL;
1268 [o_mainmenu setRateControlsEnabled: NO];
1270 else if( !p_current_input )
1272 // object is hold here and released then it is dead
1273 p_current_input = playlist_CurrentInput( pl_Get( VLCIntf ));
1274 if( p_current_input )
1276 var_AddCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1277 [self playbackStatusUpdated];
1278 [o_mainmenu setRateControlsEnabled: YES];
1279 if ( [self activeVideoPlayback] && [[o_mainwindow videoView] isHidden] )
1280 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1284 [o_playlist updateRowSelection];
1285 [o_mainwindow updateWindow];
1286 [self updateDelays];
1287 [self updateMainMenu];
1290 - (void)updateMainMenu
1292 [o_mainmenu setupMenus];
1293 [o_mainmenu updatePlaybackRate];
1296 - (void)updateMainWindow
1298 [o_mainwindow updateWindow];
1301 - (void)showMainWindow
1303 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1306 - (void)showFullscreenController
1308 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1311 - (void)updateDelays
1313 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1318 [o_mainwindow updateName];
1321 - (void)updatePlaybackPosition
1323 [o_mainwindow updateTimeSlider];
1326 - (void)updateVolume
1328 [o_mainwindow updateVolumeSlider];
1331 - (void)playlistUpdated
1333 [self playbackStatusUpdated];
1334 [o_playlist playlistUpdated];
1335 [o_mainwindow updateWindow];
1336 [o_mainwindow updateName];
1339 - (void)updateRecordState: (BOOL)b_value
1341 [o_mainmenu updateRecordState:b_value];
1344 - (void)updateInfoandMetaPanel
1346 [o_playlist outlineViewSelectionDidChange:nil];
1349 - (void)playbackStatusUpdated
1351 input_thread_t * p_input;
1353 p_input = pl_CurrentInput( p_intf );
1356 int state = var_GetInteger( p_input, "state" );
1357 if( state == PLAYING_S )
1359 /* prevent the system from sleeping */
1361 CFStringRef reasonForActivity= CFStringCreateWithCString( kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8 );
1362 if ( [self activeVideoPlayback] )
1363 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1365 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1366 CFRelease( reasonForActivity );
1368 if (success == kIOReturnSuccess)
1369 msg_Dbg( VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1371 msg_Warn( VLCIntf, "failed to prevent system sleep through IOKit");
1373 [[self mainMenu] setPause];
1374 [o_mainwindow setPause];
1379 [o_mainmenu setSubmenusEnabled: FALSE];
1380 [[self mainMenu] setPlay];
1381 [o_mainwindow setPlay];
1383 /* allow the system to sleep again */
1384 msg_Dbg( VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID );
1385 IOPMAssertionRelease( systemSleepAssertionID );
1387 vlc_object_release( p_input );
1390 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1391 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1394 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1396 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1399 deliverImmediately:YES];
1402 - (void)playbackModeUpdated
1404 vlc_value_t looping,repeating;
1405 playlist_t * p_playlist = pl_Get( VLCIntf );
1407 bool loop = var_GetBool( p_playlist, "loop" );
1408 bool repeat = var_GetBool( p_playlist, "repeat" );
1410 [o_mainwindow setRepeatOne];
1411 [o_mainmenu setRepeatOne];
1413 [o_mainwindow setRepeatAll];
1414 [o_mainmenu setRepeatAll];
1416 [o_mainwindow setRepeatOff];
1417 [o_mainmenu setRepeatOff];
1420 [o_mainwindow setShuffle];
1421 [o_mainmenu setShuffle];
1426 #pragma mark Window updater
1428 - (void)setWindowLevel:(NSNumber*)state
1430 if( var_InheritBool( p_intf, "macosx-background" ) )
1433 if ([state unsignedIntValue] & VOUT_WINDOW_STATE_ABOVE)
1434 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSStatusWindowLevel];
1436 [[[[VLCMainWindow sharedInstance] videoView] window] setLevel: NSNormalWindowLevel];
1439 - (void)setActiveVideoPlayback:(BOOL)b_value
1441 b_active_videoplayback = b_value;
1444 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1445 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1449 - (void)setNativeVideoSize:(NSSize)size
1451 [o_mainwindow setNativeVideoSize:size];
1455 #pragma mark Other objects getters
1464 return o_mainwindow;
1478 o_bookmarks = [[VLCBookmarks alloc] init];
1480 if( !nib_bookmarks_loaded )
1481 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1491 if (!nib_open_loaded)
1492 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1497 - (id)simplePreferences
1500 o_sprefs = [[VLCSimplePrefs alloc] init];
1502 if (!nib_prefs_loaded)
1503 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1511 o_prefs = [[VLCPrefs alloc] init];
1513 if( !nib_prefs_loaded )
1514 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1529 if(! nib_info_loaded )
1530 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1541 o_wizard = [[VLCWizard alloc] init];
1543 if( !nib_wizard_loaded )
1545 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1546 [o_wizard initStrings];
1551 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1553 [o_mainwindow performSelectorOnMainThread:@selector(setupVideoView) withObject:nil waitUntilDone:YES];
1554 id videoView = [o_mainwindow videoView];
1555 NSRect videoRect = [videoView frame];
1556 int i_x = (int)videoRect.origin.x;
1557 int i_y = (int)videoRect.origin.y;
1558 unsigned int i_width = (int)videoRect.size.width;
1559 unsigned int i_height = (int)videoRect.size.height;
1562 pi_width = &i_width;
1563 pi_height = &i_height;
1564 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1570 if( o_embedded_list )
1571 return o_embedded_list;
1576 - (id)coreDialogProvider
1579 return o_coredialogs;
1584 - (id)eyeTVController
1592 - (id)appleRemoteController
1597 - (BOOL)activeVideoPlayback
1599 return b_active_videoplayback;
1603 #pragma mark Crash Log
1604 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1606 NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1607 NSURL *url = [NSURL URLWithString:urlStr];
1609 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1610 [req setHTTPMethod:@"POST"];
1613 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1615 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1616 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1617 email = [emails valueAtIndex:[emails indexForIdentifier:
1618 [emails primaryIdentifier]]];
1621 email = [NSString string];
1624 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1625 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1626 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1627 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1629 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1631 /* Released from delegate */
1632 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1635 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1637 msg_Dbg( p_intf, "crash report successfully sent" );
1638 [crashLogURLConnection release];
1639 crashLogURLConnection = nil;
1642 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1644 msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1645 [crashLogURLConnection release];
1646 crashLogURLConnection = nil;
1649 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1651 NSString * crashReporter;
1652 if( OSX_MOUNTAIN_LION )
1653 crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1655 crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1656 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1658 NSString * latestLog = nil;
1659 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1660 int year = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1661 int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1662 int day = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"] : 0;
1663 int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1665 while (fname = [direnum nextObject])
1667 [direnum skipDescendents];
1668 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1670 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1671 if( [compo count] < 3 ) continue;
1672 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1673 if( [compo count] < 4 ) continue;
1676 if( year < [[compo objectAtIndex:0] intValue] ||
1677 (year ==[[compo objectAtIndex:0] intValue] &&
1678 (month < [[compo objectAtIndex:1] intValue] ||
1679 (month ==[[compo objectAtIndex:1] intValue] &&
1680 (day < [[compo objectAtIndex:2] intValue] ||
1681 (day ==[[compo objectAtIndex:2] intValue] &&
1682 hours < [[compo objectAtIndex:3] intValue] ))))))
1684 year = [[compo objectAtIndex:0] intValue];
1685 month = [[compo objectAtIndex:1] intValue];
1686 day = [[compo objectAtIndex:2] intValue];
1687 hours = [[compo objectAtIndex:3] intValue];
1688 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1693 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1696 if( !previouslySeen )
1698 [defaults setInteger:year forKey:@"LatestCrashReportYear"];
1699 [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1700 [defaults setInteger:day forKey:@"LatestCrashReportDay"];
1701 [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1706 - (NSString *)latestCrashLogPath
1708 return [self latestCrashLogPathPreviouslySeen:YES];
1711 - (void)lookForCrashLog
1713 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1714 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1715 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1716 BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1717 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1718 if( latestLog && !areCrashLogsTooOld )
1720 if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1721 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1722 else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1723 [NSApp runModalForWindow: o_crashrep_win];
1724 // bail out, the user doesn't want us to send reports
1730 - (IBAction)crashReporterAction:(id)sender
1732 if( sender == o_crashrep_send_btn ) {
1733 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1734 if ([o_crashrep_dontaskagain_ckb state])
1735 [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1737 if ([o_crashrep_dontaskagain_ckb state])
1738 [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1742 [o_crashrep_win orderOut: sender];
1745 - (IBAction)openCrashLog:(id)sender
1747 NSString * latestLog = [self latestCrashLogPath];
1750 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1754 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.") );
1759 #pragma mark Remove old prefs
1761 - (void)_removeOldPreferences
1763 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1764 static const int kCurrentPreferencesVersion = 2;
1765 NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1766 int version = [defaults integerForKey:kVLCPreferencesVersion];
1767 if( version >= kCurrentPreferencesVersion ) return;
1771 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1772 [defaults synchronize];
1774 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1777 config_SaveConfigFile( VLCIntf ); // we need to do manually, since we won't quit libvlc cleanly
1781 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1782 NSUserDomainMask, YES);
1783 if( !libraries || [libraries count] == 0) return;
1784 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1786 /* File not found, don't attempt anything */
1787 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1788 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1790 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1794 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1795 _NS("We just found an older version of VLC's preferences files."),
1796 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1797 if( res != NSOKButton )
1799 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1803 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1805 /* Move the file to trash so that user can find them later */
1806 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1808 /* really reset the defaults from now on */
1809 [NSUserDefaults resetStandardUserDefaults];
1811 [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1812 [defaults synchronize];
1816 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1818 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1824 execl(path, path, NULL);
1828 #pragma mark Errors, warnings and messages
1829 - (IBAction)updateMessagesPanel:(id)sender
1831 [self windowDidBecomeKey:nil];
1834 - (IBAction)showMessagesPanel:(id)sender
1836 [o_msgs_panel makeKeyAndOrderFront: sender];
1839 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1841 [o_msgs_table reloadData];
1842 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1845 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1847 if (aTableView == o_msgs_table)
1848 return [o_msg_arr count];
1852 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1854 NSMutableAttributedString *result = NULL;
1857 if( rowIndex < [o_msg_arr count] )
1858 result = [o_msg_arr objectAtIndex: rowIndex];
1859 [o_msg_lock unlock];
1861 if( result != NULL )
1867 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1871 NSColor *o_white = [NSColor whiteColor];
1872 NSColor *o_red = [NSColor redColor];
1873 NSColor *o_yellow = [NSColor yellowColor];
1874 NSColor *o_gray = [NSColor grayColor];
1875 NSString * firstString, * secondString;
1877 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1878 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1880 NSDictionary *o_attr;
1881 NSMutableAttributedString *o_msg_color;
1885 if( [o_msg_arr count] > 600 )
1887 [o_msg_arr removeObjectAtIndex: 0];
1888 [o_msg_arr removeObjectAtIndex: 1];
1890 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1891 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1893 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1894 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1895 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1896 [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
1897 [o_msg_arr addObject: [o_msg_color autorelease]];
1899 b_msg_arr_changed = YES;
1900 [o_msg_lock unlock];
1904 - (IBAction)saveDebugLog:(id)sender
1906 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1908 [saveFolderPanel setCanSelectHiddenExtension: NO];
1909 [saveFolderPanel setCanCreateDirectories: YES];
1910 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtf"]];
1911 [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
1912 [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
1913 if( returnCode == NSOKButton )
1915 NSUInteger count = [o_msg_arr count];
1916 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1917 for (NSUInteger i = 0; i < count; i++)
1918 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1920 NSData *data = [string RTFFromRange:NSMakeRange( 0, [string length] )
1921 documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
1923 if( [data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO )
1924 msg_Warn( p_intf, "Error while saving the debug log" );
1929 [saveFolderPanel release];
1933 #pragma mark Playlist toggling
1935 - (void)updateTogglePlaylistState
1937 [[self playlist] outlineViewSelectionDidChange: NULL];
1944 @implementation VLCMain (Internal)
1946 - (void)handlePortMessage:(NSPortMessage *)o_msg
1951 NSInvocation * o_inv;
1952 NSConditionLock * o_lock;
1954 o_data = [[o_msg components] lastObject];
1955 o_inv = *((NSInvocation **)[o_data bytes]);
1956 [o_inv getArgument: &o_value atIndex: 2];
1957 val = (id **)[o_value pointerValue];
1958 [o_inv setArgument: val[1] atIndex: 2];
1963 [o_lock unlockWithCondition: 1];
1965 - (void)resetMediaKeyJump
1967 b_mediakeyJustJumped = NO;
1969 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1971 b_mediaKeySupport = var_InheritBool( VLCIntf, "macosx-mediakeys" );
1972 if (b_mediaKeySupport)
1974 if (!o_mediaKeyController)
1975 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1976 [o_mediaKeyController startWatchingMediaKeys];
1978 else if (!b_mediaKeySupport && o_mediaKeyController)
1979 [o_mediaKeyController stopWatchingMediaKeys];
1984 /*****************************************************************************
1985 * VLCApplication interface
1986 *****************************************************************************/
1988 @implementation VLCApplication
1989 // when user selects the quit menu from dock it sends a terminate:
1990 // but we need to send a stop: to properly exits libvlc.
1991 // However, we are not able to change the action-method sent by this standard menu item.
1992 // thus we override terminate: to send a stop:
1993 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1994 - (void)terminate:(id)sender
1996 [self activateIgnoringOtherApps:YES];