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);
704 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
705 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
707 /* remove global observer watching for vout device changes correctly */
708 [[NSNotificationCenter defaultCenter] removeObserver: self];
710 /* release some other objects here, because it isn't sure whether dealloc
711 * will be called later on */
726 [crashLogURLConnection cancel];
727 [crashLogURLConnection release];
729 [o_embedded_list release];
730 [o_coredialogs release];
732 [o_mainwindow release];
734 /* unsubscribe from libvlc's debug messages */
735 vlc_Unsubscribe( p_intf->p_sys->p_sub );
737 [o_msg_arr removeAllObjects];
740 [o_msg_lock release];
742 /* write cached user defaults to disk */
743 [[NSUserDefaults standardUserDefaults] synchronize];
745 /* Make sure the Menu doesn't have any references to vlc objects anymore */
746 //FIXME: this should be moved to VLCMainMenu
747 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
748 [o_mainmenu release];
750 /* Kill the playlist, so that it doesn't accept new request
751 * such as the play request from vlc.c (we are a blocking interface). */
752 vlc_object_kill( p_playlist );
753 libvlc_Quit( p_intf->p_libvlc );
759 #pragma mark Sparkle delegate
760 /* received directly before the update gets installed, so let's shut down a bit */
761 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
763 [NSApp activateIgnoringOtherApps:YES];
764 [o_remote stopListening: self];
765 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
769 #pragma mark Media Key support
771 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
773 if( b_mediaKeySupport )
775 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
777 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
778 int keyFlags = ([event data1] & 0x0000FFFF);
779 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
780 int keyRepeat = (keyFlags & 0x1);
782 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
783 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
785 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
787 if( keyState == 0 && keyRepeat == 0 )
788 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
789 else if( keyRepeat == 1 )
791 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
792 b_mediakeyJustJumped = YES;
793 [self performSelector:@selector(resetMediaKeyJump)
799 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
801 if( keyState == 0 && keyRepeat == 0 )
802 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
803 else if( keyRepeat == 1 )
805 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
806 b_mediakeyJustJumped = YES;
807 [self performSelector:@selector(resetMediaKeyJump)
816 #pragma mark Other notification
818 /* Listen to the remote in exclusive mode, only when VLC is the active
820 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
822 if( !p_intf ) return;
823 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
824 [o_remote startListening: self];
826 - (void)applicationDidResignActive:(NSNotification *)aNotification
828 if( !p_intf ) return;
829 [o_remote stopListening: self];
832 /* Triggered when the computer goes to sleep */
833 - (void)computerWillSleep: (NSNotification *)notification
835 input_thread_t * p_input;
837 p_input = pl_CurrentInput( p_intf );
840 int state = var_GetInteger( p_input, "state" );
841 if( state == PLAYING_S )
842 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
843 vlc_object_release( p_input );
848 #pragma mark File opening
850 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
852 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
853 char *psz_uri = make_URI([o_filename UTF8String], "file" );
857 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
862 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
864 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
869 /* When user click in the Dock icon our double click in the finder */
870 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
872 if(!hasVisibleWindows)
873 [o_mainwindow makeKeyAndOrderFront:self];
879 #pragma mark Apple Remote Control
881 /* Helper method for the remote control interface in order to trigger forward/backward and volume
882 increase/decrease as long as the user holds the left/right, plus/minus button */
883 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
885 if(b_remote_button_hold)
887 switch([buttonIdentifierNumber intValue])
889 case kRemoteButtonRight_Hold:
890 [[VLCCoreInteraction sharedInstance] forward];
892 case kRemoteButtonLeft_Hold:
893 [[VLCCoreInteraction sharedInstance] backward];
895 case kRemoteButtonVolume_Plus_Hold:
896 [[VLCCoreInteraction sharedInstance] volumeUp];
898 case kRemoteButtonVolume_Minus_Hold:
899 [[VLCCoreInteraction sharedInstance] volumeDown];
902 if(b_remote_button_hold)
905 [self performSelector:@selector(executeHoldActionForRemoteButton:)
906 withObject:buttonIdentifierNumber
912 /* Apple Remote callback */
913 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
914 pressedDown: (BOOL) pressedDown
915 clickCount: (unsigned int) count
917 switch( buttonIdentifier )
919 case k2009RemoteButtonFullscreen:
920 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
922 case k2009RemoteButtonPlay:
923 [[VLCCoreInteraction sharedInstance] play];
925 case kRemoteButtonPlay:
927 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
929 [[VLCCoreInteraction sharedInstance] play];
932 case kRemoteButtonVolume_Plus:
933 [[VLCCoreInteraction sharedInstance] volumeUp];
935 case kRemoteButtonVolume_Minus:
936 [[VLCCoreInteraction sharedInstance] volumeDown];
938 case kRemoteButtonRight:
939 [[VLCCoreInteraction sharedInstance] next];
941 case kRemoteButtonLeft:
942 [[VLCCoreInteraction sharedInstance] previous];
944 case kRemoteButtonRight_Hold:
945 case kRemoteButtonLeft_Hold:
946 case kRemoteButtonVolume_Plus_Hold:
947 case kRemoteButtonVolume_Minus_Hold:
948 /* simulate an event as long as the user holds the button */
949 b_remote_button_hold = pressedDown;
952 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
953 [self performSelector:@selector(executeHoldActionForRemoteButton:)
954 withObject:buttonIdentifierNumber];
957 case kRemoteButtonMenu:
958 [o_controls showPosition: self]; //FIXME
961 /* Add here whatever you want other buttons to do */
967 #pragma mark String utility
968 // FIXME: this has nothing to do here
970 - (NSString *)localizedString:(const char *)psz
972 NSString * o_str = nil;
976 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
980 msg_Err( VLCIntf, "could not translate: %s", psz );
986 msg_Warn( VLCIntf, "can't translate empty strings" );
995 - (char *)delocalizeString:(NSString *)id
997 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
998 allowLossyConversion: NO];
1003 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1004 allowLossyConversion: YES];
1005 psz_string = malloc( [o_data length] + 1 );
1006 [o_data getBytes: psz_string];
1007 psz_string[ [o_data length] ] = '\0';
1008 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1013 psz_string = malloc( [o_data length] + 1 );
1014 [o_data getBytes: psz_string];
1015 psz_string[ [o_data length] ] = '\0';
1021 /* i_width is in pixels */
1022 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1024 NSMutableString *o_wrapped;
1025 NSString *o_out_string;
1026 NSRange glyphRange, effectiveRange, charRange;
1027 NSRect lineFragmentRect;
1028 unsigned glyphIndex, breaksInserted = 0;
1030 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1031 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1032 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1033 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1034 NSTextContainer *o_container = [[NSTextContainer alloc]
1035 initWithContainerSize: NSMakeSize(i_width, 2000)];
1037 [o_layout_manager addTextContainer: o_container];
1038 [o_container release];
1039 [o_storage addLayoutManager: o_layout_manager];
1040 [o_layout_manager release];
1042 o_wrapped = [o_in_string mutableCopy];
1043 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1045 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1046 glyphIndex += effectiveRange.length) {
1047 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1048 effectiveRange: &effectiveRange];
1049 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1050 actualGlyphRange: &effectiveRange];
1051 if([o_wrapped lineRangeForRange:
1052 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1053 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1057 o_out_string = [NSString stringWithString: o_wrapped];
1058 [o_wrapped release];
1059 [o_storage release];
1061 return o_out_string;
1066 #pragma mark Key Shortcuts
1071 unsigned int i_vlckey;
1072 } nskeys_to_vlckeys[] =
1074 { NSUpArrowFunctionKey, KEY_UP },
1075 { NSDownArrowFunctionKey, KEY_DOWN },
1076 { NSLeftArrowFunctionKey, KEY_LEFT },
1077 { NSRightArrowFunctionKey, KEY_RIGHT },
1078 { NSF1FunctionKey, KEY_F1 },
1079 { NSF2FunctionKey, KEY_F2 },
1080 { NSF3FunctionKey, KEY_F3 },
1081 { NSF4FunctionKey, KEY_F4 },
1082 { NSF5FunctionKey, KEY_F5 },
1083 { NSF6FunctionKey, KEY_F6 },
1084 { NSF7FunctionKey, KEY_F7 },
1085 { NSF8FunctionKey, KEY_F8 },
1086 { NSF9FunctionKey, KEY_F9 },
1087 { NSF10FunctionKey, KEY_F10 },
1088 { NSF11FunctionKey, KEY_F11 },
1089 { NSF12FunctionKey, KEY_F12 },
1090 { NSInsertFunctionKey, KEY_INSERT },
1091 { NSHomeFunctionKey, KEY_HOME },
1092 { NSEndFunctionKey, KEY_END },
1093 { NSPageUpFunctionKey, KEY_PAGEUP },
1094 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1095 { NSMenuFunctionKey, KEY_MENU },
1096 { NSTabCharacter, KEY_TAB },
1097 { NSCarriageReturnCharacter, KEY_ENTER },
1098 { NSEnterCharacter, KEY_ENTER },
1099 { NSBackspaceCharacter, KEY_BACKSPACE },
1100 { NSDeleteCharacter, KEY_DELETE },
1104 unsigned int CocoaKeyToVLC( unichar i_key )
1108 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1110 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1112 return nskeys_to_vlckeys[i].i_vlckey;
1115 return (unsigned int)i_key;
1118 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1120 unsigned int new = 0;
1122 if([theString rangeOfString:@"Command"].location != NSNotFound)
1123 new |= NSCommandKeyMask;
1124 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1125 new |= NSAlternateKeyMask;
1126 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1127 new |= NSShiftKeyMask;
1128 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1129 new |= NSControlKeyMask;
1133 - (NSString *)VLCKeyToString:(NSString *)theString
1135 if (![theString isEqualToString:@""]) {
1136 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1137 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1140 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1141 theString = [NSString stringWithFormat:@"%@+", theString];
1143 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1144 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1147 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1148 theString = [NSString stringWithFormat:@"%@-", theString];
1150 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1151 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1152 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1153 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1155 if ([theString length] > 1)
1157 if([theString rangeOfString:@"Up"].location != NSNotFound)
1158 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1159 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1160 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1161 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1162 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1163 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1164 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1165 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1166 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1167 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1168 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1169 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1170 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1171 else if([theString rangeOfString:@"End"].location != NSNotFound)
1172 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1173 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1174 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1175 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1176 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1177 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1178 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1179 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1180 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1181 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1182 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1183 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1184 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1185 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1186 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1187 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1188 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1189 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1190 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1191 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1192 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1193 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1194 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1195 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1196 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1197 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1198 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1199 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1200 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1201 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1202 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1203 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1204 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1205 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1206 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1207 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1208 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1209 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1216 /*****************************************************************************
1217 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1218 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1219 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1220 *****************************************************************************/
1221 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1225 unsigned int i_pressed_modifiers = 0;
1226 const struct hotkey *p_hotkeys;
1228 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1229 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1232 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1234 i_pressed_modifiers = [o_event modifierFlags];
1236 if( i_pressed_modifiers & NSShiftKeyMask ) {
1237 val.i_int |= KEY_MODIFIER_SHIFT;
1238 [tempString appendString:@"Shift-"];
1239 [tempStringPlus appendString:@"Shift+"];
1241 if( i_pressed_modifiers & NSControlKeyMask ) {
1242 val.i_int |= KEY_MODIFIER_CTRL;
1243 [tempString appendString:@"Ctrl-"];
1244 [tempStringPlus appendString:@"Ctrl+"];
1246 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1247 val.i_int |= KEY_MODIFIER_ALT;
1248 [tempString appendString:@"Alt-"];
1249 [tempStringPlus appendString:@"Alt+"];
1251 if( i_pressed_modifiers & NSCommandKeyMask ) {
1252 val.i_int |= KEY_MODIFIER_COMMAND;
1253 [tempString appendString:@"Command-"];
1254 [tempStringPlus appendString:@"Command+"];
1257 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1258 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1260 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1264 case NSDeleteCharacter:
1265 case NSDeleteFunctionKey:
1266 case NSDeleteCharFunctionKey:
1267 case NSBackspaceCharacter:
1268 case NSUpArrowFunctionKey:
1269 case NSDownArrowFunctionKey:
1270 case NSRightArrowFunctionKey:
1271 case NSLeftArrowFunctionKey:
1272 case NSEnterCharacter:
1273 case NSCarriageReturnCharacter:
1277 val.i_int |= CocoaKeyToVLC( key );
1279 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1281 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1288 - (void)updateCurrentlyUsedHotkeys
1290 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1291 /* Get the main Module */
1292 module_t *p_main = module_get_main();
1295 module_config_t *p_config;
1297 p_config = module_config_get (p_main, &confsize);
1299 for (size_t i = 0; i < confsize; i++)
1301 module_config_t *p_item = p_config + i;
1303 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1304 && !strncmp( p_item->psz_name , "key-", 4 )
1305 && !EMPTY_STR( p_item->psz_text ) )
1307 if (p_item->value.psz)
1308 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1311 module_config_free (p_config);
1312 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1316 #pragma mark Interface updaters
1317 - (void)fullscreenChanged
1319 playlist_t * p_playlist = pl_Get( VLCIntf );
1320 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1322 if (OSX_LION && b_nativeFullscreenMode)
1324 [o_mainwindow toggleFullScreen: self];
1326 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1328 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1332 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1334 if( p_input != NULL )
1337 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1339 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1340 vlc_object_release( p_input );
1345 - (void)PlaylistItemChanged
1347 input_thread_t * p_input;
1349 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1350 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1352 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1353 [o_mainmenu setRateControlsEnabled: YES];
1354 vlc_object_release( p_input );
1357 [o_mainmenu setRateControlsEnabled: NO];
1359 [o_playlist updateRowSelection];
1360 [o_mainwindow updateWindow];
1361 [self updateMainMenu];
1364 - (void)updateMainMenu
1366 [o_mainmenu setupMenus];
1367 [o_mainmenu updatePlaybackRate];
1370 - (void)updateMainWindow
1372 [o_mainwindow updateWindow];
1375 - (void)showFullscreenController
1377 [o_mainwindow showFullscreenController];
1380 - (void)updateDelays
1382 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1387 [o_mainwindow updateName];
1390 - (void)updatePlaybackPosition
1392 [o_mainwindow updateTimeSlider];
1394 input_thread_t * p_input;
1395 p_input = pl_CurrentInput( p_intf );
1398 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1399 UpdateSystemActivity( UsrActivity );
1400 vlc_object_release( p_input );
1404 - (void)updateVolume
1406 [o_mainwindow updateVolumeSlider];
1409 - (void)playlistUpdated
1411 [self playbackStatusUpdated];
1412 [o_playlist playlistUpdated];
1413 [o_mainwindow updateWindow];
1414 [o_mainwindow updateName];
1417 - (void)updateRecordState: (BOOL)b_value
1419 [o_mainmenu updateRecordState:b_value];
1422 - (void)updateInfoandMetaPanel
1424 [o_playlist outlineViewSelectionDidChange:nil];
1427 - (void)playbackStatusUpdated
1429 input_thread_t * p_input;
1431 p_input = pl_CurrentInput( p_intf );
1434 int state = var_GetInteger( p_input, "state" );
1435 if( state == PLAYING_S )
1437 [[self mainMenu] setPause];
1438 [o_mainwindow setPause];
1443 [o_mainmenu setSubmenusEnabled: FALSE];
1444 [[self mainMenu] setPlay];
1445 [o_mainwindow setPlay];
1447 vlc_object_release( p_input );
1451 - (void)playbackModeUpdated
1453 vlc_value_t looping,repeating;
1454 playlist_t * p_playlist = pl_Get( VLCIntf );
1456 bool loop = var_GetBool( p_playlist, "loop" );
1457 bool repeat = var_GetBool( p_playlist, "repeat" );
1459 [o_mainwindow setRepeatOne];
1460 [o_mainmenu setRepeatOne];
1462 [o_mainwindow setRepeatAll];
1463 [o_mainmenu setRepeatAll];
1465 [o_mainwindow setRepeatOff];
1466 [o_mainmenu setRepeatOff];
1469 [o_mainwindow setShuffle];
1470 [o_mainmenu setShuffle];
1474 #pragma mark Other objects getters
1492 o_bookmarks = [[VLCBookmarks alloc] init];
1494 if( !nib_bookmarks_loaded )
1495 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1505 if (!nib_open_loaded)
1506 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1511 - (id)simplePreferences
1514 o_sprefs = [[VLCSimplePrefs alloc] init];
1516 if (!nib_prefs_loaded)
1517 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1525 o_prefs = [[VLCPrefs alloc] init];
1527 if( !nib_prefs_loaded )
1528 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1543 if(! nib_info_loaded )
1544 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1555 o_wizard = [[VLCWizard alloc] init];
1557 if( !nib_wizard_loaded )
1559 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1560 [o_wizard initStrings];
1565 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1567 id videoView = [o_mainwindow videoView];
1568 NSRect videoRect = [videoView frame];
1569 int i_x = (int)videoRect.origin.x;
1570 int i_y = (int)videoRect.origin.y;
1571 unsigned int i_width = (int)videoRect.size.width;
1572 unsigned int i_height = (int)videoRect.size.height;
1575 pi_width = (unsigned int*)i_width;
1576 pi_height = (unsigned int*)i_height;
1577 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1581 - (void)setNativeVideoSize:(NSSize)size
1583 [o_mainwindow setNativeVideoSize:size];
1588 if( o_embedded_list )
1589 return o_embedded_list;
1594 - (id)coreDialogProvider
1597 return o_coredialogs;
1602 - (id)eyeTVController
1610 - (id)appleRemoteController
1615 - (void)setActiveVideoPlayback:(BOOL)b_value
1617 b_active_videoplayback = b_value;
1618 [o_mainwindow setVideoplayEnabled];
1619 [o_mainwindow togglePlaylist:nil];
1622 - (BOOL)activeVideoPlayback
1624 return b_active_videoplayback;
1628 #pragma mark Crash Log
1629 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1631 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1632 NSURL *url = [NSURL URLWithString:urlStr];
1634 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1635 [req setHTTPMethod:@"POST"];
1638 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1640 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1641 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1642 email = [emails valueAtIndex:[emails indexForIdentifier:
1643 [emails primaryIdentifier]]];
1646 email = [NSString string];
1649 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1650 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1651 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1652 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1654 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1656 /* Released from delegate */
1657 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1660 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1662 [crashLogURLConnection release];
1663 crashLogURLConnection = nil;
1666 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1668 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1669 [crashLogURLConnection release];
1670 crashLogURLConnection = nil;
1673 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1675 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1676 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1678 NSString * latestLog = nil;
1679 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1680 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1681 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1682 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1684 while (fname = [direnum nextObject])
1686 [direnum skipDescendents];
1687 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1689 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1690 if( [compo count] < 3 ) continue;
1691 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1692 if( [compo count] < 4 ) continue;
1695 if( year < [[compo objectAtIndex:0] intValue] ||
1696 (year ==[[compo objectAtIndex:0] intValue] &&
1697 (month < [[compo objectAtIndex:1] intValue] ||
1698 (month ==[[compo objectAtIndex:1] intValue] &&
1699 (day < [[compo objectAtIndex:2] intValue] ||
1700 (day ==[[compo objectAtIndex:2] intValue] &&
1701 hours < [[compo objectAtIndex:3] intValue] ))))))
1703 year = [[compo objectAtIndex:0] intValue];
1704 month = [[compo objectAtIndex:1] intValue];
1705 day = [[compo objectAtIndex:2] intValue];
1706 hours = [[compo objectAtIndex:3] intValue];
1707 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1712 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1715 if( !previouslySeen )
1717 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1718 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1719 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1720 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1725 - (NSString *)latestCrashLogPath
1727 return [self latestCrashLogPathPreviouslySeen:YES];
1730 - (void)lookForCrashLog
1732 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1733 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1734 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1735 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1736 if( latestLog && !areCrashLogsTooOld )
1737 [NSApp runModalForWindow: o_crashrep_win];
1741 - (IBAction)crashReporterAction:(id)sender
1743 if( sender == o_crashrep_send_btn )
1744 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1747 [o_crashrep_win orderOut: sender];
1750 - (IBAction)openCrashLog:(id)sender
1752 NSString * latestLog = [self latestCrashLogPath];
1755 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1759 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.") );
1764 #pragma mark Remove old prefs
1766 - (void)_removeOldPreferences
1768 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1769 static const int kCurrentPreferencesVersion = 1;
1770 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1771 if( version >= kCurrentPreferencesVersion ) return;
1773 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1774 NSUserDomainMask, YES);
1775 if( !libraries || [libraries count] == 0) return;
1776 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1778 /* File not found, don't attempt anything */
1779 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1780 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1782 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1786 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1787 _NS("We just found an older version of VLC's preferences files."),
1788 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1789 if( res != NSOKButton )
1791 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1795 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1797 /* Move the file to trash so that user can find them later */
1798 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1800 /* really reset the defaults from now on */
1801 [NSUserDefaults resetStandardUserDefaults];
1803 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1804 [[NSUserDefaults standardUserDefaults] synchronize];
1807 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1809 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1815 execl(path, path, NULL);
1819 #pragma mark Errors, warnings and messages
1820 - (IBAction)showMessagesPanel:(id)sender
1822 [o_msgs_panel makeKeyAndOrderFront: sender];
1825 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1827 if( [o_notification object] == o_msgs_panel )
1828 [self updateMessageDisplay];
1831 - (void)updateMessageDisplay
1833 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1836 NSEnumerator * o_enum;
1838 [o_messages setString: @""];
1842 o_enum = [o_msg_arr objectEnumerator];
1844 while( ( o_msg = [o_enum nextObject] ) != nil )
1846 [o_messages insertText: o_msg];
1849 b_msg_arr_changed = NO;
1850 [o_msg_lock unlock];
1854 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1856 NSColor *o_white = [NSColor whiteColor];
1857 NSColor *o_red = [NSColor redColor];
1858 NSColor *o_yellow = [NSColor yellowColor];
1859 NSColor *o_gray = [NSColor grayColor];
1861 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1862 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1864 NSDictionary *o_attr;
1865 NSAttributedString *o_msg_color;
1869 if( [o_msg_arr count] + 2 > 600 )
1871 [o_msg_arr removeObjectAtIndex: 0];
1872 [o_msg_arr removeObjectAtIndex: 1];
1875 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1876 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1877 [o_msg_arr addObject: [o_msg_color autorelease]];
1879 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1880 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1881 [o_msg_arr addObject: [o_msg_color autorelease]];
1883 b_msg_arr_changed = YES;
1884 [o_msg_lock unlock];
1886 [self updateMessageDisplay];
1889 - (IBAction)saveDebugLog:(id)sender
1891 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1893 [saveFolderPanel setCanSelectHiddenExtension: NO];
1894 [saveFolderPanel setCanCreateDirectories: YES];
1895 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1896 [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];
1899 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1902 if( returnCode == NSOKButton )
1904 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1906 msg_Warn( p_intf, "Error while saving the debug log" );
1911 #pragma mark Playlist toggling
1913 - (void)updateTogglePlaylistState
1915 [[self playlist] outlineViewSelectionDidChange: NULL];
1922 @implementation VLCMain (Internal)
1924 - (void)handlePortMessage:(NSPortMessage *)o_msg
1929 NSInvocation * o_inv;
1930 NSConditionLock * o_lock;
1932 o_data = [[o_msg components] lastObject];
1933 o_inv = *((NSInvocation **)[o_data bytes]);
1934 [o_inv getArgument: &o_value atIndex: 2];
1935 val = (id **)[o_value pointerValue];
1936 [o_inv setArgument: val[1] atIndex: 2];
1941 [o_lock unlockWithCondition: 1];
1943 - (void)resetMediaKeyJump
1945 b_mediakeyJustJumped = NO;
1947 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1949 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1950 if (b_mediaKeySupport) {
1951 if (!o_mediaKeyController)
1952 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1953 [o_mediaKeyController startWatchingMediaKeys];
1955 else if (!b_mediaKeySupport && o_mediaKeyController)
1957 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1958 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1959 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1960 if( returnedValue == NSOKButton )
1963 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1965 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1971 execl(path, path, NULL);
1978 /*****************************************************************************
1979 * VLCApplication interface
1980 *****************************************************************************/
1982 @implementation VLCApplication
1983 // when user selects the quit menu from dock it sends a terminate:
1984 // but we need to send a stop: to properly exits libvlc.
1985 // However, we are not able to change the action-method sent by this standard menu item.
1986 // thus we override terminat: to send a stop:
1987 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1988 - (void)terminate:(id)sender
1990 [self activateIgnoringOtherApps:YES];