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 [[[VLCMain sharedInstance] mainMenu] 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] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
264 case INPUT_EVENT_CACHE:
265 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
267 case INPUT_EVENT_STATISTICS:
268 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
272 case INPUT_EVENT_TELETEXT:
274 case INPUT_EVENT_AOUT:
276 case INPUT_EVENT_VOUT:
278 case INPUT_EVENT_ITEM_META:
279 case INPUT_EVENT_ITEM_INFO:
280 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
281 [[VLCMain sharedInstance] updateName];
282 [[VLCMain sharedInstance] 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] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
292 case INPUT_EVENT_ITEM_EPG:
294 case INPUT_EVENT_SIGNAL:
297 case INPUT_EVENT_ITEM_NAME:
298 [[VLCMain sharedInstance] 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] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:NO];
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 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
616 /* yeah, we are done */
617 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
618 nib_main_loaded = TRUE;
621 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
623 if( !p_intf ) return;
625 /* init media key support */
626 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
627 if( b_mediaKeySupport )
629 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
630 [o_mediaKeyController startWatchingMediaKeys];
631 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
632 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
635 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
637 [self _removeOldPreferences];
639 [o_mainwindow updateWindow];
640 [o_mainwindow updateTimeSlider];
641 [o_mainwindow updateVolumeSlider];
642 [o_mainwindow makeKeyAndOrderFront: self];
644 /* Handle sleep notification */
645 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
646 name:NSWorkspaceWillSleepNotification object:nil];
648 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
650 /* we will need this, so let's load it here so the interface appears to be more responsive */
651 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
656 if( !p_intf ) return;
659 [o_msgs_panel setTitle: _NS("Messages")];
660 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
661 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
663 /* crash reporter panel */
664 [o_crashrep_send_btn setTitle: _NS("Send")];
665 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
666 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
667 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
668 [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, ...")];
669 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
670 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
674 #pragma mark Termination
676 - (void)applicationWillTerminate:(NSNotification *)notification
678 playlist_t * p_playlist;
679 vout_thread_t * p_vout;
680 int returnedValue = 0;
686 config_SaveConfigFile( p_intf );
688 // don't allow a double termination call. If the user has
689 // already invoked the quit then simply return this time.
690 int isTerminating = false;
693 isTerminating = (f_appExit++ > 0 ? 1 : 0);
699 msg_Dbg( p_intf, "Terminating" );
701 /* Make sure the intf object is getting killed */
702 vlc_object_kill( p_intf );
703 p_playlist = pl_Get( p_intf );
705 /* unsubscribe from the interactive dialogues */
706 dialog_Unregister( p_intf );
707 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
708 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
709 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
710 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
711 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
712 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
713 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
714 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
715 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
716 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
717 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
718 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
719 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
720 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
721 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
722 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
723 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
724 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
726 /* remove global observer watching for vout device changes correctly */
727 [[NSNotificationCenter defaultCenter] removeObserver: self];
729 /* release some other objects here, because it isn't sure whether dealloc
730 * will be called later on */
745 [crashLogURLConnection cancel];
746 [crashLogURLConnection release];
748 [o_embedded_list release];
749 [o_coredialogs release];
751 [o_mainwindow release];
753 /* unsubscribe from libvlc's debug messages */
754 vlc_Unsubscribe( p_intf->p_sys->p_sub );
756 [o_msg_arr removeAllObjects];
759 [o_msg_lock release];
761 /* write cached user defaults to disk */
762 [[NSUserDefaults standardUserDefaults] synchronize];
764 /* Make sure the Menu doesn't have any references to vlc objects anymore */
765 //FIXME: this should be moved to VLCMainMenu
766 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
767 [o_mainmenu release];
769 /* Kill the playlist, so that it doesn't accept new request
770 * such as the play request from vlc.c (we are a blocking interface). */
771 vlc_object_kill( p_playlist );
772 libvlc_Quit( p_intf->p_libvlc );
778 #pragma mark Sparkle delegate
779 /* received directly before the update gets installed, so let's shut down a bit */
780 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
782 [NSApp activateIgnoringOtherApps:YES];
783 [o_remote stopListening: self];
784 [[VLCCoreInteraction sharedInstance] stop];
788 #pragma mark Media Key support
790 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
792 if( b_mediaKeySupport )
794 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
796 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
797 int keyFlags = ([event data1] & 0x0000FFFF);
798 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
799 int keyRepeat = (keyFlags & 0x1);
801 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
802 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
804 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
806 if( keyState == 0 && keyRepeat == 0 )
807 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
808 else if( keyRepeat == 1 )
810 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
811 b_mediakeyJustJumped = YES;
812 [self performSelector:@selector(resetMediaKeyJump)
818 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
820 if( keyState == 0 && keyRepeat == 0 )
821 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
822 else if( keyRepeat == 1 )
824 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
825 b_mediakeyJustJumped = YES;
826 [self performSelector:@selector(resetMediaKeyJump)
835 #pragma mark Other notification
837 /* Listen to the remote in exclusive mode, only when VLC is the active
839 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
841 if( !p_intf ) return;
842 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
843 [o_remote startListening: self];
845 - (void)applicationDidResignActive:(NSNotification *)aNotification
847 if( !p_intf ) return;
848 [o_remote stopListening: self];
851 /* Triggered when the computer goes to sleep */
852 - (void)computerWillSleep: (NSNotification *)notification
854 [[VLCCoreInteraction sharedInstance] pause];
858 #pragma mark File opening
860 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
862 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
863 char *psz_uri = make_URI([o_filename UTF8String], "file" );
867 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
872 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
874 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
879 /* When user click in the Dock icon our double click in the finder */
880 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
882 if(!hasVisibleWindows)
883 [o_mainwindow makeKeyAndOrderFront:self];
889 #pragma mark Apple Remote Control
891 /* Helper method for the remote control interface in order to trigger forward/backward and volume
892 increase/decrease as long as the user holds the left/right, plus/minus button */
893 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
895 if(b_remote_button_hold)
897 switch([buttonIdentifierNumber intValue])
899 case kRemoteButtonRight_Hold:
900 [[VLCCoreInteraction sharedInstance] forward];
902 case kRemoteButtonLeft_Hold:
903 [[VLCCoreInteraction sharedInstance] backward];
905 case kRemoteButtonVolume_Plus_Hold:
906 [[VLCCoreInteraction sharedInstance] volumeUp];
908 case kRemoteButtonVolume_Minus_Hold:
909 [[VLCCoreInteraction sharedInstance] volumeDown];
912 if(b_remote_button_hold)
915 [self performSelector:@selector(executeHoldActionForRemoteButton:)
916 withObject:buttonIdentifierNumber
922 /* Apple Remote callback */
923 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
924 pressedDown: (BOOL) pressedDown
925 clickCount: (unsigned int) count
927 switch( buttonIdentifier )
929 case k2009RemoteButtonFullscreen:
930 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
932 case k2009RemoteButtonPlay:
933 [[VLCCoreInteraction sharedInstance] play];
935 case kRemoteButtonPlay:
937 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
939 [[VLCCoreInteraction sharedInstance] play];
942 case kRemoteButtonVolume_Plus:
943 [[VLCCoreInteraction sharedInstance] volumeUp];
945 case kRemoteButtonVolume_Minus:
946 [[VLCCoreInteraction sharedInstance] volumeDown];
948 case kRemoteButtonRight:
949 [[VLCCoreInteraction sharedInstance] next];
951 case kRemoteButtonLeft:
952 [[VLCCoreInteraction sharedInstance] previous];
954 case kRemoteButtonRight_Hold:
955 case kRemoteButtonLeft_Hold:
956 case kRemoteButtonVolume_Plus_Hold:
957 case kRemoteButtonVolume_Minus_Hold:
958 /* simulate an event as long as the user holds the button */
959 b_remote_button_hold = pressedDown;
962 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
963 [self performSelector:@selector(executeHoldActionForRemoteButton:)
964 withObject:buttonIdentifierNumber];
967 case kRemoteButtonMenu:
968 [o_controls showPosition: self]; //FIXME
971 /* Add here whatever you want other buttons to do */
977 #pragma mark String utility
978 // FIXME: this has nothing to do here
980 - (NSString *)localizedString:(const char *)psz
982 NSString * o_str = nil;
986 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
990 msg_Err( VLCIntf, "could not translate: %s", psz );
996 msg_Warn( VLCIntf, "can't translate empty strings" );
1005 - (char *)delocalizeString:(NSString *)id
1007 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1008 allowLossyConversion: NO];
1013 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1014 allowLossyConversion: YES];
1015 psz_string = malloc( [o_data length] + 1 );
1016 [o_data getBytes: psz_string];
1017 psz_string[ [o_data length] ] = '\0';
1018 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1023 psz_string = malloc( [o_data length] + 1 );
1024 [o_data getBytes: psz_string];
1025 psz_string[ [o_data length] ] = '\0';
1031 /* i_width is in pixels */
1032 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1034 NSMutableString *o_wrapped;
1035 NSString *o_out_string;
1036 NSRange glyphRange, effectiveRange, charRange;
1037 NSRect lineFragmentRect;
1038 unsigned glyphIndex, breaksInserted = 0;
1040 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1041 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1042 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1043 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1044 NSTextContainer *o_container = [[NSTextContainer alloc]
1045 initWithContainerSize: NSMakeSize(i_width, 2000)];
1047 [o_layout_manager addTextContainer: o_container];
1048 [o_container release];
1049 [o_storage addLayoutManager: o_layout_manager];
1050 [o_layout_manager release];
1052 o_wrapped = [o_in_string mutableCopy];
1053 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1055 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1056 glyphIndex += effectiveRange.length) {
1057 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1058 effectiveRange: &effectiveRange];
1059 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1060 actualGlyphRange: &effectiveRange];
1061 if([o_wrapped lineRangeForRange:
1062 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1063 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1067 o_out_string = [NSString stringWithString: o_wrapped];
1068 [o_wrapped release];
1069 [o_storage release];
1071 return o_out_string;
1076 #pragma mark Key Shortcuts
1081 unsigned int i_vlckey;
1082 } nskeys_to_vlckeys[] =
1084 { NSUpArrowFunctionKey, KEY_UP },
1085 { NSDownArrowFunctionKey, KEY_DOWN },
1086 { NSLeftArrowFunctionKey, KEY_LEFT },
1087 { NSRightArrowFunctionKey, KEY_RIGHT },
1088 { NSF1FunctionKey, KEY_F1 },
1089 { NSF2FunctionKey, KEY_F2 },
1090 { NSF3FunctionKey, KEY_F3 },
1091 { NSF4FunctionKey, KEY_F4 },
1092 { NSF5FunctionKey, KEY_F5 },
1093 { NSF6FunctionKey, KEY_F6 },
1094 { NSF7FunctionKey, KEY_F7 },
1095 { NSF8FunctionKey, KEY_F8 },
1096 { NSF9FunctionKey, KEY_F9 },
1097 { NSF10FunctionKey, KEY_F10 },
1098 { NSF11FunctionKey, KEY_F11 },
1099 { NSF12FunctionKey, KEY_F12 },
1100 { NSInsertFunctionKey, KEY_INSERT },
1101 { NSHomeFunctionKey, KEY_HOME },
1102 { NSEndFunctionKey, KEY_END },
1103 { NSPageUpFunctionKey, KEY_PAGEUP },
1104 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1105 { NSMenuFunctionKey, KEY_MENU },
1106 { NSTabCharacter, KEY_TAB },
1107 { NSCarriageReturnCharacter, KEY_ENTER },
1108 { NSEnterCharacter, KEY_ENTER },
1109 { NSBackspaceCharacter, KEY_BACKSPACE },
1110 { NSDeleteCharacter, KEY_DELETE },
1114 unsigned int CocoaKeyToVLC( unichar i_key )
1118 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1120 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1122 return nskeys_to_vlckeys[i].i_vlckey;
1125 return (unsigned int)i_key;
1128 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1130 unsigned int new = 0;
1132 if([theString rangeOfString:@"Command"].location != NSNotFound)
1133 new |= NSCommandKeyMask;
1134 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1135 new |= NSAlternateKeyMask;
1136 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1137 new |= NSShiftKeyMask;
1138 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1139 new |= NSControlKeyMask;
1143 - (NSString *)VLCKeyToString:(NSString *)theString
1145 if (![theString isEqualToString:@""]) {
1146 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1147 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1150 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1151 theString = [NSString stringWithFormat:@"%@+", theString];
1153 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1154 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1157 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1158 theString = [NSString stringWithFormat:@"%@-", theString];
1160 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1161 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1162 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1163 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1165 if ([theString length] > 1)
1167 if([theString rangeOfString:@"Up"].location != NSNotFound)
1168 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1169 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1170 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1171 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1172 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1173 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1174 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1175 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1176 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1177 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1178 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1179 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1180 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1181 else if([theString rangeOfString:@"End"].location != NSNotFound)
1182 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1183 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1184 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1185 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1186 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1187 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1188 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1189 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1190 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1191 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1192 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1193 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1194 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1195 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1196 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1197 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1198 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1199 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1200 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1201 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1202 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1203 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1204 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1205 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1206 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1207 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1208 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1209 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1210 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1211 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1212 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1213 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1214 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1215 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1216 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1217 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1218 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1219 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1226 /*****************************************************************************
1227 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1228 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1229 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1230 *****************************************************************************/
1231 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1235 unsigned int i_pressed_modifiers = 0;
1236 const struct hotkey *p_hotkeys;
1238 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1239 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1242 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1244 i_pressed_modifiers = [o_event modifierFlags];
1246 if( i_pressed_modifiers & NSShiftKeyMask ) {
1247 val.i_int |= KEY_MODIFIER_SHIFT;
1248 [tempString appendString:@"Shift-"];
1249 [tempStringPlus appendString:@"Shift+"];
1251 if( i_pressed_modifiers & NSControlKeyMask ) {
1252 val.i_int |= KEY_MODIFIER_CTRL;
1253 [tempString appendString:@"Ctrl-"];
1254 [tempStringPlus appendString:@"Ctrl+"];
1256 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1257 val.i_int |= KEY_MODIFIER_ALT;
1258 [tempString appendString:@"Alt-"];
1259 [tempStringPlus appendString:@"Alt+"];
1261 if( i_pressed_modifiers & NSCommandKeyMask ) {
1262 val.i_int |= KEY_MODIFIER_COMMAND;
1263 [tempString appendString:@"Command-"];
1264 [tempStringPlus appendString:@"Command+"];
1267 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1268 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1270 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1274 case NSDeleteCharacter:
1275 case NSDeleteFunctionKey:
1276 case NSDeleteCharFunctionKey:
1277 case NSBackspaceCharacter:
1278 case NSUpArrowFunctionKey:
1279 case NSDownArrowFunctionKey:
1280 case NSRightArrowFunctionKey:
1281 case NSLeftArrowFunctionKey:
1282 case NSEnterCharacter:
1283 case NSCarriageReturnCharacter:
1287 if( key == 0x0020 ) // space key
1289 [[VLCCoreInteraction sharedInstance] play];
1293 val.i_int |= CocoaKeyToVLC( key );
1295 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1297 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1304 - (void)updateCurrentlyUsedHotkeys
1306 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1307 /* Get the main Module */
1308 module_t *p_main = module_get_main();
1311 module_config_t *p_config;
1313 p_config = module_config_get (p_main, &confsize);
1315 for (size_t i = 0; i < confsize; i++)
1317 module_config_t *p_item = p_config + i;
1319 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1320 && !strncmp( p_item->psz_name , "key-", 4 )
1321 && !EMPTY_STR( p_item->psz_text ) )
1323 if (p_item->value.psz)
1324 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1327 module_config_free (p_config);
1328 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1332 #pragma mark Interface updaters
1333 - (void)fullscreenChanged
1335 playlist_t * p_playlist = pl_Get( VLCIntf );
1336 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1338 if (OSX_LION && b_nativeFullscreenMode)
1340 [o_mainwindow toggleFullScreen: self];
1342 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1344 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1348 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1350 if( p_input != NULL && [self activeVideoPlayback])
1353 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1355 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1356 vlc_object_release( p_input );
1361 - (void)PlaylistItemChanged
1363 input_thread_t * p_input;
1365 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1366 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1368 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1369 [o_mainmenu setRateControlsEnabled: YES];
1370 vlc_object_release( p_input );
1373 [o_mainmenu setRateControlsEnabled: NO];
1375 [o_playlist updateRowSelection];
1376 [o_mainwindow updateWindow];
1377 [self updateMainMenu];
1380 - (void)updateMainMenu
1382 [o_mainmenu setupMenus];
1383 [o_mainmenu updatePlaybackRate];
1386 - (void)updateMainWindow
1388 [o_mainwindow updateWindow];
1391 - (void)showFullscreenController
1393 [o_mainwindow showFullscreenController];
1396 - (void)updateDelays
1398 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1403 [o_mainwindow updateName];
1406 - (void)updatePlaybackPosition
1408 [o_mainwindow updateTimeSlider];
1410 input_thread_t * p_input;
1411 p_input = pl_CurrentInput( p_intf );
1414 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1415 UpdateSystemActivity( UsrActivity );
1416 vlc_object_release( p_input );
1420 - (void)updateVolume
1422 [o_mainwindow updateVolumeSlider];
1425 - (void)playlistUpdated
1427 [self playbackStatusUpdated];
1428 [o_playlist playlistUpdated];
1429 [o_mainwindow updateWindow];
1430 [o_mainwindow updateName];
1433 - (void)updateRecordState: (BOOL)b_value
1435 [o_mainmenu updateRecordState:b_value];
1438 - (void)updateInfoandMetaPanel
1440 [o_playlist outlineViewSelectionDidChange:nil];
1443 - (void)playbackStatusUpdated
1445 input_thread_t * p_input;
1447 p_input = pl_CurrentInput( p_intf );
1450 int state = var_GetInteger( p_input, "state" );
1451 if( state == PLAYING_S )
1453 [[self mainMenu] setPause];
1454 [o_mainwindow setPause];
1459 [o_mainmenu setSubmenusEnabled: FALSE];
1460 [[self mainMenu] setPlay];
1461 [o_mainwindow setPlay];
1463 vlc_object_release( p_input );
1466 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1469 - (void)playbackModeUpdated
1471 vlc_value_t looping,repeating;
1472 playlist_t * p_playlist = pl_Get( VLCIntf );
1474 bool loop = var_GetBool( p_playlist, "loop" );
1475 bool repeat = var_GetBool( p_playlist, "repeat" );
1477 [o_mainwindow setRepeatOne];
1478 [o_mainmenu setRepeatOne];
1480 [o_mainwindow setRepeatAll];
1481 [o_mainmenu setRepeatAll];
1483 [o_mainwindow setRepeatOff];
1484 [o_mainmenu setRepeatOff];
1487 [o_mainwindow setShuffle];
1488 [o_mainmenu setShuffle];
1492 #pragma mark Other objects getters
1510 o_bookmarks = [[VLCBookmarks alloc] init];
1512 if( !nib_bookmarks_loaded )
1513 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1523 if (!nib_open_loaded)
1524 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1529 - (id)simplePreferences
1532 o_sprefs = [[VLCSimplePrefs alloc] init];
1534 if (!nib_prefs_loaded)
1535 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1543 o_prefs = [[VLCPrefs alloc] init];
1545 if( !nib_prefs_loaded )
1546 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1561 if(! nib_info_loaded )
1562 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1573 o_wizard = [[VLCWizard alloc] init];
1575 if( !nib_wizard_loaded )
1577 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1578 [o_wizard initStrings];
1583 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1585 id videoView = [o_mainwindow videoView];
1586 NSRect videoRect = [videoView frame];
1587 int i_x = (int)videoRect.origin.x;
1588 int i_y = (int)videoRect.origin.y;
1589 unsigned int i_width = (int)videoRect.size.width;
1590 unsigned int i_height = (int)videoRect.size.height;
1593 pi_width = &i_width;
1594 pi_height = &i_height;
1595 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1599 - (void)setNativeVideoSize:(NSSize)size
1601 [o_mainwindow setNativeVideoSize:size];
1606 if( o_embedded_list )
1607 return o_embedded_list;
1612 - (id)coreDialogProvider
1615 return o_coredialogs;
1620 - (id)eyeTVController
1628 - (id)appleRemoteController
1633 - (void)setActiveVideoPlayback:(BOOL)b_value
1635 b_active_videoplayback = b_value;
1636 [o_mainwindow setVideoplayEnabled];
1637 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1640 - (BOOL)activeVideoPlayback
1642 return b_active_videoplayback;
1646 #pragma mark Crash Log
1647 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1649 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1650 NSURL *url = [NSURL URLWithString:urlStr];
1652 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1653 [req setHTTPMethod:@"POST"];
1656 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1658 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1659 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1660 email = [emails valueAtIndex:[emails indexForIdentifier:
1661 [emails primaryIdentifier]]];
1664 email = [NSString string];
1667 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1668 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1669 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1670 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1672 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1674 /* Released from delegate */
1675 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1678 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1680 [crashLogURLConnection release];
1681 crashLogURLConnection = nil;
1684 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1686 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1687 [crashLogURLConnection release];
1688 crashLogURLConnection = nil;
1691 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1693 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1694 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1696 NSString * latestLog = nil;
1697 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1698 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1699 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1700 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1702 while (fname = [direnum nextObject])
1704 [direnum skipDescendents];
1705 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1707 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1708 if( [compo count] < 3 ) continue;
1709 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1710 if( [compo count] < 4 ) continue;
1713 if( year < [[compo objectAtIndex:0] intValue] ||
1714 (year ==[[compo objectAtIndex:0] intValue] &&
1715 (month < [[compo objectAtIndex:1] intValue] ||
1716 (month ==[[compo objectAtIndex:1] intValue] &&
1717 (day < [[compo objectAtIndex:2] intValue] ||
1718 (day ==[[compo objectAtIndex:2] intValue] &&
1719 hours < [[compo objectAtIndex:3] intValue] ))))))
1721 year = [[compo objectAtIndex:0] intValue];
1722 month = [[compo objectAtIndex:1] intValue];
1723 day = [[compo objectAtIndex:2] intValue];
1724 hours = [[compo objectAtIndex:3] intValue];
1725 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1730 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1733 if( !previouslySeen )
1735 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1736 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1737 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1738 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1743 - (NSString *)latestCrashLogPath
1745 return [self latestCrashLogPathPreviouslySeen:YES];
1748 - (void)lookForCrashLog
1750 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1751 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1752 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1753 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1754 if( latestLog && !areCrashLogsTooOld )
1755 [NSApp runModalForWindow: o_crashrep_win];
1759 - (IBAction)crashReporterAction:(id)sender
1761 if( sender == o_crashrep_send_btn )
1762 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1765 [o_crashrep_win orderOut: sender];
1768 - (IBAction)openCrashLog:(id)sender
1770 NSString * latestLog = [self latestCrashLogPath];
1773 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1777 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.") );
1782 #pragma mark Remove old prefs
1784 - (void)_removeOldPreferences
1786 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1787 static const int kCurrentPreferencesVersion = 1;
1788 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1789 if( version >= kCurrentPreferencesVersion ) return;
1791 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1792 NSUserDomainMask, YES);
1793 if( !libraries || [libraries count] == 0) return;
1794 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1796 /* File not found, don't attempt anything */
1797 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1798 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1800 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1804 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1805 _NS("We just found an older version of VLC's preferences files."),
1806 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1807 if( res != NSOKButton )
1809 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1813 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1815 /* Move the file to trash so that user can find them later */
1816 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1818 /* really reset the defaults from now on */
1819 [NSUserDefaults resetStandardUserDefaults];
1821 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1822 [[NSUserDefaults standardUserDefaults] synchronize];
1825 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1827 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1833 execl(path, path, NULL);
1837 #pragma mark Errors, warnings and messages
1838 - (IBAction)updateMessagesPanel:(id)sender
1840 [self windowDidBecomeKey:nil];
1843 - (IBAction)showMessagesPanel:(id)sender
1845 [o_msgs_panel makeKeyAndOrderFront: sender];
1848 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1850 [o_msgs_table reloadData];
1851 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1854 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1856 if (aTableView == o_msgs_table)
1857 return [o_msg_arr count];
1861 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1863 return [o_msg_arr objectAtIndex: rowIndex];
1866 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1868 NSColor *o_white = [NSColor whiteColor];
1869 NSColor *o_red = [NSColor redColor];
1870 NSColor *o_yellow = [NSColor yellowColor];
1871 NSColor *o_gray = [NSColor grayColor];
1872 NSString * firstString, * secondString;
1874 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1875 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1877 NSDictionary *o_attr;
1878 NSMutableAttributedString *o_msg_color;
1882 if( [o_msg_arr count] + 2 > 600 )
1884 [o_msg_arr removeObjectAtIndex: 0];
1885 [o_msg_arr removeObjectAtIndex: 1];
1887 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
1888 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
1890 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1891 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
1892 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
1893 [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
1894 [o_msg_arr addObject: [o_msg_color autorelease]];
1896 b_msg_arr_changed = YES;
1897 [o_msg_lock unlock];
1900 - (IBAction)saveDebugLog:(id)sender
1902 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1904 [saveFolderPanel setCanSelectHiddenExtension: NO];
1905 [saveFolderPanel setCanCreateDirectories: YES];
1906 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1907 [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];
1910 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1913 if( returnCode == NSOKButton )
1915 NSUInteger count = [o_msg_arr count];
1916 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
1917 for (NSUInteger i = 0; i < count; i++)
1919 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
1921 b_returned = [[string RTFDFileWrapperFromRange:NSMakeRange( 0, [string length] ) documentAttributes:[NSDictionary dictionaryWithObject: NSRTFDTextDocumentType forKey: NSDocumentTypeDocumentAttribute]] writeToFile:[[sheet URL] path] atomically:YES updateFilenames:NO];
1925 msg_Warn( p_intf, "Error while saving the debug log" );
1930 #pragma mark Playlist toggling
1932 - (void)updateTogglePlaylistState
1934 [[self playlist] outlineViewSelectionDidChange: NULL];
1941 @implementation VLCMain (Internal)
1943 - (void)handlePortMessage:(NSPortMessage *)o_msg
1948 NSInvocation * o_inv;
1949 NSConditionLock * o_lock;
1951 o_data = [[o_msg components] lastObject];
1952 o_inv = *((NSInvocation **)[o_data bytes]);
1953 [o_inv getArgument: &o_value atIndex: 2];
1954 val = (id **)[o_value pointerValue];
1955 [o_inv setArgument: val[1] atIndex: 2];
1960 [o_lock unlockWithCondition: 1];
1962 - (void)resetMediaKeyJump
1964 b_mediakeyJustJumped = NO;
1966 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1968 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1969 if (b_mediaKeySupport) {
1970 if (!o_mediaKeyController)
1971 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1972 [o_mediaKeyController startWatchingMediaKeys];
1974 else if (!b_mediaKeySupport && o_mediaKeyController)
1976 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1977 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1978 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1979 if( returnedValue == NSOKButton )
1982 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1984 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1990 execl(path, path, NULL);
1997 /*****************************************************************************
1998 * VLCApplication interface
1999 *****************************************************************************/
2001 @implementation VLCApplication
2002 // when user selects the quit menu from dock it sends a terminate:
2003 // but we need to send a stop: to properly exits libvlc.
2004 // However, we are not able to change the action-method sent by this standard menu item.
2005 // thus we override terminat: to send a stop:
2006 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2007 - (void)terminate:(id)sender
2009 [self activateIgnoringOtherApps:YES];