1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
42 #import "CompatibilityFixes.h"
48 #import "playlistinfo.h"
53 #import "coredialogs.h"
54 #import "embeddedwindow.h"
55 #import "AppleRemote.h"
57 #import "simple_prefs.h"
58 #import "CoreInteraction.h"
59 #import "TrackSynchronization.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 updateProgressPanel (void *, const char *, float);
70 static bool checkProgressPanel (void *);
71 static void destroyProgressPanel (void *);
73 static void MsgCallback( void *, const msg_item_t * );
75 static int InputEvent( vlc_object_t *, const char *,
76 vlc_value_t, vlc_value_t, void * );
77 static int PLItemChanged( vlc_object_t *, const char *,
78 vlc_value_t, vlc_value_t, void * );
79 static int PlaylistUpdated( vlc_object_t *, const char *,
80 vlc_value_t, vlc_value_t, void * );
81 static int PlaybackModeUpdated( vlc_object_t *, const char *,
82 vlc_value_t, vlc_value_t, void * );
83 static int VolumeUpdated( vlc_object_t *, const char *,
84 vlc_value_t, vlc_value_t, void * );
87 #pragma mark VLC Interface Object Callbacks
89 /*****************************************************************************
90 * OpenIntf: initialize interface
91 *****************************************************************************/
92 int OpenIntf ( vlc_object_t *p_this )
94 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
95 [VLCApplication sharedApplication];
96 intf_thread_t *p_intf = (intf_thread_t*) p_this;
98 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
99 if( p_intf->p_sys == NULL )
102 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
104 /* subscribe to LibVLCCore's messages */
105 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
106 p_intf->pf_run = Run;
107 p_intf->b_should_run_on_first_thread = true;
113 /*****************************************************************************
114 * CloseIntf: destroy interface
115 *****************************************************************************/
116 void CloseIntf ( vlc_object_t *p_this )
118 intf_thread_t *p_intf = (intf_thread_t*) p_this;
120 free( p_intf->p_sys );
123 static int WindowControl( vout_window_t *, int i_query, va_list );
125 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
127 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
128 intf_thread_t *p_intf = VLCIntf;
130 msg_Err( p_wnd, "Mac OS X interface not found" );
136 unsigned i_width = cfg->width;
137 unsigned i_height = cfg->height;
138 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
140 if ( !p_wnd->handle.nsobject ) {
141 msg_Err( p_wnd, "got no video view from the interface" );
146 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
147 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
148 p_wnd->control = WindowControl;
149 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
154 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
157 if( i_query == VOUT_WINDOW_SET_STATE )
158 NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
159 else if( i_query == VOUT_WINDOW_SET_SIZE )
161 NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
162 unsigned int i_width = va_arg( args, unsigned int );
163 unsigned int i_height = va_arg( args, unsigned int );
164 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
166 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
167 NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
169 NSLog( @"WindowControl: unknown query" );
173 void WindowClose( vout_window_t *p_wnd )
175 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
176 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
177 NSLog( @"Window Close" );
178 // tell the interface to get rid of the video, TODO
182 /*****************************************************************************
184 *****************************************************************************/
185 static NSLock * o_appLock = nil; // controls access to f_appExit
186 static int f_appExit = 0; // set to 1 when application termination signaled
188 static void Run( intf_thread_t *p_intf )
192 /* Make sure the "force quit" menu item does quit instantly.
193 * VLC overrides SIGTERM which is sent by the "force quit"
194 * menu item to make sure daemon mode quits gracefully, so
195 * we un-override SIGTERM here. */
197 sigaddset( &set, SIGTERM );
198 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
200 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
201 [VLCApplication sharedApplication];
203 o_appLock = [[NSLock alloc] init];
205 [[VLCMain sharedInstance] setIntf: p_intf];
206 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
209 [[VLCMain sharedInstance] applicationWillTerminate:nil];
215 #pragma mark Variables Callback
217 /*****************************************************************************
218 * MsgCallback: Callback triggered by the core once a new debug message is
219 * ready to be displayed. We store everything in a NSArray in our Cocoa part
221 *****************************************************************************/
222 static void MsgCallback( void *data, const msg_item_t *item )
224 int canc = vlc_savecancel();
226 /* this may happen from time to time, let's bail out as info would be useless anyway */
227 if( !item->psz_module || !item->psz_msg )
230 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
231 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item];
234 vlc_restorecancel( canc );
237 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
238 vlc_value_t oldval, vlc_value_t new_val, void *param )
240 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
241 switch (new_val.i_int) {
242 case INPUT_EVENT_STATE:
243 [[VLCMain sharedInstance] playbackStatusUpdated];
245 case INPUT_EVENT_RATE:
246 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
248 case INPUT_EVENT_POSITION:
249 [[VLCMain sharedInstance] updatePlaybackPosition];
251 case INPUT_EVENT_TITLE:
252 case INPUT_EVENT_CHAPTER:
253 [[VLCMain sharedInstance] updateMainMenu];
255 case INPUT_EVENT_CACHE:
256 [[VLCMain sharedInstance] updateMainWindow];
258 case INPUT_EVENT_STATISTICS:
259 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
263 case INPUT_EVENT_TELETEXT:
265 case INPUT_EVENT_AOUT:
267 case INPUT_EVENT_VOUT:
269 case INPUT_EVENT_ITEM_META:
270 case INPUT_EVENT_ITEM_INFO:
271 [[VLCMain sharedInstance] updateMainMenu];
272 [[VLCMain sharedInstance] updateName];
273 [[VLCMain sharedInstance] updateInfoandMetaPanel];
275 case INPUT_EVENT_BOOKMARK:
277 case INPUT_EVENT_RECORD:
278 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
280 case INPUT_EVENT_PROGRAM:
281 [[VLCMain sharedInstance] updateMainMenu];
283 case INPUT_EVENT_ITEM_EPG:
285 case INPUT_EVENT_SIGNAL:
288 case INPUT_EVENT_ITEM_NAME:
289 [[VLCMain sharedInstance] updateName];
290 [[VLCMain sharedInstance] playlistUpdated];
293 case INPUT_EVENT_AUDIO_DELAY:
294 case INPUT_EVENT_SUBTITLE_DELAY:
295 [[VLCMain sharedInstance] updateDelays];
298 case INPUT_EVENT_DEAD:
299 [[VLCMain sharedInstance] updateName];
300 [[VLCMain sharedInstance] updatePlaybackPosition];
303 case INPUT_EVENT_ABORT:
307 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
315 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
316 vlc_value_t oldval, vlc_value_t new_val, void *param )
318 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
319 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
325 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
326 vlc_value_t oldval, vlc_value_t new_val, void *param )
328 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
329 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
335 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
336 vlc_value_t oldval, vlc_value_t new_val, void *param )
338 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
339 [[VLCMain sharedInstance] playbackModeUpdated];
345 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
346 vlc_value_t oldval, vlc_value_t new_val, void *param )
348 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
349 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
355 /*****************************************************************************
356 * ShowController: Callback triggered by the show-intf playlist variable
357 * through the ShowIntf-control-intf, to let us show the controller-win;
358 * usually when in fullscreen-mode
359 *****************************************************************************/
360 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
361 vlc_value_t old_val, vlc_value_t new_val, void *param )
363 intf_thread_t * p_intf = VLCIntf;
364 if( p_intf && p_intf->p_sys )
366 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
371 /*****************************************************************************
372 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
373 * variable, to let the intf update the controller.
374 *****************************************************************************/
375 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
376 vlc_value_t old_val, vlc_value_t new_val, void *param )
378 intf_thread_t * p_intf = VLCIntf;
381 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
382 [[VLCMain sharedInstance] fullscreenChanged];
388 /*****************************************************************************
389 * DialogCallback: Callback triggered by the "dialog-*" variables
390 * to let the intf display error and interaction dialogs
391 *****************************************************************************/
392 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
394 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
395 VLCMain *interface = (VLCMain *)data;
397 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
399 /* the progress panel needs to update itself and therefore wants special treatment within this context */
400 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
402 p_dialog->pf_update = updateProgressPanel;
403 p_dialog->pf_check = checkProgressPanel;
404 p_dialog->pf_destroy = destroyProgressPanel;
405 p_dialog->p_sys = VLCIntf->p_libvlc;
408 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
409 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
415 void updateProgressPanel (void *priv, const char *text, float value)
417 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
421 o_txt = [NSString stringWithUTF8String: text];
425 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
430 void destroyProgressPanel (void *priv)
432 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
433 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
437 bool checkProgressPanel (void *priv)
439 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
440 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
447 input_thread_t *getInput(void)
449 intf_thread_t *p_intf = VLCIntf;
452 return pl_CurrentInput(p_intf);
455 vout_thread_t *getVout(void)
457 input_thread_t *p_input = getInput();
460 vout_thread_t *p_vout = input_GetVout(p_input);
461 vlc_object_release(p_input);
465 audio_output_t *getAout(void)
467 input_thread_t *p_input = getInput();
470 audio_output_t *p_aout = input_GetAout(p_input);
471 vlc_object_release(p_input);
478 @interface VLCMain ()
479 - (void)_removeOldPreferences;
482 /*****************************************************************************
483 * VLCMain implementation
484 *****************************************************************************/
485 @implementation VLCMain
488 #pragma mark Initialization
490 static VLCMain *_o_sharedMainInstance = nil;
492 + (VLCMain *)sharedInstance
494 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
499 if( _o_sharedMainInstance)
502 return _o_sharedMainInstance;
505 _o_sharedMainInstance = [super init];
509 o_msg_lock = [[NSLock alloc] init];
510 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
512 o_open = [[VLCOpen alloc] init];
513 //o_embedded_list = [[VLCEmbeddedList alloc] init];
514 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
515 o_info = [[VLCInfo alloc] init];
516 o_mainmenu = [[VLCMainMenu alloc] init];
517 o_coreinteraction = [[VLCCoreInteraction alloc] init];
518 o_eyetv = [[VLCEyeTVController alloc] init];
519 o_mainwindow = [[VLCMainWindow alloc] init];
521 /* announce our launch to a potential eyetv plugin */
522 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
523 object: @"VLCEyeTVSupport"
525 deliverImmediately: YES];
526 return _o_sharedMainInstance;
529 - (void)setIntf: (intf_thread_t *)p_mainintf {
533 - (intf_thread_t *)intf {
539 playlist_t *p_playlist;
541 if( !p_intf ) return;
542 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
544 /* Check if we already did this once. Opening the other nibs calls it too,
545 because VLCMain is the owner */
546 if( nib_main_loaded ) return;
548 [o_msgs_panel setExcludedFromWindowsMenu: YES];
549 [o_msgs_panel setDelegate: self];
551 p_playlist = pl_Get( p_intf );
555 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
556 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
557 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
558 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
559 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
560 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
561 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
562 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
563 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
564 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
565 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
566 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
567 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
569 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
570 var_SetBool( p_playlist, "fullscreen", YES );
572 /* load our Core Dialogs nib */
573 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
575 /* subscribe to various interactive dialogues */
576 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
577 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
578 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
579 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
580 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
581 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
582 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
583 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
584 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
585 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
586 dialog_Register( p_intf );
588 [self playbackModeUpdated];
590 /* init Apple Remote support */
591 o_remote = [[AppleRemote alloc] init];
592 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
593 [o_remote setDelegate: _o_sharedMainInstance];
595 /* yeah, we are done */
596 nib_main_loaded = TRUE;
599 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
601 if( !p_intf ) return;
603 /* init media key support */
604 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
605 if( b_mediaKeySupport )
607 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
608 [o_mediaKeyController startWatchingMediaKeys];
609 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
610 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
613 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
615 [self _removeOldPreferences];
617 [o_mainwindow updateWindow];
618 [o_mainwindow updateTimeSlider];
619 [o_mainwindow updateVolumeSlider];
620 [o_mainwindow makeKeyAndOrderFront: self];
622 /* Handle sleep notification */
623 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
624 name:NSWorkspaceWillSleepNotification object:nil];
626 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
631 if( !p_intf ) return;
634 [o_msgs_panel setTitle: _NS("Messages")];
635 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
636 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
638 /* crash reporter panel */
639 [o_crashrep_send_btn setTitle: _NS("Send")];
640 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
641 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
642 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
643 [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, ...")];
644 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
645 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
649 #pragma mark Termination
651 - (void)applicationWillTerminate:(NSNotification *)notification
653 playlist_t * p_playlist;
654 vout_thread_t * p_vout;
655 int returnedValue = 0;
660 // don't allow a double termination call. If the user has
661 // already invoked the quit then simply return this time.
662 int isTerminating = false;
665 isTerminating = (f_appExit++ > 0 ? 1 : 0);
671 msg_Dbg( p_intf, "Terminating" );
673 /* Make sure the intf object is getting killed */
674 vlc_object_kill( p_intf );
675 p_playlist = pl_Get( p_intf );
677 /* unsubscribe from the interactive dialogues */
678 dialog_Unregister( p_intf );
679 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
680 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
681 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
682 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
683 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
684 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
685 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
686 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
687 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
688 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
689 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
690 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
691 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
692 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
693 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
694 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
696 /* remove global observer watching for vout device changes correctly */
697 [[NSNotificationCenter defaultCenter] removeObserver: self];
699 /* release some other objects here, because it isn't sure whether dealloc
700 * will be called later on */
715 [crashLogURLConnection cancel];
716 [crashLogURLConnection release];
718 [o_embedded_list release];
719 [o_coredialogs release];
721 [o_mainwindow release];
723 /* unsubscribe from libvlc's debug messages */
724 vlc_Unsubscribe( p_intf->p_sys->p_sub );
726 [o_msg_arr removeAllObjects];
729 [o_msg_lock release];
731 /* write cached user defaults to disk */
732 [[NSUserDefaults standardUserDefaults] synchronize];
734 /* Make sure the Menu doesn't have any references to vlc objects anymore */
735 //FIXME: this should be moved to VLCMainMenu
736 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
737 [o_mainmenu release];
739 /* Kill the playlist, so that it doesn't accept new request
740 * such as the play request from vlc.c (we are a blocking interface). */
741 vlc_object_kill( p_playlist );
742 libvlc_Quit( p_intf->p_libvlc );
748 #pragma mark Sparkle delegate
749 /* received directly before the update gets installed, so let's shut down a bit */
750 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
752 [NSApp activateIgnoringOtherApps:YES];
753 [o_remote stopListening: self];
754 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
758 #pragma mark Media Key support
760 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
762 if( b_mediaKeySupport )
764 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
766 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
767 int keyFlags = ([event data1] & 0x0000FFFF);
768 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
769 int keyRepeat = (keyFlags & 0x1);
771 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
772 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
774 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
776 if( keyState == 0 && keyRepeat == 0 )
777 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
778 else if( keyRepeat == 1 )
780 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
781 b_mediakeyJustJumped = YES;
782 [self performSelector:@selector(resetMediaKeyJump)
788 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
790 if( keyState == 0 && keyRepeat == 0 )
791 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
792 else if( keyRepeat == 1 )
794 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
795 b_mediakeyJustJumped = YES;
796 [self performSelector:@selector(resetMediaKeyJump)
805 #pragma mark Other notification
807 /* Listen to the remote in exclusive mode, only when VLC is the active
809 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
811 if( !p_intf ) return;
812 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
813 [o_remote startListening: self];
815 - (void)applicationDidResignActive:(NSNotification *)aNotification
817 if( !p_intf ) return;
818 [o_remote stopListening: self];
821 /* Triggered when the computer goes to sleep */
822 - (void)computerWillSleep: (NSNotification *)notification
824 input_thread_t * p_input;
826 p_input = pl_CurrentInput( p_intf );
829 int state = var_GetInteger( p_input, "state" );
830 if( state == PLAYING_S )
831 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
832 vlc_object_release( p_input );
837 #pragma mark File opening
839 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
841 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
842 char *psz_uri = make_URI([o_filename UTF8String], "file" );
846 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
851 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
853 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
858 /* When user click in the Dock icon our double click in the finder */
859 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
861 if(!hasVisibleWindows)
862 [o_mainwindow makeKeyAndOrderFront:self];
868 #pragma mark Apple Remote Control
870 /* Helper method for the remote control interface in order to trigger forward/backward and volume
871 increase/decrease as long as the user holds the left/right, plus/minus button */
872 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
874 if(b_remote_button_hold)
876 switch([buttonIdentifierNumber intValue])
878 case kRemoteButtonRight_Hold:
879 [[VLCCoreInteraction sharedInstance] forward];
881 case kRemoteButtonLeft_Hold:
882 [[VLCCoreInteraction sharedInstance] backward];
884 case kRemoteButtonVolume_Plus_Hold:
885 [[VLCCoreInteraction sharedInstance] volumeUp];
887 case kRemoteButtonVolume_Minus_Hold:
888 [[VLCCoreInteraction sharedInstance] volumeDown];
891 if(b_remote_button_hold)
894 [self performSelector:@selector(executeHoldActionForRemoteButton:)
895 withObject:buttonIdentifierNumber
901 /* Apple Remote callback */
902 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
903 pressedDown: (BOOL) pressedDown
904 clickCount: (unsigned int) count
906 switch( buttonIdentifier )
908 case k2009RemoteButtonFullscreen:
909 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
911 case k2009RemoteButtonPlay:
912 [[VLCCoreInteraction sharedInstance] play];
914 case kRemoteButtonPlay:
916 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
918 [[VLCCoreInteraction sharedInstance] play];
921 case kRemoteButtonVolume_Plus:
922 [[VLCCoreInteraction sharedInstance] volumeUp];
924 case kRemoteButtonVolume_Minus:
925 [[VLCCoreInteraction sharedInstance] volumeDown];
927 case kRemoteButtonRight:
928 [[VLCCoreInteraction sharedInstance] next];
930 case kRemoteButtonLeft:
931 [[VLCCoreInteraction sharedInstance] previous];
933 case kRemoteButtonRight_Hold:
934 case kRemoteButtonLeft_Hold:
935 case kRemoteButtonVolume_Plus_Hold:
936 case kRemoteButtonVolume_Minus_Hold:
937 /* simulate an event as long as the user holds the button */
938 b_remote_button_hold = pressedDown;
941 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
942 [self performSelector:@selector(executeHoldActionForRemoteButton:)
943 withObject:buttonIdentifierNumber];
946 case kRemoteButtonMenu:
947 [o_controls showPosition: self]; //FIXME
950 /* Add here whatever you want other buttons to do */
956 #pragma mark String utility
957 // FIXME: this has nothing to do here
959 - (NSString *)localizedString:(const char *)psz
961 NSString * o_str = nil;
965 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
969 msg_Err( VLCIntf, "could not translate: %s", psz );
975 msg_Warn( VLCIntf, "can't translate empty strings" );
984 - (char *)delocalizeString:(NSString *)id
986 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
987 allowLossyConversion: NO];
992 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
993 allowLossyConversion: YES];
994 psz_string = malloc( [o_data length] + 1 );
995 [o_data getBytes: psz_string];
996 psz_string[ [o_data length] ] = '\0';
997 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1002 psz_string = malloc( [o_data length] + 1 );
1003 [o_data getBytes: psz_string];
1004 psz_string[ [o_data length] ] = '\0';
1010 /* i_width is in pixels */
1011 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1013 NSMutableString *o_wrapped;
1014 NSString *o_out_string;
1015 NSRange glyphRange, effectiveRange, charRange;
1016 NSRect lineFragmentRect;
1017 unsigned glyphIndex, breaksInserted = 0;
1019 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1020 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1021 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1022 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1023 NSTextContainer *o_container = [[NSTextContainer alloc]
1024 initWithContainerSize: NSMakeSize(i_width, 2000)];
1026 [o_layout_manager addTextContainer: o_container];
1027 [o_container release];
1028 [o_storage addLayoutManager: o_layout_manager];
1029 [o_layout_manager release];
1031 o_wrapped = [o_in_string mutableCopy];
1032 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1034 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1035 glyphIndex += effectiveRange.length) {
1036 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1037 effectiveRange: &effectiveRange];
1038 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1039 actualGlyphRange: &effectiveRange];
1040 if([o_wrapped lineRangeForRange:
1041 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1042 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1046 o_out_string = [NSString stringWithString: o_wrapped];
1047 [o_wrapped release];
1048 [o_storage release];
1050 return o_out_string;
1055 #pragma mark Key Shortcuts
1060 unsigned int i_vlckey;
1061 } nskeys_to_vlckeys[] =
1063 { NSUpArrowFunctionKey, KEY_UP },
1064 { NSDownArrowFunctionKey, KEY_DOWN },
1065 { NSLeftArrowFunctionKey, KEY_LEFT },
1066 { NSRightArrowFunctionKey, KEY_RIGHT },
1067 { NSF1FunctionKey, KEY_F1 },
1068 { NSF2FunctionKey, KEY_F2 },
1069 { NSF3FunctionKey, KEY_F3 },
1070 { NSF4FunctionKey, KEY_F4 },
1071 { NSF5FunctionKey, KEY_F5 },
1072 { NSF6FunctionKey, KEY_F6 },
1073 { NSF7FunctionKey, KEY_F7 },
1074 { NSF8FunctionKey, KEY_F8 },
1075 { NSF9FunctionKey, KEY_F9 },
1076 { NSF10FunctionKey, KEY_F10 },
1077 { NSF11FunctionKey, KEY_F11 },
1078 { NSF12FunctionKey, KEY_F12 },
1079 { NSInsertFunctionKey, KEY_INSERT },
1080 { NSHomeFunctionKey, KEY_HOME },
1081 { NSEndFunctionKey, KEY_END },
1082 { NSPageUpFunctionKey, KEY_PAGEUP },
1083 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1084 { NSMenuFunctionKey, KEY_MENU },
1085 { NSTabCharacter, KEY_TAB },
1086 { NSCarriageReturnCharacter, KEY_ENTER },
1087 { NSEnterCharacter, KEY_ENTER },
1088 { NSBackspaceCharacter, KEY_BACKSPACE },
1092 unsigned int CocoaKeyToVLC( unichar i_key )
1096 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1098 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1100 return nskeys_to_vlckeys[i].i_vlckey;
1103 return (unsigned int)i_key;
1106 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1108 unsigned int new = 0;
1110 if([theString rangeOfString:@"Command"].location != NSNotFound)
1111 new |= NSCommandKeyMask;
1112 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1113 new |= NSAlternateKeyMask;
1114 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1115 new |= NSShiftKeyMask;
1116 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1117 new |= NSControlKeyMask;
1121 - (NSString *)VLCKeyToString:(NSString *)theString
1123 if (![theString isEqualToString:@""]) {
1124 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1125 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1126 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1127 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1128 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1129 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1135 /*****************************************************************************
1136 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1137 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1138 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1139 *****************************************************************************/
1140 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1144 unsigned int i_pressed_modifiers = 0;
1145 const struct hotkey *p_hotkeys;
1147 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1148 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1151 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1153 i_pressed_modifiers = [o_event modifierFlags];
1155 if( i_pressed_modifiers & NSShiftKeyMask ) {
1156 val.i_int |= KEY_MODIFIER_SHIFT;
1157 [tempString appendString:@"Shift-"];
1158 [tempStringPlus appendString:@"Shift+"];
1160 if( i_pressed_modifiers & NSControlKeyMask ) {
1161 val.i_int |= KEY_MODIFIER_CTRL;
1162 [tempString appendString:@"Ctrl-"];
1163 [tempStringPlus appendString:@"Ctrl+"];
1165 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1166 val.i_int |= KEY_MODIFIER_ALT;
1167 [tempString appendString:@"Alt-"];
1168 [tempStringPlus appendString:@"Alt+"];
1170 if( i_pressed_modifiers & NSCommandKeyMask ) {
1171 val.i_int |= KEY_MODIFIER_COMMAND;
1172 [tempString appendString:@"Command-"];
1173 [tempStringPlus appendString:@"Command+"];
1176 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1177 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1179 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1183 case NSDeleteCharacter:
1184 case NSDeleteFunctionKey:
1185 case NSDeleteCharFunctionKey:
1186 case NSBackspaceCharacter:
1187 case NSUpArrowFunctionKey:
1188 case NSDownArrowFunctionKey:
1189 case NSRightArrowFunctionKey:
1190 case NSLeftArrowFunctionKey:
1191 case NSEnterCharacter:
1192 case NSCarriageReturnCharacter:
1196 val.i_int |= CocoaKeyToVLC( key );
1198 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1200 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1207 - (void)updateCurrentlyUsedHotkeys
1209 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1210 /* Get the main Module */
1211 module_t *p_main = module_get_main();
1214 module_config_t *p_config;
1216 p_config = module_config_get (p_main, &confsize);
1218 for (size_t i = 0; i < confsize; i++)
1220 module_config_t *p_item = p_config + i;
1222 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1223 && !strncmp( p_item->psz_name , "key-", 4 )
1224 && !EMPTY_STR( p_item->psz_text ) )
1226 if (p_item->value.psz)
1227 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1230 module_config_free (p_config);
1231 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1235 #pragma mark Interface updaters
1236 - (void)fullscreenChanged
1238 playlist_t * p_playlist = pl_Get( VLCIntf );
1239 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1243 [o_mainwindow toggleFullScreen: self];
1245 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1247 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1251 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1253 if( p_input != NULL )
1256 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1258 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1259 vlc_object_release( p_input );
1264 - (void)PlaylistItemChanged
1266 input_thread_t * p_input;
1268 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1269 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1271 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1272 [o_mainmenu setRateControlsEnabled: YES];
1273 vlc_object_release( p_input );
1276 [o_mainmenu setRateControlsEnabled: NO];
1278 [o_playlist updateRowSelection];
1279 [o_mainwindow updateWindow];
1280 [self updateMainMenu];
1283 - (void)updateMainMenu
1285 [o_mainmenu setupMenus];
1286 [o_mainmenu updatePlaybackRate];
1289 - (void)updateMainWindow
1291 [o_mainwindow updateWindow];
1294 - (void)showFullscreenController
1296 [o_mainwindow showFullscreenController];
1299 - (void)updateDelays
1301 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1306 [o_mainwindow updateName];
1309 - (void)updatePlaybackPosition
1311 [o_mainwindow updateTimeSlider];
1313 input_thread_t * p_input;
1314 p_input = pl_CurrentInput( p_intf );
1317 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1318 UpdateSystemActivity( UsrActivity );
1319 vlc_object_release( p_input );
1323 - (void)updateVolume
1325 [o_mainwindow updateVolumeSlider];
1328 - (void)playlistUpdated
1330 [self playbackStatusUpdated];
1331 [o_playlist playlistUpdated];
1332 [o_mainwindow updateWindow];
1335 - (void)updateRecordState: (BOOL)b_value
1337 [o_mainmenu updateRecordState:b_value];
1340 - (void)updateInfoandMetaPanel
1342 [o_playlist outlineViewSelectionDidChange:nil];
1345 - (void)playbackStatusUpdated
1347 input_thread_t * p_input;
1349 p_input = pl_CurrentInput( p_intf );
1352 int state = var_GetInteger( p_input, "state" );
1353 if( state == PLAYING_S )
1355 [[self mainMenu] setPause];
1356 [o_mainwindow setPause];
1361 [o_mainmenu setSubmenusEnabled: FALSE];
1362 [[self mainMenu] setPlay];
1363 [o_mainwindow setPlay];
1365 vlc_object_release( p_input );
1369 - (void)playbackModeUpdated
1371 vlc_value_t looping,repeating;
1372 playlist_t * p_playlist = pl_Get( VLCIntf );
1374 bool loop = var_GetBool( p_playlist, "loop" );
1375 bool repeat = var_GetBool( p_playlist, "repeat" );
1377 [o_mainwindow setRepeatOne];
1378 [o_mainmenu setRepeatOne];
1380 [o_mainwindow setRepeatAll];
1381 [o_mainmenu setRepeatAll];
1383 [o_mainwindow setRepeatOff];
1384 [o_mainmenu setRepeatOff];
1387 [o_mainwindow setShuffle];
1388 [o_mainmenu setShuffle];
1392 #pragma mark Other objects getters
1410 o_bookmarks = [[VLCBookmarks alloc] init];
1412 if( !nib_bookmarks_loaded )
1413 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1423 if (!nib_open_loaded)
1424 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1429 - (id)simplePreferences
1432 o_sprefs = [[VLCSimplePrefs alloc] init];
1434 if (!nib_prefs_loaded)
1435 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1443 o_prefs = [[VLCPrefs alloc] init];
1445 if( !nib_prefs_loaded )
1446 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1461 if(! nib_info_loaded )
1462 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1473 o_wizard = [[VLCWizard alloc] init];
1475 if( !nib_wizard_loaded )
1477 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1478 [o_wizard initStrings];
1483 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1485 id videoView = [o_mainwindow videoView];
1486 NSRect videoRect = [videoView frame];
1487 int i_x = (int)videoRect.origin.x;
1488 int i_y = (int)videoRect.origin.y;
1489 unsigned int i_width = (int)videoRect.size.width;
1490 unsigned int i_height = (int)videoRect.size.height;
1493 pi_width = (unsigned int*)i_width;
1494 pi_height = (unsigned int*)i_height;
1495 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1499 - (void)setNativeVideoSize:(NSSize)size
1501 [o_mainwindow setNativeVideoSize:size];
1506 if( o_embedded_list )
1507 return o_embedded_list;
1512 - (id)coreDialogProvider
1515 return o_coredialogs;
1520 - (id)eyeTVController
1528 - (id)appleRemoteController
1533 - (void)setActiveVideoPlayback:(BOOL)b_value
1535 b_active_videoplayback = b_value;
1536 [o_mainwindow setVideoplayEnabled];
1537 [o_mainwindow togglePlaylist:nil];
1540 - (BOOL)activeVideoPlayback
1542 return b_active_videoplayback;
1546 #pragma mark Crash Log
1547 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1549 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1550 NSURL *url = [NSURL URLWithString:urlStr];
1552 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1553 [req setHTTPMethod:@"POST"];
1556 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1558 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1559 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1560 email = [emails valueAtIndex:[emails indexForIdentifier:
1561 [emails primaryIdentifier]]];
1564 email = [NSString string];
1567 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1568 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1569 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1570 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1572 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1574 /* Released from delegate */
1575 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1578 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1580 [crashLogURLConnection release];
1581 crashLogURLConnection = nil;
1584 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1586 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1587 [crashLogURLConnection release];
1588 crashLogURLConnection = nil;
1591 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1593 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1594 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1596 NSString * latestLog = nil;
1597 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1598 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1599 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1600 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1602 while (fname = [direnum nextObject])
1604 [direnum skipDescendents];
1605 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1607 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1608 if( [compo count] < 3 ) continue;
1609 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1610 if( [compo count] < 4 ) continue;
1613 if( year < [[compo objectAtIndex:0] intValue] ||
1614 (year ==[[compo objectAtIndex:0] intValue] &&
1615 (month < [[compo objectAtIndex:1] intValue] ||
1616 (month ==[[compo objectAtIndex:1] intValue] &&
1617 (day < [[compo objectAtIndex:2] intValue] ||
1618 (day ==[[compo objectAtIndex:2] intValue] &&
1619 hours < [[compo objectAtIndex:3] intValue] ))))))
1621 year = [[compo objectAtIndex:0] intValue];
1622 month = [[compo objectAtIndex:1] intValue];
1623 day = [[compo objectAtIndex:2] intValue];
1624 hours = [[compo objectAtIndex:3] intValue];
1625 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1630 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1633 if( !previouslySeen )
1635 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1636 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1637 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1638 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1643 - (NSString *)latestCrashLogPath
1645 return [self latestCrashLogPathPreviouslySeen:YES];
1648 - (void)lookForCrashLog
1650 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1651 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1652 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1653 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1654 if( latestLog && !areCrashLogsTooOld )
1655 [NSApp runModalForWindow: o_crashrep_win];
1659 - (IBAction)crashReporterAction:(id)sender
1661 if( sender == o_crashrep_send_btn )
1662 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1665 [o_crashrep_win orderOut: sender];
1668 - (IBAction)openCrashLog:(id)sender
1670 NSString * latestLog = [self latestCrashLogPath];
1673 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1677 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.") );
1682 #pragma mark Remove old prefs
1684 - (void)_removeOldPreferences
1686 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1687 static const int kCurrentPreferencesVersion = 1;
1688 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1689 if( version >= kCurrentPreferencesVersion ) return;
1691 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1692 NSUserDomainMask, YES);
1693 if( !libraries || [libraries count] == 0) return;
1694 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1696 /* File not found, don't attempt anything */
1697 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1698 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1700 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1704 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1705 _NS("We just found an older version of VLC's preferences files."),
1706 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1707 if( res != NSOKButton )
1709 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1713 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1715 /* Move the file to trash so that user can find them later */
1716 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1718 /* really reset the defaults from now on */
1719 [NSUserDefaults resetStandardUserDefaults];
1721 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1722 [[NSUserDefaults standardUserDefaults] synchronize];
1725 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1727 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1733 execl(path, path, NULL);
1737 #pragma mark Errors, warnings and messages
1738 - (IBAction)showMessagesPanel:(id)sender
1740 [o_msgs_panel makeKeyAndOrderFront: sender];
1743 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1745 if( [o_notification object] == o_msgs_panel )
1746 [self updateMessageDisplay];
1749 - (void)updateMessageDisplay
1751 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1754 NSEnumerator * o_enum;
1756 [o_messages setString: @""];
1760 o_enum = [o_msg_arr objectEnumerator];
1762 while( ( o_msg = [o_enum nextObject] ) != nil )
1764 [o_messages insertText: o_msg];
1767 b_msg_arr_changed = NO;
1768 [o_msg_lock unlock];
1772 - (void)processReceivedlibvlcMessage:(const msg_item_t *)item
1774 NSColor *o_white = [NSColor whiteColor];
1775 NSColor *o_red = [NSColor redColor];
1776 NSColor *o_yellow = [NSColor yellowColor];
1777 NSColor *o_gray = [NSColor grayColor];
1779 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1780 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1782 NSDictionary *o_attr;
1783 NSAttributedString *o_msg_color;
1785 int i_type = item->i_type;
1789 if( [o_msg_arr count] + 2 > 600 )
1791 [o_msg_arr removeObjectAtIndex: 0];
1792 [o_msg_arr removeObjectAtIndex: 1];
1795 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1796 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1797 [o_msg_arr addObject: [o_msg_color autorelease]];
1799 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1800 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", item->psz_msg] attributes: o_attr];
1801 [o_msg_arr addObject: [o_msg_color autorelease]];
1803 b_msg_arr_changed = YES;
1804 [o_msg_lock unlock];
1806 [self updateMessageDisplay];
1809 - (IBAction)saveDebugLog:(id)sender
1811 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1813 [saveFolderPanel setCanSelectHiddenExtension: NO];
1814 [saveFolderPanel setCanCreateDirectories: YES];
1815 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1816 [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];
1819 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1822 if( returnCode == NSOKButton )
1824 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1826 msg_Warn( p_intf, "Error while saving the debug log" );
1831 #pragma mark Playlist toggling
1833 - (void)updateTogglePlaylistState
1835 [[self playlist] outlineViewSelectionDidChange: NULL];
1842 @implementation VLCMain (Internal)
1844 - (void)handlePortMessage:(NSPortMessage *)o_msg
1849 NSInvocation * o_inv;
1850 NSConditionLock * o_lock;
1852 o_data = [[o_msg components] lastObject];
1853 o_inv = *((NSInvocation **)[o_data bytes]);
1854 [o_inv getArgument: &o_value atIndex: 2];
1855 val = (id **)[o_value pointerValue];
1856 [o_inv setArgument: val[1] atIndex: 2];
1861 [o_lock unlockWithCondition: 1];
1863 - (void)resetMediaKeyJump
1865 b_mediakeyJustJumped = NO;
1867 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1869 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1870 if (b_mediaKeySupport) {
1871 if (!o_mediaKeyController)
1872 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1873 [o_mediaKeyController startWatchingMediaKeys];
1875 else if (!b_mediaKeySupport && o_mediaKeyController)
1877 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1878 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1879 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1880 if( returnedValue == NSOKButton )
1883 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1885 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1891 execl(path, path, NULL);
1898 /*****************************************************************************
1899 * VLCApplication interface
1900 *****************************************************************************/
1902 @implementation VLCApplication
1903 // when user selects the quit menu from dock it sends a terminate:
1904 // but we need to send a stop: to properly exits libvlc.
1905 // However, we are not able to change the action-method sent by this standard menu item.
1906 // thus we override terminat: to send a stop:
1907 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1908 - (void)terminate:(id)sender
1910 [self activateIgnoringOtherApps:YES];