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_aout_intf.h>
43 #include <vlc_vout_window.h>
44 #include <unistd.h> /* execl() */
46 #import "CompatibilityFixes.h"
52 #import "playlistinfo.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.h"
60 #import "simple_prefs.h"
61 #import "CoreInteraction.h"
62 #import "TrackSynchronization.h"
64 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
65 #import <Sparkle/Sparkle.h> /* we're the update delegate */
67 /*****************************************************************************
69 *****************************************************************************/
70 static void Run ( intf_thread_t *p_intf );
72 static void updateProgressPanel (void *, const char *, float);
73 static bool checkProgressPanel (void *);
74 static void destroyProgressPanel (void *);
76 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
78 static int InputEvent( vlc_object_t *, const char *,
79 vlc_value_t, vlc_value_t, void * );
80 static int PLItemChanged( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int PlaylistUpdated( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
84 static int PlaybackModeUpdated( vlc_object_t *, const char *,
85 vlc_value_t, vlc_value_t, void * );
86 static int VolumeUpdated( vlc_object_t *, const char *,
87 vlc_value_t, vlc_value_t, void * );
90 #pragma mark VLC Interface Object Callbacks
92 /*****************************************************************************
93 * OpenIntf: initialize interface
94 *****************************************************************************/
95 int OpenIntf ( vlc_object_t *p_this )
97 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
98 [VLCApplication sharedApplication];
99 intf_thread_t *p_intf = (intf_thread_t*) p_this;
101 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
102 if( p_intf->p_sys == NULL )
105 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
107 /* subscribe to LibVLCCore's messages */
108 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
109 p_intf->pf_run = Run;
110 p_intf->b_should_run_on_first_thread = true;
116 /*****************************************************************************
117 * CloseIntf: destroy interface
118 *****************************************************************************/
119 void CloseIntf ( vlc_object_t *p_this )
121 intf_thread_t *p_intf = (intf_thread_t*) p_this;
123 free( p_intf->p_sys );
126 static int WindowControl( vout_window_t *, int i_query, va_list );
128 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
130 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
131 intf_thread_t *p_intf = VLCIntf;
133 msg_Err( p_wnd, "Mac OS X interface not found" );
139 unsigned i_width = cfg->width;
140 unsigned i_height = cfg->height;
141 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
143 if ( !p_wnd->handle.nsobject ) {
144 msg_Err( p_wnd, "got no video view from the interface" );
149 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
150 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
151 p_wnd->control = WindowControl;
152 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
157 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
160 if( i_query == VOUT_WINDOW_SET_STATE )
161 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
162 else if( i_query == VOUT_WINDOW_SET_SIZE )
164 unsigned int i_width = va_arg( args, unsigned int );
165 unsigned int i_height = va_arg( args, unsigned int );
166 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
168 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
170 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
171 [[VLCMain sharedInstance] fullscreenChanged];
175 msg_Dbg( p_wnd, "WindowControl: unknown query" );
179 void WindowClose( vout_window_t *p_wnd )
181 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
182 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
187 /*****************************************************************************
189 *****************************************************************************/
190 static NSLock * o_appLock = nil; // controls access to f_appExit
191 static int f_appExit = 0; // set to 1 when application termination signaled
193 static void Run( intf_thread_t *p_intf )
197 /* Make sure the "force quit" menu item does quit instantly.
198 * VLC overrides SIGTERM which is sent by the "force quit"
199 * menu item to make sure daemon mode quits gracefully, so
200 * we un-override SIGTERM here. */
202 sigaddset( &set, SIGTERM );
203 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
205 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
206 [VLCApplication sharedApplication];
208 o_appLock = [[NSLock alloc] init];
210 [[VLCMain sharedInstance] setIntf: p_intf];
211 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
214 [[VLCMain sharedInstance] applicationWillTerminate:nil];
220 #pragma mark Variables Callback
222 /*****************************************************************************
223 * MsgCallback: Callback triggered by the core once a new debug message is
224 * ready to be displayed. We store everything in a NSArray in our Cocoa part
226 *****************************************************************************/
227 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
229 int canc = vlc_savecancel();
232 if (vasprintf( &str, format, ap ) == -1)
234 vlc_restorecancel( canc );
238 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
239 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
242 vlc_restorecancel( canc );
246 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
247 vlc_value_t oldval, vlc_value_t new_val, void *param )
249 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
250 switch (new_val.i_int) {
251 case INPUT_EVENT_STATE:
252 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
254 case INPUT_EVENT_RATE:
255 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
257 case INPUT_EVENT_POSITION:
258 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
260 case INPUT_EVENT_TITLE:
261 case INPUT_EVENT_CHAPTER:
262 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
264 case INPUT_EVENT_CACHE:
265 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
267 case INPUT_EVENT_STATISTICS:
268 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
272 case INPUT_EVENT_TELETEXT:
274 case INPUT_EVENT_AOUT:
276 case INPUT_EVENT_VOUT:
278 case INPUT_EVENT_ITEM_META:
279 case INPUT_EVENT_ITEM_INFO:
280 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
281 [[VLCMain sharedInstance] updateName];
282 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
284 case INPUT_EVENT_BOOKMARK:
286 case INPUT_EVENT_RECORD:
287 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
289 case INPUT_EVENT_PROGRAM:
290 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
292 case INPUT_EVENT_ITEM_EPG:
294 case INPUT_EVENT_SIGNAL:
297 case INPUT_EVENT_ITEM_NAME:
298 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
299 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
302 case INPUT_EVENT_AUDIO_DELAY:
303 case INPUT_EVENT_SUBTITLE_DELAY:
304 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
307 case INPUT_EVENT_DEAD:
308 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
309 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
312 case INPUT_EVENT_ABORT:
313 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
314 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
318 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
326 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
327 vlc_value_t oldval, vlc_value_t new_val, void *param )
329 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
330 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
336 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
337 vlc_value_t oldval, vlc_value_t new_val, void *param )
339 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
340 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
346 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
347 vlc_value_t oldval, vlc_value_t new_val, void *param )
349 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
350 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
356 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
357 vlc_value_t oldval, vlc_value_t new_val, void *param )
359 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
360 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
366 /*****************************************************************************
367 * ShowController: Callback triggered by the show-intf playlist variable
368 * through the ShowIntf-control-intf, to let us show the controller-win;
369 * usually when in fullscreen-mode
370 *****************************************************************************/
371 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
372 vlc_value_t old_val, vlc_value_t new_val, void *param )
374 intf_thread_t * p_intf = VLCIntf;
375 if( p_intf && p_intf->p_sys )
377 playlist_t * p_playlist = pl_Get( p_intf );
378 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
379 if( strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen )
381 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
385 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
391 /*****************************************************************************
392 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
393 * variable, to let the intf update the controller.
394 *****************************************************************************/
395 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
396 vlc_value_t old_val, vlc_value_t new_val, void *param )
398 intf_thread_t * p_intf = VLCIntf;
401 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
402 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
408 /*****************************************************************************
409 * DialogCallback: Callback triggered by the "dialog-*" variables
410 * to let the intf display error and interaction dialogs
411 *****************************************************************************/
412 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
414 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
415 VLCMain *interface = (VLCMain *)data;
417 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
419 /* the progress panel needs to update itself and therefore wants special treatment within this context */
420 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
422 p_dialog->pf_update = updateProgressPanel;
423 p_dialog->pf_check = checkProgressPanel;
424 p_dialog->pf_destroy = destroyProgressPanel;
425 p_dialog->p_sys = VLCIntf->p_libvlc;
428 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
429 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
435 void updateProgressPanel (void *priv, const char *text, float value)
437 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
441 o_txt = [NSString stringWithUTF8String: text];
445 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
450 void destroyProgressPanel (void *priv)
452 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
453 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:NO];
457 bool checkProgressPanel (void *priv)
459 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
460 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
467 input_thread_t *getInput(void)
469 intf_thread_t *p_intf = VLCIntf;
472 return pl_CurrentInput(p_intf);
475 vout_thread_t *getVout(void)
477 input_thread_t *p_input = getInput();
480 vout_thread_t *p_vout = input_GetVout(p_input);
481 vlc_object_release(p_input);
485 audio_output_t *getAout(void)
487 input_thread_t *p_input = getInput();
490 audio_output_t *p_aout = input_GetAout(p_input);
491 vlc_object_release(p_input);
498 @interface VLCMain ()
499 - (void)_removeOldPreferences;
502 /*****************************************************************************
503 * VLCMain implementation
504 *****************************************************************************/
505 @implementation VLCMain
508 #pragma mark Initialization
510 static VLCMain *_o_sharedMainInstance = nil;
512 + (VLCMain *)sharedInstance
514 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
519 if( _o_sharedMainInstance)
522 return _o_sharedMainInstance;
525 _o_sharedMainInstance = [super init];
529 o_msg_lock = [[NSLock alloc] init];
530 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
532 o_open = [[VLCOpen alloc] init];
533 //o_embedded_list = [[VLCEmbeddedList alloc] init];
534 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
535 o_info = [[VLCInfo alloc] init];
536 o_mainmenu = [[VLCMainMenu alloc] init];
537 o_coreinteraction = [[VLCCoreInteraction alloc] init];
538 o_eyetv = [[VLCEyeTVController alloc] init];
539 o_mainwindow = [[VLCMainWindow alloc] init];
541 /* announce our launch to a potential eyetv plugin */
542 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
543 object: @"VLCEyeTVSupport"
545 deliverImmediately: YES];
547 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
548 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
549 [defaults registerDefaults:appDefaults];
551 return _o_sharedMainInstance;
554 - (void)setIntf: (intf_thread_t *)p_mainintf {
558 - (intf_thread_t *)intf {
564 playlist_t *p_playlist;
566 if( !p_intf ) return;
567 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
569 /* Check if we already did this once. Opening the other nibs calls it too,
570 because VLCMain is the owner */
571 if( nib_main_loaded ) return;
573 [o_msgs_panel setExcludedFromWindowsMenu: YES];
574 [o_msgs_panel setDelegate: self];
576 p_playlist = pl_Get( p_intf );
580 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
581 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
582 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
583 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
584 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
585 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
586 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
587 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
588 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
589 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
590 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
591 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
592 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
593 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
597 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
598 var_SetBool( p_playlist, "fullscreen", YES );
601 /* load our Core Dialogs nib */
602 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
604 /* subscribe to various interactive dialogues */
605 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
606 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
607 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
608 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
609 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
610 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
611 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
612 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
613 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
614 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
615 dialog_Register( p_intf );
617 [self playbackModeUpdated];
619 /* init Apple Remote support */
620 o_remote = [[AppleRemote alloc] init];
621 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
622 [o_remote setDelegate: _o_sharedMainInstance];
624 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
626 /* yeah, we are done */
627 b_nativeFullscreenMode = NO;
628 #ifdef MAC_OS_X_VERSION_10_7
629 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
631 nib_main_loaded = TRUE;
634 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
636 if( !p_intf ) return;
638 /* init media key support */
639 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
640 if( b_mediaKeySupport )
642 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
643 [o_mediaKeyController startWatchingMediaKeys];
644 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
645 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
648 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
650 [self _removeOldPreferences];
652 [o_mainwindow updateWindow];
653 [o_mainwindow updateTimeSlider];
654 [o_mainwindow updateVolumeSlider];
655 [o_mainwindow makeKeyAndOrderFront: self];
657 /* Handle sleep notification */
658 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
659 name:NSWorkspaceWillSleepNotification object:nil];
661 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
663 /* we will need this, so let's load it here so the interface appears to be more responsive */
664 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
670 if( !p_intf ) return;
673 [o_msgs_panel setTitle: _NS("Messages")];
674 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
675 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
677 /* crash reporter panel */
678 [o_crashrep_send_btn setTitle: _NS("Send")];
679 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
680 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
681 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
682 [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, ...")];
683 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
684 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
688 #pragma mark Termination
690 - (void)applicationWillTerminate:(NSNotification *)notification
692 if (notification == nil)
693 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
695 playlist_t * p_playlist;
696 int returnedValue = 0;
702 config_SaveConfigFile( p_intf );
704 // don't allow a double termination call. If the user has
705 // already invoked the quit then simply return this time.
706 int isTerminating = false;
709 isTerminating = (f_appExit++ > 0 ? 1 : 0);
715 msg_Dbg( p_intf, "Terminating" );
717 p_playlist = pl_Get( p_intf );
719 /* unsubscribe from the interactive dialogues */
720 dialog_Unregister( p_intf );
721 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
722 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
723 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
724 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
725 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
726 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
727 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
728 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
729 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
730 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
731 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
732 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
733 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
734 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
735 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
736 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
737 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
738 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
739 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
741 /* remove global observer watching for vout device changes correctly */
742 [[NSNotificationCenter defaultCenter] removeObserver: self];
744 /* release some other objects here, because it isn't sure whether dealloc
745 * will be called later on */
760 [crashLogURLConnection cancel];
761 [crashLogURLConnection release];
763 [o_embedded_list release];
764 [o_coredialogs release];
766 [o_mainwindow release];
768 /* unsubscribe from libvlc's debug messages */
769 vlc_Unsubscribe( p_intf->p_sys->p_sub );
771 [o_msg_arr removeAllObjects];
774 [o_msg_lock release];
776 /* write cached user defaults to disk */
777 [[NSUserDefaults standardUserDefaults] synchronize];
779 /* Make sure the Menu doesn't have any references to vlc objects anymore */
780 //FIXME: this should be moved to VLCMainMenu
781 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
782 [o_mainmenu release];
784 libvlc_Quit( p_intf->p_libvlc );
790 #pragma mark Sparkle delegate
791 /* received directly before the update gets installed, so let's shut down a bit */
792 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
794 [NSApp activateIgnoringOtherApps:YES];
795 [o_remote stopListening: self];
796 [[VLCCoreInteraction sharedInstance] stop];
800 #pragma mark Media Key support
802 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
804 if( b_mediaKeySupport )
806 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
808 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
809 int keyFlags = ([event data1] & 0x0000FFFF);
810 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
811 int keyRepeat = (keyFlags & 0x1);
813 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
814 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
816 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
818 if( keyState == 0 && keyRepeat == 0 )
819 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
820 else if( keyRepeat == 1 )
822 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
823 b_mediakeyJustJumped = YES;
824 [self performSelector:@selector(resetMediaKeyJump)
830 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
832 if( keyState == 0 && keyRepeat == 0 )
833 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
834 else if( keyRepeat == 1 )
836 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
837 b_mediakeyJustJumped = YES;
838 [self performSelector:@selector(resetMediaKeyJump)
847 #pragma mark Other notification
849 /* Listen to the remote in exclusive mode, only when VLC is the active
851 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
853 if( !p_intf ) return;
854 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
855 [o_remote startListening: self];
857 - (void)applicationDidResignActive:(NSNotification *)aNotification
859 if( !p_intf ) return;
860 [o_remote stopListening: self];
863 /* Triggered when the computer goes to sleep */
864 - (void)computerWillSleep: (NSNotification *)notification
866 [[VLCCoreInteraction sharedInstance] pause];
870 #pragma mark File opening
872 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
874 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
875 char *psz_uri = make_URI([o_filename UTF8String], "file" );
879 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
884 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
886 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
891 /* When user click in the Dock icon our double click in the finder */
892 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
894 if(!hasVisibleWindows)
895 [o_mainwindow makeKeyAndOrderFront:self];
901 #pragma mark Apple Remote Control
903 /* Helper method for the remote control interface in order to trigger forward/backward and volume
904 increase/decrease as long as the user holds the left/right, plus/minus button */
905 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
907 if(b_remote_button_hold)
909 switch([buttonIdentifierNumber intValue])
911 case kRemoteButtonRight_Hold:
912 [[VLCCoreInteraction sharedInstance] forward];
914 case kRemoteButtonLeft_Hold:
915 [[VLCCoreInteraction sharedInstance] backward];
917 case kRemoteButtonVolume_Plus_Hold:
918 [[VLCCoreInteraction sharedInstance] volumeUp];
920 case kRemoteButtonVolume_Minus_Hold:
921 [[VLCCoreInteraction sharedInstance] volumeDown];
924 if(b_remote_button_hold)
927 [self performSelector:@selector(executeHoldActionForRemoteButton:)
928 withObject:buttonIdentifierNumber
934 /* Apple Remote callback */
935 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
936 pressedDown: (BOOL) pressedDown
937 clickCount: (unsigned int) count
939 switch( buttonIdentifier )
941 case k2009RemoteButtonFullscreen:
942 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
944 case k2009RemoteButtonPlay:
945 [[VLCCoreInteraction sharedInstance] play];
947 case kRemoteButtonPlay:
949 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
951 [[VLCCoreInteraction sharedInstance] play];
954 case kRemoteButtonVolume_Plus:
955 [[VLCCoreInteraction sharedInstance] volumeUp];
957 case kRemoteButtonVolume_Minus:
958 [[VLCCoreInteraction sharedInstance] volumeDown];
960 case kRemoteButtonRight:
961 [[VLCCoreInteraction sharedInstance] next];
963 case kRemoteButtonLeft:
964 [[VLCCoreInteraction sharedInstance] previous];
966 case kRemoteButtonRight_Hold:
967 case kRemoteButtonLeft_Hold:
968 case kRemoteButtonVolume_Plus_Hold:
969 case kRemoteButtonVolume_Minus_Hold:
970 /* simulate an event as long as the user holds the button */
971 b_remote_button_hold = pressedDown;
974 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
975 [self performSelector:@selector(executeHoldActionForRemoteButton:)
976 withObject:buttonIdentifierNumber];
979 case kRemoteButtonMenu:
980 [o_controls showPosition: self]; //FIXME
983 /* Add here whatever you want other buttons to do */
989 #pragma mark String utility
990 // FIXME: this has nothing to do here
992 - (NSString *)localizedString:(const char *)psz
994 NSString * o_str = nil;
998 o_str = [NSString stringWithCString: _(psz) encoding:NSUTF8StringEncoding];
1002 msg_Err( VLCIntf, "could not translate: %s", psz );
1008 msg_Warn( VLCIntf, "can't translate empty strings" );
1017 - (char *)delocalizeString:(NSString *)id
1019 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1020 allowLossyConversion: NO];
1025 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1026 allowLossyConversion: YES];
1027 psz_string = malloc( [o_data length] + 1 );
1028 [o_data getBytes: psz_string];
1029 psz_string[ [o_data length] ] = '\0';
1030 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1035 psz_string = malloc( [o_data length] + 1 );
1036 [o_data getBytes: psz_string];
1037 psz_string[ [o_data length] ] = '\0';
1043 /* i_width is in pixels */
1044 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1046 NSMutableString *o_wrapped;
1047 NSString *o_out_string;
1048 NSRange glyphRange, effectiveRange, charRange;
1049 NSRect lineFragmentRect;
1050 unsigned glyphIndex, breaksInserted = 0;
1052 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1053 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1054 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1055 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1056 NSTextContainer *o_container = [[NSTextContainer alloc]
1057 initWithContainerSize: NSMakeSize(i_width, 2000)];
1059 [o_layout_manager addTextContainer: o_container];
1060 [o_container release];
1061 [o_storage addLayoutManager: o_layout_manager];
1062 [o_layout_manager release];
1064 o_wrapped = [o_in_string mutableCopy];
1065 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1067 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1068 glyphIndex += effectiveRange.length) {
1069 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1070 effectiveRange: &effectiveRange];
1071 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1072 actualGlyphRange: &effectiveRange];
1073 if([o_wrapped lineRangeForRange:
1074 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1075 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1079 o_out_string = [NSString stringWithString: o_wrapped];
1080 [o_wrapped release];
1081 [o_storage release];
1083 return o_out_string;
1088 #pragma mark Key Shortcuts
1093 unsigned int i_vlckey;
1094 } nskeys_to_vlckeys[] =
1096 { NSUpArrowFunctionKey, KEY_UP },
1097 { NSDownArrowFunctionKey, KEY_DOWN },
1098 { NSLeftArrowFunctionKey, KEY_LEFT },
1099 { NSRightArrowFunctionKey, KEY_RIGHT },
1100 { NSF1FunctionKey, KEY_F1 },
1101 { NSF2FunctionKey, KEY_F2 },
1102 { NSF3FunctionKey, KEY_F3 },
1103 { NSF4FunctionKey, KEY_F4 },
1104 { NSF5FunctionKey, KEY_F5 },
1105 { NSF6FunctionKey, KEY_F6 },
1106 { NSF7FunctionKey, KEY_F7 },
1107 { NSF8FunctionKey, KEY_F8 },
1108 { NSF9FunctionKey, KEY_F9 },
1109 { NSF10FunctionKey, KEY_F10 },
1110 { NSF11FunctionKey, KEY_F11 },
1111 { NSF12FunctionKey, KEY_F12 },
1112 { NSInsertFunctionKey, KEY_INSERT },
1113 { NSHomeFunctionKey, KEY_HOME },
1114 { NSEndFunctionKey, KEY_END },
1115 { NSPageUpFunctionKey, KEY_PAGEUP },
1116 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1117 { NSMenuFunctionKey, KEY_MENU },
1118 { NSTabCharacter, KEY_TAB },
1119 { NSCarriageReturnCharacter, KEY_ENTER },
1120 { NSEnterCharacter, KEY_ENTER },
1121 { NSBackspaceCharacter, KEY_BACKSPACE },
1122 { NSDeleteCharacter, KEY_DELETE },
1126 unsigned int CocoaKeyToVLC( unichar i_key )
1130 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1132 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1134 return nskeys_to_vlckeys[i].i_vlckey;
1137 return (unsigned int)i_key;
1140 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1142 unsigned int new = 0;
1144 if([theString rangeOfString:@"Command"].location != NSNotFound)
1145 new |= NSCommandKeyMask;
1146 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1147 new |= NSAlternateKeyMask;
1148 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1149 new |= NSShiftKeyMask;
1150 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1151 new |= NSControlKeyMask;
1155 - (NSString *)VLCKeyToString:(NSString *)theString
1157 if (![theString isEqualToString:@""]) {
1158 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1159 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1162 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1163 theString = [NSString stringWithFormat:@"%@+", theString];
1165 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1166 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1169 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1170 theString = [NSString stringWithFormat:@"%@-", theString];
1172 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1173 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1174 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1175 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1177 if ([theString length] > 1)
1179 if([theString rangeOfString:@"Up"].location != NSNotFound)
1180 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1181 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1182 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1183 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1184 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1185 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1186 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1187 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1188 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1189 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1190 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1191 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1192 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1193 else if([theString rangeOfString:@"End"].location != NSNotFound)
1194 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1195 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1196 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1197 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1198 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1199 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1200 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1201 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1202 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1203 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1204 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1205 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1206 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1207 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1208 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1209 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1210 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1211 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1212 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1213 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1214 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1215 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1216 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1217 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1218 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1219 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1220 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1221 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1222 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1223 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1224 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1225 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1226 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1227 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1228 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1229 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1230 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1231 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1238 /*****************************************************************************
1239 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1240 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1241 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1242 *****************************************************************************/
1243 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1247 unsigned int i_pressed_modifiers = 0;
1248 const struct hotkey *p_hotkeys;
1250 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1251 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1254 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1256 i_pressed_modifiers = [o_event modifierFlags];
1258 if( i_pressed_modifiers & NSShiftKeyMask ) {
1259 val.i_int |= KEY_MODIFIER_SHIFT;
1260 [tempString appendString:@"Shift-"];
1261 [tempStringPlus appendString:@"Shift+"];
1263 if( i_pressed_modifiers & NSControlKeyMask ) {
1264 val.i_int |= KEY_MODIFIER_CTRL;
1265 [tempString appendString:@"Ctrl-"];
1266 [tempStringPlus appendString:@"Ctrl+"];
1268 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1269 val.i_int |= KEY_MODIFIER_ALT;
1270 [tempString appendString:@"Alt-"];
1271 [tempStringPlus appendString:@"Alt+"];
1273 if( i_pressed_modifiers & NSCommandKeyMask ) {
1274 val.i_int |= KEY_MODIFIER_COMMAND;
1275 [tempString appendString:@"Command-"];
1276 [tempStringPlus appendString:@"Command+"];
1279 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1280 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1282 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1286 case NSDeleteCharacter:
1287 case NSDeleteFunctionKey:
1288 case NSDeleteCharFunctionKey:
1289 case NSBackspaceCharacter:
1290 case NSUpArrowFunctionKey:
1291 case NSDownArrowFunctionKey:
1292 case NSRightArrowFunctionKey:
1293 case NSLeftArrowFunctionKey:
1294 case NSEnterCharacter:
1295 case NSCarriageReturnCharacter:
1299 if( key == 0x0020 ) // space key
1301 [[VLCCoreInteraction sharedInstance] play];
1305 val.i_int |= CocoaKeyToVLC( key );
1307 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1309 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1316 - (void)updateCurrentlyUsedHotkeys
1318 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1319 /* Get the main Module */
1320 module_t *p_main = module_get_main();
1323 module_config_t *p_config;
1325 p_config = module_config_get (p_main, &confsize);
1327 for (size_t i = 0; i < confsize; i++)
1329 module_config_t *p_item = p_config + i;
1331 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1332 && !strncmp( p_item->psz_name , "key-", 4 )
1333 && !EMPTY_STR( p_item->psz_text ) )
1335 if (p_item->value.psz)
1336 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1339 module_config_free (p_config);
1340 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1344 #pragma mark Interface updaters
1345 - (void)fullscreenChanged
1347 playlist_t * p_playlist = pl_Get( VLCIntf );
1348 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1350 if (OSX_LION && b_nativeFullscreenMode)
1352 [o_mainwindow toggleFullScreen: self];
1354 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1356 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1362 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1363 if( p_input != NULL && [self activeVideoPlayback] )
1365 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1366 vlc_object_release( p_input );
1371 // leaving fullscreen is always allowed
1372 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1377 - (void)PlaylistItemChanged
1379 input_thread_t * p_input;
1381 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1382 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1384 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1385 [o_mainmenu setRateControlsEnabled: YES];
1386 vlc_object_release( p_input );
1389 [o_mainmenu setRateControlsEnabled: NO];
1391 [o_playlist updateRowSelection];
1392 [o_mainwindow updateWindow];
1393 [self updateMainMenu];
1396 - (void)updateMainMenu
1398 [o_mainmenu setupMenus];
1399 [o_mainmenu updatePlaybackRate];
1402 - (void)updateMainWindow
1404 [o_mainwindow updateWindow];
1407 - (void)showMainWindow
1409 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1412 - (void)showFullscreenController
1414 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1417 - (void)updateDelays
1419 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1424 [o_mainwindow updateName];
1427 - (void)updatePlaybackPosition
1429 [o_mainwindow updateTimeSlider];
1431 input_thread_t * p_input;
1432 p_input = pl_CurrentInput( p_intf );
1435 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1436 UpdateSystemActivity( UsrActivity );
1437 vlc_object_release( p_input );
1441 - (void)updateVolume
1443 [o_mainwindow updateVolumeSlider];
1446 - (void)playlistUpdated
1448 [self playbackStatusUpdated];
1449 [o_playlist playlistUpdated];
1450 [o_mainwindow updateWindow];
1451 [o_mainwindow updateName];
1454 - (void)updateRecordState: (BOOL)b_value
1456 [o_mainmenu updateRecordState:b_value];
1459 - (void)updateInfoandMetaPanel
1461 [o_playlist outlineViewSelectionDidChange:nil];
1464 - (void)playbackStatusUpdated
1466 input_thread_t * p_input;
1468 p_input = pl_CurrentInput( p_intf );
1471 int state = var_GetInteger( p_input, "state" );
1472 if( state == PLAYING_S )
1474 [[self mainMenu] setPause];
1475 [o_mainwindow setPause];
1480 [o_mainmenu setSubmenusEnabled: FALSE];
1481 [[self mainMenu] setPlay];
1482 [o_mainwindow setPlay];
1484 vlc_object_release( p_input );
1487 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1488 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1491 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1493 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1496 deliverImmediately:YES];
1499 - (void)playbackModeUpdated
1501 vlc_value_t looping,repeating;
1502 playlist_t * p_playlist = pl_Get( VLCIntf );
1504 bool loop = var_GetBool( p_playlist, "loop" );
1505 bool repeat = var_GetBool( p_playlist, "repeat" );
1507 [o_mainwindow setRepeatOne];
1508 [o_mainmenu setRepeatOne];
1510 [o_mainwindow setRepeatAll];
1511 [o_mainmenu setRepeatAll];
1513 [o_mainwindow setRepeatOff];
1514 [o_mainmenu setRepeatOff];
1517 [o_mainwindow setShuffle];
1518 [o_mainmenu setShuffle];
1522 #pragma mark Other objects getters
1540 o_bookmarks = [[VLCBookmarks alloc] init];
1542 if( !nib_bookmarks_loaded )
1543 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1553 if (!nib_open_loaded)
1554 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1559 - (id)simplePreferences
1562 o_sprefs = [[VLCSimplePrefs alloc] init];
1564 if (!nib_prefs_loaded)
1565 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1573 o_prefs = [[VLCPrefs alloc] init];
1575 if( !nib_prefs_loaded )
1576 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1591 if(! nib_info_loaded )
1592 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1603 o_wizard = [[VLCWizard alloc] init];
1605 if( !nib_wizard_loaded )
1607 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1608 [o_wizard initStrings];
1613 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1615 id videoView = [o_mainwindow videoView];
1616 NSRect videoRect = [videoView frame];
1617 int i_x = (int)videoRect.origin.x;
1618 int i_y = (int)videoRect.origin.y;
1619 unsigned int i_width = (int)videoRect.size.width;
1620 unsigned int i_height = (int)videoRect.size.height;
1623 pi_width = &i_width;
1624 pi_height = &i_height;
1625 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1629 - (void)setNativeVideoSize:(NSSize)size
1631 [o_mainwindow setNativeVideoSize:size];
1636 if( o_embedded_list )
1637 return o_embedded_list;
1642 - (id)coreDialogProvider
1645 return o_coredialogs;
1650 - (id)eyeTVController
1658 - (id)appleRemoteController
1663 - (void)setActiveVideoPlayback:(BOOL)b_value
1665 b_active_videoplayback = b_value;
1666 [o_mainwindow setVideoplayEnabled];
1667 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1670 - (BOOL)activeVideoPlayback
1672 return b_active_videoplayback;
1676 #pragma mark Crash Log
1677 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1679 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1680 NSURL *url = [NSURL URLWithString:urlStr];
1682 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1683 [req setHTTPMethod:@"POST"];
1686 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1688 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1689 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1690 email = [emails valueAtIndex:[emails indexForIdentifier:
1691 [emails primaryIdentifier]]];
1694 email = [NSString string];
1697 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1698 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1699 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1700 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1702 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1704 /* Released from delegate */
1705 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1708 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1710 [crashLogURLConnection release];
1711 crashLogURLConnection = nil;
1714 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1716 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1717 [crashLogURLConnection release];
1718 crashLogURLConnection = nil;
1721 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1723 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1724 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1726 NSString * latestLog = nil;
1727 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1728 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1729 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1730 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1732 while (fname = [direnum nextObject])
1734 [direnum skipDescendents];
1735 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1737 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1738 if( [compo count] < 3 ) continue;
1739 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1740 if( [compo count] < 4 ) continue;
1743 if( year < [[compo objectAtIndex:0] intValue] ||
1744 (year ==[[compo objectAtIndex:0] intValue] &&
1745 (month < [[compo objectAtIndex:1] intValue] ||
1746 (month ==[[compo objectAtIndex:1] intValue] &&
1747 (day < [[compo objectAtIndex:2] intValue] ||
1748 (day ==[[compo objectAtIndex:2] intValue] &&
1749 hours < [[compo objectAtIndex:3] intValue] ))))))
1751 year = [[compo objectAtIndex:0] intValue];
1752 month = [[compo objectAtIndex:1] intValue];
1753 day = [[compo objectAtIndex:2] intValue];
1754 hours = [[compo objectAtIndex:3] intValue];
1755 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1760 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1763 if( !previouslySeen )
1765 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1766 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1767 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1768 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1773 - (NSString *)latestCrashLogPath
1775 return [self latestCrashLogPathPreviouslySeen:YES];
1778 - (void)lookForCrashLog
1780 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1781 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1782 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1783 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1784 if( latestLog && !areCrashLogsTooOld )
1785 [NSApp runModalForWindow: o_crashrep_win];
1789 - (IBAction)crashReporterAction:(id)sender
1791 if( sender == o_crashrep_send_btn )
1792 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1795 [o_crashrep_win orderOut: sender];
1798 - (IBAction)openCrashLog:(id)sender
1800 NSString * latestLog = [self latestCrashLogPath];
1803 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1807 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.") );
1812 #pragma mark Remove old prefs
1814 - (void)_removeOldPreferences
1816 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1817 static const int kCurrentPreferencesVersion = 1;
1818 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1819 if( version >= kCurrentPreferencesVersion ) return;
1821 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1822 NSUserDomainMask, YES);
1823 if( !libraries || [libraries count] == 0) return;
1824 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1826 /* File not found, don't attempt anything */
1827 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1828 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1830 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1834 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1835 _NS("We just found an older version of VLC's preferences files."),
1836 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1837 if( res != NSOKButton )
1839 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1843 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1845 /* Move the file to trash so that user can find them later */
1846 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1848 /* really reset the defaults from now on */
1849 [NSUserDefaults resetStandardUserDefaults];
1851 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1852 [[NSUserDefaults standardUserDefaults] synchronize];
1855 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1857 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1863 execl(path, path, NULL);
1867 #pragma mark Errors, warnings and messages
1868 - (IBAction)updateMessagesPanel:(id)sender
1870 [self windowDidBecomeKey:nil];
1873 - (IBAction)showMessagesPanel:(id)sender
1875 [o_msgs_panel makeKeyAndOrderFront: sender];
1878 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1880 [o_msgs_table reloadData];
1881 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1884 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1886 if (aTableView == o_msgs_table)
1887 return [o_msg_arr count];
1891 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1893 NSMutableAttributedString *result = NULL;
1896 if( rowIndex < [o_msg_arr count] )
1897 result = [o_msg_arr objectAtIndex: rowIndex];
1898 [o_msg_lock unlock];
1900 if( result != NULL )
1906 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1908 NSColor *o_white = [NSColor whiteColor];
1909 NSColor *o_red = [NSColor redColor];
1910 NSColor *o_yellow = [NSColor yellowColor];
1911 NSColor *o_gray = [NSColor grayColor];
1912 NSString * firstString, * secondString;
1914 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1915 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1917 NSDictionary *o_attr;
1918 NSMutableAttributedString *o_msg_color;
1922 if( [o_msg_arr count] + 2 > 600 )
1924 [o_msg_arr removeObjectAtIndex: 0];
1925 [o_msg_arr removeObjectAtIndex: 1];
1927 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1928 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1930 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1931 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1932 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1933 [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
1934 [o_msg_arr addObject: [o_msg_color autorelease]];
1936 b_msg_arr_changed = YES;
1937 [o_msg_lock unlock];
1940 - (IBAction)saveDebugLog:(id)sender
1942 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1944 [saveFolderPanel setCanSelectHiddenExtension: NO];
1945 [saveFolderPanel setCanCreateDirectories: YES];
1946 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1947 [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VERSION_MESSAGE] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
1950 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1953 if( returnCode == NSOKButton )
1955 NSUInteger count = [o_msg_arr count];
1956 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1957 for (NSUInteger i = 0; i < count; i++)
1959 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1961 b_returned = [[string RTFDFileWrapperFromRange:NSMakeRange( 0, [string length] ) documentAttributes:[NSDictionary dictionaryWithObject: NSRTFDTextDocumentType forKey: NSDocumentTypeDocumentAttribute]] writeToFile:[[sheet URL] path] atomically:YES updateFilenames:NO];
1965 msg_Warn( p_intf, "Error while saving the debug log" );
1970 #pragma mark Playlist toggling
1972 - (void)updateTogglePlaylistState
1974 [[self playlist] outlineViewSelectionDidChange: NULL];
1981 @implementation VLCMain (Internal)
1983 - (void)handlePortMessage:(NSPortMessage *)o_msg
1988 NSInvocation * o_inv;
1989 NSConditionLock * o_lock;
1991 o_data = [[o_msg components] lastObject];
1992 o_inv = *((NSInvocation **)[o_data bytes]);
1993 [o_inv getArgument: &o_value atIndex: 2];
1994 val = (id **)[o_value pointerValue];
1995 [o_inv setArgument: val[1] atIndex: 2];
2000 [o_lock unlockWithCondition: 1];
2002 - (void)resetMediaKeyJump
2004 b_mediakeyJustJumped = NO;
2006 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2008 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2009 if (b_mediaKeySupport) {
2010 if (!o_mediaKeyController)
2011 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2012 [o_mediaKeyController startWatchingMediaKeys];
2014 else if (!b_mediaKeySupport && o_mediaKeyController)
2016 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
2017 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
2018 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
2019 if( returnedValue == NSOKButton )
2022 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2024 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2030 execl(path, path, NULL);
2037 /*****************************************************************************
2038 * VLCApplication interface
2039 *****************************************************************************/
2041 @implementation VLCApplication
2042 // when user selects the quit menu from dock it sends a terminate:
2043 // but we need to send a stop: to properly exits libvlc.
2044 // However, we are not able to change the action-method sent by this standard menu item.
2045 // thus we override terminat: to send a stop:
2046 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2047 - (void)terminate:(id)sender
2049 [self activateIgnoringOtherApps:YES];