1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2012 VLC authors and VideoLAN
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
34 #include <stdlib.h> /* malloc(), free() */
35 #include <sys/param.h> /* for MAXPATHLEN */
37 #include <vlc_common.h>
39 #include <vlc_dialog.h>
41 #include <vlc_modules.h>
42 #include <vlc_aout_intf.h>
43 #include <vlc_vout_window.h>
44 #include <unistd.h> /* execl() */
46 #import "CompatibilityFixes.h"
52 #import "playlistinfo.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.h"
60 #import "simple_prefs.h"
61 #import "CoreInteraction.h"
62 #import "TrackSynchronization.h"
64 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
65 #import <Sparkle/Sparkle.h> /* we're the update delegate */
67 /*****************************************************************************
69 *****************************************************************************/
70 static void Run ( intf_thread_t *p_intf );
72 static void updateProgressPanel (void *, const char *, float);
73 static bool checkProgressPanel (void *);
74 static void destroyProgressPanel (void *);
76 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
78 static int InputEvent( vlc_object_t *, const char *,
79 vlc_value_t, vlc_value_t, void * );
80 static int PLItemChanged( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int PlaylistUpdated( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
84 static int PlaybackModeUpdated( vlc_object_t *, const char *,
85 vlc_value_t, vlc_value_t, void * );
86 static int VolumeUpdated( vlc_object_t *, const char *,
87 vlc_value_t, vlc_value_t, void * );
90 #pragma mark VLC Interface Object Callbacks
92 /*****************************************************************************
93 * OpenIntf: initialize interface
94 *****************************************************************************/
95 int OpenIntf ( vlc_object_t *p_this )
97 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
98 [VLCApplication sharedApplication];
99 intf_thread_t *p_intf = (intf_thread_t*) p_this;
101 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
102 if( p_intf->p_sys == NULL )
105 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
107 /* subscribe to LibVLCCore's messages */
108 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
109 p_intf->pf_run = Run;
110 p_intf->b_should_run_on_first_thread = true;
116 /*****************************************************************************
117 * CloseIntf: destroy interface
118 *****************************************************************************/
119 void CloseIntf ( vlc_object_t *p_this )
121 intf_thread_t *p_intf = (intf_thread_t*) p_this;
123 free( p_intf->p_sys );
126 static int WindowControl( vout_window_t *, int i_query, va_list );
128 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
130 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
131 intf_thread_t *p_intf = VLCIntf;
133 msg_Err( p_wnd, "Mac OS X interface not found" );
139 unsigned i_width = cfg->width;
140 unsigned i_height = cfg->height;
141 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
143 if ( !p_wnd->handle.nsobject ) {
144 msg_Err( p_wnd, "got no video view from the interface" );
149 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
150 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
151 p_wnd->control = WindowControl;
152 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
157 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
160 if( i_query == VOUT_WINDOW_SET_STATE )
161 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
162 else if( i_query == VOUT_WINDOW_SET_SIZE )
164 unsigned int i_width = va_arg( args, unsigned int );
165 unsigned int i_height = va_arg( args, unsigned int );
166 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
168 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
170 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
171 [[VLCMain sharedInstance] fullscreenChanged];
175 msg_Dbg( p_wnd, "WindowControl: unknown query" );
179 void WindowClose( vout_window_t *p_wnd )
181 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
182 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
187 /*****************************************************************************
189 *****************************************************************************/
190 static NSLock * o_appLock = nil; // controls access to f_appExit
191 static int f_appExit = 0; // set to 1 when application termination signaled
193 static void Run( intf_thread_t *p_intf )
197 /* Make sure the "force quit" menu item does quit instantly.
198 * VLC overrides SIGTERM which is sent by the "force quit"
199 * menu item to make sure daemon mode quits gracefully, so
200 * we un-override SIGTERM here. */
202 sigaddset( &set, SIGTERM );
203 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
205 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
206 [VLCApplication sharedApplication];
208 o_appLock = [[NSLock alloc] init];
210 [[VLCMain sharedInstance] setIntf: p_intf];
211 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
214 [[VLCMain sharedInstance] applicationWillTerminate:nil];
220 #pragma mark Variables Callback
222 /*****************************************************************************
223 * MsgCallback: Callback triggered by the core once a new debug message is
224 * ready to be displayed. We store everything in a NSArray in our Cocoa part
226 *****************************************************************************/
227 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
229 int canc = vlc_savecancel();
232 if (vasprintf( &str, format, ap ) == -1)
234 vlc_restorecancel( canc );
238 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
239 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
242 vlc_restorecancel( canc );
246 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
247 vlc_value_t oldval, vlc_value_t new_val, void *param )
249 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
250 switch (new_val.i_int) {
251 case INPUT_EVENT_STATE:
252 [[VLCMain sharedInstance] playbackStatusUpdated];
254 case INPUT_EVENT_RATE:
255 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
257 case INPUT_EVENT_POSITION:
258 [[VLCMain sharedInstance] updatePlaybackPosition];
260 case INPUT_EVENT_TITLE:
261 case INPUT_EVENT_CHAPTER:
262 [[VLCMain sharedInstance] updateMainMenu];
264 case INPUT_EVENT_CACHE:
265 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
267 case INPUT_EVENT_STATISTICS:
268 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
272 case INPUT_EVENT_TELETEXT:
274 case INPUT_EVENT_AOUT:
276 case INPUT_EVENT_VOUT:
278 case INPUT_EVENT_ITEM_META:
279 case INPUT_EVENT_ITEM_INFO:
280 [[VLCMain sharedInstance] updateMainMenu];
281 [[VLCMain sharedInstance] updateName];
282 [[VLCMain sharedInstance] updateInfoandMetaPanel];
284 case INPUT_EVENT_BOOKMARK:
286 case INPUT_EVENT_RECORD:
287 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
289 case INPUT_EVENT_PROGRAM:
290 [[VLCMain sharedInstance] updateMainMenu];
292 case INPUT_EVENT_ITEM_EPG:
294 case INPUT_EVENT_SIGNAL:
297 case INPUT_EVENT_ITEM_NAME:
298 [[VLCMain sharedInstance] updateName];
299 [[VLCMain sharedInstance] playlistUpdated];
302 case INPUT_EVENT_AUDIO_DELAY:
303 case INPUT_EVENT_SUBTITLE_DELAY:
304 [[VLCMain sharedInstance] updateDelays];
307 case INPUT_EVENT_DEAD:
308 [[VLCMain sharedInstance] updateName];
309 [[VLCMain sharedInstance] updatePlaybackPosition];
312 case INPUT_EVENT_ABORT:
313 [[VLCMain sharedInstance] updateName];
314 [[VLCMain sharedInstance] updatePlaybackPosition];
318 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
326 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
327 vlc_value_t oldval, vlc_value_t new_val, void *param )
329 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
330 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
336 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
337 vlc_value_t oldval, vlc_value_t new_val, void *param )
339 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
340 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
346 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
347 vlc_value_t oldval, vlc_value_t new_val, void *param )
349 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
350 [[VLCMain sharedInstance] playbackModeUpdated];
356 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
357 vlc_value_t oldval, vlc_value_t new_val, void *param )
359 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
360 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
366 /*****************************************************************************
367 * ShowController: Callback triggered by the show-intf playlist variable
368 * through the ShowIntf-control-intf, to let us show the controller-win;
369 * usually when in fullscreen-mode
370 *****************************************************************************/
371 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
372 vlc_value_t old_val, vlc_value_t new_val, void *param )
374 intf_thread_t * p_intf = VLCIntf;
375 if( p_intf && p_intf->p_sys )
377 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
382 /*****************************************************************************
383 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
384 * variable, to let the intf update the controller.
385 *****************************************************************************/
386 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
387 vlc_value_t old_val, vlc_value_t new_val, void *param )
389 intf_thread_t * p_intf = VLCIntf;
392 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
393 [[VLCMain sharedInstance] fullscreenChanged];
399 /*****************************************************************************
400 * DialogCallback: Callback triggered by the "dialog-*" variables
401 * to let the intf display error and interaction dialogs
402 *****************************************************************************/
403 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
405 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
406 VLCMain *interface = (VLCMain *)data;
408 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
410 /* the progress panel needs to update itself and therefore wants special treatment within this context */
411 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
413 p_dialog->pf_update = updateProgressPanel;
414 p_dialog->pf_check = checkProgressPanel;
415 p_dialog->pf_destroy = destroyProgressPanel;
416 p_dialog->p_sys = VLCIntf->p_libvlc;
419 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
420 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
426 void updateProgressPanel (void *priv, const char *text, float value)
428 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
432 o_txt = [NSString stringWithUTF8String: text];
436 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
441 void destroyProgressPanel (void *priv)
443 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
444 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
448 bool checkProgressPanel (void *priv)
450 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
451 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
458 input_thread_t *getInput(void)
460 intf_thread_t *p_intf = VLCIntf;
463 return pl_CurrentInput(p_intf);
466 vout_thread_t *getVout(void)
468 input_thread_t *p_input = getInput();
471 vout_thread_t *p_vout = input_GetVout(p_input);
472 vlc_object_release(p_input);
476 audio_output_t *getAout(void)
478 input_thread_t *p_input = getInput();
481 audio_output_t *p_aout = input_GetAout(p_input);
482 vlc_object_release(p_input);
489 @interface VLCMain ()
490 - (void)_removeOldPreferences;
493 /*****************************************************************************
494 * VLCMain implementation
495 *****************************************************************************/
496 @implementation VLCMain
499 #pragma mark Initialization
501 static VLCMain *_o_sharedMainInstance = nil;
503 + (VLCMain *)sharedInstance
505 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
510 if( _o_sharedMainInstance)
513 return _o_sharedMainInstance;
516 _o_sharedMainInstance = [super init];
520 o_msg_lock = [[NSLock alloc] init];
521 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
523 o_open = [[VLCOpen alloc] init];
524 //o_embedded_list = [[VLCEmbeddedList alloc] init];
525 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
526 o_info = [[VLCInfo alloc] init];
527 o_mainmenu = [[VLCMainMenu alloc] init];
528 o_coreinteraction = [[VLCCoreInteraction alloc] init];
529 o_eyetv = [[VLCEyeTVController alloc] init];
530 o_mainwindow = [[VLCMainWindow alloc] init];
532 /* announce our launch to a potential eyetv plugin */
533 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
534 object: @"VLCEyeTVSupport"
536 deliverImmediately: YES];
538 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
539 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
540 [defaults registerDefaults:appDefaults];
542 return _o_sharedMainInstance;
545 - (void)setIntf: (intf_thread_t *)p_mainintf {
549 - (intf_thread_t *)intf {
555 playlist_t *p_playlist;
557 if( !p_intf ) return;
558 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
560 /* Check if we already did this once. Opening the other nibs calls it too,
561 because VLCMain is the owner */
562 if( nib_main_loaded ) return;
564 [o_msgs_panel setExcludedFromWindowsMenu: YES];
565 [o_msgs_panel setDelegate: self];
567 p_playlist = pl_Get( p_intf );
571 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
572 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
573 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
574 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
575 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
576 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
577 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
578 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
579 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
580 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
581 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
582 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
583 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
587 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
588 var_SetBool( p_playlist, "fullscreen", YES );
591 /* load our Core Dialogs nib */
592 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
594 /* subscribe to various interactive dialogues */
595 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
596 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
597 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
598 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
599 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
600 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
601 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
602 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
603 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
604 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
605 dialog_Register( p_intf );
607 [self playbackModeUpdated];
609 /* init Apple Remote support */
610 o_remote = [[AppleRemote alloc] init];
611 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
612 [o_remote setDelegate: _o_sharedMainInstance];
614 b_msg_live_update = [[NSUserDefaults standardUserDefaults] boolForKey:@"LiveUpdateTheMessagesPanel"];
615 [o_msgs_liveUpdate_ckb setState: b_msg_live_update];
617 /* yeah, we are done */
618 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
619 nib_main_loaded = TRUE;
622 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
624 if( !p_intf ) return;
626 /* init media key support */
627 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
628 if( b_mediaKeySupport )
630 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
631 [o_mediaKeyController startWatchingMediaKeys];
632 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
633 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
636 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
638 [self _removeOldPreferences];
640 [o_mainwindow updateWindow];
641 [o_mainwindow updateTimeSlider];
642 [o_mainwindow updateVolumeSlider];
643 [o_mainwindow makeKeyAndOrderFront: self];
645 /* Handle sleep notification */
646 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
647 name:NSWorkspaceWillSleepNotification object:nil];
649 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
651 /* we will need this, so let's load it here so the interface appears to be more responsive */
652 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
657 if( !p_intf ) return;
660 [o_msgs_panel setTitle: _NS("Messages")];
661 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
662 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
663 [o_msgs_liveUpdate_ckb setTitle: _NS("Live Update")];
665 /* crash reporter panel */
666 [o_crashrep_send_btn setTitle: _NS("Send")];
667 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
668 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
669 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
670 [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, ...")];
671 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
672 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
676 #pragma mark Termination
678 - (void)applicationWillTerminate:(NSNotification *)notification
680 playlist_t * p_playlist;
681 vout_thread_t * p_vout;
682 int returnedValue = 0;
688 config_SaveConfigFile( p_intf );
690 // don't allow a double termination call. If the user has
691 // already invoked the quit then simply return this time.
692 int isTerminating = false;
695 isTerminating = (f_appExit++ > 0 ? 1 : 0);
701 msg_Dbg( p_intf, "Terminating" );
703 /* Make sure the intf object is getting killed */
704 vlc_object_kill( p_intf );
705 p_playlist = pl_Get( p_intf );
707 /* unsubscribe from the interactive dialogues */
708 dialog_Unregister( p_intf );
709 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
710 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
711 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
712 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
713 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
714 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
715 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
716 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
717 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
718 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
719 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
720 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
721 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
722 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
723 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
724 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
725 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
726 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
728 /* remove global observer watching for vout device changes correctly */
729 [[NSNotificationCenter defaultCenter] removeObserver: self];
731 /* release some other objects here, because it isn't sure whether dealloc
732 * will be called later on */
747 [crashLogURLConnection cancel];
748 [crashLogURLConnection release];
750 [o_embedded_list release];
751 [o_coredialogs release];
753 [o_mainwindow release];
755 /* unsubscribe from libvlc's debug messages */
756 vlc_Unsubscribe( p_intf->p_sys->p_sub );
758 [o_msg_arr removeAllObjects];
761 [o_msg_lock release];
763 /* write cached user defaults to disk */
764 [[NSUserDefaults standardUserDefaults] synchronize];
766 /* Make sure the Menu doesn't have any references to vlc objects anymore */
767 //FIXME: this should be moved to VLCMainMenu
768 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
769 [o_mainmenu release];
771 /* Kill the playlist, so that it doesn't accept new request
772 * such as the play request from vlc.c (we are a blocking interface). */
773 vlc_object_kill( p_playlist );
774 libvlc_Quit( p_intf->p_libvlc );
780 #pragma mark Sparkle delegate
781 /* received directly before the update gets installed, so let's shut down a bit */
782 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
784 [NSApp activateIgnoringOtherApps:YES];
785 [o_remote stopListening: self];
786 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
790 #pragma mark Media Key support
792 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
794 if( b_mediaKeySupport )
796 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
798 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
799 int keyFlags = ([event data1] & 0x0000FFFF);
800 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
801 int keyRepeat = (keyFlags & 0x1);
803 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
804 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
806 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
808 if( keyState == 0 && keyRepeat == 0 )
809 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
810 else if( keyRepeat == 1 )
812 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
813 b_mediakeyJustJumped = YES;
814 [self performSelector:@selector(resetMediaKeyJump)
820 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
822 if( keyState == 0 && keyRepeat == 0 )
823 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
824 else if( keyRepeat == 1 )
826 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
827 b_mediakeyJustJumped = YES;
828 [self performSelector:@selector(resetMediaKeyJump)
837 #pragma mark Other notification
839 /* Listen to the remote in exclusive mode, only when VLC is the active
841 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
843 if( !p_intf ) return;
844 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
845 [o_remote startListening: self];
847 - (void)applicationDidResignActive:(NSNotification *)aNotification
849 if( !p_intf ) return;
850 [o_remote stopListening: self];
853 /* Triggered when the computer goes to sleep */
854 - (void)computerWillSleep: (NSNotification *)notification
856 input_thread_t * p_input;
858 p_input = pl_CurrentInput( p_intf );
861 int state = var_GetInteger( p_input, "state" );
862 if( state == PLAYING_S )
863 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
864 vlc_object_release( p_input );
869 #pragma mark File opening
871 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
873 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
874 char *psz_uri = make_URI([o_filename UTF8String], "file" );
878 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
883 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
885 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
890 /* When user click in the Dock icon our double click in the finder */
891 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
893 if(!hasVisibleWindows)
894 [o_mainwindow makeKeyAndOrderFront:self];
900 #pragma mark Apple Remote Control
902 /* Helper method for the remote control interface in order to trigger forward/backward and volume
903 increase/decrease as long as the user holds the left/right, plus/minus button */
904 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
906 if(b_remote_button_hold)
908 switch([buttonIdentifierNumber intValue])
910 case kRemoteButtonRight_Hold:
911 [[VLCCoreInteraction sharedInstance] forward];
913 case kRemoteButtonLeft_Hold:
914 [[VLCCoreInteraction sharedInstance] backward];
916 case kRemoteButtonVolume_Plus_Hold:
917 [[VLCCoreInteraction sharedInstance] volumeUp];
919 case kRemoteButtonVolume_Minus_Hold:
920 [[VLCCoreInteraction sharedInstance] volumeDown];
923 if(b_remote_button_hold)
926 [self performSelector:@selector(executeHoldActionForRemoteButton:)
927 withObject:buttonIdentifierNumber
933 /* Apple Remote callback */
934 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
935 pressedDown: (BOOL) pressedDown
936 clickCount: (unsigned int) count
938 switch( buttonIdentifier )
940 case k2009RemoteButtonFullscreen:
941 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
943 case k2009RemoteButtonPlay:
944 [[VLCCoreInteraction sharedInstance] play];
946 case kRemoteButtonPlay:
948 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
950 [[VLCCoreInteraction sharedInstance] play];
953 case kRemoteButtonVolume_Plus:
954 [[VLCCoreInteraction sharedInstance] volumeUp];
956 case kRemoteButtonVolume_Minus:
957 [[VLCCoreInteraction sharedInstance] volumeDown];
959 case kRemoteButtonRight:
960 [[VLCCoreInteraction sharedInstance] next];
962 case kRemoteButtonLeft:
963 [[VLCCoreInteraction sharedInstance] previous];
965 case kRemoteButtonRight_Hold:
966 case kRemoteButtonLeft_Hold:
967 case kRemoteButtonVolume_Plus_Hold:
968 case kRemoteButtonVolume_Minus_Hold:
969 /* simulate an event as long as the user holds the button */
970 b_remote_button_hold = pressedDown;
973 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
974 [self performSelector:@selector(executeHoldActionForRemoteButton:)
975 withObject:buttonIdentifierNumber];
978 case kRemoteButtonMenu:
979 [o_controls showPosition: self]; //FIXME
982 /* Add here whatever you want other buttons to do */
988 #pragma mark String utility
989 // FIXME: this has nothing to do here
991 - (NSString *)localizedString:(const char *)psz
993 NSString * o_str = nil;
997 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
1001 msg_Err( VLCIntf, "could not translate: %s", psz );
1007 msg_Warn( VLCIntf, "can't translate empty strings" );
1016 - (char *)delocalizeString:(NSString *)id
1018 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1019 allowLossyConversion: NO];
1024 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1025 allowLossyConversion: YES];
1026 psz_string = malloc( [o_data length] + 1 );
1027 [o_data getBytes: psz_string];
1028 psz_string[ [o_data length] ] = '\0';
1029 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1034 psz_string = malloc( [o_data length] + 1 );
1035 [o_data getBytes: psz_string];
1036 psz_string[ [o_data length] ] = '\0';
1042 /* i_width is in pixels */
1043 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1045 NSMutableString *o_wrapped;
1046 NSString *o_out_string;
1047 NSRange glyphRange, effectiveRange, charRange;
1048 NSRect lineFragmentRect;
1049 unsigned glyphIndex, breaksInserted = 0;
1051 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1052 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1053 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1054 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1055 NSTextContainer *o_container = [[NSTextContainer alloc]
1056 initWithContainerSize: NSMakeSize(i_width, 2000)];
1058 [o_layout_manager addTextContainer: o_container];
1059 [o_container release];
1060 [o_storage addLayoutManager: o_layout_manager];
1061 [o_layout_manager release];
1063 o_wrapped = [o_in_string mutableCopy];
1064 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1066 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1067 glyphIndex += effectiveRange.length) {
1068 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1069 effectiveRange: &effectiveRange];
1070 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1071 actualGlyphRange: &effectiveRange];
1072 if([o_wrapped lineRangeForRange:
1073 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1074 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1078 o_out_string = [NSString stringWithString: o_wrapped];
1079 [o_wrapped release];
1080 [o_storage release];
1082 return o_out_string;
1087 #pragma mark Key Shortcuts
1092 unsigned int i_vlckey;
1093 } nskeys_to_vlckeys[] =
1095 { NSUpArrowFunctionKey, KEY_UP },
1096 { NSDownArrowFunctionKey, KEY_DOWN },
1097 { NSLeftArrowFunctionKey, KEY_LEFT },
1098 { NSRightArrowFunctionKey, KEY_RIGHT },
1099 { NSF1FunctionKey, KEY_F1 },
1100 { NSF2FunctionKey, KEY_F2 },
1101 { NSF3FunctionKey, KEY_F3 },
1102 { NSF4FunctionKey, KEY_F4 },
1103 { NSF5FunctionKey, KEY_F5 },
1104 { NSF6FunctionKey, KEY_F6 },
1105 { NSF7FunctionKey, KEY_F7 },
1106 { NSF8FunctionKey, KEY_F8 },
1107 { NSF9FunctionKey, KEY_F9 },
1108 { NSF10FunctionKey, KEY_F10 },
1109 { NSF11FunctionKey, KEY_F11 },
1110 { NSF12FunctionKey, KEY_F12 },
1111 { NSInsertFunctionKey, KEY_INSERT },
1112 { NSHomeFunctionKey, KEY_HOME },
1113 { NSEndFunctionKey, KEY_END },
1114 { NSPageUpFunctionKey, KEY_PAGEUP },
1115 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1116 { NSMenuFunctionKey, KEY_MENU },
1117 { NSTabCharacter, KEY_TAB },
1118 { NSCarriageReturnCharacter, KEY_ENTER },
1119 { NSEnterCharacter, KEY_ENTER },
1120 { NSBackspaceCharacter, KEY_BACKSPACE },
1121 { NSDeleteCharacter, KEY_DELETE },
1125 unsigned int CocoaKeyToVLC( unichar i_key )
1129 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1131 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1133 return nskeys_to_vlckeys[i].i_vlckey;
1136 return (unsigned int)i_key;
1139 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1141 unsigned int new = 0;
1143 if([theString rangeOfString:@"Command"].location != NSNotFound)
1144 new |= NSCommandKeyMask;
1145 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1146 new |= NSAlternateKeyMask;
1147 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1148 new |= NSShiftKeyMask;
1149 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1150 new |= NSControlKeyMask;
1154 - (NSString *)VLCKeyToString:(NSString *)theString
1156 if (![theString isEqualToString:@""]) {
1157 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1158 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1161 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1162 theString = [NSString stringWithFormat:@"%@+", theString];
1164 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1165 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1168 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1169 theString = [NSString stringWithFormat:@"%@-", theString];
1171 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1172 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1173 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1174 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1176 if ([theString length] > 1)
1178 if([theString rangeOfString:@"Up"].location != NSNotFound)
1179 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1180 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1181 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1182 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1183 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1184 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1185 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1186 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1187 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1188 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1189 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1190 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1191 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1192 else if([theString rangeOfString:@"End"].location != NSNotFound)
1193 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1194 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1195 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1196 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1197 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1198 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1199 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1200 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1201 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1202 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1203 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1204 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1205 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1206 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1207 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1208 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1209 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1210 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1211 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1212 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1213 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1214 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1215 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1216 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1217 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1218 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1219 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1220 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1221 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1222 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1223 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1224 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1225 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1226 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1227 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1228 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1229 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1230 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1237 /*****************************************************************************
1238 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1239 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1240 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1241 *****************************************************************************/
1242 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1246 unsigned int i_pressed_modifiers = 0;
1247 const struct hotkey *p_hotkeys;
1249 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1250 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1253 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1255 i_pressed_modifiers = [o_event modifierFlags];
1257 if( i_pressed_modifiers & NSShiftKeyMask ) {
1258 val.i_int |= KEY_MODIFIER_SHIFT;
1259 [tempString appendString:@"Shift-"];
1260 [tempStringPlus appendString:@"Shift+"];
1262 if( i_pressed_modifiers & NSControlKeyMask ) {
1263 val.i_int |= KEY_MODIFIER_CTRL;
1264 [tempString appendString:@"Ctrl-"];
1265 [tempStringPlus appendString:@"Ctrl+"];
1267 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1268 val.i_int |= KEY_MODIFIER_ALT;
1269 [tempString appendString:@"Alt-"];
1270 [tempStringPlus appendString:@"Alt+"];
1272 if( i_pressed_modifiers & NSCommandKeyMask ) {
1273 val.i_int |= KEY_MODIFIER_COMMAND;
1274 [tempString appendString:@"Command-"];
1275 [tempStringPlus appendString:@"Command+"];
1278 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1279 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1281 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1285 case NSDeleteCharacter:
1286 case NSDeleteFunctionKey:
1287 case NSDeleteCharFunctionKey:
1288 case NSBackspaceCharacter:
1289 case NSUpArrowFunctionKey:
1290 case NSDownArrowFunctionKey:
1291 case NSRightArrowFunctionKey:
1292 case NSLeftArrowFunctionKey:
1293 case NSEnterCharacter:
1294 case NSCarriageReturnCharacter:
1298 if( key == 0x0020 ) // space key
1300 [[VLCCoreInteraction sharedInstance] play];
1304 val.i_int |= CocoaKeyToVLC( key );
1306 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1308 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1315 - (void)updateCurrentlyUsedHotkeys
1317 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1318 /* Get the main Module */
1319 module_t *p_main = module_get_main();
1322 module_config_t *p_config;
1324 p_config = module_config_get (p_main, &confsize);
1326 for (size_t i = 0; i < confsize; i++)
1328 module_config_t *p_item = p_config + i;
1330 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1331 && !strncmp( p_item->psz_name , "key-", 4 )
1332 && !EMPTY_STR( p_item->psz_text ) )
1334 if (p_item->value.psz)
1335 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1338 module_config_free (p_config);
1339 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1343 #pragma mark Interface updaters
1344 - (void)fullscreenChanged
1346 playlist_t * p_playlist = pl_Get( VLCIntf );
1347 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1349 if (OSX_LION && b_nativeFullscreenMode)
1351 [o_mainwindow toggleFullScreen: self];
1353 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1355 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1359 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1361 if( p_input != NULL && [self activeVideoPlayback])
1364 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1366 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1367 vlc_object_release( p_input );
1372 - (void)PlaylistItemChanged
1374 input_thread_t * p_input;
1376 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1377 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1379 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1380 [o_mainmenu setRateControlsEnabled: YES];
1381 vlc_object_release( p_input );
1384 [o_mainmenu setRateControlsEnabled: NO];
1386 [o_playlist updateRowSelection];
1387 [o_mainwindow updateWindow];
1388 [self updateMainMenu];
1391 - (void)updateMainMenu
1393 [o_mainmenu setupMenus];
1394 [o_mainmenu updatePlaybackRate];
1397 - (void)updateMainWindow
1399 [o_mainwindow updateWindow];
1402 - (void)showFullscreenController
1404 [o_mainwindow showFullscreenController];
1407 - (void)updateDelays
1409 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1414 [o_mainwindow updateName];
1417 - (void)updatePlaybackPosition
1419 [o_mainwindow updateTimeSlider];
1421 input_thread_t * p_input;
1422 p_input = pl_CurrentInput( p_intf );
1425 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1426 UpdateSystemActivity( UsrActivity );
1427 vlc_object_release( p_input );
1431 - (void)updateVolume
1433 [o_mainwindow updateVolumeSlider];
1436 - (void)playlistUpdated
1438 [self playbackStatusUpdated];
1439 [o_playlist playlistUpdated];
1440 [o_mainwindow updateWindow];
1441 [o_mainwindow updateName];
1444 - (void)updateRecordState: (BOOL)b_value
1446 [o_mainmenu updateRecordState:b_value];
1449 - (void)updateInfoandMetaPanel
1451 [o_playlist outlineViewSelectionDidChange:nil];
1454 - (void)playbackStatusUpdated
1456 input_thread_t * p_input;
1458 p_input = pl_CurrentInput( p_intf );
1461 int state = var_GetInteger( p_input, "state" );
1462 if( state == PLAYING_S )
1464 [[self mainMenu] setPause];
1465 [o_mainwindow setPause];
1470 [o_mainmenu setSubmenusEnabled: FALSE];
1471 [[self mainMenu] setPlay];
1472 [o_mainwindow setPlay];
1474 vlc_object_release( p_input );
1477 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1480 - (void)playbackModeUpdated
1482 vlc_value_t looping,repeating;
1483 playlist_t * p_playlist = pl_Get( VLCIntf );
1485 bool loop = var_GetBool( p_playlist, "loop" );
1486 bool repeat = var_GetBool( p_playlist, "repeat" );
1488 [o_mainwindow setRepeatOne];
1489 [o_mainmenu setRepeatOne];
1491 [o_mainwindow setRepeatAll];
1492 [o_mainmenu setRepeatAll];
1494 [o_mainwindow setRepeatOff];
1495 [o_mainmenu setRepeatOff];
1498 [o_mainwindow setShuffle];
1499 [o_mainmenu setShuffle];
1503 #pragma mark Other objects getters
1521 o_bookmarks = [[VLCBookmarks alloc] init];
1523 if( !nib_bookmarks_loaded )
1524 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1534 if (!nib_open_loaded)
1535 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1540 - (id)simplePreferences
1543 o_sprefs = [[VLCSimplePrefs alloc] init];
1545 if (!nib_prefs_loaded)
1546 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1554 o_prefs = [[VLCPrefs alloc] init];
1556 if( !nib_prefs_loaded )
1557 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1572 if(! nib_info_loaded )
1573 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1584 o_wizard = [[VLCWizard alloc] init];
1586 if( !nib_wizard_loaded )
1588 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1589 [o_wizard initStrings];
1594 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1596 id videoView = [o_mainwindow videoView];
1597 NSRect videoRect = [videoView frame];
1598 int i_x = (int)videoRect.origin.x;
1599 int i_y = (int)videoRect.origin.y;
1600 unsigned int i_width = (int)videoRect.size.width;
1601 unsigned int i_height = (int)videoRect.size.height;
1604 pi_width = &i_width;
1605 pi_height = &i_height;
1606 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1610 - (void)setNativeVideoSize:(NSSize)size
1612 [o_mainwindow setNativeVideoSize:size];
1617 if( o_embedded_list )
1618 return o_embedded_list;
1623 - (id)coreDialogProvider
1626 return o_coredialogs;
1631 - (id)eyeTVController
1639 - (id)appleRemoteController
1644 - (void)setActiveVideoPlayback:(BOOL)b_value
1646 b_active_videoplayback = b_value;
1647 [o_mainwindow setVideoplayEnabled];
1648 [o_mainwindow togglePlaylist:nil];
1651 - (BOOL)activeVideoPlayback
1653 return b_active_videoplayback;
1657 #pragma mark Crash Log
1658 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1660 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1661 NSURL *url = [NSURL URLWithString:urlStr];
1663 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1664 [req setHTTPMethod:@"POST"];
1667 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1669 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1670 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1671 email = [emails valueAtIndex:[emails indexForIdentifier:
1672 [emails primaryIdentifier]]];
1675 email = [NSString string];
1678 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1679 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1680 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1681 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1683 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1685 /* Released from delegate */
1686 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1689 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1691 [crashLogURLConnection release];
1692 crashLogURLConnection = nil;
1695 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1697 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1698 [crashLogURLConnection release];
1699 crashLogURLConnection = nil;
1702 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1704 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1705 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1707 NSString * latestLog = nil;
1708 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1709 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1710 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1711 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1713 while (fname = [direnum nextObject])
1715 [direnum skipDescendents];
1716 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1718 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1719 if( [compo count] < 3 ) continue;
1720 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1721 if( [compo count] < 4 ) continue;
1724 if( year < [[compo objectAtIndex:0] intValue] ||
1725 (year ==[[compo objectAtIndex:0] intValue] &&
1726 (month < [[compo objectAtIndex:1] intValue] ||
1727 (month ==[[compo objectAtIndex:1] intValue] &&
1728 (day < [[compo objectAtIndex:2] intValue] ||
1729 (day ==[[compo objectAtIndex:2] intValue] &&
1730 hours < [[compo objectAtIndex:3] intValue] ))))))
1732 year = [[compo objectAtIndex:0] intValue];
1733 month = [[compo objectAtIndex:1] intValue];
1734 day = [[compo objectAtIndex:2] intValue];
1735 hours = [[compo objectAtIndex:3] intValue];
1736 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1741 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1744 if( !previouslySeen )
1746 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1747 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1748 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1749 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1754 - (NSString *)latestCrashLogPath
1756 return [self latestCrashLogPathPreviouslySeen:YES];
1759 - (void)lookForCrashLog
1761 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1762 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1763 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1764 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1765 if( latestLog && !areCrashLogsTooOld )
1766 [NSApp runModalForWindow: o_crashrep_win];
1770 - (IBAction)crashReporterAction:(id)sender
1772 if( sender == o_crashrep_send_btn )
1773 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1776 [o_crashrep_win orderOut: sender];
1779 - (IBAction)openCrashLog:(id)sender
1781 NSString * latestLog = [self latestCrashLogPath];
1784 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1788 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.") );
1793 #pragma mark Remove old prefs
1795 - (void)_removeOldPreferences
1797 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1798 static const int kCurrentPreferencesVersion = 1;
1799 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1800 if( version >= kCurrentPreferencesVersion ) return;
1802 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1803 NSUserDomainMask, YES);
1804 if( !libraries || [libraries count] == 0) return;
1805 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1807 /* File not found, don't attempt anything */
1808 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1809 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1811 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1815 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1816 _NS("We just found an older version of VLC's preferences files."),
1817 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1818 if( res != NSOKButton )
1820 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1824 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1826 /* Move the file to trash so that user can find them later */
1827 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1829 /* really reset the defaults from now on */
1830 [NSUserDefaults resetStandardUserDefaults];
1832 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1833 [[NSUserDefaults standardUserDefaults] synchronize];
1836 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1838 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1844 execl(path, path, NULL);
1848 #pragma mark Errors, warnings and messages
1849 - (IBAction)liveUpdateMessagesPanel:(id)sender
1851 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"LiveUpdateTheMessagesPanel"])
1852 [[NSUserDefaults standardUserDefaults] setObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
1854 [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"LiveUpdateTheMessagesPanel"];
1856 b_msg_live_update = [[NSUserDefaults standardUserDefaults] boolForKey:@"LiveUpdateTheMessagesPanel"];
1857 [o_msgs_liveUpdate_ckb setState: b_msg_live_update];
1860 - (IBAction)showMessagesPanel:(id)sender
1862 [o_msgs_panel makeKeyAndOrderFront: sender];
1865 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1867 if( [o_notification object] == o_msgs_panel )
1868 [self updateMessageDisplay];
1871 - (void)updateMessageDisplay
1873 if( [o_msgs_panel isVisible] && (b_msg_live_update || [o_msgs_panel isKeyWindow]) && b_msg_arr_changed )
1876 NSEnumerator * o_enum;
1878 [o_messages setString: @""];
1882 o_enum = [o_msg_arr objectEnumerator];
1884 while( ( o_msg = [o_enum nextObject] ) != NULL )
1885 [o_messages insertText: o_msg];
1887 b_msg_arr_changed = NO;
1888 [o_msg_lock unlock];
1892 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1894 NSColor *o_white = [NSColor whiteColor];
1895 NSColor *o_red = [NSColor redColor];
1896 NSColor *o_yellow = [NSColor yellowColor];
1897 NSColor *o_gray = [NSColor grayColor];
1899 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1900 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1902 NSDictionary *o_attr;
1903 NSAttributedString *o_msg_color;
1907 if( [o_msg_arr count] + 2 > 600 )
1909 [o_msg_arr removeObjectAtIndex: 0];
1910 [o_msg_arr removeObjectAtIndex: 1];
1913 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1914 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1915 [o_msg_arr addObject: [o_msg_color autorelease]];
1917 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1918 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1919 [o_msg_arr addObject: [o_msg_color autorelease]];
1921 b_msg_arr_changed = YES;
1922 [o_msg_lock unlock];
1924 [self performSelectorOnMainThread:@selector(updateMessageDisplay) withObject: nil waitUntilDone:NO];
1927 - (IBAction)saveDebugLog:(id)sender
1929 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1931 [saveFolderPanel setCanSelectHiddenExtension: NO];
1932 [saveFolderPanel setCanCreateDirectories: YES];
1933 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1934 [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];
1937 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1940 if( returnCode == NSOKButton )
1942 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1944 msg_Warn( p_intf, "Error while saving the debug log" );
1949 #pragma mark Playlist toggling
1951 - (void)updateTogglePlaylistState
1953 [[self playlist] outlineViewSelectionDidChange: NULL];
1960 @implementation VLCMain (Internal)
1962 - (void)handlePortMessage:(NSPortMessage *)o_msg
1967 NSInvocation * o_inv;
1968 NSConditionLock * o_lock;
1970 o_data = [[o_msg components] lastObject];
1971 o_inv = *((NSInvocation **)[o_data bytes]);
1972 [o_inv getArgument: &o_value atIndex: 2];
1973 val = (id **)[o_value pointerValue];
1974 [o_inv setArgument: val[1] atIndex: 2];
1979 [o_lock unlockWithCondition: 1];
1981 - (void)resetMediaKeyJump
1983 b_mediakeyJustJumped = NO;
1985 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1987 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1988 if (b_mediaKeySupport) {
1989 if (!o_mediaKeyController)
1990 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1991 [o_mediaKeyController startWatchingMediaKeys];
1993 else if (!b_mediaKeySupport && o_mediaKeyController)
1995 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1996 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1997 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1998 if( returnedValue == NSOKButton )
2001 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2003 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2009 execl(path, path, NULL);
2016 /*****************************************************************************
2017 * VLCApplication interface
2018 *****************************************************************************/
2020 @implementation VLCApplication
2021 // when user selects the quit menu from dock it sends a terminate:
2022 // but we need to send a stop: to properly exits libvlc.
2023 // However, we are not able to change the action-method sent by this standard menu item.
2024 // thus we override terminat: to send a stop:
2025 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2026 - (void)terminate:(id)sender
2028 [self activateIgnoringOtherApps:YES];