1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
42 #import "CompatibilityFixes.h"
48 #import "playlistinfo.h"
53 #import "coredialogs.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
57 #import "CoreInteraction.h"
58 #import "TrackSynchronization.h"
60 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
61 #import <Sparkle/Sparkle.h> /* we're the update delegate */
63 /*****************************************************************************
65 *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
68 static void updateProgressPanel (void *, const char *, float);
69 static bool checkProgressPanel (void *);
70 static void destroyProgressPanel (void *);
72 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
74 static int InputEvent( vlc_object_t *, const char *,
75 vlc_value_t, vlc_value_t, void * );
76 static int PLItemChanged( vlc_object_t *, const char *,
77 vlc_value_t, vlc_value_t, void * );
78 static int PlaylistUpdated( vlc_object_t *, const char *,
79 vlc_value_t, vlc_value_t, void * );
80 static int PlaybackModeUpdated( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int VolumeUpdated( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
86 #pragma mark VLC Interface Object Callbacks
88 /*****************************************************************************
89 * OpenIntf: initialize interface
90 *****************************************************************************/
91 int OpenIntf ( vlc_object_t *p_this )
93 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
94 [VLCApplication sharedApplication];
95 intf_thread_t *p_intf = (intf_thread_t*) p_this;
97 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
98 if( p_intf->p_sys == NULL )
101 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
103 /* subscribe to LibVLCCore's messages */
104 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
105 p_intf->pf_run = Run;
106 p_intf->b_should_run_on_first_thread = true;
112 /*****************************************************************************
113 * CloseIntf: destroy interface
114 *****************************************************************************/
115 void CloseIntf ( vlc_object_t *p_this )
117 intf_thread_t *p_intf = (intf_thread_t*) p_this;
119 free( p_intf->p_sys );
122 static int WindowControl( vout_window_t *, int i_query, va_list );
124 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
126 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
127 intf_thread_t *p_intf = VLCIntf;
129 msg_Err( p_wnd, "Mac OS X interface not found" );
135 unsigned i_width = cfg->width;
136 unsigned i_height = cfg->height;
137 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
139 if ( !p_wnd->handle.nsobject ) {
140 msg_Err( p_wnd, "got no video view from the interface" );
145 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
146 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
147 p_wnd->control = WindowControl;
148 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
153 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
156 if( i_query == VOUT_WINDOW_SET_STATE )
157 NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
158 else if( i_query == VOUT_WINDOW_SET_SIZE )
160 NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
161 unsigned int i_width = va_arg( args, unsigned int );
162 unsigned int i_height = va_arg( args, unsigned int );
163 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
165 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
166 NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
168 NSLog( @"WindowControl: unknown query" );
172 void WindowClose( vout_window_t *p_wnd )
174 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
175 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
176 NSLog( @"Window Close" );
177 // tell the interface to get rid of the video, TODO
181 /*****************************************************************************
183 *****************************************************************************/
184 static NSLock * o_appLock = nil; // controls access to f_appExit
185 static int f_appExit = 0; // set to 1 when application termination signaled
187 static void Run( intf_thread_t *p_intf )
191 /* Make sure the "force quit" menu item does quit instantly.
192 * VLC overrides SIGTERM which is sent by the "force quit"
193 * menu item to make sure daemon mode quits gracefully, so
194 * we un-override SIGTERM here. */
196 sigaddset( &set, SIGTERM );
197 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
199 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
200 [VLCApplication sharedApplication];
202 o_appLock = [[NSLock alloc] init];
204 [[VLCMain sharedInstance] setIntf: p_intf];
205 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
208 [[VLCMain sharedInstance] applicationWillTerminate:nil];
214 #pragma mark Variables Callback
216 /*****************************************************************************
217 * MsgCallback: Callback triggered by the core once a new debug message is
218 * ready to be displayed. We store everything in a NSArray in our Cocoa part
220 *****************************************************************************/
221 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
223 int canc = vlc_savecancel();
226 if (vasprintf( &str, format, ap ) == -1)
228 vlc_restorecancel( canc );
232 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
233 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
236 vlc_restorecancel( canc );
240 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
241 vlc_value_t oldval, vlc_value_t new_val, void *param )
243 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
244 switch (new_val.i_int) {
245 case INPUT_EVENT_STATE:
246 [[VLCMain sharedInstance] playbackStatusUpdated];
248 case INPUT_EVENT_RATE:
249 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
251 case INPUT_EVENT_POSITION:
252 [[VLCMain sharedInstance] updatePlaybackPosition];
254 case INPUT_EVENT_TITLE:
255 case INPUT_EVENT_CHAPTER:
256 [[VLCMain sharedInstance] updateMainMenu];
258 case INPUT_EVENT_CACHE:
259 [[VLCMain sharedInstance] updateMainWindow];
261 case INPUT_EVENT_STATISTICS:
262 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
266 case INPUT_EVENT_TELETEXT:
268 case INPUT_EVENT_AOUT:
270 case INPUT_EVENT_VOUT:
272 case INPUT_EVENT_ITEM_META:
273 case INPUT_EVENT_ITEM_INFO:
274 [[VLCMain sharedInstance] updateMainMenu];
275 [[VLCMain sharedInstance] updateName];
276 [[VLCMain sharedInstance] updateInfoandMetaPanel];
278 case INPUT_EVENT_BOOKMARK:
280 case INPUT_EVENT_RECORD:
281 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
283 case INPUT_EVENT_PROGRAM:
284 [[VLCMain sharedInstance] updateMainMenu];
286 case INPUT_EVENT_ITEM_EPG:
288 case INPUT_EVENT_SIGNAL:
291 case INPUT_EVENT_ITEM_NAME:
292 [[VLCMain sharedInstance] updateName];
293 [[VLCMain sharedInstance] playlistUpdated];
296 case INPUT_EVENT_AUDIO_DELAY:
297 case INPUT_EVENT_SUBTITLE_DELAY:
298 [[VLCMain sharedInstance] updateDelays];
301 case INPUT_EVENT_DEAD:
302 [[VLCMain sharedInstance] updateName];
303 [[VLCMain sharedInstance] updatePlaybackPosition];
306 case INPUT_EVENT_ABORT:
307 [[VLCMain sharedInstance] updateName];
308 [[VLCMain sharedInstance] updatePlaybackPosition];
312 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
320 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
321 vlc_value_t oldval, vlc_value_t new_val, void *param )
323 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
324 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
330 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
331 vlc_value_t oldval, vlc_value_t new_val, void *param )
333 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
340 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
341 vlc_value_t oldval, vlc_value_t new_val, void *param )
343 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
344 [[VLCMain sharedInstance] playbackModeUpdated];
350 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
351 vlc_value_t oldval, vlc_value_t new_val, void *param )
353 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
354 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
360 /*****************************************************************************
361 * ShowController: Callback triggered by the show-intf playlist variable
362 * through the ShowIntf-control-intf, to let us show the controller-win;
363 * usually when in fullscreen-mode
364 *****************************************************************************/
365 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
366 vlc_value_t old_val, vlc_value_t new_val, void *param )
368 intf_thread_t * p_intf = VLCIntf;
369 if( p_intf && p_intf->p_sys )
371 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
376 /*****************************************************************************
377 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
378 * variable, to let the intf update the controller.
379 *****************************************************************************/
380 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
381 vlc_value_t old_val, vlc_value_t new_val, void *param )
383 intf_thread_t * p_intf = VLCIntf;
386 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
387 [[VLCMain sharedInstance] fullscreenChanged];
393 /*****************************************************************************
394 * DialogCallback: Callback triggered by the "dialog-*" variables
395 * to let the intf display error and interaction dialogs
396 *****************************************************************************/
397 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
399 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
400 VLCMain *interface = (VLCMain *)data;
402 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
404 /* the progress panel needs to update itself and therefore wants special treatment within this context */
405 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
407 p_dialog->pf_update = updateProgressPanel;
408 p_dialog->pf_check = checkProgressPanel;
409 p_dialog->pf_destroy = destroyProgressPanel;
410 p_dialog->p_sys = VLCIntf->p_libvlc;
413 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
414 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
420 void updateProgressPanel (void *priv, const char *text, float value)
422 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
426 o_txt = [NSString stringWithUTF8String: text];
430 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
435 void destroyProgressPanel (void *priv)
437 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
438 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
442 bool checkProgressPanel (void *priv)
444 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
445 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
452 input_thread_t *getInput(void)
454 intf_thread_t *p_intf = VLCIntf;
457 return pl_CurrentInput(p_intf);
460 vout_thread_t *getVout(void)
462 input_thread_t *p_input = getInput();
465 vout_thread_t *p_vout = input_GetVout(p_input);
466 vlc_object_release(p_input);
470 audio_output_t *getAout(void)
472 input_thread_t *p_input = getInput();
475 audio_output_t *p_aout = input_GetAout(p_input);
476 vlc_object_release(p_input);
483 @interface VLCMain ()
484 - (void)_removeOldPreferences;
487 /*****************************************************************************
488 * VLCMain implementation
489 *****************************************************************************/
490 @implementation VLCMain
493 #pragma mark Initialization
495 static VLCMain *_o_sharedMainInstance = nil;
497 + (VLCMain *)sharedInstance
499 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
504 if( _o_sharedMainInstance)
507 return _o_sharedMainInstance;
510 _o_sharedMainInstance = [super init];
514 o_msg_lock = [[NSLock alloc] init];
515 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
517 o_open = [[VLCOpen alloc] init];
518 //o_embedded_list = [[VLCEmbeddedList alloc] init];
519 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
520 o_info = [[VLCInfo alloc] init];
521 o_mainmenu = [[VLCMainMenu alloc] init];
522 o_coreinteraction = [[VLCCoreInteraction alloc] init];
523 o_eyetv = [[VLCEyeTVController alloc] init];
524 o_mainwindow = [[VLCMainWindow alloc] init];
526 /* announce our launch to a potential eyetv plugin */
527 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
528 object: @"VLCEyeTVSupport"
530 deliverImmediately: YES];
531 return _o_sharedMainInstance;
534 - (void)setIntf: (intf_thread_t *)p_mainintf {
538 - (intf_thread_t *)intf {
544 playlist_t *p_playlist;
546 if( !p_intf ) return;
547 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
549 /* Check if we already did this once. Opening the other nibs calls it too,
550 because VLCMain is the owner */
551 if( nib_main_loaded ) return;
553 [o_msgs_panel setExcludedFromWindowsMenu: YES];
554 [o_msgs_panel setDelegate: self];
556 p_playlist = pl_Get( p_intf );
560 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
561 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
562 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
563 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
564 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
565 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
566 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
567 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
568 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
569 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
570 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
571 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
572 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
574 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
575 var_SetBool( p_playlist, "fullscreen", YES );
577 /* load our Core Dialogs nib */
578 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
580 /* subscribe to various interactive dialogues */
581 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
582 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
583 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
584 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
585 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
586 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
587 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
588 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
589 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
590 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
591 dialog_Register( p_intf );
593 [self playbackModeUpdated];
595 /* init Apple Remote support */
596 o_remote = [[AppleRemote alloc] init];
597 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
598 [o_remote setDelegate: _o_sharedMainInstance];
600 /* yeah, we are done */
601 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
602 nib_main_loaded = TRUE;
605 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
607 if( !p_intf ) return;
609 /* init media key support */
610 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
611 if( b_mediaKeySupport )
613 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
614 [o_mediaKeyController startWatchingMediaKeys];
615 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
616 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
619 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
621 [self _removeOldPreferences];
623 [o_mainwindow updateWindow];
624 [o_mainwindow updateTimeSlider];
625 [o_mainwindow updateVolumeSlider];
626 [o_mainwindow makeKeyAndOrderFront: self];
628 /* Handle sleep notification */
629 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
630 name:NSWorkspaceWillSleepNotification object:nil];
632 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
637 if( !p_intf ) return;
640 [o_msgs_panel setTitle: _NS("Messages")];
641 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
642 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
644 /* crash reporter panel */
645 [o_crashrep_send_btn setTitle: _NS("Send")];
646 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
647 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
648 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
649 [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
650 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
651 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
655 #pragma mark Termination
657 - (void)applicationWillTerminate:(NSNotification *)notification
659 playlist_t * p_playlist;
660 vout_thread_t * p_vout;
661 int returnedValue = 0;
667 config_SaveConfigFile( p_intf );
669 // don't allow a double termination call. If the user has
670 // already invoked the quit then simply return this time.
671 int isTerminating = false;
674 isTerminating = (f_appExit++ > 0 ? 1 : 0);
680 msg_Dbg( p_intf, "Terminating" );
682 /* Make sure the intf object is getting killed */
683 vlc_object_kill( p_intf );
684 p_playlist = pl_Get( p_intf );
686 /* unsubscribe from the interactive dialogues */
687 dialog_Unregister( p_intf );
688 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
689 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
690 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
691 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
692 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
693 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
694 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
695 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
696 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
697 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
698 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
699 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
700 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
701 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
702 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
703 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
705 /* remove global observer watching for vout device changes correctly */
706 [[NSNotificationCenter defaultCenter] removeObserver: self];
708 /* release some other objects here, because it isn't sure whether dealloc
709 * will be called later on */
724 [crashLogURLConnection cancel];
725 [crashLogURLConnection release];
727 [o_embedded_list release];
728 [o_coredialogs release];
730 [o_mainwindow release];
732 /* unsubscribe from libvlc's debug messages */
733 vlc_Unsubscribe( p_intf->p_sys->p_sub );
735 [o_msg_arr removeAllObjects];
738 [o_msg_lock release];
740 /* write cached user defaults to disk */
741 [[NSUserDefaults standardUserDefaults] synchronize];
743 /* Make sure the Menu doesn't have any references to vlc objects anymore */
744 //FIXME: this should be moved to VLCMainMenu
745 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
746 [o_mainmenu release];
748 /* Kill the playlist, so that it doesn't accept new request
749 * such as the play request from vlc.c (we are a blocking interface). */
750 vlc_object_kill( p_playlist );
751 libvlc_Quit( p_intf->p_libvlc );
757 #pragma mark Sparkle delegate
758 /* received directly before the update gets installed, so let's shut down a bit */
759 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
761 [NSApp activateIgnoringOtherApps:YES];
762 [o_remote stopListening: self];
763 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
767 #pragma mark Media Key support
769 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
771 if( b_mediaKeySupport )
773 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
775 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
776 int keyFlags = ([event data1] & 0x0000FFFF);
777 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
778 int keyRepeat = (keyFlags & 0x1);
780 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
781 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
783 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
785 if( keyState == 0 && keyRepeat == 0 )
786 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
787 else if( keyRepeat == 1 )
789 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
790 b_mediakeyJustJumped = YES;
791 [self performSelector:@selector(resetMediaKeyJump)
797 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
799 if( keyState == 0 && keyRepeat == 0 )
800 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
801 else if( keyRepeat == 1 )
803 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
804 b_mediakeyJustJumped = YES;
805 [self performSelector:@selector(resetMediaKeyJump)
814 #pragma mark Other notification
816 /* Listen to the remote in exclusive mode, only when VLC is the active
818 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
820 if( !p_intf ) return;
821 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
822 [o_remote startListening: self];
824 - (void)applicationDidResignActive:(NSNotification *)aNotification
826 if( !p_intf ) return;
827 [o_remote stopListening: self];
830 /* Triggered when the computer goes to sleep */
831 - (void)computerWillSleep: (NSNotification *)notification
833 input_thread_t * p_input;
835 p_input = pl_CurrentInput( p_intf );
838 int state = var_GetInteger( p_input, "state" );
839 if( state == PLAYING_S )
840 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
841 vlc_object_release( p_input );
846 #pragma mark File opening
848 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
850 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
851 char *psz_uri = make_URI([o_filename UTF8String], "file" );
855 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
860 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
862 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
867 /* When user click in the Dock icon our double click in the finder */
868 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
870 if(!hasVisibleWindows)
871 [o_mainwindow makeKeyAndOrderFront:self];
877 #pragma mark Apple Remote Control
879 /* Helper method for the remote control interface in order to trigger forward/backward and volume
880 increase/decrease as long as the user holds the left/right, plus/minus button */
881 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
883 if(b_remote_button_hold)
885 switch([buttonIdentifierNumber intValue])
887 case kRemoteButtonRight_Hold:
888 [[VLCCoreInteraction sharedInstance] forward];
890 case kRemoteButtonLeft_Hold:
891 [[VLCCoreInteraction sharedInstance] backward];
893 case kRemoteButtonVolume_Plus_Hold:
894 [[VLCCoreInteraction sharedInstance] volumeUp];
896 case kRemoteButtonVolume_Minus_Hold:
897 [[VLCCoreInteraction sharedInstance] volumeDown];
900 if(b_remote_button_hold)
903 [self performSelector:@selector(executeHoldActionForRemoteButton:)
904 withObject:buttonIdentifierNumber
910 /* Apple Remote callback */
911 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
912 pressedDown: (BOOL) pressedDown
913 clickCount: (unsigned int) count
915 switch( buttonIdentifier )
917 case k2009RemoteButtonFullscreen:
918 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
920 case k2009RemoteButtonPlay:
921 [[VLCCoreInteraction sharedInstance] play];
923 case kRemoteButtonPlay:
925 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
927 [[VLCCoreInteraction sharedInstance] play];
930 case kRemoteButtonVolume_Plus:
931 [[VLCCoreInteraction sharedInstance] volumeUp];
933 case kRemoteButtonVolume_Minus:
934 [[VLCCoreInteraction sharedInstance] volumeDown];
936 case kRemoteButtonRight:
937 [[VLCCoreInteraction sharedInstance] next];
939 case kRemoteButtonLeft:
940 [[VLCCoreInteraction sharedInstance] previous];
942 case kRemoteButtonRight_Hold:
943 case kRemoteButtonLeft_Hold:
944 case kRemoteButtonVolume_Plus_Hold:
945 case kRemoteButtonVolume_Minus_Hold:
946 /* simulate an event as long as the user holds the button */
947 b_remote_button_hold = pressedDown;
950 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
951 [self performSelector:@selector(executeHoldActionForRemoteButton:)
952 withObject:buttonIdentifierNumber];
955 case kRemoteButtonMenu:
956 [o_controls showPosition: self]; //FIXME
959 /* Add here whatever you want other buttons to do */
965 #pragma mark String utility
966 // FIXME: this has nothing to do here
968 - (NSString *)localizedString:(const char *)psz
970 NSString * o_str = nil;
974 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
978 msg_Err( VLCIntf, "could not translate: %s", psz );
984 msg_Warn( VLCIntf, "can't translate empty strings" );
993 - (char *)delocalizeString:(NSString *)id
995 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
996 allowLossyConversion: NO];
1001 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1002 allowLossyConversion: YES];
1003 psz_string = malloc( [o_data length] + 1 );
1004 [o_data getBytes: psz_string];
1005 psz_string[ [o_data length] ] = '\0';
1006 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1011 psz_string = malloc( [o_data length] + 1 );
1012 [o_data getBytes: psz_string];
1013 psz_string[ [o_data length] ] = '\0';
1019 /* i_width is in pixels */
1020 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1022 NSMutableString *o_wrapped;
1023 NSString *o_out_string;
1024 NSRange glyphRange, effectiveRange, charRange;
1025 NSRect lineFragmentRect;
1026 unsigned glyphIndex, breaksInserted = 0;
1028 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1029 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1030 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1031 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1032 NSTextContainer *o_container = [[NSTextContainer alloc]
1033 initWithContainerSize: NSMakeSize(i_width, 2000)];
1035 [o_layout_manager addTextContainer: o_container];
1036 [o_container release];
1037 [o_storage addLayoutManager: o_layout_manager];
1038 [o_layout_manager release];
1040 o_wrapped = [o_in_string mutableCopy];
1041 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1043 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1044 glyphIndex += effectiveRange.length) {
1045 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1046 effectiveRange: &effectiveRange];
1047 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1048 actualGlyphRange: &effectiveRange];
1049 if([o_wrapped lineRangeForRange:
1050 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1051 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1055 o_out_string = [NSString stringWithString: o_wrapped];
1056 [o_wrapped release];
1057 [o_storage release];
1059 return o_out_string;
1064 #pragma mark Key Shortcuts
1069 unsigned int i_vlckey;
1070 } nskeys_to_vlckeys[] =
1072 { NSUpArrowFunctionKey, KEY_UP },
1073 { NSDownArrowFunctionKey, KEY_DOWN },
1074 { NSLeftArrowFunctionKey, KEY_LEFT },
1075 { NSRightArrowFunctionKey, KEY_RIGHT },
1076 { NSF1FunctionKey, KEY_F1 },
1077 { NSF2FunctionKey, KEY_F2 },
1078 { NSF3FunctionKey, KEY_F3 },
1079 { NSF4FunctionKey, KEY_F4 },
1080 { NSF5FunctionKey, KEY_F5 },
1081 { NSF6FunctionKey, KEY_F6 },
1082 { NSF7FunctionKey, KEY_F7 },
1083 { NSF8FunctionKey, KEY_F8 },
1084 { NSF9FunctionKey, KEY_F9 },
1085 { NSF10FunctionKey, KEY_F10 },
1086 { NSF11FunctionKey, KEY_F11 },
1087 { NSF12FunctionKey, KEY_F12 },
1088 { NSInsertFunctionKey, KEY_INSERT },
1089 { NSHomeFunctionKey, KEY_HOME },
1090 { NSEndFunctionKey, KEY_END },
1091 { NSPageUpFunctionKey, KEY_PAGEUP },
1092 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1093 { NSMenuFunctionKey, KEY_MENU },
1094 { NSTabCharacter, KEY_TAB },
1095 { NSCarriageReturnCharacter, KEY_ENTER },
1096 { NSEnterCharacter, KEY_ENTER },
1097 { NSBackspaceCharacter, KEY_BACKSPACE },
1101 unsigned int CocoaKeyToVLC( unichar i_key )
1105 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1107 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1109 return nskeys_to_vlckeys[i].i_vlckey;
1112 return (unsigned int)i_key;
1115 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1117 unsigned int new = 0;
1119 if([theString rangeOfString:@"Command"].location != NSNotFound)
1120 new |= NSCommandKeyMask;
1121 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1122 new |= NSAlternateKeyMask;
1123 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1124 new |= NSShiftKeyMask;
1125 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1126 new |= NSControlKeyMask;
1130 - (NSString *)VLCKeyToString:(NSString *)theString
1132 if (![theString isEqualToString:@""]) {
1133 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1134 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1135 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1136 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1137 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1138 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1144 /*****************************************************************************
1145 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1146 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1147 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1148 *****************************************************************************/
1149 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1153 unsigned int i_pressed_modifiers = 0;
1154 const struct hotkey *p_hotkeys;
1156 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1157 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1160 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1162 i_pressed_modifiers = [o_event modifierFlags];
1164 if( i_pressed_modifiers & NSShiftKeyMask ) {
1165 val.i_int |= KEY_MODIFIER_SHIFT;
1166 [tempString appendString:@"Shift-"];
1167 [tempStringPlus appendString:@"Shift+"];
1169 if( i_pressed_modifiers & NSControlKeyMask ) {
1170 val.i_int |= KEY_MODIFIER_CTRL;
1171 [tempString appendString:@"Ctrl-"];
1172 [tempStringPlus appendString:@"Ctrl+"];
1174 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1175 val.i_int |= KEY_MODIFIER_ALT;
1176 [tempString appendString:@"Alt-"];
1177 [tempStringPlus appendString:@"Alt+"];
1179 if( i_pressed_modifiers & NSCommandKeyMask ) {
1180 val.i_int |= KEY_MODIFIER_COMMAND;
1181 [tempString appendString:@"Command-"];
1182 [tempStringPlus appendString:@"Command+"];
1185 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1186 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1188 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1192 case NSDeleteCharacter:
1193 case NSDeleteFunctionKey:
1194 case NSDeleteCharFunctionKey:
1195 case NSBackspaceCharacter:
1196 case NSUpArrowFunctionKey:
1197 case NSDownArrowFunctionKey:
1198 case NSRightArrowFunctionKey:
1199 case NSLeftArrowFunctionKey:
1200 case NSEnterCharacter:
1201 case NSCarriageReturnCharacter:
1205 val.i_int |= CocoaKeyToVLC( key );
1207 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1209 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1216 - (void)updateCurrentlyUsedHotkeys
1218 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1219 /* Get the main Module */
1220 module_t *p_main = module_get_main();
1223 module_config_t *p_config;
1225 p_config = module_config_get (p_main, &confsize);
1227 for (size_t i = 0; i < confsize; i++)
1229 module_config_t *p_item = p_config + i;
1231 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1232 && !strncmp( p_item->psz_name , "key-", 4 )
1233 && !EMPTY_STR( p_item->psz_text ) )
1235 if (p_item->value.psz)
1236 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1239 module_config_free (p_config);
1240 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1244 #pragma mark Interface updaters
1245 - (void)fullscreenChanged
1247 playlist_t * p_playlist = pl_Get( VLCIntf );
1248 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1250 if (OSX_LION && b_nativeFullscreenMode)
1252 [o_mainwindow toggleFullScreen: self];
1254 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1256 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1260 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1262 if( p_input != NULL )
1265 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1267 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1268 vlc_object_release( p_input );
1273 - (void)PlaylistItemChanged
1275 input_thread_t * p_input;
1277 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1278 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1280 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1281 [o_mainmenu setRateControlsEnabled: YES];
1282 vlc_object_release( p_input );
1285 [o_mainmenu setRateControlsEnabled: NO];
1287 [o_playlist updateRowSelection];
1288 [o_mainwindow updateWindow];
1289 [self updateMainMenu];
1292 - (void)updateMainMenu
1294 [o_mainmenu setupMenus];
1295 [o_mainmenu updatePlaybackRate];
1298 - (void)updateMainWindow
1300 [o_mainwindow updateWindow];
1303 - (void)showFullscreenController
1305 [o_mainwindow showFullscreenController];
1308 - (void)updateDelays
1310 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1315 [o_mainwindow updateName];
1318 - (void)updatePlaybackPosition
1320 [o_mainwindow updateTimeSlider];
1322 input_thread_t * p_input;
1323 p_input = pl_CurrentInput( p_intf );
1326 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1327 UpdateSystemActivity( UsrActivity );
1328 vlc_object_release( p_input );
1332 - (void)updateVolume
1334 [o_mainwindow updateVolumeSlider];
1337 - (void)playlistUpdated
1339 [self playbackStatusUpdated];
1340 [o_playlist playlistUpdated];
1341 [o_mainwindow updateWindow];
1342 [o_mainwindow updateName];
1345 - (void)updateRecordState: (BOOL)b_value
1347 [o_mainmenu updateRecordState:b_value];
1350 - (void)updateInfoandMetaPanel
1352 [o_playlist outlineViewSelectionDidChange:nil];
1355 - (void)playbackStatusUpdated
1357 input_thread_t * p_input;
1359 p_input = pl_CurrentInput( p_intf );
1362 int state = var_GetInteger( p_input, "state" );
1363 if( state == PLAYING_S )
1365 [[self mainMenu] setPause];
1366 [o_mainwindow setPause];
1371 [o_mainmenu setSubmenusEnabled: FALSE];
1372 [[self mainMenu] setPlay];
1373 [o_mainwindow setPlay];
1375 vlc_object_release( p_input );
1379 - (void)playbackModeUpdated
1381 vlc_value_t looping,repeating;
1382 playlist_t * p_playlist = pl_Get( VLCIntf );
1384 bool loop = var_GetBool( p_playlist, "loop" );
1385 bool repeat = var_GetBool( p_playlist, "repeat" );
1387 [o_mainwindow setRepeatOne];
1388 [o_mainmenu setRepeatOne];
1390 [o_mainwindow setRepeatAll];
1391 [o_mainmenu setRepeatAll];
1393 [o_mainwindow setRepeatOff];
1394 [o_mainmenu setRepeatOff];
1397 [o_mainwindow setShuffle];
1398 [o_mainmenu setShuffle];
1402 #pragma mark Other objects getters
1420 o_bookmarks = [[VLCBookmarks alloc] init];
1422 if( !nib_bookmarks_loaded )
1423 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1433 if (!nib_open_loaded)
1434 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1439 - (id)simplePreferences
1442 o_sprefs = [[VLCSimplePrefs alloc] init];
1444 if (!nib_prefs_loaded)
1445 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1453 o_prefs = [[VLCPrefs alloc] init];
1455 if( !nib_prefs_loaded )
1456 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1471 if(! nib_info_loaded )
1472 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1483 o_wizard = [[VLCWizard alloc] init];
1485 if( !nib_wizard_loaded )
1487 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1488 [o_wizard initStrings];
1493 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1495 id videoView = [o_mainwindow videoView];
1496 NSRect videoRect = [videoView frame];
1497 int i_x = (int)videoRect.origin.x;
1498 int i_y = (int)videoRect.origin.y;
1499 unsigned int i_width = (int)videoRect.size.width;
1500 unsigned int i_height = (int)videoRect.size.height;
1503 pi_width = (unsigned int*)i_width;
1504 pi_height = (unsigned int*)i_height;
1505 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1509 - (void)setNativeVideoSize:(NSSize)size
1511 [o_mainwindow setNativeVideoSize:size];
1516 if( o_embedded_list )
1517 return o_embedded_list;
1522 - (id)coreDialogProvider
1525 return o_coredialogs;
1530 - (id)eyeTVController
1538 - (id)appleRemoteController
1543 - (void)setActiveVideoPlayback:(BOOL)b_value
1545 b_active_videoplayback = b_value;
1546 [o_mainwindow setVideoplayEnabled];
1547 [o_mainwindow togglePlaylist:nil];
1550 - (BOOL)activeVideoPlayback
1552 return b_active_videoplayback;
1556 #pragma mark Crash Log
1557 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1559 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1560 NSURL *url = [NSURL URLWithString:urlStr];
1562 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1563 [req setHTTPMethod:@"POST"];
1566 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1568 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1569 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1570 email = [emails valueAtIndex:[emails indexForIdentifier:
1571 [emails primaryIdentifier]]];
1574 email = [NSString string];
1577 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1578 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1579 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1580 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1582 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1584 /* Released from delegate */
1585 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1588 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1590 [crashLogURLConnection release];
1591 crashLogURLConnection = nil;
1594 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1596 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1597 [crashLogURLConnection release];
1598 crashLogURLConnection = nil;
1601 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1603 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1604 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1606 NSString * latestLog = nil;
1607 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1608 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1609 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1610 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1612 while (fname = [direnum nextObject])
1614 [direnum skipDescendents];
1615 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1617 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1618 if( [compo count] < 3 ) continue;
1619 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1620 if( [compo count] < 4 ) continue;
1623 if( year < [[compo objectAtIndex:0] intValue] ||
1624 (year ==[[compo objectAtIndex:0] intValue] &&
1625 (month < [[compo objectAtIndex:1] intValue] ||
1626 (month ==[[compo objectAtIndex:1] intValue] &&
1627 (day < [[compo objectAtIndex:2] intValue] ||
1628 (day ==[[compo objectAtIndex:2] intValue] &&
1629 hours < [[compo objectAtIndex:3] intValue] ))))))
1631 year = [[compo objectAtIndex:0] intValue];
1632 month = [[compo objectAtIndex:1] intValue];
1633 day = [[compo objectAtIndex:2] intValue];
1634 hours = [[compo objectAtIndex:3] intValue];
1635 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1640 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1643 if( !previouslySeen )
1645 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1646 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1647 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1648 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1653 - (NSString *)latestCrashLogPath
1655 return [self latestCrashLogPathPreviouslySeen:YES];
1658 - (void)lookForCrashLog
1660 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1661 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1662 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1663 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1664 if( latestLog && !areCrashLogsTooOld )
1665 [NSApp runModalForWindow: o_crashrep_win];
1669 - (IBAction)crashReporterAction:(id)sender
1671 if( sender == o_crashrep_send_btn )
1672 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1675 [o_crashrep_win orderOut: sender];
1678 - (IBAction)openCrashLog:(id)sender
1680 NSString * latestLog = [self latestCrashLogPath];
1683 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1687 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.") );
1692 #pragma mark Remove old prefs
1694 - (void)_removeOldPreferences
1696 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1697 static const int kCurrentPreferencesVersion = 1;
1698 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1699 if( version >= kCurrentPreferencesVersion ) return;
1701 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1702 NSUserDomainMask, YES);
1703 if( !libraries || [libraries count] == 0) return;
1704 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1706 /* File not found, don't attempt anything */
1707 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1708 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1710 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1714 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1715 _NS("We just found an older version of VLC's preferences files."),
1716 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1717 if( res != NSOKButton )
1719 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1723 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1725 /* Move the file to trash so that user can find them later */
1726 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1728 /* really reset the defaults from now on */
1729 [NSUserDefaults resetStandardUserDefaults];
1731 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1732 [[NSUserDefaults standardUserDefaults] synchronize];
1735 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1737 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1743 execl(path, path, NULL);
1747 #pragma mark Errors, warnings and messages
1748 - (IBAction)showMessagesPanel:(id)sender
1750 [o_msgs_panel makeKeyAndOrderFront: sender];
1753 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1755 if( [o_notification object] == o_msgs_panel )
1756 [self updateMessageDisplay];
1759 - (void)updateMessageDisplay
1761 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1764 NSEnumerator * o_enum;
1766 [o_messages setString: @""];
1770 o_enum = [o_msg_arr objectEnumerator];
1772 while( ( o_msg = [o_enum nextObject] ) != nil )
1774 [o_messages insertText: o_msg];
1777 b_msg_arr_changed = NO;
1778 [o_msg_lock unlock];
1782 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1784 NSColor *o_white = [NSColor whiteColor];
1785 NSColor *o_red = [NSColor redColor];
1786 NSColor *o_yellow = [NSColor yellowColor];
1787 NSColor *o_gray = [NSColor grayColor];
1789 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1790 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1792 NSDictionary *o_attr;
1793 NSAttributedString *o_msg_color;
1797 if( [o_msg_arr count] + 2 > 600 )
1799 [o_msg_arr removeObjectAtIndex: 0];
1800 [o_msg_arr removeObjectAtIndex: 1];
1803 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1804 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1805 [o_msg_arr addObject: [o_msg_color autorelease]];
1807 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1808 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1809 [o_msg_arr addObject: [o_msg_color autorelease]];
1811 b_msg_arr_changed = YES;
1812 [o_msg_lock unlock];
1814 [self updateMessageDisplay];
1817 - (IBAction)saveDebugLog:(id)sender
1819 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1821 [saveFolderPanel setCanSelectHiddenExtension: NO];
1822 [saveFolderPanel setCanCreateDirectories: YES];
1823 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1824 [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];
1827 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1830 if( returnCode == NSOKButton )
1832 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1834 msg_Warn( p_intf, "Error while saving the debug log" );
1839 #pragma mark Playlist toggling
1841 - (void)updateTogglePlaylistState
1843 [[self playlist] outlineViewSelectionDidChange: NULL];
1850 @implementation VLCMain (Internal)
1852 - (void)handlePortMessage:(NSPortMessage *)o_msg
1857 NSInvocation * o_inv;
1858 NSConditionLock * o_lock;
1860 o_data = [[o_msg components] lastObject];
1861 o_inv = *((NSInvocation **)[o_data bytes]);
1862 [o_inv getArgument: &o_value atIndex: 2];
1863 val = (id **)[o_value pointerValue];
1864 [o_inv setArgument: val[1] atIndex: 2];
1869 [o_lock unlockWithCondition: 1];
1871 - (void)resetMediaKeyJump
1873 b_mediakeyJustJumped = NO;
1875 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1877 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1878 if (b_mediaKeySupport) {
1879 if (!o_mediaKeyController)
1880 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1881 [o_mediaKeyController startWatchingMediaKeys];
1883 else if (!b_mediaKeySupport && o_mediaKeyController)
1885 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1886 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1887 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1888 if( returnedValue == NSOKButton )
1891 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1893 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1899 execl(path, path, NULL);
1906 /*****************************************************************************
1907 * VLCApplication interface
1908 *****************************************************************************/
1910 @implementation VLCApplication
1911 // when user selects the quit menu from dock it sends a terminate:
1912 // but we need to send a stop: to properly exits libvlc.
1913 // However, we are not able to change the action-method sent by this standard menu item.
1914 // thus we override terminat: to send a stop:
1915 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1916 - (void)terminate:(id)sender
1918 [self activateIgnoringOtherApps:YES];