1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 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 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
42 #import "CompatibilityFixes.h"
48 #import "playlistinfo.h"
53 #import "coredialogs.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
57 #import "CoreInteraction.h"
58 #import "TrackSynchronization.h"
60 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
61 #import <Sparkle/Sparkle.h> /* we're the update delegate */
63 /*****************************************************************************
65 *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
68 static void updateProgressPanel (void *, const char *, float);
69 static bool checkProgressPanel (void *);
70 static void destroyProgressPanel (void *);
72 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
74 static int InputEvent( vlc_object_t *, const char *,
75 vlc_value_t, vlc_value_t, void * );
76 static int PLItemChanged( vlc_object_t *, const char *,
77 vlc_value_t, vlc_value_t, void * );
78 static int PlaylistUpdated( vlc_object_t *, const char *,
79 vlc_value_t, vlc_value_t, void * );
80 static int PlaybackModeUpdated( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int VolumeUpdated( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
86 #pragma mark VLC Interface Object Callbacks
88 /*****************************************************************************
89 * OpenIntf: initialize interface
90 *****************************************************************************/
91 int OpenIntf ( vlc_object_t *p_this )
93 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
94 [VLCApplication sharedApplication];
95 intf_thread_t *p_intf = (intf_thread_t*) p_this;
97 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
98 if( p_intf->p_sys == NULL )
101 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
103 /* subscribe to LibVLCCore's messages */
104 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
105 p_intf->pf_run = Run;
106 p_intf->b_should_run_on_first_thread = true;
112 /*****************************************************************************
113 * CloseIntf: destroy interface
114 *****************************************************************************/
115 void CloseIntf ( vlc_object_t *p_this )
117 intf_thread_t *p_intf = (intf_thread_t*) p_this;
119 free( p_intf->p_sys );
122 static int WindowControl( vout_window_t *, int i_query, va_list );
124 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
126 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
127 intf_thread_t *p_intf = VLCIntf;
129 msg_Err( p_wnd, "Mac OS X interface not found" );
135 unsigned i_width = cfg->width;
136 unsigned i_height = cfg->height;
137 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
139 if ( !p_wnd->handle.nsobject ) {
140 msg_Err( p_wnd, "got no video view from the interface" );
145 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
146 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
147 p_wnd->control = WindowControl;
148 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
153 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
156 if( i_query == VOUT_WINDOW_SET_STATE )
157 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
158 else if( i_query == VOUT_WINDOW_SET_SIZE )
160 unsigned int i_width = va_arg( args, unsigned int );
161 unsigned int i_height = va_arg( args, unsigned int );
162 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
164 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
165 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
167 msg_Dbg( p_wnd, "WindowControl: unknown query" );
171 void WindowClose( vout_window_t *p_wnd )
173 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
174 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
179 /*****************************************************************************
181 *****************************************************************************/
182 static NSLock * o_appLock = nil; // controls access to f_appExit
183 static int f_appExit = 0; // set to 1 when application termination signaled
185 static void Run( intf_thread_t *p_intf )
189 /* Make sure the "force quit" menu item does quit instantly.
190 * VLC overrides SIGTERM which is sent by the "force quit"
191 * menu item to make sure daemon mode quits gracefully, so
192 * we un-override SIGTERM here. */
194 sigaddset( &set, SIGTERM );
195 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
197 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
198 [VLCApplication sharedApplication];
200 o_appLock = [[NSLock alloc] init];
202 [[VLCMain sharedInstance] setIntf: p_intf];
203 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
206 [[VLCMain sharedInstance] applicationWillTerminate:nil];
212 #pragma mark Variables Callback
214 /*****************************************************************************
215 * MsgCallback: Callback triggered by the core once a new debug message is
216 * ready to be displayed. We store everything in a NSArray in our Cocoa part
218 *****************************************************************************/
219 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
221 int canc = vlc_savecancel();
224 if (vasprintf( &str, format, ap ) == -1)
226 vlc_restorecancel( canc );
230 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
231 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
234 vlc_restorecancel( canc );
238 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
239 vlc_value_t oldval, vlc_value_t new_val, void *param )
241 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
242 switch (new_val.i_int) {
243 case INPUT_EVENT_STATE:
244 [[VLCMain sharedInstance] playbackStatusUpdated];
246 case INPUT_EVENT_RATE:
247 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
249 case INPUT_EVENT_POSITION:
250 [[VLCMain sharedInstance] updatePlaybackPosition];
252 case INPUT_EVENT_TITLE:
253 case INPUT_EVENT_CHAPTER:
254 [[VLCMain sharedInstance] updateMainMenu];
256 case INPUT_EVENT_CACHE:
257 [[VLCMain sharedInstance] updateMainWindow];
259 case INPUT_EVENT_STATISTICS:
260 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
264 case INPUT_EVENT_TELETEXT:
266 case INPUT_EVENT_AOUT:
268 case INPUT_EVENT_VOUT:
270 case INPUT_EVENT_ITEM_META:
271 case INPUT_EVENT_ITEM_INFO:
272 [[VLCMain sharedInstance] updateMainMenu];
273 [[VLCMain sharedInstance] updateName];
274 [[VLCMain sharedInstance] updateInfoandMetaPanel];
276 case INPUT_EVENT_BOOKMARK:
278 case INPUT_EVENT_RECORD:
279 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
281 case INPUT_EVENT_PROGRAM:
282 [[VLCMain sharedInstance] updateMainMenu];
284 case INPUT_EVENT_ITEM_EPG:
286 case INPUT_EVENT_SIGNAL:
289 case INPUT_EVENT_ITEM_NAME:
290 [[VLCMain sharedInstance] updateName];
291 [[VLCMain sharedInstance] playlistUpdated];
294 case INPUT_EVENT_AUDIO_DELAY:
295 case INPUT_EVENT_SUBTITLE_DELAY:
296 [[VLCMain sharedInstance] updateDelays];
299 case INPUT_EVENT_DEAD:
300 [[VLCMain sharedInstance] updateName];
301 [[VLCMain sharedInstance] updatePlaybackPosition];
304 case INPUT_EVENT_ABORT:
305 [[VLCMain sharedInstance] updateName];
306 [[VLCMain sharedInstance] updatePlaybackPosition];
310 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
318 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
319 vlc_value_t oldval, vlc_value_t new_val, void *param )
321 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
322 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
328 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
329 vlc_value_t oldval, vlc_value_t new_val, void *param )
331 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
332 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
338 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
339 vlc_value_t oldval, vlc_value_t new_val, void *param )
341 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
342 [[VLCMain sharedInstance] playbackModeUpdated];
348 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
349 vlc_value_t oldval, vlc_value_t new_val, void *param )
351 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
352 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
358 /*****************************************************************************
359 * ShowController: Callback triggered by the show-intf playlist variable
360 * through the ShowIntf-control-intf, to let us show the controller-win;
361 * usually when in fullscreen-mode
362 *****************************************************************************/
363 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
364 vlc_value_t old_val, vlc_value_t new_val, void *param )
366 intf_thread_t * p_intf = VLCIntf;
367 if( p_intf && p_intf->p_sys )
369 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
374 /*****************************************************************************
375 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
376 * variable, to let the intf update the controller.
377 *****************************************************************************/
378 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
379 vlc_value_t old_val, vlc_value_t new_val, void *param )
381 intf_thread_t * p_intf = VLCIntf;
384 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
385 [[VLCMain sharedInstance] fullscreenChanged];
391 /*****************************************************************************
392 * DialogCallback: Callback triggered by the "dialog-*" variables
393 * to let the intf display error and interaction dialogs
394 *****************************************************************************/
395 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
397 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
398 VLCMain *interface = (VLCMain *)data;
400 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
402 /* the progress panel needs to update itself and therefore wants special treatment within this context */
403 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
405 p_dialog->pf_update = updateProgressPanel;
406 p_dialog->pf_check = checkProgressPanel;
407 p_dialog->pf_destroy = destroyProgressPanel;
408 p_dialog->p_sys = VLCIntf->p_libvlc;
411 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
412 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
418 void updateProgressPanel (void *priv, const char *text, float value)
420 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
424 o_txt = [NSString stringWithUTF8String: text];
428 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
433 void destroyProgressPanel (void *priv)
435 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
436 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
440 bool checkProgressPanel (void *priv)
442 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
443 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
450 input_thread_t *getInput(void)
452 intf_thread_t *p_intf = VLCIntf;
455 return pl_CurrentInput(p_intf);
458 vout_thread_t *getVout(void)
460 input_thread_t *p_input = getInput();
463 vout_thread_t *p_vout = input_GetVout(p_input);
464 vlc_object_release(p_input);
468 audio_output_t *getAout(void)
470 input_thread_t *p_input = getInput();
473 audio_output_t *p_aout = input_GetAout(p_input);
474 vlc_object_release(p_input);
481 @interface VLCMain ()
482 - (void)_removeOldPreferences;
485 /*****************************************************************************
486 * VLCMain implementation
487 *****************************************************************************/
488 @implementation VLCMain
491 #pragma mark Initialization
493 static VLCMain *_o_sharedMainInstance = nil;
495 + (VLCMain *)sharedInstance
497 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
502 if( _o_sharedMainInstance)
505 return _o_sharedMainInstance;
508 _o_sharedMainInstance = [super init];
512 o_msg_lock = [[NSLock alloc] init];
513 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
515 o_open = [[VLCOpen alloc] init];
516 //o_embedded_list = [[VLCEmbeddedList alloc] init];
517 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
518 o_info = [[VLCInfo alloc] init];
519 o_mainmenu = [[VLCMainMenu alloc] init];
520 o_coreinteraction = [[VLCCoreInteraction alloc] init];
521 o_eyetv = [[VLCEyeTVController alloc] init];
522 o_mainwindow = [[VLCMainWindow alloc] init];
524 /* announce our launch to a potential eyetv plugin */
525 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
526 object: @"VLCEyeTVSupport"
528 deliverImmediately: YES];
529 return _o_sharedMainInstance;
532 - (void)setIntf: (intf_thread_t *)p_mainintf {
536 - (intf_thread_t *)intf {
542 playlist_t *p_playlist;
544 if( !p_intf ) return;
545 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
547 /* Check if we already did this once. Opening the other nibs calls it too,
548 because VLCMain is the owner */
549 if( nib_main_loaded ) return;
551 [o_msgs_panel setExcludedFromWindowsMenu: YES];
552 [o_msgs_panel setDelegate: self];
554 p_playlist = pl_Get( p_intf );
558 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
559 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
560 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
561 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
562 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
563 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
564 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
565 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
566 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
567 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
568 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
569 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
570 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
574 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
575 var_SetBool( p_playlist, "fullscreen", YES );
578 /* load our Core Dialogs nib */
579 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
581 /* subscribe to various interactive dialogues */
582 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
583 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
584 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
585 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
586 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
587 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
588 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
589 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
590 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
591 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
592 dialog_Register( p_intf );
594 [self playbackModeUpdated];
596 /* init Apple Remote support */
597 o_remote = [[AppleRemote alloc] init];
598 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
599 [o_remote setDelegate: _o_sharedMainInstance];
601 /* yeah, we are done */
602 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
603 nib_main_loaded = TRUE;
606 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
608 if( !p_intf ) return;
610 /* init media key support */
611 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
612 if( b_mediaKeySupport )
614 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
615 [o_mediaKeyController startWatchingMediaKeys];
616 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
617 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
620 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
622 [self _removeOldPreferences];
624 [o_mainwindow updateWindow];
625 [o_mainwindow updateTimeSlider];
626 [o_mainwindow updateVolumeSlider];
627 [o_mainwindow makeKeyAndOrderFront: self];
629 /* Handle sleep notification */
630 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
631 name:NSWorkspaceWillSleepNotification object:nil];
633 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
638 if( !p_intf ) return;
641 [o_msgs_panel setTitle: _NS("Messages")];
642 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
643 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
645 /* crash reporter panel */
646 [o_crashrep_send_btn setTitle: _NS("Send")];
647 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
648 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
649 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
650 [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, ...")];
651 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
652 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
656 #pragma mark Termination
658 - (void)applicationWillTerminate:(NSNotification *)notification
660 playlist_t * p_playlist;
661 vout_thread_t * p_vout;
662 int returnedValue = 0;
668 config_SaveConfigFile( p_intf );
670 // don't allow a double termination call. If the user has
671 // already invoked the quit then simply return this time.
672 int isTerminating = false;
675 isTerminating = (f_appExit++ > 0 ? 1 : 0);
681 msg_Dbg( p_intf, "Terminating" );
683 /* Make sure the intf object is getting killed */
684 vlc_object_kill( p_intf );
685 p_playlist = pl_Get( p_intf );
687 /* unsubscribe from the interactive dialogues */
688 dialog_Unregister( p_intf );
689 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
690 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
691 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
692 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
693 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
694 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
695 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
696 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
697 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
698 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
699 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
700 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
701 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
702 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
703 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
704 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
705 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
706 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
708 /* remove global observer watching for vout device changes correctly */
709 [[NSNotificationCenter defaultCenter] removeObserver: self];
711 /* release some other objects here, because it isn't sure whether dealloc
712 * will be called later on */
727 [crashLogURLConnection cancel];
728 [crashLogURLConnection release];
730 [o_embedded_list release];
731 [o_coredialogs release];
733 [o_mainwindow release];
735 /* unsubscribe from libvlc's debug messages */
736 vlc_Unsubscribe( p_intf->p_sys->p_sub );
738 [o_msg_arr removeAllObjects];
741 [o_msg_lock release];
743 /* write cached user defaults to disk */
744 [[NSUserDefaults standardUserDefaults] synchronize];
746 /* Make sure the Menu doesn't have any references to vlc objects anymore */
747 //FIXME: this should be moved to VLCMainMenu
748 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
749 [o_mainmenu release];
751 /* Kill the playlist, so that it doesn't accept new request
752 * such as the play request from vlc.c (we are a blocking interface). */
753 vlc_object_kill( p_playlist );
754 libvlc_Quit( p_intf->p_libvlc );
760 #pragma mark Sparkle delegate
761 /* received directly before the update gets installed, so let's shut down a bit */
762 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
764 [NSApp activateIgnoringOtherApps:YES];
765 [o_remote stopListening: self];
766 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
770 #pragma mark Media Key support
772 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
774 if( b_mediaKeySupport )
776 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
778 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
779 int keyFlags = ([event data1] & 0x0000FFFF);
780 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
781 int keyRepeat = (keyFlags & 0x1);
783 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
784 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
786 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
788 if( keyState == 0 && keyRepeat == 0 )
789 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
790 else if( keyRepeat == 1 )
792 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
793 b_mediakeyJustJumped = YES;
794 [self performSelector:@selector(resetMediaKeyJump)
800 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
802 if( keyState == 0 && keyRepeat == 0 )
803 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
804 else if( keyRepeat == 1 )
806 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
807 b_mediakeyJustJumped = YES;
808 [self performSelector:@selector(resetMediaKeyJump)
817 #pragma mark Other notification
819 /* Listen to the remote in exclusive mode, only when VLC is the active
821 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
823 if( !p_intf ) return;
824 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
825 [o_remote startListening: self];
827 - (void)applicationDidResignActive:(NSNotification *)aNotification
829 if( !p_intf ) return;
830 [o_remote stopListening: self];
833 /* Triggered when the computer goes to sleep */
834 - (void)computerWillSleep: (NSNotification *)notification
836 input_thread_t * p_input;
838 p_input = pl_CurrentInput( p_intf );
841 int state = var_GetInteger( p_input, "state" );
842 if( state == PLAYING_S )
843 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
844 vlc_object_release( p_input );
849 #pragma mark File opening
851 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
853 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
854 char *psz_uri = make_URI([o_filename UTF8String], "file" );
858 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
863 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
865 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
870 /* When user click in the Dock icon our double click in the finder */
871 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
873 if(!hasVisibleWindows)
874 [o_mainwindow makeKeyAndOrderFront:self];
880 #pragma mark Apple Remote Control
882 /* Helper method for the remote control interface in order to trigger forward/backward and volume
883 increase/decrease as long as the user holds the left/right, plus/minus button */
884 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
886 if(b_remote_button_hold)
888 switch([buttonIdentifierNumber intValue])
890 case kRemoteButtonRight_Hold:
891 [[VLCCoreInteraction sharedInstance] forward];
893 case kRemoteButtonLeft_Hold:
894 [[VLCCoreInteraction sharedInstance] backward];
896 case kRemoteButtonVolume_Plus_Hold:
897 [[VLCCoreInteraction sharedInstance] volumeUp];
899 case kRemoteButtonVolume_Minus_Hold:
900 [[VLCCoreInteraction sharedInstance] volumeDown];
903 if(b_remote_button_hold)
906 [self performSelector:@selector(executeHoldActionForRemoteButton:)
907 withObject:buttonIdentifierNumber
913 /* Apple Remote callback */
914 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
915 pressedDown: (BOOL) pressedDown
916 clickCount: (unsigned int) count
918 switch( buttonIdentifier )
920 case k2009RemoteButtonFullscreen:
921 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
923 case k2009RemoteButtonPlay:
924 [[VLCCoreInteraction sharedInstance] play];
926 case kRemoteButtonPlay:
928 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
930 [[VLCCoreInteraction sharedInstance] play];
933 case kRemoteButtonVolume_Plus:
934 [[VLCCoreInteraction sharedInstance] volumeUp];
936 case kRemoteButtonVolume_Minus:
937 [[VLCCoreInteraction sharedInstance] volumeDown];
939 case kRemoteButtonRight:
940 [[VLCCoreInteraction sharedInstance] next];
942 case kRemoteButtonLeft:
943 [[VLCCoreInteraction sharedInstance] previous];
945 case kRemoteButtonRight_Hold:
946 case kRemoteButtonLeft_Hold:
947 case kRemoteButtonVolume_Plus_Hold:
948 case kRemoteButtonVolume_Minus_Hold:
949 /* simulate an event as long as the user holds the button */
950 b_remote_button_hold = pressedDown;
953 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
954 [self performSelector:@selector(executeHoldActionForRemoteButton:)
955 withObject:buttonIdentifierNumber];
958 case kRemoteButtonMenu:
959 [o_controls showPosition: self]; //FIXME
962 /* Add here whatever you want other buttons to do */
968 #pragma mark String utility
969 // FIXME: this has nothing to do here
971 - (NSString *)localizedString:(const char *)psz
973 NSString * o_str = nil;
977 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
981 msg_Err( VLCIntf, "could not translate: %s", psz );
987 msg_Warn( VLCIntf, "can't translate empty strings" );
996 - (char *)delocalizeString:(NSString *)id
998 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
999 allowLossyConversion: NO];
1004 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1005 allowLossyConversion: YES];
1006 psz_string = malloc( [o_data length] + 1 );
1007 [o_data getBytes: psz_string];
1008 psz_string[ [o_data length] ] = '\0';
1009 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1014 psz_string = malloc( [o_data length] + 1 );
1015 [o_data getBytes: psz_string];
1016 psz_string[ [o_data length] ] = '\0';
1022 /* i_width is in pixels */
1023 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1025 NSMutableString *o_wrapped;
1026 NSString *o_out_string;
1027 NSRange glyphRange, effectiveRange, charRange;
1028 NSRect lineFragmentRect;
1029 unsigned glyphIndex, breaksInserted = 0;
1031 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1032 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1033 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1034 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1035 NSTextContainer *o_container = [[NSTextContainer alloc]
1036 initWithContainerSize: NSMakeSize(i_width, 2000)];
1038 [o_layout_manager addTextContainer: o_container];
1039 [o_container release];
1040 [o_storage addLayoutManager: o_layout_manager];
1041 [o_layout_manager release];
1043 o_wrapped = [o_in_string mutableCopy];
1044 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1046 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1047 glyphIndex += effectiveRange.length) {
1048 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1049 effectiveRange: &effectiveRange];
1050 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1051 actualGlyphRange: &effectiveRange];
1052 if([o_wrapped lineRangeForRange:
1053 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1054 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1058 o_out_string = [NSString stringWithString: o_wrapped];
1059 [o_wrapped release];
1060 [o_storage release];
1062 return o_out_string;
1067 #pragma mark Key Shortcuts
1072 unsigned int i_vlckey;
1073 } nskeys_to_vlckeys[] =
1075 { NSUpArrowFunctionKey, KEY_UP },
1076 { NSDownArrowFunctionKey, KEY_DOWN },
1077 { NSLeftArrowFunctionKey, KEY_LEFT },
1078 { NSRightArrowFunctionKey, KEY_RIGHT },
1079 { NSF1FunctionKey, KEY_F1 },
1080 { NSF2FunctionKey, KEY_F2 },
1081 { NSF3FunctionKey, KEY_F3 },
1082 { NSF4FunctionKey, KEY_F4 },
1083 { NSF5FunctionKey, KEY_F5 },
1084 { NSF6FunctionKey, KEY_F6 },
1085 { NSF7FunctionKey, KEY_F7 },
1086 { NSF8FunctionKey, KEY_F8 },
1087 { NSF9FunctionKey, KEY_F9 },
1088 { NSF10FunctionKey, KEY_F10 },
1089 { NSF11FunctionKey, KEY_F11 },
1090 { NSF12FunctionKey, KEY_F12 },
1091 { NSInsertFunctionKey, KEY_INSERT },
1092 { NSHomeFunctionKey, KEY_HOME },
1093 { NSEndFunctionKey, KEY_END },
1094 { NSPageUpFunctionKey, KEY_PAGEUP },
1095 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1096 { NSMenuFunctionKey, KEY_MENU },
1097 { NSTabCharacter, KEY_TAB },
1098 { NSCarriageReturnCharacter, KEY_ENTER },
1099 { NSEnterCharacter, KEY_ENTER },
1100 { NSBackspaceCharacter, KEY_BACKSPACE },
1101 { NSDeleteCharacter, KEY_DELETE },
1105 unsigned int CocoaKeyToVLC( unichar i_key )
1109 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1111 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1113 return nskeys_to_vlckeys[i].i_vlckey;
1116 return (unsigned int)i_key;
1119 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1121 unsigned int new = 0;
1123 if([theString rangeOfString:@"Command"].location != NSNotFound)
1124 new |= NSCommandKeyMask;
1125 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1126 new |= NSAlternateKeyMask;
1127 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1128 new |= NSShiftKeyMask;
1129 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1130 new |= NSControlKeyMask;
1134 - (NSString *)VLCKeyToString:(NSString *)theString
1136 if (![theString isEqualToString:@""]) {
1137 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1138 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1141 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1142 theString = [NSString stringWithFormat:@"%@+", theString];
1144 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1145 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1148 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1149 theString = [NSString stringWithFormat:@"%@-", theString];
1151 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1152 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1153 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1154 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1156 if ([theString length] > 1)
1158 if([theString rangeOfString:@"Up"].location != NSNotFound)
1159 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1160 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1161 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1162 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1163 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1164 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1165 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1166 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1167 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1168 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1169 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1170 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1171 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1172 else if([theString rangeOfString:@"End"].location != NSNotFound)
1173 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1174 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1175 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1176 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1177 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1178 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1179 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1180 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1181 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1182 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1183 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1184 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1185 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1186 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1187 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1188 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1189 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1190 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1191 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1192 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1193 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1194 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1195 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1196 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1197 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1198 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1199 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1200 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1201 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1202 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1203 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1204 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1205 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1206 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1207 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1208 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1209 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1210 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1217 /*****************************************************************************
1218 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1219 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1220 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1221 *****************************************************************************/
1222 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1226 unsigned int i_pressed_modifiers = 0;
1227 const struct hotkey *p_hotkeys;
1229 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1230 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1233 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1235 i_pressed_modifiers = [o_event modifierFlags];
1237 if( i_pressed_modifiers & NSShiftKeyMask ) {
1238 val.i_int |= KEY_MODIFIER_SHIFT;
1239 [tempString appendString:@"Shift-"];
1240 [tempStringPlus appendString:@"Shift+"];
1242 if( i_pressed_modifiers & NSControlKeyMask ) {
1243 val.i_int |= KEY_MODIFIER_CTRL;
1244 [tempString appendString:@"Ctrl-"];
1245 [tempStringPlus appendString:@"Ctrl+"];
1247 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1248 val.i_int |= KEY_MODIFIER_ALT;
1249 [tempString appendString:@"Alt-"];
1250 [tempStringPlus appendString:@"Alt+"];
1252 if( i_pressed_modifiers & NSCommandKeyMask ) {
1253 val.i_int |= KEY_MODIFIER_COMMAND;
1254 [tempString appendString:@"Command-"];
1255 [tempStringPlus appendString:@"Command+"];
1258 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1259 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1261 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1265 case NSDeleteCharacter:
1266 case NSDeleteFunctionKey:
1267 case NSDeleteCharFunctionKey:
1268 case NSBackspaceCharacter:
1269 case NSUpArrowFunctionKey:
1270 case NSDownArrowFunctionKey:
1271 case NSRightArrowFunctionKey:
1272 case NSLeftArrowFunctionKey:
1273 case NSEnterCharacter:
1274 case NSCarriageReturnCharacter:
1278 if( key == 0x0020 ) // space key
1280 [[VLCCoreInteraction sharedInstance] play];
1284 val.i_int |= CocoaKeyToVLC( key );
1286 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1288 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1295 - (void)updateCurrentlyUsedHotkeys
1297 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1298 /* Get the main Module */
1299 module_t *p_main = module_get_main();
1302 module_config_t *p_config;
1304 p_config = module_config_get (p_main, &confsize);
1306 for (size_t i = 0; i < confsize; i++)
1308 module_config_t *p_item = p_config + i;
1310 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1311 && !strncmp( p_item->psz_name , "key-", 4 )
1312 && !EMPTY_STR( p_item->psz_text ) )
1314 if (p_item->value.psz)
1315 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1318 module_config_free (p_config);
1319 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1323 #pragma mark Interface updaters
1324 - (void)fullscreenChanged
1326 playlist_t * p_playlist = pl_Get( VLCIntf );
1327 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1329 if (OSX_LION && b_nativeFullscreenMode)
1331 [o_mainwindow toggleFullScreen: self];
1333 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1335 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1339 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1341 if( p_input != NULL )
1344 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1346 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1347 vlc_object_release( p_input );
1352 - (void)PlaylistItemChanged
1354 input_thread_t * p_input;
1356 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1357 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1359 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1360 [o_mainmenu setRateControlsEnabled: YES];
1361 vlc_object_release( p_input );
1364 [o_mainmenu setRateControlsEnabled: NO];
1366 [o_playlist updateRowSelection];
1367 [o_mainwindow updateWindow];
1368 [self updateMainMenu];
1371 - (void)updateMainMenu
1373 [o_mainmenu setupMenus];
1374 [o_mainmenu updatePlaybackRate];
1377 - (void)updateMainWindow
1379 [o_mainwindow updateWindow];
1382 - (void)showFullscreenController
1384 [o_mainwindow showFullscreenController];
1387 - (void)updateDelays
1389 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1394 [o_mainwindow updateName];
1397 - (void)updatePlaybackPosition
1399 [o_mainwindow updateTimeSlider];
1401 input_thread_t * p_input;
1402 p_input = pl_CurrentInput( p_intf );
1405 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1406 UpdateSystemActivity( UsrActivity );
1407 vlc_object_release( p_input );
1411 - (void)updateVolume
1413 [o_mainwindow updateVolumeSlider];
1416 - (void)playlistUpdated
1418 [self playbackStatusUpdated];
1419 [o_playlist playlistUpdated];
1420 [o_mainwindow updateWindow];
1421 [o_mainwindow updateName];
1424 - (void)updateRecordState: (BOOL)b_value
1426 [o_mainmenu updateRecordState:b_value];
1429 - (void)updateInfoandMetaPanel
1431 [o_playlist outlineViewSelectionDidChange:nil];
1434 - (void)playbackStatusUpdated
1436 input_thread_t * p_input;
1438 p_input = pl_CurrentInput( p_intf );
1441 int state = var_GetInteger( p_input, "state" );
1442 if( state == PLAYING_S )
1444 [[self mainMenu] setPause];
1445 [o_mainwindow setPause];
1450 [o_mainmenu setSubmenusEnabled: FALSE];
1451 [[self mainMenu] setPlay];
1452 [o_mainwindow setPlay];
1454 vlc_object_release( p_input );
1458 - (void)playbackModeUpdated
1460 vlc_value_t looping,repeating;
1461 playlist_t * p_playlist = pl_Get( VLCIntf );
1463 bool loop = var_GetBool( p_playlist, "loop" );
1464 bool repeat = var_GetBool( p_playlist, "repeat" );
1466 [o_mainwindow setRepeatOne];
1467 [o_mainmenu setRepeatOne];
1469 [o_mainwindow setRepeatAll];
1470 [o_mainmenu setRepeatAll];
1472 [o_mainwindow setRepeatOff];
1473 [o_mainmenu setRepeatOff];
1476 [o_mainwindow setShuffle];
1477 [o_mainmenu setShuffle];
1481 #pragma mark Other objects getters
1499 o_bookmarks = [[VLCBookmarks alloc] init];
1501 if( !nib_bookmarks_loaded )
1502 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1512 if (!nib_open_loaded)
1513 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1518 - (id)simplePreferences
1521 o_sprefs = [[VLCSimplePrefs alloc] init];
1523 if (!nib_prefs_loaded)
1524 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1532 o_prefs = [[VLCPrefs alloc] init];
1534 if( !nib_prefs_loaded )
1535 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1550 if(! nib_info_loaded )
1551 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1562 o_wizard = [[VLCWizard alloc] init];
1564 if( !nib_wizard_loaded )
1566 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1567 [o_wizard initStrings];
1572 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1574 id videoView = [o_mainwindow videoView];
1575 NSRect videoRect = [videoView frame];
1576 int i_x = (int)videoRect.origin.x;
1577 int i_y = (int)videoRect.origin.y;
1578 unsigned int i_width = (int)videoRect.size.width;
1579 unsigned int i_height = (int)videoRect.size.height;
1582 pi_width = (unsigned int*)i_width;
1583 pi_height = (unsigned int*)i_height;
1584 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1588 - (void)setNativeVideoSize:(NSSize)size
1590 [o_mainwindow setNativeVideoSize:size];
1595 if( o_embedded_list )
1596 return o_embedded_list;
1601 - (id)coreDialogProvider
1604 return o_coredialogs;
1609 - (id)eyeTVController
1617 - (id)appleRemoteController
1622 - (void)setActiveVideoPlayback:(BOOL)b_value
1624 b_active_videoplayback = b_value;
1625 [o_mainwindow setVideoplayEnabled];
1626 [o_mainwindow togglePlaylist:nil];
1629 - (BOOL)activeVideoPlayback
1631 return b_active_videoplayback;
1635 #pragma mark Crash Log
1636 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1638 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1639 NSURL *url = [NSURL URLWithString:urlStr];
1641 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1642 [req setHTTPMethod:@"POST"];
1645 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1647 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1648 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1649 email = [emails valueAtIndex:[emails indexForIdentifier:
1650 [emails primaryIdentifier]]];
1653 email = [NSString string];
1656 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1657 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1658 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1659 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1661 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1663 /* Released from delegate */
1664 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1667 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1669 [crashLogURLConnection release];
1670 crashLogURLConnection = nil;
1673 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1675 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1676 [crashLogURLConnection release];
1677 crashLogURLConnection = nil;
1680 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1682 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1683 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1685 NSString * latestLog = nil;
1686 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1687 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1688 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1689 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1691 while (fname = [direnum nextObject])
1693 [direnum skipDescendents];
1694 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1696 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1697 if( [compo count] < 3 ) continue;
1698 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1699 if( [compo count] < 4 ) continue;
1702 if( year < [[compo objectAtIndex:0] intValue] ||
1703 (year ==[[compo objectAtIndex:0] intValue] &&
1704 (month < [[compo objectAtIndex:1] intValue] ||
1705 (month ==[[compo objectAtIndex:1] intValue] &&
1706 (day < [[compo objectAtIndex:2] intValue] ||
1707 (day ==[[compo objectAtIndex:2] intValue] &&
1708 hours < [[compo objectAtIndex:3] intValue] ))))))
1710 year = [[compo objectAtIndex:0] intValue];
1711 month = [[compo objectAtIndex:1] intValue];
1712 day = [[compo objectAtIndex:2] intValue];
1713 hours = [[compo objectAtIndex:3] intValue];
1714 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1719 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1722 if( !previouslySeen )
1724 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1725 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1726 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1727 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1732 - (NSString *)latestCrashLogPath
1734 return [self latestCrashLogPathPreviouslySeen:YES];
1737 - (void)lookForCrashLog
1739 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1740 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1741 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1742 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1743 if( latestLog && !areCrashLogsTooOld )
1744 [NSApp runModalForWindow: o_crashrep_win];
1748 - (IBAction)crashReporterAction:(id)sender
1750 if( sender == o_crashrep_send_btn )
1751 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1754 [o_crashrep_win orderOut: sender];
1757 - (IBAction)openCrashLog:(id)sender
1759 NSString * latestLog = [self latestCrashLogPath];
1762 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1766 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.") );
1771 #pragma mark Remove old prefs
1773 - (void)_removeOldPreferences
1775 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1776 static const int kCurrentPreferencesVersion = 1;
1777 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1778 if( version >= kCurrentPreferencesVersion ) return;
1780 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1781 NSUserDomainMask, YES);
1782 if( !libraries || [libraries count] == 0) return;
1783 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1785 /* File not found, don't attempt anything */
1786 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1787 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1789 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1793 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1794 _NS("We just found an older version of VLC's preferences files."),
1795 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1796 if( res != NSOKButton )
1798 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1802 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1804 /* Move the file to trash so that user can find them later */
1805 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1807 /* really reset the defaults from now on */
1808 [NSUserDefaults resetStandardUserDefaults];
1810 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1811 [[NSUserDefaults standardUserDefaults] synchronize];
1814 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1816 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1822 execl(path, path, NULL);
1826 #pragma mark Errors, warnings and messages
1827 - (IBAction)showMessagesPanel:(id)sender
1829 [o_msgs_panel makeKeyAndOrderFront: sender];
1832 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1834 if( [o_notification object] == o_msgs_panel )
1835 [self updateMessageDisplay];
1838 - (void)updateMessageDisplay
1840 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1843 NSEnumerator * o_enum;
1845 [o_messages setString: @""];
1849 o_enum = [o_msg_arr objectEnumerator];
1851 while( ( o_msg = [o_enum nextObject] ) != nil )
1853 [o_messages insertText: o_msg];
1856 b_msg_arr_changed = NO;
1857 [o_msg_lock unlock];
1861 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1863 NSColor *o_white = [NSColor whiteColor];
1864 NSColor *o_red = [NSColor redColor];
1865 NSColor *o_yellow = [NSColor yellowColor];
1866 NSColor *o_gray = [NSColor grayColor];
1868 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1869 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1871 NSDictionary *o_attr;
1872 NSAttributedString *o_msg_color;
1876 if( [o_msg_arr count] + 2 > 600 )
1878 [o_msg_arr removeObjectAtIndex: 0];
1879 [o_msg_arr removeObjectAtIndex: 1];
1882 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1883 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1884 [o_msg_arr addObject: [o_msg_color autorelease]];
1886 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1887 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1888 [o_msg_arr addObject: [o_msg_color autorelease]];
1890 b_msg_arr_changed = YES;
1891 [o_msg_lock unlock];
1893 [self updateMessageDisplay];
1896 - (IBAction)saveDebugLog:(id)sender
1898 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1900 [saveFolderPanel setCanSelectHiddenExtension: NO];
1901 [saveFolderPanel setCanCreateDirectories: YES];
1902 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1903 [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];
1906 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1909 if( returnCode == NSOKButton )
1911 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1913 msg_Warn( p_intf, "Error while saving the debug log" );
1918 #pragma mark Playlist toggling
1920 - (void)updateTogglePlaylistState
1922 [[self playlist] outlineViewSelectionDidChange: NULL];
1929 @implementation VLCMain (Internal)
1931 - (void)handlePortMessage:(NSPortMessage *)o_msg
1936 NSInvocation * o_inv;
1937 NSConditionLock * o_lock;
1939 o_data = [[o_msg components] lastObject];
1940 o_inv = *((NSInvocation **)[o_data bytes]);
1941 [o_inv getArgument: &o_value atIndex: 2];
1942 val = (id **)[o_value pointerValue];
1943 [o_inv setArgument: val[1] atIndex: 2];
1948 [o_lock unlockWithCondition: 1];
1950 - (void)resetMediaKeyJump
1952 b_mediakeyJustJumped = NO;
1954 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1956 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1957 if (b_mediaKeySupport) {
1958 if (!o_mediaKeyController)
1959 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1960 [o_mediaKeyController startWatchingMediaKeys];
1962 else if (!b_mediaKeySupport && o_mediaKeyController)
1964 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1965 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1966 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1967 if( returnedValue == NSOKButton )
1970 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1972 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1978 execl(path, path, NULL);
1985 /*****************************************************************************
1986 * VLCApplication interface
1987 *****************************************************************************/
1989 @implementation VLCApplication
1990 // when user selects the quit menu from dock it sends a terminate:
1991 // but we need to send a stop: to properly exits libvlc.
1992 // However, we are not able to change the action-method sent by this standard menu item.
1993 // thus we override terminat: to send a stop:
1994 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1995 - (void)terminate:(id)sender
1997 [self activateIgnoringOtherApps:YES];