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 <unistd.h> /* execl() */
47 #import "playlistinfo.h"
52 #import "coredialogs.h"
53 #import "embeddedwindow.h"
54 #import "AppleRemote.h"
56 #import "simple_prefs.h"
57 #import "CoreInteraction.h"
59 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
60 #import <Sparkle/Sparkle.h> /* we're the update delegate */
62 /*****************************************************************************
64 *****************************************************************************/
65 static void Run ( intf_thread_t *p_intf );
67 static void * ManageThread( void *user_data );
69 static void updateProgressPanel (void *, const char *, float);
70 static bool checkProgressPanel (void *);
71 static void destroyProgressPanel (void *);
73 static void MsgCallback( msg_cb_data_t *, const msg_item_t * );
76 #pragma mark VLC Interface Object Callbacks
78 /*****************************************************************************
79 * OpenIntf: initialize interface
80 *****************************************************************************/
81 int OpenIntf ( vlc_object_t *p_this )
83 intf_thread_t *p_intf = (intf_thread_t*) p_this;
85 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
86 if( p_intf->p_sys == NULL )
89 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
91 /* subscribe to LibVLCCore's messages */
92 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
94 p_intf->b_should_run_on_first_thread = true;
99 /*****************************************************************************
100 * CloseIntf: destroy interface
101 *****************************************************************************/
102 void CloseIntf ( vlc_object_t *p_this )
104 intf_thread_t *p_intf = (intf_thread_t*) p_this;
106 free( p_intf->p_sys );
109 /*****************************************************************************
111 *****************************************************************************/
112 static NSLock * o_appLock = nil; // controls access to f_appExit
113 static int f_appExit = 0; // set to 1 when application termination signaled
115 static void Run( intf_thread_t *p_intf )
119 /* Make sure the "force quit" menu item does quit instantly.
120 * VLC overrides SIGTERM which is sent by the "force quit"
121 * menu item to make sure deamon mode quits gracefully, so
122 * we un-override SIGTERM here. */
124 sigaddset( &set, SIGTERM );
125 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
127 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
129 o_appLock = [[NSLock alloc] init];
131 [VLCApplication sharedApplication];
133 [[VLCMain sharedInstance] setIntf: p_intf];
134 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
137 [[VLCMain sharedInstance] applicationWillTerminate:nil];
143 #pragma mark Variables Callback
145 /*****************************************************************************
146 * MsgCallback: Callback triggered by the core once a new debug message is
147 * ready to be displayed. We store everything in a NSArray in our Cocoa part
148 * of this file, so we are forwarding everything through notifications.
149 *****************************************************************************/
150 static void MsgCallback( msg_cb_data_t *data, const msg_item_t *item )
152 int canc = vlc_savecancel();
153 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
155 /* this may happen from time to time, let's bail out as info would be useless anyway */
156 if( !item->psz_module || !item->psz_msg )
159 NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
160 [NSString stringWithUTF8String: item->psz_module], @"Module",
161 [NSString stringWithUTF8String: item->psz_msg], @"Message",
162 [NSNumber numberWithInt: item->i_type], @"Type", nil];
164 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
169 vlc_restorecancel( canc );
172 /*****************************************************************************
173 * playlistChanged: Callback triggered by the intf-change playlist
174 * variable, to let the intf update the playlist.
175 *****************************************************************************/
176 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
177 vlc_value_t old_val, vlc_value_t new_val, void *param )
179 intf_thread_t * p_intf = VLCIntf;
180 if( p_intf && p_intf->p_sys )
182 p_intf->p_sys->b_intf_update = true;
183 p_intf->p_sys->b_playlist_update = true;
184 p_intf->p_sys->b_playmode_update = true;
185 p_intf->p_sys->b_current_title_update = true;
190 /*****************************************************************************
191 * ShowController: Callback triggered by the show-intf playlist variable
192 * through the ShowIntf-control-intf, to let us show the controller-win;
193 * usually when in fullscreen-mode
194 *****************************************************************************/
195 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
196 vlc_value_t old_val, vlc_value_t new_val, void *param )
198 intf_thread_t * p_intf = VLCIntf;
199 if( p_intf && p_intf->p_sys )
200 p_intf->p_sys->b_intf_show = true;
204 /*****************************************************************************
205 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
206 * variable, to let the intf update the controller.
207 *****************************************************************************/
208 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
209 vlc_value_t old_val, vlc_value_t new_val, void *param )
211 intf_thread_t * p_intf = VLCIntf;
212 if( p_intf && p_intf->p_sys )
213 p_intf->p_sys->b_fullscreen_update = true;
217 /*****************************************************************************
218 * DialogCallback: Callback triggered by the "dialog-*" variables
219 * to let the intf display error and interaction dialogs
220 *****************************************************************************/
221 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
223 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
224 VLCMain *interface = (VLCMain *)data;
226 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
228 /* the progress panel needs to update itself and therefore wants special treatment within this context */
229 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
231 p_dialog->pf_update = updateProgressPanel;
232 p_dialog->pf_check = checkProgressPanel;
233 p_dialog->pf_destroy = destroyProgressPanel;
234 p_dialog->p_sys = VLCIntf->p_libvlc;
237 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
238 [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface coreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
244 void updateProgressPanel (void *priv, const char *text, float value)
246 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
250 o_txt = [NSString stringWithUTF8String: text];
254 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
259 void destroyProgressPanel (void *priv)
261 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
262 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
266 bool checkProgressPanel (void *priv)
268 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
269 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
276 input_thread_t *getInput(void)
278 intf_thread_t *p_intf = VLCIntf;
281 return pl_CurrentInput(p_intf);
284 vout_thread_t *getVout(void)
286 input_thread_t *p_input = getInput();
289 vout_thread_t *p_vout = input_GetVout(p_input);
290 vlc_object_release(p_input);
294 aout_instance_t *getAout(void)
296 input_thread_t *p_input = getInput();
299 aout_instance_t *p_aout = input_GetAout(p_input);
300 vlc_object_release(p_input);
307 @interface VLCMain ()
308 - (void)_removeOldPreferences;
311 /*****************************************************************************
312 * VLCMain implementation
313 *****************************************************************************/
314 @implementation VLCMain
317 #pragma mark Initialization
319 static VLCMain *_o_sharedMainInstance = nil;
321 + (VLCMain *)sharedInstance
323 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
328 if( _o_sharedMainInstance)
331 return _o_sharedMainInstance;
334 _o_sharedMainInstance = [super init];
338 o_msg_lock = [[NSLock alloc] init];
339 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
340 /* subscribe to LibVLC's debug messages as early as possible (for us) */
341 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
343 o_open = [[VLCOpen alloc] init];
344 //o_embedded_list = [[VLCEmbeddedList alloc] init];
345 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
346 o_info = [[VLCInfo alloc] init];
347 o_mainmenu = [[VLCMainMenu alloc] init];
348 o_coreinteraction = [[VLCCoreInteraction alloc] init];
350 i_lastShownVolume = -1;
352 o_eyetv = [[VLCEyeTVController alloc] init];
354 /* announce our launch to a potential eyetv plugin */
355 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
356 object: @"VLCEyeTVSupport"
358 deliverImmediately: YES];
359 return _o_sharedMainInstance;
362 - (void)setIntf: (intf_thread_t *)p_mainintf {
366 - (intf_thread_t *)intf {
372 playlist_t *p_playlist;
374 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
376 [o_volumeslider setEnabled: YES];
377 [self manageVolumeSlider];
378 [o_window setDelegate: self];
379 [o_window setExcludedFromWindowsMenu: YES];
380 [o_msgs_panel setExcludedFromWindowsMenu: YES];
381 [o_msgs_panel setDelegate: self];
383 // Set that here as IB seems to be buggy
384 [o_window setContentMinSize:NSMakeSize(500., 200.)];
386 p_playlist = pl_Get( p_intf );
390 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
391 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
393 /* load our Core Dialogs nib */
394 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
396 /* subscribe to various interactive dialogues */
397 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
398 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
399 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
400 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
401 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
402 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
403 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
404 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
405 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
406 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
407 dialog_Register( p_intf );
409 /* update the playmode stuff */
410 p_intf->p_sys->b_playmode_update = true;
412 /* take care of tint changes during runtime */
413 o_img_play = [NSImage imageNamed: @"play"];
414 o_img_pause = [NSImage imageNamed: @"pause"];
416 /* init Apple Remote support */
417 o_remote = [[AppleRemote alloc] init];
418 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
419 [o_remote setDelegate: _o_sharedMainInstance];
421 /* yeah, we are done */
422 nib_main_loaded = TRUE;
425 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
427 if( !p_intf ) return;
429 /* FIXME: don't poll */
430 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
431 target: self selector: @selector(manageIntf:)
432 userInfo: nil repeats: FALSE] retain];
434 /* Note: we use the pthread API to support pre-10.5 */
435 pthread_create( &manage_thread, NULL, ManageThread, self );
438 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
440 if( !p_intf ) return;
442 /* init media key support */
443 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
444 if( b_mediaKeySupport )
446 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
447 [o_mediaKeyController startWatchingMediaKeys];
448 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
449 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
452 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
454 [self _removeOldPreferences];
456 /* Handle sleep notification */
457 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
458 name:NSWorkspaceWillSleepNotification object:nil];
460 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
465 if( !p_intf ) return;
467 [o_window setTitle: _NS("VLC media player")];
468 [self setScrollField:_NS("VLC media player") stopAfter:-1];
470 /* button controls */
471 [o_btn_prev setToolTip: _NS("Previous")];
472 [o_btn_rewind setToolTip: _NS("Rewind")];
473 [o_btn_play setToolTip: _NS("Play")];
474 [o_btn_stop setToolTip: _NS("Stop")];
475 [o_btn_ff setToolTip: _NS("Fast Forward")];
476 [o_btn_next setToolTip: _NS("Next")];
477 [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
478 [o_volumeslider setToolTip: _NS("Volume")];
479 [o_timeslider setToolTip: _NS("Position")];
480 [o_btn_playlist setToolTip: _NS("Playlist")];
483 [o_msgs_panel setTitle: _NS("Messages")];
484 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
485 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
487 /* crash reporter panel */
488 [o_crashrep_send_btn setTitle: _NS("Send")];
489 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
490 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
491 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
492 [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, ...")];
493 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
494 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
498 #pragma mark Termination
500 - (void)applicationWillTerminate:(NSNotification *)notification
502 playlist_t * p_playlist;
503 vout_thread_t * p_vout;
504 int returnedValue = 0;
509 // don't allow a double termination call. If the user has
510 // already invoked the quit then simply return this time.
511 int isTerminating = false;
514 isTerminating = (f_appExit++ > 0 ? 1 : 0);
520 msg_Dbg( p_intf, "Terminating" );
522 pthread_join( manage_thread, NULL );
524 /* Make sure the intf object is getting killed */
525 vlc_object_kill( p_intf );
527 /* Make sure the interfaceTimer is destroyed */
528 [interfaceTimer invalidate];
529 [interfaceTimer release];
530 interfaceTimer = nil;
532 /* make sure that the current volume is saved */
533 config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
535 /* unsubscribe from the interactive dialogues */
536 dialog_Unregister( p_intf );
537 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
538 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
539 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
540 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
541 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
543 /* remove global observer watching for vout device changes correctly */
544 [[NSNotificationCenter defaultCenter] removeObserver: self];
546 /* release some other objects here, because it isn't sure whether dealloc
547 * will be called later on */
565 [crashLogURLConnection cancel];
566 [crashLogURLConnection release];
568 [o_embedded_list release];
569 [o_coredialogs release];
572 [o_img_pause_pressed release];
573 [o_img_play_pressed release];
574 [o_img_pause release];
575 [o_img_play release];
577 /* unsubscribe from libvlc's debug messages */
578 msg_Unsubscribe( p_intf->p_sys->p_sub );
580 [o_msg_arr removeAllObjects];
583 [o_msg_lock release];
585 /* write cached user defaults to disk */
586 [[NSUserDefaults standardUserDefaults] synchronize];
588 /* Make sure the Menu doesn't have any references to vlc objects anymore */
589 //FIXME: this should be moved to VLCMainMenu
590 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
591 [o_mainmenu release];
593 /* Kill the playlist, so that it doesn't accept new request
594 * such as the play request from vlc.c (we are a blocking interface). */
595 p_playlist = pl_Get( p_intf );
596 vlc_object_kill( p_playlist );
597 libvlc_Quit( p_intf->p_libvlc );
603 #pragma mark Sparkle delegate
604 /* received directly before the update gets installed, so let's shut down a bit */
605 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
607 [o_remote stopListening: self];
608 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
610 /* Close the window directly, because we do know that there
611 * won't be anymore video. It's currently waiting a bit. */
612 [[[o_coreinteraction voutView] window] orderOut:self];
616 #pragma mark Media Key support
618 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
620 if( b_mediaKeySupport )
622 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
624 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
625 int keyFlags = ([event data1] & 0x0000FFFF);
626 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
627 int keyRepeat = (keyFlags & 0x1);
629 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
630 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
632 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
634 if( keyState == 0 && keyRepeat == 0 )
635 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
636 else if( keyRepeat == 1 )
638 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
639 b_mediakeyJustJumped = YES;
640 [self performSelector:@selector(resetMediaKeyJump)
646 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
648 if( keyState == 0 && keyRepeat == 0 )
649 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
650 else if( keyRepeat == 1 )
652 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
653 b_mediakeyJustJumped = YES;
654 [self performSelector:@selector(resetMediaKeyJump)
663 #pragma mark Other notification
665 /* Listen to the remote in exclusive mode, only when VLC is the active
667 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
669 if( !p_intf ) return;
670 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
671 [o_remote startListening: self];
673 - (void)applicationDidResignActive:(NSNotification *)aNotification
675 if( !p_intf ) return;
676 [o_remote stopListening: self];
679 /* Triggered when the computer goes to sleep */
680 - (void)computerWillSleep: (NSNotification *)notification
683 if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
685 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
690 #pragma mark File opening
692 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
694 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
695 char *psz_uri = make_URI([o_filename UTF8String], "file" );
699 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
704 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
706 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
711 /* When user click in the Dock icon our double click in the finder */
712 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
714 if(!hasVisibleWindows)
715 [o_window makeKeyAndOrderFront:self];
721 #pragma mark Apple Remote Control
723 /* Helper method for the remote control interface in order to trigger forward/backward and volume
724 increase/decrease as long as the user holds the left/right, plus/minus button */
725 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
727 if(b_remote_button_hold)
729 switch([buttonIdentifierNumber intValue])
731 case kRemoteButtonRight_Hold:
732 [o_controls forward: self];
734 case kRemoteButtonLeft_Hold:
735 [o_controls backward: self];
737 case kRemoteButtonVolume_Plus_Hold:
738 [o_controls volumeUp: self];
740 case kRemoteButtonVolume_Minus_Hold:
741 [o_controls volumeDown: self];
744 if(b_remote_button_hold)
747 [self performSelector:@selector(executeHoldActionForRemoteButton:)
748 withObject:buttonIdentifierNumber
754 /* Apple Remote callback */
755 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
756 pressedDown: (BOOL) pressedDown
757 clickCount: (unsigned int) count
759 switch( buttonIdentifier )
761 case k2009RemoteButtonFullscreen:
762 [o_controls toogleFullscreen:self];
764 case k2009RemoteButtonPlay:
765 [o_controls play:self];
767 case kRemoteButtonPlay:
769 [o_controls toogleFullscreen:self];
771 [o_controls play: self];
774 case kRemoteButtonVolume_Plus:
775 [o_controls volumeUp: self];
777 case kRemoteButtonVolume_Minus:
778 [o_controls volumeDown: self];
780 case kRemoteButtonRight:
781 [o_controls next: self];
783 case kRemoteButtonLeft:
784 [o_controls prev: self];
786 case kRemoteButtonRight_Hold:
787 case kRemoteButtonLeft_Hold:
788 case kRemoteButtonVolume_Plus_Hold:
789 case kRemoteButtonVolume_Minus_Hold:
790 /* simulate an event as long as the user holds the button */
791 b_remote_button_hold = pressedDown;
794 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
795 [self performSelector:@selector(executeHoldActionForRemoteButton:)
796 withObject:buttonIdentifierNumber];
799 case kRemoteButtonMenu:
800 [o_controls showPosition: self];
803 /* Add here whatever you want other buttons to do */
809 #pragma mark String utility
810 // FIXME: this has nothing to do here
812 - (NSString *)localizedString:(const char *)psz
814 NSString * o_str = nil;
818 o_str = [[[NSString alloc] initWithFormat:@"%s", psz] autorelease];
822 msg_Err( VLCIntf, "could not translate: %s", psz );
828 msg_Warn( VLCIntf, "can't translate empty strings" );
837 - (char *)delocalizeString:(NSString *)id
839 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
840 allowLossyConversion: NO];
845 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
846 allowLossyConversion: YES];
847 psz_string = malloc( [o_data length] + 1 );
848 [o_data getBytes: psz_string];
849 psz_string[ [o_data length] ] = '\0';
850 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
855 psz_string = malloc( [o_data length] + 1 );
856 [o_data getBytes: psz_string];
857 psz_string[ [o_data length] ] = '\0';
863 /* i_width is in pixels */
864 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
866 NSMutableString *o_wrapped;
867 NSString *o_out_string;
868 NSRange glyphRange, effectiveRange, charRange;
869 NSRect lineFragmentRect;
870 unsigned glyphIndex, breaksInserted = 0;
872 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
873 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
874 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
875 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
876 NSTextContainer *o_container = [[NSTextContainer alloc]
877 initWithContainerSize: NSMakeSize(i_width, 2000)];
879 [o_layout_manager addTextContainer: o_container];
880 [o_container release];
881 [o_storage addLayoutManager: o_layout_manager];
882 [o_layout_manager release];
884 o_wrapped = [o_in_string mutableCopy];
885 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
887 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
888 glyphIndex += effectiveRange.length) {
889 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
890 effectiveRange: &effectiveRange];
891 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
892 actualGlyphRange: &effectiveRange];
893 if([o_wrapped lineRangeForRange:
894 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
895 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
899 o_out_string = [NSString stringWithString: o_wrapped];
908 #pragma mark Key Shortcuts
913 unsigned int i_vlckey;
914 } nskeys_to_vlckeys[] =
916 { NSUpArrowFunctionKey, KEY_UP },
917 { NSDownArrowFunctionKey, KEY_DOWN },
918 { NSLeftArrowFunctionKey, KEY_LEFT },
919 { NSRightArrowFunctionKey, KEY_RIGHT },
920 { NSF1FunctionKey, KEY_F1 },
921 { NSF2FunctionKey, KEY_F2 },
922 { NSF3FunctionKey, KEY_F3 },
923 { NSF4FunctionKey, KEY_F4 },
924 { NSF5FunctionKey, KEY_F5 },
925 { NSF6FunctionKey, KEY_F6 },
926 { NSF7FunctionKey, KEY_F7 },
927 { NSF8FunctionKey, KEY_F8 },
928 { NSF9FunctionKey, KEY_F9 },
929 { NSF10FunctionKey, KEY_F10 },
930 { NSF11FunctionKey, KEY_F11 },
931 { NSF12FunctionKey, KEY_F12 },
932 { NSInsertFunctionKey, KEY_INSERT },
933 { NSHomeFunctionKey, KEY_HOME },
934 { NSEndFunctionKey, KEY_END },
935 { NSPageUpFunctionKey, KEY_PAGEUP },
936 { NSPageDownFunctionKey, KEY_PAGEDOWN },
937 { NSMenuFunctionKey, KEY_MENU },
938 { NSTabCharacter, KEY_TAB },
939 { NSCarriageReturnCharacter, KEY_ENTER },
940 { NSEnterCharacter, KEY_ENTER },
941 { NSBackspaceCharacter, KEY_BACKSPACE },
945 unsigned int CocoaKeyToVLC( unichar i_key )
949 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
951 if( nskeys_to_vlckeys[i].i_nskey == i_key )
953 return nskeys_to_vlckeys[i].i_vlckey;
956 return (unsigned int)i_key;
959 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
961 unsigned int new = 0;
963 if([theString rangeOfString:@"Command"].location != NSNotFound)
964 new |= NSCommandKeyMask;
965 if([theString rangeOfString:@"Alt"].location != NSNotFound)
966 new |= NSAlternateKeyMask;
967 if([theString rangeOfString:@"Shift"].location != NSNotFound)
968 new |= NSShiftKeyMask;
969 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
970 new |= NSControlKeyMask;
974 - (NSString *)VLCKeyToString:(NSString *)theString
976 if (![theString isEqualToString:@""]) {
977 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
978 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
979 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
980 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
981 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
982 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
988 /*****************************************************************************
989 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
990 * shortcut key. If it is, pass it off to VLC for handling and return YES,
991 * otherwise ignore it and return NO (where it will get handled by Cocoa).
992 *****************************************************************************/
993 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
997 unsigned int i_pressed_modifiers = 0;
998 const struct hotkey *p_hotkeys;
1000 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1001 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1004 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1006 i_pressed_modifiers = [o_event modifierFlags];
1008 if( i_pressed_modifiers & NSShiftKeyMask ) {
1009 val.i_int |= KEY_MODIFIER_SHIFT;
1010 [tempString appendString:@"Shift-"];
1011 [tempStringPlus appendString:@"Shift+"];
1013 if( i_pressed_modifiers & NSControlKeyMask ) {
1014 val.i_int |= KEY_MODIFIER_CTRL;
1015 [tempString appendString:@"Ctrl-"];
1016 [tempStringPlus appendString:@"Ctrl+"];
1018 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1019 val.i_int |= KEY_MODIFIER_ALT;
1020 [tempString appendString:@"Alt-"];
1021 [tempStringPlus appendString:@"Alt+"];
1023 if( i_pressed_modifiers & NSCommandKeyMask ) {
1024 val.i_int |= KEY_MODIFIER_COMMAND;
1025 [tempString appendString:@"Command-"];
1026 [tempStringPlus appendString:@"Command+"];
1029 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1030 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1032 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1036 case NSDeleteCharacter:
1037 case NSDeleteFunctionKey:
1038 case NSDeleteCharFunctionKey:
1039 case NSBackspaceCharacter:
1040 case NSUpArrowFunctionKey:
1041 case NSDownArrowFunctionKey:
1042 case NSRightArrowFunctionKey:
1043 case NSLeftArrowFunctionKey:
1044 case NSEnterCharacter:
1045 case NSCarriageReturnCharacter:
1049 val.i_int |= CocoaKeyToVLC( key );
1051 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1053 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1060 - (void)updateCurrentlyUsedHotkeys
1062 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1063 /* Get the main Module */
1064 module_t *p_main = module_get_main();
1067 module_config_t *p_config;
1069 p_config = module_config_get (p_main, &confsize);
1071 for (size_t i = 0; i < confsize; i++)
1073 module_config_t *p_item = p_config + i;
1075 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1076 && !strncmp( p_item->psz_name , "key-", 4 )
1077 && !EMPTY_STR( p_item->psz_text ) )
1079 if (p_item->value.psz)
1080 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1083 module_config_free (p_config);
1084 module_release (p_main);
1085 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1090 #pragma mark Other objects getters
1108 o_bookmarks = [[VLCBookmarks alloc] init];
1110 if( !nib_bookmarks_loaded )
1111 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1121 if (!nib_open_loaded)
1122 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1127 - (id)simplePreferences
1130 o_sprefs = [[VLCSimplePrefs alloc] init];
1132 if (!nib_prefs_loaded)
1133 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1141 o_prefs = [[VLCPrefs alloc] init];
1143 if( !nib_prefs_loaded )
1144 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1157 - (BOOL)isPlaylistCollapsed
1159 return ![o_btn_playlist state];
1164 if(! nib_info_loaded )
1165 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1176 o_wizard = [[VLCWizard alloc] init];
1178 if( !nib_wizard_loaded )
1180 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1181 [o_wizard initStrings];
1188 if( o_embedded_list )
1189 return o_embedded_list;
1194 - (id)coreDialogProvider
1197 return o_coredialogs;
1205 return o_main_pgbar;
1210 - (id)controllerWindow
1217 - (id)eyeTVController
1225 - (id)appleRemoteController
1231 #pragma mark Polling
1233 /*****************************************************************************
1234 * ManageThread: An ugly thread that polls
1235 *****************************************************************************/
1236 static void * ManageThread( void *user_data )
1238 id self = user_data;
1245 struct manage_cleanup_stack {
1246 intf_thread_t * p_intf;
1247 input_thread_t ** p_input;
1248 playlist_t * p_playlist;
1252 static void manage_cleanup( void * args )
1254 struct manage_cleanup_stack * manage_cleanup_stack = args;
1255 intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1256 input_thread_t * p_input = *manage_cleanup_stack->p_input;
1257 id self = manage_cleanup_stack->self;
1258 playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1260 var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1261 var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1262 var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1263 var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1264 var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1266 if( p_input ) vlc_object_release( p_input );
1271 playlist_t * p_playlist;
1272 input_thread_t * p_input = NULL;
1274 /* new thread requires a new pool */
1276 p_playlist = pl_Get( p_intf );
1278 var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1279 var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1280 var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1281 var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1282 var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1284 struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1285 pthread_cleanup_push(manage_cleanup, &stack);
1287 bool exitLoop = false;
1290 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1294 p_input = playlist_CurrentInput( p_playlist );
1296 /* Refresh the interface */
1299 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1300 p_intf->p_sys->b_input_update = true;
1303 else if( !vlc_object_alive (p_input) || p_input->b_dead )
1306 p_intf->p_sys->b_intf_update = true;
1307 p_intf->p_sys->i_play_status = END_S;
1308 msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1309 vlc_object_release( p_input );
1312 else if( cachedInputState != input_GetState( p_input ) )
1314 p_intf->p_sys->b_intf_update = true;
1317 /* Manage volume status */
1318 [self manageVolumeSlider];
1320 msleep( INTF_IDLE_SLEEP );
1325 exitLoop = (f_appExit != 0 ? true : false);
1329 pthread_cleanup_pop(1);
1332 - (void)manageVolumeSlider
1334 audio_volume_t i_volume;
1335 playlist_t * p_playlist = pl_Get( p_intf );
1337 i_volume = aout_VolumeGet( p_playlist );
1339 if( i_volume != i_lastShownVolume )
1341 i_lastShownVolume = i_volume;
1342 p_intf->p_sys->b_volume_update = TRUE;
1346 - (void)manageIntf:(NSTimer *)o_timer
1349 playlist_t * p_playlist;
1350 input_thread_t * p_input;
1352 if( p_intf->p_sys->b_input_update )
1354 /* Called when new input is opened */
1355 p_intf->p_sys->b_current_title_update = true;
1356 p_intf->p_sys->b_intf_update = true;
1357 p_intf->p_sys->b_input_update = false;
1358 [o_mainmenu setupMenus]; /* Make sure input menu is up to date */
1360 /* update our info-panel to reflect the new item, if we don't show
1361 * the playlist or the selection is empty */
1362 if( [self isPlaylistCollapsed] == YES )
1364 playlist_t * p_playlist = pl_Get( p_intf );
1366 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1369 [[self info] updatePanelWithItem: p_item->p_input];
1372 if( p_intf->p_sys->b_intf_update )
1374 bool b_input = false;
1375 bool b_plmul = false;
1376 bool b_control = false;
1377 bool b_seekable = false;
1378 bool b_chapters = false;
1380 playlist_t * p_playlist = pl_Get( p_intf );
1383 b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1386 p_input = playlist_CurrentInput( p_playlist );
1388 bool b_buffering = NO;
1390 if( ( b_input = ( p_input != NULL ) ) )
1392 /* seekable streams */
1393 cachedInputState = input_GetState( p_input );
1394 if ( cachedInputState == INIT_S ||
1395 cachedInputState == OPENING_S )
1400 /* seekable streams */
1401 b_seekable = var_GetBool( p_input, "can-seek" );
1403 /* check whether slow/fast motion is possible */
1404 b_control = var_GetBool( p_input, "can-rate" );
1406 /* chapters & titles */
1407 //b_chapters = p_input->stream.i_area_nb > 1;
1408 vlc_object_release( p_input );
1413 [o_main_pgbar startAnimation:self];
1414 [o_main_pgbar setIndeterminate:YES];
1415 [o_main_pgbar setHidden:NO];
1419 [o_main_pgbar stopAnimation:self];
1420 [o_main_pgbar setHidden:YES];
1423 [o_btn_stop setEnabled: b_input];
1424 [o_embedded_window setStop: b_input];
1425 [o_btn_ff setEnabled: b_seekable];
1426 [o_btn_rewind setEnabled: b_seekable];
1427 [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1428 [o_embedded_window setPrev: (b_plmul || b_chapters)];
1429 [o_btn_next setEnabled: (b_plmul || b_chapters)];
1430 [o_embedded_window setNext: (b_plmul || b_chapters)];
1431 [o_mainmenu setRateControlsEnabled: b_control];
1433 [o_timeslider setFloatValue: 0.0];
1434 [o_timeslider setEnabled: b_seekable];
1435 [o_timefield setStringValue: @"00:00"];
1436 [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1437 [[[self controls] fspanel] setSeekable: b_seekable];
1439 [o_embedded_window setSeekable: b_seekable];
1440 [o_embedded_window setTime:@"00:00" position:0.0];
1442 p_intf->p_sys->b_current_title_update = true;
1444 p_intf->p_sys->b_intf_update = false;
1447 if( p_intf->p_sys->b_playmode_update )
1449 [o_playlist playModeUpdated];
1450 p_intf->p_sys->b_playmode_update = false;
1452 if( p_intf->p_sys->b_playlist_update )
1454 [o_playlist playlistUpdated];
1455 p_intf->p_sys->b_playlist_update = false;
1458 if( p_intf->p_sys->b_fullscreen_update )
1460 p_intf->p_sys->b_fullscreen_update = false;
1463 if( p_intf->p_sys->b_intf_show )
1465 if( [[o_coreinteraction voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1466 [[o_controls fspanel] fadeIn];
1468 [o_window makeKeyAndOrderFront: self];
1470 p_intf->p_sys->b_intf_show = false;
1473 p_input = pl_CurrentInput( p_intf );
1474 if( p_input && vlc_object_alive (p_input) )
1478 if( p_intf->p_sys->b_current_title_update )
1481 input_item_t * p_item = input_GetItem( p_input );
1482 char * name = input_item_GetNowPlaying( p_item );
1485 name = input_item_GetName( p_item );
1487 aString = [NSString stringWithUTF8String:name];
1491 [self setScrollField: aString stopAfter:-1];
1492 [[[self controls] fspanel] setStreamTitle: aString];
1494 [[o_coreinteraction voutView] updateTitle];
1496 [o_playlist updateRowSelection];
1498 p_intf->p_sys->b_current_title_update = FALSE;
1501 if( [o_timeslider isEnabled] )
1503 /* Update the slider */
1507 char psz_time[MSTRTIME_MAX_SIZE];
1510 var_Get( p_input, "position", &pos );
1511 f_updated = 10000. * pos.f_float;
1512 [o_timeslider setFloatValue: f_updated];
1514 var_Get( p_input, "time", &time );
1516 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1517 if( b_time_remaining && dur != -1 )
1519 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1522 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1524 [o_timefield setStringValue: o_time];
1525 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1526 [o_embedded_window setTime: o_time position: f_updated];
1529 /* Manage Playing status */
1530 var_Get( p_input, "state", &val );
1531 if( p_intf->p_sys->i_play_status != val.i_int )
1533 p_intf->p_sys->i_play_status = val.i_int;
1534 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1535 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1537 vlc_object_release( p_input );
1541 vlc_object_release( p_input );
1545 p_intf->p_sys->i_play_status = END_S;
1546 [self playStatusUpdated: p_intf->p_sys->i_play_status];
1547 [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1548 [o_mainmenu setSubmenusEnabled: FALSE];
1551 if( p_intf->p_sys->b_volume_update )
1554 int i_volume_step = 0;
1555 o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1556 if( i_lastShownVolume != -1 )
1557 [self setScrollField:o_text stopAfter:1000000];
1558 i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1559 [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1560 [o_volumeslider setEnabled: TRUE];
1561 [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1562 [o_embedded_window setVolumeEnabled: TRUE];
1563 [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1564 p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1565 p_intf->p_sys->b_volume_update = FALSE;
1569 [self updateMessageDisplay];
1571 if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1572 [self resetScrollField];
1574 [interfaceTimer autorelease];
1576 interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1577 target: self selector: @selector(manageIntf:)
1578 userInfo: nil repeats: FALSE] retain];
1582 #pragma mark Interface update
1584 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1587 i_end_scroll = mdate() + timeout;
1590 [o_scrollfield setStringValue: o_string];
1591 [o_embedded_window setScrollString: o_string];
1594 - (void)resetScrollField
1596 playlist_t * p_playlist = pl_Get( p_intf );
1597 input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1600 if( p_input && vlc_object_alive (p_input) )
1604 playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1605 if( input_item_GetNowPlaying( p_item->p_input ) )
1606 o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
1608 o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
1610 [self setScrollField: o_temp stopAfter:-1];
1611 [[[self controls] fspanel] setStreamTitle: o_temp];
1612 vlc_object_release( p_input );
1615 [self setScrollField: _NS("VLC media player") stopAfter:-1];
1618 - (void)playStatusUpdated:(int)i_status
1620 if( i_status == PLAYING_S )
1622 [[[self controls] fspanel] setPause];
1623 [[self mainMenu] setPause];
1624 [o_btn_play setImage: o_img_pause];
1625 [o_btn_play setAlternateImage: o_img_pause_pressed];
1626 [o_btn_play setToolTip: _NS("Pause")];
1630 [[[self controls] fspanel] setPlay];
1631 [[self mainMenu] setPlay];
1632 [o_btn_play setImage: o_img_play];
1633 [o_btn_play setAlternateImage: o_img_play_pressed];
1634 [o_btn_play setToolTip: _NS("Play")];
1638 - (IBAction)timesliderUpdate:(id)sender
1641 playlist_t * p_playlist;
1642 input_thread_t * p_input;
1644 switch( [[NSApp currentEvent] type] )
1647 case NSLeftMouseDown:
1648 case NSLeftMouseDragged:
1649 f_updated = [sender floatValue];
1655 p_playlist = pl_Get( p_intf );
1656 p_input = playlist_CurrentInput( p_playlist );
1657 if( p_input != NULL )
1662 char psz_time[MSTRTIME_MAX_SIZE];
1664 pos.f_float = f_updated / 10000.;
1665 var_Set( p_input, "position", pos );
1666 [o_timeslider setFloatValue: f_updated];
1668 var_Get( p_input, "time", &time );
1670 mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1671 if( b_time_remaining && dur != -1 )
1673 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
1676 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1678 [o_timefield setStringValue: o_time];
1679 [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1680 [o_embedded_window setTime: o_time position: f_updated];
1681 vlc_object_release( p_input );
1685 - (IBAction)timeFieldWasClicked:(id)sender
1687 b_time_remaining = !b_time_remaining;
1690 - (IBAction)showController:(id)sender
1692 //FIXME: temporary hack until we have VLCMainWindow
1693 [o_window makeKeyAndOrderFront:sender];
1697 #pragma mark Crash Log
1698 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1700 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1701 NSURL *url = [NSURL URLWithString:urlStr];
1703 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1704 [req setHTTPMethod:@"POST"];
1707 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1709 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1710 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1711 email = [emails valueAtIndex:[emails indexForIdentifier:
1712 [emails primaryIdentifier]]];
1715 email = [NSString string];
1718 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1719 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1720 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1721 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1723 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1725 /* Released from delegate */
1726 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1729 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1731 [crashLogURLConnection release];
1732 crashLogURLConnection = nil;
1735 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1737 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1738 [crashLogURLConnection release];
1739 crashLogURLConnection = nil;
1742 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1744 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1745 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1747 NSString * latestLog = nil;
1748 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1749 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1750 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1751 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1753 while (fname = [direnum nextObject])
1755 [direnum skipDescendents];
1756 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1758 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1759 if( [compo count] < 3 ) continue;
1760 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1761 if( [compo count] < 4 ) continue;
1764 if( year < [[compo objectAtIndex:0] intValue] ||
1765 (year ==[[compo objectAtIndex:0] intValue] &&
1766 (month < [[compo objectAtIndex:1] intValue] ||
1767 (month ==[[compo objectAtIndex:1] intValue] &&
1768 (day < [[compo objectAtIndex:2] intValue] ||
1769 (day ==[[compo objectAtIndex:2] intValue] &&
1770 hours < [[compo objectAtIndex:3] intValue] ))))))
1772 year = [[compo objectAtIndex:0] intValue];
1773 month = [[compo objectAtIndex:1] intValue];
1774 day = [[compo objectAtIndex:2] intValue];
1775 hours = [[compo objectAtIndex:3] intValue];
1776 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1781 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1784 if( !previouslySeen )
1786 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1787 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1788 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1789 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1794 - (NSString *)latestCrashLogPath
1796 return [self latestCrashLogPathPreviouslySeen:YES];
1799 - (void)lookForCrashLog
1801 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1802 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1803 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1804 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1805 if( latestLog && !areCrashLogsTooOld )
1806 [NSApp runModalForWindow: o_crashrep_win];
1810 - (IBAction)crashReporterAction:(id)sender
1812 if( sender == o_crashrep_send_btn )
1813 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1816 [o_crashrep_win orderOut: sender];
1819 - (IBAction)openCrashLog:(id)sender
1821 NSString * latestLog = [self latestCrashLogPath];
1824 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1828 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.") );
1833 #pragma mark Remove old prefs
1835 - (void)_removeOldPreferences
1837 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1838 static const int kCurrentPreferencesVersion = 1;
1839 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1840 if( version >= kCurrentPreferencesVersion ) return;
1842 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1843 NSUserDomainMask, YES);
1844 if( !libraries || [libraries count] == 0) return;
1845 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1847 /* File not found, don't attempt anything */
1848 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1849 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1851 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1855 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1856 _NS("We just found an older version of VLC's preferences files."),
1857 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1858 if( res != NSOKButton )
1860 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1864 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1866 /* Move the file to trash so that user can find them later */
1867 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1869 /* really reset the defaults from now on */
1870 [NSUserDefaults resetStandardUserDefaults];
1872 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1873 [[NSUserDefaults standardUserDefaults] synchronize];
1876 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1878 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1884 execl(path, path, NULL);
1888 #pragma mark Errors, warnings and messages
1889 - (IBAction)showMessagesPanel:(id)sender
1891 [o_msgs_panel makeKeyAndOrderFront: sender];
1894 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1896 if( [o_notification object] == o_msgs_panel )
1897 [self updateMessageDisplay];
1900 - (void)updateMessageDisplay
1902 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1905 NSEnumerator * o_enum;
1907 [o_messages setString: @""];
1911 o_enum = [o_msg_arr objectEnumerator];
1913 while( ( o_msg = [o_enum nextObject] ) != nil )
1915 [o_messages insertText: o_msg];
1918 b_msg_arr_changed = NO;
1919 [o_msg_lock unlock];
1923 - (void)libvlcMessageReceived: (NSNotification *)o_notification
1925 NSColor *o_white = [NSColor whiteColor];
1926 NSColor *o_red = [NSColor redColor];
1927 NSColor *o_yellow = [NSColor yellowColor];
1928 NSColor *o_gray = [NSColor grayColor];
1930 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1931 static const char * ppsz_type[4] = { ": ", " error: ",
1932 " warning: ", " debug: " };
1935 NSDictionary *o_attr;
1936 NSAttributedString *o_msg_color;
1938 int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
1942 if( [o_msg_arr count] + 2 > 600 )
1944 [o_msg_arr removeObjectAtIndex: 0];
1945 [o_msg_arr removeObjectAtIndex: 1];
1948 o_attr = [NSDictionary dictionaryWithObject: o_gray
1949 forKey: NSForegroundColorAttributeName];
1950 o_msg = [NSString stringWithFormat: @"%@%s",
1951 [[o_notification userInfo] objectForKey: @"Module"],
1953 o_msg_color = [[NSAttributedString alloc]
1954 initWithString: o_msg attributes: o_attr];
1955 [o_msg_arr addObject: [o_msg_color autorelease]];
1957 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1958 forKey: NSForegroundColorAttributeName];
1959 o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
1960 o_msg_color = [[NSAttributedString alloc]
1961 initWithString: o_msg attributes: o_attr];
1962 [o_msg_arr addObject: [o_msg_color autorelease]];
1964 b_msg_arr_changed = YES;
1965 [o_msg_lock unlock];
1968 - (IBAction)saveDebugLog:(id)sender
1970 NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
1972 [saveFolderPanel setCanChooseDirectories: NO];
1973 [saveFolderPanel setCanChooseFiles: YES];
1974 [saveFolderPanel setCanSelectHiddenExtension: NO];
1975 [saveFolderPanel setCanCreateDirectories: YES];
1976 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1977 [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];
1980 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1983 if( returnCode == NSOKButton )
1985 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1987 msg_Warn( p_intf, "Error while saving the debug log" );
1992 #pragma mark Playlist toggling
1994 - (IBAction)togglePlaylist:(id)sender
1996 NSLog( @"needs to be re-implemented" );
1999 - (void)updateTogglePlaylistState
2001 [[self playlist] outlineViewSelectionDidChange: NULL];
2008 @implementation VLCMain (Internal)
2010 - (void)handlePortMessage:(NSPortMessage *)o_msg
2015 NSInvocation * o_inv;
2016 NSConditionLock * o_lock;
2018 o_data = [[o_msg components] lastObject];
2019 o_inv = *((NSInvocation **)[o_data bytes]);
2020 [o_inv getArgument: &o_value atIndex: 2];
2021 val = (id **)[o_value pointerValue];
2022 [o_inv setArgument: val[1] atIndex: 2];
2027 [o_lock unlockWithCondition: 1];
2029 - (void)resetMediaKeyJump
2031 b_mediakeyJustJumped = NO;
2033 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2035 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2036 if (b_mediaKeySupport) {
2037 if (!o_mediaKeyController)
2038 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2039 [o_mediaKeyController startWatchingMediaKeys];
2041 else if (!b_mediaKeySupport && o_mediaKeyController)
2043 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
2044 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
2045 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
2046 if( returnedValue == NSOKButton )
2049 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2051 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2057 execl(path, path, NULL);
2064 /*****************************************************************************
2065 * VLCApplication interface
2066 *****************************************************************************/
2068 @implementation VLCApplication
2069 // when user selects the quit menu from dock it sends a terminate:
2070 // but we need to send a stop: to properly exits libvlc.
2071 // However, we are not able to change the action-method sent by this standard menu item.
2072 // thus we override terminat: to send a stop:
2073 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2074 - (void)terminate:(id)sender
2076 [self activateIgnoringOtherApps:YES];