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() */
44 #import "MainWindow.h"
49 #import "playlistinfo.h"
54 #import "coredialogs.h"
55 #import "embeddedwindow.h"
56 #import "AppleRemote.h"
58 #import "simple_prefs.h"
59 #import "CoreInteraction.h"
61 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
62 #import <Sparkle/Sparkle.h> /* we're the update delegate */
64 /*****************************************************************************
66 *****************************************************************************/
67 static void Run ( intf_thread_t *p_intf );
69 static void * ManageThread( void *user_data );
71 static void updateProgressPanel (void *, const char *, float);
72 static bool checkProgressPanel (void *);
73 static void destroyProgressPanel (void *);
75 static void MsgCallback( msg_cb_data_t *, const msg_item_t * );
78 #pragma mark VLC Interface Object Callbacks
80 /*****************************************************************************
81 * OpenIntf: initialize interface
82 *****************************************************************************/
83 int OpenIntf ( vlc_object_t *p_this )
85 intf_thread_t *p_intf = (intf_thread_t*) p_this;
87 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
88 if( p_intf->p_sys == NULL )
91 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
93 /* subscribe to LibVLCCore's messages */
94 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
96 p_intf->b_should_run_on_first_thread = true;
101 /*****************************************************************************
102 * CloseIntf: destroy interface
103 *****************************************************************************/
104 void CloseIntf ( vlc_object_t *p_this )
106 intf_thread_t *p_intf = (intf_thread_t*) p_this;
108 free( p_intf->p_sys );
111 static int WindowControl( vout_window_t *, int i_query, va_list );
113 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
115 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
116 intf_thread_t *p_intf = VLCIntf;
118 msg_Err( p_wnd, "Mac OS X interface not found" );
122 msg_Dbg( p_wnd, "looking for video view" );
125 unsigned i_width = cfg->width;
126 unsigned i_height = cfg->height;
127 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
129 if ( !p_wnd->handle.nsobject ) {
130 msg_Err( p_wnd, "got no video view from the interface" );
135 [[VLCMainWindow sharedInstance] setVideoplayEnabled:YES];
136 [[VLCMainWindow sharedInstance] togglePlaylist:nil];
137 p_wnd->control = WindowControl;
138 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
143 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
146 if( i_query == VOUT_WINDOW_SET_STATE )
147 NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
148 else if( i_query == VOUT_WINDOW_SET_SIZE )
149 NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
150 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
151 NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
153 NSLog( @"WindowControl: unknown query" );
157 void WindowClose( vout_window_t *p_wnd )
159 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
160 [[VLCMainWindow sharedInstance] setVideoplayEnabled:NO];
161 NSLog( @"Window Close" );
162 // tell the interface to get rid of the video, TODO
166 /*****************************************************************************
168 *****************************************************************************/
169 static NSLock * o_appLock = nil; // controls access to f_appExit
170 static int f_appExit = 0; // set to 1 when application termination signaled
172 static void Run( intf_thread_t *p_intf )
176 /* Make sure the "force quit" menu item does quit instantly.
177 * VLC overrides SIGTERM which is sent by the "force quit"
178 * menu item to make sure deamon mode quits gracefully, so
179 * we un-override SIGTERM here. */
181 sigaddset( &set, SIGTERM );
182 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
184 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
186 o_appLock = [[NSLock alloc] init];
188 [VLCApplication sharedApplication];
190 [[VLCMain sharedInstance] setIntf: p_intf];
191 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
194 [[VLCMain sharedInstance] applicationWillTerminate:nil];
200 #pragma mark Variables Callback
202 /*****************************************************************************
203 * MsgCallback: Callback triggered by the core once a new debug message is
204 * ready to be displayed. We store everything in a NSArray in our Cocoa part
206 *****************************************************************************/
207 static void MsgCallback( msg_cb_data_t *data, const msg_item_t *item )
209 int canc = vlc_savecancel();
211 /* this may happen from time to time, let's bail out as info would be useless anyway */
212 if( !item->psz_module || !item->psz_msg )
215 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
216 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item];
219 vlc_restorecancel( canc );
222 /*****************************************************************************
223 * playlistChanged: Callback triggered by the intf-change playlist
224 * variable, to let the intf update the playlist.
225 *****************************************************************************/
226 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
227 vlc_value_t old_val, vlc_value_t new_val, void *param )
229 intf_thread_t * p_intf = VLCIntf;
230 if( p_intf && p_intf->p_sys )
232 NSLog( @"event from %s", psz_variable );
233 p_intf->p_sys->b_intf_update = true;
234 p_intf->p_sys->b_playlist_update = true;
235 p_intf->p_sys->b_playmode_update = true;
236 p_intf->p_sys->b_current_title_update = true;
241 /*****************************************************************************
242 * ShowController: Callback triggered by the show-intf playlist variable
243 * through the ShowIntf-control-intf, to let us show the controller-win;
244 * usually when in fullscreen-mode
245 *****************************************************************************/
246 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
247 vlc_value_t old_val, vlc_value_t new_val, void *param )
249 intf_thread_t * p_intf = VLCIntf;
250 if( p_intf && p_intf->p_sys )
252 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
253 if( [[[VLCCoreInteraction sharedInstance] voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
254 [[[[VLCMain sharedInstance] controls] fspanel] fadeIn];
256 [[VLCMainWindow sharedInstance] makeKeyAndOrderFront: nil];
262 /*****************************************************************************
263 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
264 * variable, to let the intf update the controller.
265 *****************************************************************************/
266 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
267 vlc_value_t old_val, vlc_value_t new_val, void *param )
269 intf_thread_t * p_intf = VLCIntf;
270 if( p_intf && p_intf->p_sys )
271 NSLog( @"we should update fullscreen state" ); //FIXME
275 /*****************************************************************************
276 * DialogCallback: Callback triggered by the "dialog-*" variables
277 * to let the intf display error and interaction dialogs
278 *****************************************************************************/
279 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
281 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
282 VLCMain *interface = (VLCMain *)data;
284 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
286 /* the progress panel needs to update itself and therefore wants special treatment within this context */
287 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
289 p_dialog->pf_update = updateProgressPanel;
290 p_dialog->pf_check = checkProgressPanel;
291 p_dialog->pf_destroy = destroyProgressPanel;
292 p_dialog->p_sys = VLCIntf->p_libvlc;
295 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
296 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
302 void updateProgressPanel (void *priv, const char *text, float value)
304 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
308 o_txt = [NSString stringWithUTF8String: text];
312 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
317 void destroyProgressPanel (void *priv)
319 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
320 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
324 bool checkProgressPanel (void *priv)
326 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
327 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
334 input_thread_t *getInput(void)
336 intf_thread_t *p_intf = VLCIntf;
339 return pl_CurrentInput(p_intf);
342 vout_thread_t *getVout(void)
344 input_thread_t *p_input = getInput();
347 vout_thread_t *p_vout = input_GetVout(p_input);
348 vlc_object_release(p_input);
352 aout_instance_t *getAout(void)
354 input_thread_t *p_input = getInput();
357 aout_instance_t *p_aout = input_GetAout(p_input);
358 vlc_object_release(p_input);
365 @interface VLCMain ()
366 - (void)_removeOldPreferences;
369 /*****************************************************************************
370 * VLCMain implementation
371 *****************************************************************************/
372 @implementation VLCMain
375 #pragma mark Initialization
377 static VLCMain *_o_sharedMainInstance = nil;
379 + (VLCMain *)sharedInstance
381 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
386 if( _o_sharedMainInstance)
389 return _o_sharedMainInstance;
392 _o_sharedMainInstance = [super init];
396 o_msg_lock = [[NSLock alloc] init];
397 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
398 /* subscribe to LibVLC's debug messages as early as possible (for us) */
399 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
401 o_open = [[VLCOpen alloc] init];
402 //o_embedded_list = [[VLCEmbeddedList alloc] init];
403 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
404 o_info = [[VLCInfo alloc] init];
405 o_mainmenu = [[VLCMainMenu alloc] init];
406 o_coreinteraction = [[VLCCoreInteraction alloc] init];
407 o_eyetv = [[VLCEyeTVController alloc] init];
409 /* announce our launch to a potential eyetv plugin */
410 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
411 object: @"VLCEyeTVSupport"
413 deliverImmediately: YES];
414 return _o_sharedMainInstance;
417 - (void)setIntf: (intf_thread_t *)p_mainintf {
421 - (intf_thread_t *)intf {
427 playlist_t *p_playlist;
429 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
431 [o_msgs_panel setExcludedFromWindowsMenu: YES];
432 [o_msgs_panel setDelegate: self];
434 p_playlist = pl_Get( p_intf );
438 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
439 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
441 /* load our Core Dialogs nib */
442 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
444 /* subscribe to various interactive dialogues */
445 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
446 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
447 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
448 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
449 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
450 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
451 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
452 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
453 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
454 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
455 dialog_Register( p_intf );
457 /* update the playmode stuff */
458 p_intf->p_sys->b_playmode_update = true;
460 /* init Apple Remote support */
461 o_remote = [[AppleRemote alloc] init];
462 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
463 [o_remote setDelegate: _o_sharedMainInstance];
465 /* yeah, we are done */
466 nib_main_loaded = TRUE;
469 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
471 if( !p_intf ) return;
473 /* FIXME: don't poll */
474 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
475 target: self selector: @selector(manageIntf:)
476 userInfo: nil repeats: FALSE] retain];
478 /* Note: we use the pthread API to support pre-10.5 */
479 pthread_create( &manage_thread, NULL, ManageThread, self );
482 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
484 if( !p_intf ) return;
486 /* init media key support */
487 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
488 if( b_mediaKeySupport )
490 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
491 [o_mediaKeyController startWatchingMediaKeys];
492 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
493 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
496 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
498 [self _removeOldPreferences];
500 [o_mainwindow makeKeyAndOrderFront: self];
502 /* Handle sleep notification */
503 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
504 name:NSWorkspaceWillSleepNotification object:nil];
506 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
511 if( !p_intf ) return;
514 [o_msgs_panel setTitle: _NS("Messages")];
515 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
516 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
518 /* crash reporter panel */
519 [o_crashrep_send_btn setTitle: _NS("Send")];
520 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
521 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
522 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
523 [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, ...")];
524 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
525 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
529 #pragma mark Termination
531 - (void)applicationWillTerminate:(NSNotification *)notification
533 playlist_t * p_playlist;
534 vout_thread_t * p_vout;
535 int returnedValue = 0;
540 // don't allow a double termination call. If the user has
541 // already invoked the quit then simply return this time.
542 int isTerminating = false;
545 isTerminating = (f_appExit++ > 0 ? 1 : 0);
551 msg_Dbg( p_intf, "Terminating" );
553 pthread_join( manage_thread, NULL );
555 /* Make sure the intf object is getting killed */
556 vlc_object_kill( p_intf );
558 /* Make sure the interfaceTimer is destroyed */
559 [interfaceTimer invalidate];
560 [interfaceTimer release];
561 interfaceTimer = nil;
563 /* unsubscribe from the interactive dialogues */
564 dialog_Unregister( p_intf );
565 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
566 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
567 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
568 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
569 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
571 /* remove global observer watching for vout device changes correctly */
572 [[NSNotificationCenter defaultCenter] removeObserver: self];
574 /* release some other objects here, because it isn't sure whether dealloc
575 * will be called later on */
593 [crashLogURLConnection cancel];
594 [crashLogURLConnection release];
596 [o_embedded_list release];
597 [o_coredialogs release];
600 /* unsubscribe from libvlc's debug messages */
601 msg_Unsubscribe( p_intf->p_sys->p_sub );
603 [o_msg_arr removeAllObjects];
606 [o_msg_lock release];
608 /* write cached user defaults to disk */
609 [[NSUserDefaults standardUserDefaults] synchronize];
611 /* Make sure the Menu doesn't have any references to vlc objects anymore */
612 //FIXME: this should be moved to VLCMainMenu
613 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
614 [o_mainmenu release];
616 /* Kill the playlist, so that it doesn't accept new request
617 * such as the play request from vlc.c (we are a blocking interface). */
618 p_playlist = pl_Get( p_intf );
619 vlc_object_kill( p_playlist );
620 libvlc_Quit( p_intf->p_libvlc );
626 #pragma mark Sparkle delegate
627 /* received directly before the update gets installed, so let's shut down a bit */
628 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
630 [o_remote stopListening: self];
631 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
633 /* Close the window directly, because we do know that there
634 * won't be anymore video. It's currently waiting a bit. */
635 [[[o_coreinteraction voutView] window] orderOut:self];
639 #pragma mark Media Key support
641 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
643 if( b_mediaKeySupport )
645 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
647 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
648 int keyFlags = ([event data1] & 0x0000FFFF);
649 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
650 int keyRepeat = (keyFlags & 0x1);
652 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
653 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
655 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
657 if( keyState == 0 && keyRepeat == 0 )
658 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
659 else if( keyRepeat == 1 )
661 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
662 b_mediakeyJustJumped = YES;
663 [self performSelector:@selector(resetMediaKeyJump)
669 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
671 if( keyState == 0 && keyRepeat == 0 )
672 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
673 else if( keyRepeat == 1 )
675 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
676 b_mediakeyJustJumped = YES;
677 [self performSelector:@selector(resetMediaKeyJump)
686 #pragma mark Other notification
688 /* Listen to the remote in exclusive mode, only when VLC is the active
690 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
692 if( !p_intf ) return;
693 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
694 [o_remote startListening: self];
696 - (void)applicationDidResignActive:(NSNotification *)aNotification
698 if( !p_intf ) return;
699 [o_remote stopListening: self];
702 /* Triggered when the computer goes to sleep */
703 - (void)computerWillSleep: (NSNotification *)notification
706 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
708 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
713 #pragma mark File opening
715 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
717 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
718 char *psz_uri = make_URI([o_filename UTF8String], "file" );
722 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
727 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
729 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
734 /* When user click in the Dock icon our double click in the finder */
735 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
737 if(!hasVisibleWindows)
738 [o_mainwindow makeKeyAndOrderFront:self];
744 #pragma mark Apple Remote Control
746 /* Helper method for the remote control interface in order to trigger forward/backward and volume
747 increase/decrease as long as the user holds the left/right, plus/minus button */
748 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
750 if(b_remote_button_hold)
752 switch([buttonIdentifierNumber intValue])
754 case kRemoteButtonRight_Hold:
755 [o_controls forward: self];
757 case kRemoteButtonLeft_Hold:
758 [o_controls backward: self];
760 case kRemoteButtonVolume_Plus_Hold:
761 [o_controls volumeUp: self];
763 case kRemoteButtonVolume_Minus_Hold:
764 [o_controls volumeDown: self];
767 if(b_remote_button_hold)
770 [self performSelector:@selector(executeHoldActionForRemoteButton:)
771 withObject:buttonIdentifierNumber
777 /* Apple Remote callback */
778 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
779 pressedDown: (BOOL) pressedDown
780 clickCount: (unsigned int) count
782 switch( buttonIdentifier )
784 case k2009RemoteButtonFullscreen:
785 [o_controls toogleFullscreen:self];
787 case k2009RemoteButtonPlay:
788 [o_controls play:self];
790 case kRemoteButtonPlay:
792 [o_controls toogleFullscreen:self];
794 [o_controls play: self];
797 case kRemoteButtonVolume_Plus:
798 [o_controls volumeUp: self];
800 case kRemoteButtonVolume_Minus:
801 [o_controls volumeDown: self];
803 case kRemoteButtonRight:
804 [o_controls next: self];
806 case kRemoteButtonLeft:
807 [o_controls prev: self];
809 case kRemoteButtonRight_Hold:
810 case kRemoteButtonLeft_Hold:
811 case kRemoteButtonVolume_Plus_Hold:
812 case kRemoteButtonVolume_Minus_Hold:
813 /* simulate an event as long as the user holds the button */
814 b_remote_button_hold = pressedDown;
817 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
818 [self performSelector:@selector(executeHoldActionForRemoteButton:)
819 withObject:buttonIdentifierNumber];
822 case kRemoteButtonMenu:
823 [o_controls showPosition: self];
826 /* Add here whatever you want other buttons to do */
832 #pragma mark String utility
833 // FIXME: this has nothing to do here
835 - (NSString *)localizedString:(const char *)psz
837 NSString * o_str = nil;
841 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
845 msg_Err( VLCIntf, "could not translate: %s", psz );
851 msg_Warn( VLCIntf, "can't translate empty strings" );
860 - (char *)delocalizeString:(NSString *)id
862 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
863 allowLossyConversion: NO];
868 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
869 allowLossyConversion: YES];
870 psz_string = malloc( [o_data length] + 1 );
871 [o_data getBytes: psz_string];
872 psz_string[ [o_data length] ] = '\0';
873 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
878 psz_string = malloc( [o_data length] + 1 );
879 [o_data getBytes: psz_string];
880 psz_string[ [o_data length] ] = '\0';
886 /* i_width is in pixels */
887 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
889 NSMutableString *o_wrapped;
890 NSString *o_out_string;
891 NSRange glyphRange, effectiveRange, charRange;
892 NSRect lineFragmentRect;
893 unsigned glyphIndex, breaksInserted = 0;
895 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
896 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
897 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
898 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
899 NSTextContainer *o_container = [[NSTextContainer alloc]
900 initWithContainerSize: NSMakeSize(i_width, 2000)];
902 [o_layout_manager addTextContainer: o_container];
903 [o_container release];
904 [o_storage addLayoutManager: o_layout_manager];
905 [o_layout_manager release];
907 o_wrapped = [o_in_string mutableCopy];
908 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
910 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
911 glyphIndex += effectiveRange.length) {
912 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
913 effectiveRange: &effectiveRange];
914 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
915 actualGlyphRange: &effectiveRange];
916 if([o_wrapped lineRangeForRange:
917 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
918 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
922 o_out_string = [NSString stringWithString: o_wrapped];
931 #pragma mark Key Shortcuts
936 unsigned int i_vlckey;
937 } nskeys_to_vlckeys[] =
939 { NSUpArrowFunctionKey, KEY_UP },
940 { NSDownArrowFunctionKey, KEY_DOWN },
941 { NSLeftArrowFunctionKey, KEY_LEFT },
942 { NSRightArrowFunctionKey, KEY_RIGHT },
943 { NSF1FunctionKey, KEY_F1 },
944 { NSF2FunctionKey, KEY_F2 },
945 { NSF3FunctionKey, KEY_F3 },
946 { NSF4FunctionKey, KEY_F4 },
947 { NSF5FunctionKey, KEY_F5 },
948 { NSF6FunctionKey, KEY_F6 },
949 { NSF7FunctionKey, KEY_F7 },
950 { NSF8FunctionKey, KEY_F8 },
951 { NSF9FunctionKey, KEY_F9 },
952 { NSF10FunctionKey, KEY_F10 },
953 { NSF11FunctionKey, KEY_F11 },
954 { NSF12FunctionKey, KEY_F12 },
955 { NSInsertFunctionKey, KEY_INSERT },
956 { NSHomeFunctionKey, KEY_HOME },
957 { NSEndFunctionKey, KEY_END },
958 { NSPageUpFunctionKey, KEY_PAGEUP },
959 { NSPageDownFunctionKey, KEY_PAGEDOWN },
960 { NSMenuFunctionKey, KEY_MENU },
961 { NSTabCharacter, KEY_TAB },
962 { NSCarriageReturnCharacter, KEY_ENTER },
963 { NSEnterCharacter, KEY_ENTER },
964 { NSBackspaceCharacter, KEY_BACKSPACE },
968 unsigned int CocoaKeyToVLC( unichar i_key )
972 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
974 if( nskeys_to_vlckeys[i].i_nskey == i_key )
976 return nskeys_to_vlckeys[i].i_vlckey;
979 return (unsigned int)i_key;
982 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
984 unsigned int new = 0;
986 if([theString rangeOfString:@"Command"].location != NSNotFound)
987 new |= NSCommandKeyMask;
988 if([theString rangeOfString:@"Alt"].location != NSNotFound)
989 new |= NSAlternateKeyMask;
990 if([theString rangeOfString:@"Shift"].location != NSNotFound)
991 new |= NSShiftKeyMask;
992 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
993 new |= NSControlKeyMask;
997 - (NSString *)VLCKeyToString:(NSString *)theString
999 if (![theString isEqualToString:@""]) {
1000 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1001 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1002 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1003 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1004 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1005 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1011 /*****************************************************************************
1012 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1013 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1014 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1015 *****************************************************************************/
1016 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1020 unsigned int i_pressed_modifiers = 0;
1021 const struct hotkey *p_hotkeys;
1023 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1024 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1027 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1029 i_pressed_modifiers = [o_event modifierFlags];
1031 if( i_pressed_modifiers & NSShiftKeyMask ) {
1032 val.i_int |= KEY_MODIFIER_SHIFT;
1033 [tempString appendString:@"Shift-"];
1034 [tempStringPlus appendString:@"Shift+"];
1036 if( i_pressed_modifiers & NSControlKeyMask ) {
1037 val.i_int |= KEY_MODIFIER_CTRL;
1038 [tempString appendString:@"Ctrl-"];
1039 [tempStringPlus appendString:@"Ctrl+"];
1041 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1042 val.i_int |= KEY_MODIFIER_ALT;
1043 [tempString appendString:@"Alt-"];
1044 [tempStringPlus appendString:@"Alt+"];
1046 if( i_pressed_modifiers & NSCommandKeyMask ) {
1047 val.i_int |= KEY_MODIFIER_COMMAND;
1048 [tempString appendString:@"Command-"];
1049 [tempStringPlus appendString:@"Command+"];
1052 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1053 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1055 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1059 case NSDeleteCharacter:
1060 case NSDeleteFunctionKey:
1061 case NSDeleteCharFunctionKey:
1062 case NSBackspaceCharacter:
1063 case NSUpArrowFunctionKey:
1064 case NSDownArrowFunctionKey:
1065 case NSRightArrowFunctionKey:
1066 case NSLeftArrowFunctionKey:
1067 case NSEnterCharacter:
1068 case NSCarriageReturnCharacter:
1072 val.i_int |= CocoaKeyToVLC( key );
1074 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1076 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1083 - (void)updateCurrentlyUsedHotkeys
1085 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1086 /* Get the main Module */
1087 module_t *p_main = module_get_main();
1090 module_config_t *p_config;
1092 p_config = module_config_get (p_main, &confsize);
1094 for (size_t i = 0; i < confsize; i++)
1096 module_config_t *p_item = p_config + i;
1098 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1099 && !strncmp( p_item->psz_name , "key-", 4 )
1100 && !EMPTY_STR( p_item->psz_text ) )
1102 if (p_item->value.psz)
1103 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1106 module_config_free (p_config);
1107 module_release (p_main);
1108 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1113 #pragma mark Other objects getters
1131 o_bookmarks = [[VLCBookmarks alloc] init];
1133 if( !nib_bookmarks_loaded )
1134 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1144 if (!nib_open_loaded)
1145 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1150 - (id)simplePreferences
1153 o_sprefs = [[VLCSimplePrefs alloc] init];
1155 if (!nib_prefs_loaded)
1156 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1164 o_prefs = [[VLCPrefs alloc] init];
1166 if( !nib_prefs_loaded )
1167 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1182 if(! nib_info_loaded )
1183 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1194 o_wizard = [[VLCWizard alloc] init];
1196 if( !nib_wizard_loaded )
1198 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1199 [o_wizard initStrings];
1204 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1206 id videoView = [o_mainwindow videoView];
1207 NSRect videoRect = [videoView frame];
1208 int i_x = (int)videoRect.origin.x;
1209 int i_y = (int)videoRect.origin.y;
1210 unsigned int i_width = (int)videoRect.size.width;
1211 unsigned int i_height = (int)videoRect.size.height;
1214 pi_width = (unsigned int*)i_width;
1215 pi_height = (unsigned int*)i_height;
1216 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1222 if( o_embedded_list )
1223 return o_embedded_list;
1228 - (id)coreDialogProvider
1231 return o_coredialogs;
1236 - (id)eyeTVController
1244 - (id)appleRemoteController
1250 #pragma mark Polling
1252 /*****************************************************************************
1253 * ManageThread: An ugly thread that polls
1254 *****************************************************************************/
1255 static void * ManageThread( void *user_data )
1257 id self = user_data;
1264 struct manage_cleanup_stack {
1265 intf_thread_t * p_intf;
1266 input_thread_t ** p_input;
1267 playlist_t * p_playlist;
1271 static void manage_cleanup( void * args )
1273 struct manage_cleanup_stack * manage_cleanup_stack = args;
1274 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1275 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1276 id self = manage_cleanup_stack->self;
1277 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1279 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1280 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1281 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1282 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1283 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1285 if( p_input ) vlc_object_release( p_input );
1290 playlist_t * p_playlist;
1291 input_thread_t * p_input = NULL;
1293 /* new thread requires a new pool */
1295 p_playlist = pl_Get( p_intf );
1297 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1298 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1299 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1300 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1301 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1303 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1304 pthread_cleanup_push(manage_cleanup, &stack);
1306 bool exitLoop = false;
1309 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1313 p_input = playlist_CurrentInput( p_playlist );
1315 /* Refresh the interface */
1318 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1319 p_intf->p_sys->b_input_update = true;
1322 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1325 p_intf->p_sys->b_intf_update = true;
1326 p_intf->p_sys->i_play_status = END_S;
1327 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1328 vlc_object_release( p_input );
1331 else if( cachedInputState != input_GetState( p_input ) )
1333 cachedInputState = input_GetState( p_input );
1334 p_intf->p_sys->b_intf_update = true;
1337 /* Manage volume status */
1338 [o_mainwindow updateVolumeSlider];
1340 msleep( INTF_IDLE_SLEEP );
1345 exitLoop = (f_appExit != 0 ? true : false);
1349 pthread_cleanup_pop(1);
1352 - (void)manageIntf:(NSTimer *)o_timer
1355 playlist_t * p_playlist;
1356 input_thread_t * p_input;
1358 if( p_intf->p_sys->b_input_update )
1360 /* Called when new input is opened */
1361 p_intf->p_sys->b_current_title_update = true;
1362 p_intf->p_sys->b_intf_update = true;
1363 p_intf->p_sys->b_input_update = false;
1364 [o_mainmenu setupMenus]; /* Make sure input menu is up to date */
1366 if( p_intf->p_sys->b_intf_update )
1368 [o_mainwindow updateWindow];
1369 p_intf->p_sys->b_current_title_update = true;
1370 p_intf->p_sys->b_intf_update = false;
1373 if( p_intf->p_sys->b_playmode_update )
1375 [o_playlist playModeUpdated];
1376 p_intf->p_sys->b_playmode_update = false;
1378 if( p_intf->p_sys->b_playlist_update )
1380 [o_playlist playlistUpdated];
1381 p_intf->p_sys->b_playlist_update = false;
1384 p_input = pl_CurrentInput( p_intf );
1385 if( p_input && vlc_object_alive (p_input) )
1389 if( p_intf->p_sys->b_current_title_update )
1392 input_item_t * p_item = input_GetItem( p_input );
1393 char * name = input_item_GetNowPlaying( p_item );
1396 name = input_item_GetName( p_item );
1398 aString = [NSString stringWithUTF8String:name];
1402 [o_mainwindow setTitle: aString];
1403 [[[self controls] fspanel] setStreamTitle: aString];
1405 [[o_coreinteraction voutView] updateTitle];
1407 [o_playlist updateRowSelection];
1409 p_intf->p_sys->b_current_title_update = FALSE;
1412 [o_mainwindow updateTimeSlider];
1414 /* Manage Playing status */
1415 var_Get( p_input, "state", &val );
1416 if( p_intf->p_sys->i_play_status != val.i_int )
1418 p_intf->p_sys->i_play_status = val.i_int;
1419 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1421 vlc_object_release( p_input );
1425 vlc_object_release( p_input );
1429 p_intf->p_sys->i_play_status = END_S;
1430 if (p_intf->p_sys->i_old_play_status != p_intf->p_sys->i_play_status)
1432 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1433 [o_mainmenu setSubmenusEnabled: FALSE];
1434 p_intf->p_sys->i_old_play_status = p_intf->p_sys->i_play_status;
1438 [self updateMessageDisplay];
1440 [interfaceTimer autorelease];
1442 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1443 target: self selector: @selector(manageIntf:)
1444 userInfo: nil repeats: FALSE] retain];
1448 #pragma mark Interface update
1450 - (void)playStatusUpdated:(int)i_status
1452 if( i_status == PLAYING_S )
1454 [[[self controls] fspanel] setPause];
1455 [[self mainMenu] setPause];
1456 [o_mainwindow setPause];
1460 [[[self controls] fspanel] setPlay];
1461 [[self mainMenu] setPlay];
1462 [o_mainwindow setPlay];
1466 - (IBAction)showController:(id)sender
1468 //FIXME: why is this function here?!
1469 [o_mainwindow makeKeyAndOrderFront:sender];
1473 #pragma mark Crash Log
1474 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1476 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1477 NSURL *url = [NSURL URLWithString:urlStr];
1479 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1480 [req setHTTPMethod:@"POST"];
1483 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1485 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1486 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1487 email = [emails valueAtIndex:[emails indexForIdentifier:
1488 [emails primaryIdentifier]]];
1491 email = [NSString string];
1494 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1495 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1496 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1497 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1499 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1501 /* Released from delegate */
1502 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1505 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1507 [crashLogURLConnection release];
1508 crashLogURLConnection = nil;
1511 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1513 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1514 [crashLogURLConnection release];
1515 crashLogURLConnection = nil;
1518 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1520 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1521 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1523 NSString * latestLog = nil;
1524 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1525 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1526 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1527 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1529 while (fname = [direnum nextObject])
1531 [direnum skipDescendents];
1532 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1534 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1535 if( [compo count] < 3 ) continue;
1536 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1537 if( [compo count] < 4 ) continue;
1540 if( year < [[compo objectAtIndex:0] intValue] ||
1541 (year ==[[compo objectAtIndex:0] intValue] &&
1542 (month < [[compo objectAtIndex:1] intValue] ||
1543 (month ==[[compo objectAtIndex:1] intValue] &&
1544 (day < [[compo objectAtIndex:2] intValue] ||
1545 (day ==[[compo objectAtIndex:2] intValue] &&
1546 hours < [[compo objectAtIndex:3] intValue] ))))))
1548 year = [[compo objectAtIndex:0] intValue];
1549 month = [[compo objectAtIndex:1] intValue];
1550 day = [[compo objectAtIndex:2] intValue];
1551 hours = [[compo objectAtIndex:3] intValue];
1552 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1557 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1560 if( !previouslySeen )
1562 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1563 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1564 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1565 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1570 - (NSString *)latestCrashLogPath
1572 return [self latestCrashLogPathPreviouslySeen:YES];
1575 - (void)lookForCrashLog
1577 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1578 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1579 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1580 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1581 if( latestLog && !areCrashLogsTooOld )
1582 [NSApp runModalForWindow: o_crashrep_win];
1586 - (IBAction)crashReporterAction:(id)sender
1588 if( sender == o_crashrep_send_btn )
1589 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1592 [o_crashrep_win orderOut: sender];
1595 - (IBAction)openCrashLog:(id)sender
1597 NSString * latestLog = [self latestCrashLogPath];
1600 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1604 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.") );
1609 #pragma mark Remove old prefs
1611 - (void)_removeOldPreferences
1613 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1614 static const int kCurrentPreferencesVersion = 1;
1615 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1616 if( version >= kCurrentPreferencesVersion ) return;
1618 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1619 NSUserDomainMask, YES);
1620 if( !libraries || [libraries count] == 0) return;
1621 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1623 /* File not found, don't attempt anything */
1624 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1625 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1627 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1631 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1632 _NS("We just found an older version of VLC's preferences files."),
1633 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1634 if( res != NSOKButton )
1636 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1640 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1642 /* Move the file to trash so that user can find them later */
1643 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1645 /* really reset the defaults from now on */
1646 [NSUserDefaults resetStandardUserDefaults];
1648 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1649 [[NSUserDefaults standardUserDefaults] synchronize];
1652 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1654 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1660 execl(path, path, NULL);
1664 #pragma mark Errors, warnings and messages
1665 - (IBAction)showMessagesPanel:(id)sender
1667 [o_msgs_panel makeKeyAndOrderFront: sender];
1670 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1672 if( [o_notification object] == o_msgs_panel )
1673 [self updateMessageDisplay];
1676 - (void)updateMessageDisplay
1678 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1681 NSEnumerator * o_enum;
1683 [o_messages setString: @""];
1687 o_enum = [o_msg_arr objectEnumerator];
1689 while( ( o_msg = [o_enum nextObject] ) != nil )
1691 [o_messages insertText: o_msg];
1694 b_msg_arr_changed = NO;
1695 [o_msg_lock unlock];
1699 - (void)processReceivedlibvlcMessage:(const msg_item_t *)item
1701 NSColor *o_white = [NSColor whiteColor];
1702 NSColor *o_red = [NSColor redColor];
1703 NSColor *o_yellow = [NSColor yellowColor];
1704 NSColor *o_gray = [NSColor grayColor];
1706 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1707 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1709 NSDictionary *o_attr;
1710 NSAttributedString *o_msg_color;
1712 int i_type = item->i_type;
1716 if( [o_msg_arr count] + 2 > 600 )
1718 [o_msg_arr removeObjectAtIndex: 0];
1719 [o_msg_arr removeObjectAtIndex: 1];
1722 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1723 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1724 [o_msg_arr addObject: [o_msg_color autorelease]];
1726 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1727 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", item->psz_msg] attributes: o_attr];
1728 [o_msg_arr addObject: [o_msg_color autorelease]];
1730 b_msg_arr_changed = YES;
1731 [o_msg_lock unlock];
1734 - (IBAction)saveDebugLog:(id)sender
1736 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
1738 [saveFolderPanel setCanChooseDirectories: NO];
1739 [saveFolderPanel setCanChooseFiles: YES];
1740 [saveFolderPanel setCanSelectHiddenExtension: NO];
1741 [saveFolderPanel setCanCreateDirectories: YES];
1742 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1743 [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];
1746 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1749 if( returnCode == NSOKButton )
1751 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1753 msg_Warn( p_intf, "Error while saving the debug log" );
1758 #pragma mark Playlist toggling
1760 - (IBAction)togglePlaylist:(id)sender
1762 NSLog( @"needs to be re-implemented" );
1765 - (void)updateTogglePlaylistState
1767 [[self playlist] outlineViewSelectionDidChange: NULL];
1774 @implementation VLCMain (Internal)
1776 - (void)handlePortMessage:(NSPortMessage *)o_msg
1781 NSInvocation * o_inv;
1782 NSConditionLock * o_lock;
1784 o_data = [[o_msg components] lastObject];
1785 o_inv = *((NSInvocation **)[o_data bytes]);
1786 [o_inv getArgument: &o_value atIndex: 2];
1787 val = (id **)[o_value pointerValue];
1788 [o_inv setArgument: val[1] atIndex: 2];
1793 [o_lock unlockWithCondition: 1];
1795 - (void)resetMediaKeyJump
1797 b_mediakeyJustJumped = NO;
1799 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1801 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1802 if (b_mediaKeySupport) {
1803 if (!o_mediaKeyController)
1804 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1805 [o_mediaKeyController startWatchingMediaKeys];
1807 else if (!b_mediaKeySupport && o_mediaKeyController)
1809 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1810 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1811 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1812 if( returnedValue == NSOKButton )
1815 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1817 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1823 execl(path, path, NULL);
1830 /*****************************************************************************
1831 * VLCApplication interface
1832 *****************************************************************************/
1834 @implementation VLCApplication
1835 // when user selects the quit menu from dock it sends a terminate:
1836 // but we need to send a stop: to properly exits libvlc.
1837 // However, we are not able to change the action-method sent by this standard menu item.
1838 // thus we override terminat: to send a stop:
1839 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1840 - (void)terminate:(id)sender
1842 [self activateIgnoringOtherApps:YES];