1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 the VideoLAN team
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 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
42 #import "CompatibilityFixes.h"
48 #import "playlistinfo.h"
53 #import "coredialogs.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
57 #import "CoreInteraction.h"
58 #import "TrackSynchronization.h"
60 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
61 #import <Sparkle/Sparkle.h> /* we're the update delegate */
63 /*****************************************************************************
65 *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
68 static void updateProgressPanel (void *, const char *, float);
69 static bool checkProgressPanel (void *);
70 static void destroyProgressPanel (void *);
72 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
74 static int InputEvent( vlc_object_t *, const char *,
75 vlc_value_t, vlc_value_t, void * );
76 static int PLItemChanged( vlc_object_t *, const char *,
77 vlc_value_t, vlc_value_t, void * );
78 static int PlaylistUpdated( vlc_object_t *, const char *,
79 vlc_value_t, vlc_value_t, void * );
80 static int PlaybackModeUpdated( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int VolumeUpdated( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
86 #pragma mark VLC Interface Object Callbacks
88 /*****************************************************************************
89 * OpenIntf: initialize interface
90 *****************************************************************************/
91 int OpenIntf ( vlc_object_t *p_this )
93 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
94 [VLCApplication sharedApplication];
95 intf_thread_t *p_intf = (intf_thread_t*) p_this;
97 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
98 if( p_intf->p_sys == NULL )
101 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
103 /* subscribe to LibVLCCore's messages */
104 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
105 p_intf->pf_run = Run;
106 p_intf->b_should_run_on_first_thread = true;
112 /*****************************************************************************
113 * CloseIntf: destroy interface
114 *****************************************************************************/
115 void CloseIntf ( vlc_object_t *p_this )
117 intf_thread_t *p_intf = (intf_thread_t*) p_this;
119 free( p_intf->p_sys );
122 static int WindowControl( vout_window_t *, int i_query, va_list );
124 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
126 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
127 intf_thread_t *p_intf = VLCIntf;
129 msg_Err( p_wnd, "Mac OS X interface not found" );
135 unsigned i_width = cfg->width;
136 unsigned i_height = cfg->height;
137 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
139 if ( !p_wnd->handle.nsobject ) {
140 msg_Err( p_wnd, "got no video view from the interface" );
145 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
146 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
147 p_wnd->control = WindowControl;
148 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
153 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
156 if( i_query == VOUT_WINDOW_SET_STATE )
157 NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
158 else if( i_query == VOUT_WINDOW_SET_SIZE )
160 NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
161 unsigned int i_width = va_arg( args, unsigned int );
162 unsigned int i_height = va_arg( args, unsigned int );
163 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
165 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
166 NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
168 NSLog( @"WindowControl: unknown query" );
172 void WindowClose( vout_window_t *p_wnd )
174 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
175 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
176 NSLog( @"Window Close" );
177 // tell the interface to get rid of the video, TODO
181 /*****************************************************************************
183 *****************************************************************************/
184 static NSLock * o_appLock = nil; // controls access to f_appExit
185 static int f_appExit = 0; // set to 1 when application termination signaled
187 static void Run( intf_thread_t *p_intf )
191 /* Make sure the "force quit" menu item does quit instantly.
192 * VLC overrides SIGTERM which is sent by the "force quit"
193 * menu item to make sure daemon mode quits gracefully, so
194 * we un-override SIGTERM here. */
196 sigaddset( &set, SIGTERM );
197 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
199 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
200 [VLCApplication sharedApplication];
202 o_appLock = [[NSLock alloc] init];
204 [[VLCMain sharedInstance] setIntf: p_intf];
205 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
208 [[VLCMain sharedInstance] applicationWillTerminate:nil];
214 #pragma mark Variables Callback
216 /*****************************************************************************
217 * MsgCallback: Callback triggered by the core once a new debug message is
218 * ready to be displayed. We store everything in a NSArray in our Cocoa part
220 *****************************************************************************/
221 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
223 int canc = vlc_savecancel();
226 if (vasprintf( &str, format, ap ) == -1)
228 vlc_restorecancel( canc );
232 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
233 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
236 vlc_restorecancel( canc );
240 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
241 vlc_value_t oldval, vlc_value_t new_val, void *param )
243 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
244 switch (new_val.i_int) {
245 case INPUT_EVENT_STATE:
246 [[VLCMain sharedInstance] playbackStatusUpdated];
248 case INPUT_EVENT_RATE:
249 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
251 case INPUT_EVENT_POSITION:
252 [[VLCMain sharedInstance] updatePlaybackPosition];
254 case INPUT_EVENT_TITLE:
255 case INPUT_EVENT_CHAPTER:
256 [[VLCMain sharedInstance] updateMainMenu];
258 case INPUT_EVENT_CACHE:
259 [[VLCMain sharedInstance] updateMainWindow];
261 case INPUT_EVENT_STATISTICS:
262 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
266 case INPUT_EVENT_TELETEXT:
268 case INPUT_EVENT_AOUT:
270 case INPUT_EVENT_VOUT:
272 case INPUT_EVENT_ITEM_META:
273 case INPUT_EVENT_ITEM_INFO:
274 [[VLCMain sharedInstance] updateMainMenu];
275 [[VLCMain sharedInstance] updateName];
276 [[VLCMain sharedInstance] updateInfoandMetaPanel];
278 case INPUT_EVENT_BOOKMARK:
280 case INPUT_EVENT_RECORD:
281 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
283 case INPUT_EVENT_PROGRAM:
284 [[VLCMain sharedInstance] updateMainMenu];
286 case INPUT_EVENT_ITEM_EPG:
288 case INPUT_EVENT_SIGNAL:
291 case INPUT_EVENT_ITEM_NAME:
292 [[VLCMain sharedInstance] updateName];
293 [[VLCMain sharedInstance] playlistUpdated];
296 case INPUT_EVENT_AUDIO_DELAY:
297 case INPUT_EVENT_SUBTITLE_DELAY:
298 [[VLCMain sharedInstance] updateDelays];
301 case INPUT_EVENT_DEAD:
302 [[VLCMain sharedInstance] updateName];
303 [[VLCMain sharedInstance] updatePlaybackPosition];
306 case INPUT_EVENT_ABORT:
307 [[VLCMain sharedInstance] updateName];
308 [[VLCMain sharedInstance] updatePlaybackPosition];
312 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
320 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
321 vlc_value_t oldval, vlc_value_t new_val, void *param )
323 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
324 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
330 static int PlaylistUpdated( 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(playlistUpdated) withObject:nil waitUntilDone:NO];
340 static int PlaybackModeUpdated( 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] playbackModeUpdated];
350 static int VolumeUpdated( 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(updateVolume) withObject:nil waitUntilDone:NO];
360 /*****************************************************************************
361 * ShowController: Callback triggered by the show-intf playlist variable
362 * through the ShowIntf-control-intf, to let us show the controller-win;
363 * usually when in fullscreen-mode
364 *****************************************************************************/
365 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
366 vlc_value_t old_val, vlc_value_t new_val, void *param )
368 intf_thread_t * p_intf = VLCIntf;
369 if( p_intf && p_intf->p_sys )
371 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
376 /*****************************************************************************
377 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
378 * variable, to let the intf update the controller.
379 *****************************************************************************/
380 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
381 vlc_value_t old_val, vlc_value_t new_val, void *param )
383 intf_thread_t * p_intf = VLCIntf;
386 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
387 [[VLCMain sharedInstance] fullscreenChanged];
393 /*****************************************************************************
394 * DialogCallback: Callback triggered by the "dialog-*" variables
395 * to let the intf display error and interaction dialogs
396 *****************************************************************************/
397 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
399 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
400 VLCMain *interface = (VLCMain *)data;
402 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
404 /* the progress panel needs to update itself and therefore wants special treatment within this context */
405 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
407 p_dialog->pf_update = updateProgressPanel;
408 p_dialog->pf_check = checkProgressPanel;
409 p_dialog->pf_destroy = destroyProgressPanel;
410 p_dialog->p_sys = VLCIntf->p_libvlc;
413 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
414 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
420 void updateProgressPanel (void *priv, const char *text, float value)
422 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
426 o_txt = [NSString stringWithUTF8String: text];
430 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
435 void destroyProgressPanel (void *priv)
437 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
438 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
442 bool checkProgressPanel (void *priv)
444 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
445 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
452 input_thread_t *getInput(void)
454 intf_thread_t *p_intf = VLCIntf;
457 return pl_CurrentInput(p_intf);
460 vout_thread_t *getVout(void)
462 input_thread_t *p_input = getInput();
465 vout_thread_t *p_vout = input_GetVout(p_input);
466 vlc_object_release(p_input);
470 audio_output_t *getAout(void)
472 input_thread_t *p_input = getInput();
475 audio_output_t *p_aout = input_GetAout(p_input);
476 vlc_object_release(p_input);
483 @interface VLCMain ()
484 - (void)_removeOldPreferences;
487 /*****************************************************************************
488 * VLCMain implementation
489 *****************************************************************************/
490 @implementation VLCMain
493 #pragma mark Initialization
495 static VLCMain *_o_sharedMainInstance = nil;
497 + (VLCMain *)sharedInstance
499 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
504 if( _o_sharedMainInstance)
507 return _o_sharedMainInstance;
510 _o_sharedMainInstance = [super init];
514 o_msg_lock = [[NSLock alloc] init];
515 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
517 o_open = [[VLCOpen alloc] init];
518 //o_embedded_list = [[VLCEmbeddedList alloc] init];
519 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
520 o_info = [[VLCInfo alloc] init];
521 o_mainmenu = [[VLCMainMenu alloc] init];
522 o_coreinteraction = [[VLCCoreInteraction alloc] init];
523 o_eyetv = [[VLCEyeTVController alloc] init];
524 o_mainwindow = [[VLCMainWindow alloc] init];
526 /* announce our launch to a potential eyetv plugin */
527 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
528 object: @"VLCEyeTVSupport"
530 deliverImmediately: YES];
531 return _o_sharedMainInstance;
534 - (void)setIntf: (intf_thread_t *)p_mainintf {
538 - (intf_thread_t *)intf {
544 playlist_t *p_playlist;
546 if( !p_intf ) return;
547 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
549 /* Check if we already did this once. Opening the other nibs calls it too,
550 because VLCMain is the owner */
551 if( nib_main_loaded ) return;
553 [o_msgs_panel setExcludedFromWindowsMenu: YES];
554 [o_msgs_panel setDelegate: self];
556 p_playlist = pl_Get( p_intf );
560 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
561 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
562 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
563 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
564 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
565 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
566 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
567 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
568 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
569 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
570 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
571 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
572 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
574 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
575 var_SetBool( p_playlist, "fullscreen", YES );
577 /* load our Core Dialogs nib */
578 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
580 /* subscribe to various interactive dialogues */
581 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
582 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
583 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
584 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
585 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
586 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
587 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
588 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
589 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
590 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
591 dialog_Register( p_intf );
593 [self playbackModeUpdated];
595 /* init Apple Remote support */
596 o_remote = [[AppleRemote alloc] init];
597 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
598 [o_remote setDelegate: _o_sharedMainInstance];
600 /* yeah, we are done */
601 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
602 nib_main_loaded = TRUE;
605 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
607 if( !p_intf ) return;
609 /* init media key support */
610 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
611 if( b_mediaKeySupport )
613 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
614 [o_mediaKeyController startWatchingMediaKeys];
615 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
616 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
619 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
621 [self _removeOldPreferences];
623 [o_mainwindow updateWindow];
624 [o_mainwindow updateTimeSlider];
625 [o_mainwindow updateVolumeSlider];
626 [o_mainwindow makeKeyAndOrderFront: self];
628 /* Handle sleep notification */
629 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
630 name:NSWorkspaceWillSleepNotification object:nil];
632 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
637 if( !p_intf ) return;
640 [o_msgs_panel setTitle: _NS("Messages")];
641 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
642 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
644 /* crash reporter panel */
645 [o_crashrep_send_btn setTitle: _NS("Send")];
646 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
647 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
648 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
649 [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, ...")];
650 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
651 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
655 #pragma mark Termination
657 - (void)applicationWillTerminate:(NSNotification *)notification
659 playlist_t * p_playlist;
660 vout_thread_t * p_vout;
661 int returnedValue = 0;
667 config_SaveConfigFile( p_intf );
669 // don't allow a double termination call. If the user has
670 // already invoked the quit then simply return this time.
671 int isTerminating = false;
674 isTerminating = (f_appExit++ > 0 ? 1 : 0);
680 msg_Dbg( p_intf, "Terminating" );
682 /* Make sure the intf object is getting killed */
683 vlc_object_kill( p_intf );
684 p_playlist = pl_Get( p_intf );
686 /* unsubscribe from the interactive dialogues */
687 dialog_Unregister( p_intf );
688 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
689 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
690 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
691 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
692 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
693 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
694 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
695 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
696 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
697 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
698 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
699 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
700 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
701 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
702 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
703 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
705 /* remove global observer watching for vout device changes correctly */
706 [[NSNotificationCenter defaultCenter] removeObserver: self];
708 /* release some other objects here, because it isn't sure whether dealloc
709 * will be called later on */
724 [crashLogURLConnection cancel];
725 [crashLogURLConnection release];
727 [o_embedded_list release];
728 [o_coredialogs release];
730 [o_mainwindow release];
732 /* unsubscribe from libvlc's debug messages */
733 vlc_Unsubscribe( p_intf->p_sys->p_sub );
735 [o_msg_arr removeAllObjects];
738 [o_msg_lock release];
740 /* write cached user defaults to disk */
741 [[NSUserDefaults standardUserDefaults] synchronize];
743 /* Make sure the Menu doesn't have any references to vlc objects anymore */
744 //FIXME: this should be moved to VLCMainMenu
745 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
746 [o_mainmenu release];
748 /* Kill the playlist, so that it doesn't accept new request
749 * such as the play request from vlc.c (we are a blocking interface). */
750 vlc_object_kill( p_playlist );
751 libvlc_Quit( p_intf->p_libvlc );
757 #pragma mark Sparkle delegate
758 /* received directly before the update gets installed, so let's shut down a bit */
759 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
761 [NSApp activateIgnoringOtherApps:YES];
762 [o_remote stopListening: self];
763 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
767 #pragma mark Media Key support
769 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
771 if( b_mediaKeySupport )
773 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
775 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
776 int keyFlags = ([event data1] & 0x0000FFFF);
777 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
778 int keyRepeat = (keyFlags & 0x1);
780 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
781 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
783 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
785 if( keyState == 0 && keyRepeat == 0 )
786 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
787 else if( keyRepeat == 1 )
789 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
790 b_mediakeyJustJumped = YES;
791 [self performSelector:@selector(resetMediaKeyJump)
797 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
799 if( keyState == 0 && keyRepeat == 0 )
800 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
801 else if( keyRepeat == 1 )
803 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
804 b_mediakeyJustJumped = YES;
805 [self performSelector:@selector(resetMediaKeyJump)
814 #pragma mark Other notification
816 /* Listen to the remote in exclusive mode, only when VLC is the active
818 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
820 if( !p_intf ) return;
821 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
822 [o_remote startListening: self];
824 - (void)applicationDidResignActive:(NSNotification *)aNotification
826 if( !p_intf ) return;
827 [o_remote stopListening: self];
830 /* Triggered when the computer goes to sleep */
831 - (void)computerWillSleep: (NSNotification *)notification
833 input_thread_t * p_input;
835 p_input = pl_CurrentInput( p_intf );
838 int state = var_GetInteger( p_input, "state" );
839 if( state == PLAYING_S )
840 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
841 vlc_object_release( p_input );
846 #pragma mark File opening
848 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
850 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
851 char *psz_uri = make_URI([o_filename UTF8String], "file" );
855 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
860 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
862 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
867 /* When user click in the Dock icon our double click in the finder */
868 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
870 if(!hasVisibleWindows)
871 [o_mainwindow makeKeyAndOrderFront:self];
877 #pragma mark Apple Remote Control
879 /* Helper method for the remote control interface in order to trigger forward/backward and volume
880 increase/decrease as long as the user holds the left/right, plus/minus button */
881 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
883 if(b_remote_button_hold)
885 switch([buttonIdentifierNumber intValue])
887 case kRemoteButtonRight_Hold:
888 [[VLCCoreInteraction sharedInstance] forward];
890 case kRemoteButtonLeft_Hold:
891 [[VLCCoreInteraction sharedInstance] backward];
893 case kRemoteButtonVolume_Plus_Hold:
894 [[VLCCoreInteraction sharedInstance] volumeUp];
896 case kRemoteButtonVolume_Minus_Hold:
897 [[VLCCoreInteraction sharedInstance] volumeDown];
900 if(b_remote_button_hold)
903 [self performSelector:@selector(executeHoldActionForRemoteButton:)
904 withObject:buttonIdentifierNumber
910 /* Apple Remote callback */
911 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
912 pressedDown: (BOOL) pressedDown
913 clickCount: (unsigned int) count
915 switch( buttonIdentifier )
917 case k2009RemoteButtonFullscreen:
918 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
920 case k2009RemoteButtonPlay:
921 [[VLCCoreInteraction sharedInstance] play];
923 case kRemoteButtonPlay:
925 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
927 [[VLCCoreInteraction sharedInstance] play];
930 case kRemoteButtonVolume_Plus:
931 [[VLCCoreInteraction sharedInstance] volumeUp];
933 case kRemoteButtonVolume_Minus:
934 [[VLCCoreInteraction sharedInstance] volumeDown];
936 case kRemoteButtonRight:
937 [[VLCCoreInteraction sharedInstance] next];
939 case kRemoteButtonLeft:
940 [[VLCCoreInteraction sharedInstance] previous];
942 case kRemoteButtonRight_Hold:
943 case kRemoteButtonLeft_Hold:
944 case kRemoteButtonVolume_Plus_Hold:
945 case kRemoteButtonVolume_Minus_Hold:
946 /* simulate an event as long as the user holds the button */
947 b_remote_button_hold = pressedDown;
950 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
951 [self performSelector:@selector(executeHoldActionForRemoteButton:)
952 withObject:buttonIdentifierNumber];
955 case kRemoteButtonMenu:
956 [o_controls showPosition: self]; //FIXME
959 /* Add here whatever you want other buttons to do */
965 #pragma mark String utility
966 // FIXME: this has nothing to do here
968 - (NSString *)localizedString:(const char *)psz
970 NSString * o_str = nil;
974 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
978 msg_Err( VLCIntf, "could not translate: %s", psz );
984 msg_Warn( VLCIntf, "can't translate empty strings" );
993 - (char *)delocalizeString:(NSString *)id
995 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
996 allowLossyConversion: NO];
1001 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1002 allowLossyConversion: YES];
1003 psz_string = malloc( [o_data length] + 1 );
1004 [o_data getBytes: psz_string];
1005 psz_string[ [o_data length] ] = '\0';
1006 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1011 psz_string = malloc( [o_data length] + 1 );
1012 [o_data getBytes: psz_string];
1013 psz_string[ [o_data length] ] = '\0';
1019 /* i_width is in pixels */
1020 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1022 NSMutableString *o_wrapped;
1023 NSString *o_out_string;
1024 NSRange glyphRange, effectiveRange, charRange;
1025 NSRect lineFragmentRect;
1026 unsigned glyphIndex, breaksInserted = 0;
1028 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1029 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1030 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1031 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1032 NSTextContainer *o_container = [[NSTextContainer alloc]
1033 initWithContainerSize: NSMakeSize(i_width, 2000)];
1035 [o_layout_manager addTextContainer: o_container];
1036 [o_container release];
1037 [o_storage addLayoutManager: o_layout_manager];
1038 [o_layout_manager release];
1040 o_wrapped = [o_in_string mutableCopy];
1041 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1043 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1044 glyphIndex += effectiveRange.length) {
1045 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1046 effectiveRange: &effectiveRange];
1047 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1048 actualGlyphRange: &effectiveRange];
1049 if([o_wrapped lineRangeForRange:
1050 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1051 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1055 o_out_string = [NSString stringWithString: o_wrapped];
1056 [o_wrapped release];
1057 [o_storage release];
1059 return o_out_string;
1064 #pragma mark Key Shortcuts
1069 unsigned int i_vlckey;
1070 } nskeys_to_vlckeys[] =
1072 { NSUpArrowFunctionKey, KEY_UP },
1073 { NSDownArrowFunctionKey, KEY_DOWN },
1074 { NSLeftArrowFunctionKey, KEY_LEFT },
1075 { NSRightArrowFunctionKey, KEY_RIGHT },
1076 { NSF1FunctionKey, KEY_F1 },
1077 { NSF2FunctionKey, KEY_F2 },
1078 { NSF3FunctionKey, KEY_F3 },
1079 { NSF4FunctionKey, KEY_F4 },
1080 { NSF5FunctionKey, KEY_F5 },
1081 { NSF6FunctionKey, KEY_F6 },
1082 { NSF7FunctionKey, KEY_F7 },
1083 { NSF8FunctionKey, KEY_F8 },
1084 { NSF9FunctionKey, KEY_F9 },
1085 { NSF10FunctionKey, KEY_F10 },
1086 { NSF11FunctionKey, KEY_F11 },
1087 { NSF12FunctionKey, KEY_F12 },
1088 { NSInsertFunctionKey, KEY_INSERT },
1089 { NSHomeFunctionKey, KEY_HOME },
1090 { NSEndFunctionKey, KEY_END },
1091 { NSPageUpFunctionKey, KEY_PAGEUP },
1092 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1093 { NSMenuFunctionKey, KEY_MENU },
1094 { NSTabCharacter, KEY_TAB },
1095 { NSCarriageReturnCharacter, KEY_ENTER },
1096 { NSEnterCharacter, KEY_ENTER },
1097 { NSBackspaceCharacter, KEY_BACKSPACE },
1098 { NSDeleteCharacter, KEY_DELETE },
1102 unsigned int CocoaKeyToVLC( unichar i_key )
1106 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1108 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1110 return nskeys_to_vlckeys[i].i_vlckey;
1113 return (unsigned int)i_key;
1116 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1118 unsigned int new = 0;
1120 if([theString rangeOfString:@"Command"].location != NSNotFound)
1121 new |= NSCommandKeyMask;
1122 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1123 new |= NSAlternateKeyMask;
1124 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1125 new |= NSShiftKeyMask;
1126 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1127 new |= NSControlKeyMask;
1131 - (NSString *)VLCKeyToString:(NSString *)theString
1133 if (![theString isEqualToString:@""]) {
1134 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1135 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1138 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1139 theString = [NSString stringWithFormat:@"%@+", theString];
1141 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1142 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1145 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1146 theString = [NSString stringWithFormat:@"%@-", theString];
1148 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1149 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1150 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1151 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1153 if ([theString length] > 1)
1155 if([theString rangeOfString:@"Up"].location != NSNotFound)
1156 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1157 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1158 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1159 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1160 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1161 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1162 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1163 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1164 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1165 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1166 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1167 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1168 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1169 else if([theString rangeOfString:@"End"].location != NSNotFound)
1170 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1171 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1172 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1173 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1174 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1175 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1176 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1177 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1178 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1179 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1180 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1181 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1182 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1183 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1184 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1185 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1186 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1187 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1188 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1189 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1190 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1191 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1192 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1193 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1194 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1195 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1196 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1197 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1198 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1199 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1200 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1201 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1202 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1203 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1204 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1205 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1206 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1207 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1214 /*****************************************************************************
1215 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1216 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1217 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1218 *****************************************************************************/
1219 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1223 unsigned int i_pressed_modifiers = 0;
1224 const struct hotkey *p_hotkeys;
1226 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1227 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1230 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1232 i_pressed_modifiers = [o_event modifierFlags];
1234 if( i_pressed_modifiers & NSShiftKeyMask ) {
1235 val.i_int |= KEY_MODIFIER_SHIFT;
1236 [tempString appendString:@"Shift-"];
1237 [tempStringPlus appendString:@"Shift+"];
1239 if( i_pressed_modifiers & NSControlKeyMask ) {
1240 val.i_int |= KEY_MODIFIER_CTRL;
1241 [tempString appendString:@"Ctrl-"];
1242 [tempStringPlus appendString:@"Ctrl+"];
1244 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1245 val.i_int |= KEY_MODIFIER_ALT;
1246 [tempString appendString:@"Alt-"];
1247 [tempStringPlus appendString:@"Alt+"];
1249 if( i_pressed_modifiers & NSCommandKeyMask ) {
1250 val.i_int |= KEY_MODIFIER_COMMAND;
1251 [tempString appendString:@"Command-"];
1252 [tempStringPlus appendString:@"Command+"];
1255 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1256 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1258 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1262 case NSDeleteCharacter:
1263 case NSDeleteFunctionKey:
1264 case NSDeleteCharFunctionKey:
1265 case NSBackspaceCharacter:
1266 case NSUpArrowFunctionKey:
1267 case NSDownArrowFunctionKey:
1268 case NSRightArrowFunctionKey:
1269 case NSLeftArrowFunctionKey:
1270 case NSEnterCharacter:
1271 case NSCarriageReturnCharacter:
1275 val.i_int |= CocoaKeyToVLC( key );
1277 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1279 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1286 - (void)updateCurrentlyUsedHotkeys
1288 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1289 /* Get the main Module */
1290 module_t *p_main = module_get_main();
1293 module_config_t *p_config;
1295 p_config = module_config_get (p_main, &confsize);
1297 for (size_t i = 0; i < confsize; i++)
1299 module_config_t *p_item = p_config + i;
1301 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1302 && !strncmp( p_item->psz_name , "key-", 4 )
1303 && !EMPTY_STR( p_item->psz_text ) )
1305 if (p_item->value.psz)
1306 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1309 module_config_free (p_config);
1310 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1314 #pragma mark Interface updaters
1315 - (void)fullscreenChanged
1317 playlist_t * p_playlist = pl_Get( VLCIntf );
1318 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1320 if (OSX_LION && b_nativeFullscreenMode)
1322 [o_mainwindow toggleFullScreen: self];
1324 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1326 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1330 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1332 if( p_input != NULL )
1335 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1337 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1338 vlc_object_release( p_input );
1343 - (void)PlaylistItemChanged
1345 input_thread_t * p_input;
1347 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1348 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1350 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1351 [o_mainmenu setRateControlsEnabled: YES];
1352 vlc_object_release( p_input );
1355 [o_mainmenu setRateControlsEnabled: NO];
1357 [o_playlist updateRowSelection];
1358 [o_mainwindow updateWindow];
1359 [self updateMainMenu];
1362 - (void)updateMainMenu
1364 [o_mainmenu setupMenus];
1365 [o_mainmenu updatePlaybackRate];
1368 - (void)updateMainWindow
1370 [o_mainwindow updateWindow];
1373 - (void)showFullscreenController
1375 [o_mainwindow showFullscreenController];
1378 - (void)updateDelays
1380 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1385 [o_mainwindow updateName];
1388 - (void)updatePlaybackPosition
1390 [o_mainwindow updateTimeSlider];
1392 input_thread_t * p_input;
1393 p_input = pl_CurrentInput( p_intf );
1396 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1397 UpdateSystemActivity( UsrActivity );
1398 vlc_object_release( p_input );
1402 - (void)updateVolume
1404 [o_mainwindow updateVolumeSlider];
1407 - (void)playlistUpdated
1409 [self playbackStatusUpdated];
1410 [o_playlist playlistUpdated];
1411 [o_mainwindow updateWindow];
1412 [o_mainwindow updateName];
1415 - (void)updateRecordState: (BOOL)b_value
1417 [o_mainmenu updateRecordState:b_value];
1420 - (void)updateInfoandMetaPanel
1422 [o_playlist outlineViewSelectionDidChange:nil];
1425 - (void)playbackStatusUpdated
1427 input_thread_t * p_input;
1429 p_input = pl_CurrentInput( p_intf );
1432 int state = var_GetInteger( p_input, "state" );
1433 if( state == PLAYING_S )
1435 [[self mainMenu] setPause];
1436 [o_mainwindow setPause];
1441 [o_mainmenu setSubmenusEnabled: FALSE];
1442 [[self mainMenu] setPlay];
1443 [o_mainwindow setPlay];
1445 vlc_object_release( p_input );
1449 - (void)playbackModeUpdated
1451 vlc_value_t looping,repeating;
1452 playlist_t * p_playlist = pl_Get( VLCIntf );
1454 bool loop = var_GetBool( p_playlist, "loop" );
1455 bool repeat = var_GetBool( p_playlist, "repeat" );
1457 [o_mainwindow setRepeatOne];
1458 [o_mainmenu setRepeatOne];
1460 [o_mainwindow setRepeatAll];
1461 [o_mainmenu setRepeatAll];
1463 [o_mainwindow setRepeatOff];
1464 [o_mainmenu setRepeatOff];
1467 [o_mainwindow setShuffle];
1468 [o_mainmenu setShuffle];
1472 #pragma mark Other objects getters
1490 o_bookmarks = [[VLCBookmarks alloc] init];
1492 if( !nib_bookmarks_loaded )
1493 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1503 if (!nib_open_loaded)
1504 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1509 - (id)simplePreferences
1512 o_sprefs = [[VLCSimplePrefs alloc] init];
1514 if (!nib_prefs_loaded)
1515 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1523 o_prefs = [[VLCPrefs alloc] init];
1525 if( !nib_prefs_loaded )
1526 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1541 if(! nib_info_loaded )
1542 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1553 o_wizard = [[VLCWizard alloc] init];
1555 if( !nib_wizard_loaded )
1557 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1558 [o_wizard initStrings];
1563 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1565 id videoView = [o_mainwindow videoView];
1566 NSRect videoRect = [videoView frame];
1567 int i_x = (int)videoRect.origin.x;
1568 int i_y = (int)videoRect.origin.y;
1569 unsigned int i_width = (int)videoRect.size.width;
1570 unsigned int i_height = (int)videoRect.size.height;
1573 pi_width = (unsigned int*)i_width;
1574 pi_height = (unsigned int*)i_height;
1575 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1579 - (void)setNativeVideoSize:(NSSize)size
1581 [o_mainwindow setNativeVideoSize:size];
1586 if( o_embedded_list )
1587 return o_embedded_list;
1592 - (id)coreDialogProvider
1595 return o_coredialogs;
1600 - (id)eyeTVController
1608 - (id)appleRemoteController
1613 - (void)setActiveVideoPlayback:(BOOL)b_value
1615 b_active_videoplayback = b_value;
1616 [o_mainwindow setVideoplayEnabled];
1617 [o_mainwindow togglePlaylist:nil];
1620 - (BOOL)activeVideoPlayback
1622 return b_active_videoplayback;
1626 #pragma mark Crash Log
1627 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1629 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1630 NSURL *url = [NSURL URLWithString:urlStr];
1632 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1633 [req setHTTPMethod:@"POST"];
1636 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1638 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1639 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1640 email = [emails valueAtIndex:[emails indexForIdentifier:
1641 [emails primaryIdentifier]]];
1644 email = [NSString string];
1647 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1648 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1649 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1650 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1652 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1654 /* Released from delegate */
1655 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1658 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1660 [crashLogURLConnection release];
1661 crashLogURLConnection = nil;
1664 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1666 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1667 [crashLogURLConnection release];
1668 crashLogURLConnection = nil;
1671 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1673 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1674 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1676 NSString * latestLog = nil;
1677 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1678 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1679 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1680 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1682 while (fname = [direnum nextObject])
1684 [direnum skipDescendents];
1685 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1687 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1688 if( [compo count] < 3 ) continue;
1689 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1690 if( [compo count] < 4 ) continue;
1693 if( year < [[compo objectAtIndex:0] intValue] ||
1694 (year ==[[compo objectAtIndex:0] intValue] &&
1695 (month < [[compo objectAtIndex:1] intValue] ||
1696 (month ==[[compo objectAtIndex:1] intValue] &&
1697 (day < [[compo objectAtIndex:2] intValue] ||
1698 (day ==[[compo objectAtIndex:2] intValue] &&
1699 hours < [[compo objectAtIndex:3] intValue] ))))))
1701 year = [[compo objectAtIndex:0] intValue];
1702 month = [[compo objectAtIndex:1] intValue];
1703 day = [[compo objectAtIndex:2] intValue];
1704 hours = [[compo objectAtIndex:3] intValue];
1705 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1710 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1713 if( !previouslySeen )
1715 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1716 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1717 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1718 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1723 - (NSString *)latestCrashLogPath
1725 return [self latestCrashLogPathPreviouslySeen:YES];
1728 - (void)lookForCrashLog
1730 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1731 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1732 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1733 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1734 if( latestLog && !areCrashLogsTooOld )
1735 [NSApp runModalForWindow: o_crashrep_win];
1739 - (IBAction)crashReporterAction:(id)sender
1741 if( sender == o_crashrep_send_btn )
1742 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1745 [o_crashrep_win orderOut: sender];
1748 - (IBAction)openCrashLog:(id)sender
1750 NSString * latestLog = [self latestCrashLogPath];
1753 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1757 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.") );
1762 #pragma mark Remove old prefs
1764 - (void)_removeOldPreferences
1766 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1767 static const int kCurrentPreferencesVersion = 1;
1768 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1769 if( version >= kCurrentPreferencesVersion ) return;
1771 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1772 NSUserDomainMask, YES);
1773 if( !libraries || [libraries count] == 0) return;
1774 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1776 /* File not found, don't attempt anything */
1777 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1778 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1780 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1784 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1785 _NS("We just found an older version of VLC's preferences files."),
1786 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1787 if( res != NSOKButton )
1789 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1793 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1795 /* Move the file to trash so that user can find them later */
1796 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1798 /* really reset the defaults from now on */
1799 [NSUserDefaults resetStandardUserDefaults];
1801 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1802 [[NSUserDefaults standardUserDefaults] synchronize];
1805 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1807 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1813 execl(path, path, NULL);
1817 #pragma mark Errors, warnings and messages
1818 - (IBAction)showMessagesPanel:(id)sender
1820 [o_msgs_panel makeKeyAndOrderFront: sender];
1823 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1825 if( [o_notification object] == o_msgs_panel )
1826 [self updateMessageDisplay];
1829 - (void)updateMessageDisplay
1831 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1834 NSEnumerator * o_enum;
1836 [o_messages setString: @""];
1840 o_enum = [o_msg_arr objectEnumerator];
1842 while( ( o_msg = [o_enum nextObject] ) != nil )
1844 [o_messages insertText: o_msg];
1847 b_msg_arr_changed = NO;
1848 [o_msg_lock unlock];
1852 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1854 NSColor *o_white = [NSColor whiteColor];
1855 NSColor *o_red = [NSColor redColor];
1856 NSColor *o_yellow = [NSColor yellowColor];
1857 NSColor *o_gray = [NSColor grayColor];
1859 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1860 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1862 NSDictionary *o_attr;
1863 NSAttributedString *o_msg_color;
1867 if( [o_msg_arr count] + 2 > 600 )
1869 [o_msg_arr removeObjectAtIndex: 0];
1870 [o_msg_arr removeObjectAtIndex: 1];
1873 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1874 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1875 [o_msg_arr addObject: [o_msg_color autorelease]];
1877 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1878 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1879 [o_msg_arr addObject: [o_msg_color autorelease]];
1881 b_msg_arr_changed = YES;
1882 [o_msg_lock unlock];
1884 [self updateMessageDisplay];
1887 - (IBAction)saveDebugLog:(id)sender
1889 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1891 [saveFolderPanel setCanSelectHiddenExtension: NO];
1892 [saveFolderPanel setCanCreateDirectories: YES];
1893 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1894 [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];
1897 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1900 if( returnCode == NSOKButton )
1902 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1904 msg_Warn( p_intf, "Error while saving the debug log" );
1909 #pragma mark Playlist toggling
1911 - (void)updateTogglePlaylistState
1913 [[self playlist] outlineViewSelectionDidChange: NULL];
1920 @implementation VLCMain (Internal)
1922 - (void)handlePortMessage:(NSPortMessage *)o_msg
1927 NSInvocation * o_inv;
1928 NSConditionLock * o_lock;
1930 o_data = [[o_msg components] lastObject];
1931 o_inv = *((NSInvocation **)[o_data bytes]);
1932 [o_inv getArgument: &o_value atIndex: 2];
1933 val = (id **)[o_value pointerValue];
1934 [o_inv setArgument: val[1] atIndex: 2];
1939 [o_lock unlockWithCondition: 1];
1941 - (void)resetMediaKeyJump
1943 b_mediakeyJustJumped = NO;
1945 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1947 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1948 if (b_mediaKeySupport) {
1949 if (!o_mediaKeyController)
1950 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1951 [o_mediaKeyController startWatchingMediaKeys];
1953 else if (!b_mediaKeySupport && o_mediaKeyController)
1955 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1956 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1957 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1958 if( returnedValue == NSOKButton )
1961 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1963 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1969 execl(path, path, NULL);
1976 /*****************************************************************************
1977 * VLCApplication interface
1978 *****************************************************************************/
1980 @implementation VLCApplication
1981 // when user selects the quit menu from dock it sends a terminate:
1982 // but we need to send a stop: to properly exits libvlc.
1983 // However, we are not able to change the action-method sent by this standard menu item.
1984 // thus we override terminat: to send a stop:
1985 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1986 - (void)terminate:(id)sender
1988 [self activateIgnoringOtherApps:YES];