1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 VLC authors and VideoLAN
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
34 #include <stdlib.h> /* malloc(), free() */
35 #include <sys/param.h> /* for MAXPATHLEN */
37 #include <vlc_common.h>
39 #include <vlc_dialog.h>
41 #include <vlc_modules.h>
42 #include <vlc_aout_intf.h>
43 #include <vlc_vout_window.h>
44 #include <unistd.h> /* execl() */
46 #import "CompatibilityFixes.h"
52 #import "playlistinfo.h"
57 #import "coredialogs.h"
58 #import "AppleRemote.h"
60 #import "simple_prefs.h"
61 #import "CoreInteraction.h"
62 #import "TrackSynchronization.h"
64 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
66 # import <Sparkle/Sparkle.h> /* we're the update delegate */
69 /*****************************************************************************
71 *****************************************************************************/
72 static void Run ( intf_thread_t *p_intf );
74 static void updateProgressPanel (void *, const char *, float);
75 static bool checkProgressPanel (void *);
76 static void destroyProgressPanel (void *);
78 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
80 static int InputEvent( vlc_object_t *, const char *,
81 vlc_value_t, vlc_value_t, void * );
82 static int PLItemChanged( vlc_object_t *, const char *,
83 vlc_value_t, vlc_value_t, void * );
84 static int PlaylistUpdated( vlc_object_t *, const char *,
85 vlc_value_t, vlc_value_t, void * );
86 static int PlaybackModeUpdated( vlc_object_t *, const char *,
87 vlc_value_t, vlc_value_t, void * );
88 static int VolumeUpdated( vlc_object_t *, const char *,
89 vlc_value_t, vlc_value_t, void * );
92 #pragma mark VLC Interface Object Callbacks
94 /*****************************************************************************
95 * OpenIntf: initialize interface
96 *****************************************************************************/
97 int OpenIntf ( vlc_object_t *p_this )
99 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
100 [VLCApplication sharedApplication];
101 intf_thread_t *p_intf = (intf_thread_t*) p_this;
103 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
104 if( p_intf->p_sys == NULL )
107 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
109 /* subscribe to LibVLCCore's messages */
110 p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
111 p_intf->pf_run = Run;
112 p_intf->b_should_run_on_first_thread = true;
118 /*****************************************************************************
119 * CloseIntf: destroy interface
120 *****************************************************************************/
121 void CloseIntf ( vlc_object_t *p_this )
123 intf_thread_t *p_intf = (intf_thread_t*) p_this;
125 free( p_intf->p_sys );
128 static int WindowControl( vout_window_t *, int i_query, va_list );
130 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
132 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
133 intf_thread_t *p_intf = VLCIntf;
135 msg_Err( p_wnd, "Mac OS X interface not found" );
141 unsigned i_width = cfg->width;
142 unsigned i_height = cfg->height;
143 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
145 if ( !p_wnd->handle.nsobject ) {
146 msg_Err( p_wnd, "got no video view from the interface" );
151 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
152 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
153 p_wnd->control = WindowControl;
154 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
159 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
162 if( i_query == VOUT_WINDOW_SET_STATE )
163 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
164 else if( i_query == VOUT_WINDOW_SET_SIZE )
166 unsigned int i_width = va_arg( args, unsigned int );
167 unsigned int i_height = va_arg( args, unsigned int );
168 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
170 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
171 msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
173 msg_Dbg( p_wnd, "WindowControl: unknown query" );
177 void WindowClose( vout_window_t *p_wnd )
179 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
180 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
185 /*****************************************************************************
187 *****************************************************************************/
188 static NSLock * o_appLock = nil; // controls access to f_appExit
189 static int f_appExit = 0; // set to 1 when application termination signaled
191 static void Run( intf_thread_t *p_intf )
195 /* Make sure the "force quit" menu item does quit instantly.
196 * VLC overrides SIGTERM which is sent by the "force quit"
197 * menu item to make sure daemon mode quits gracefully, so
198 * we un-override SIGTERM here. */
200 sigaddset( &set, SIGTERM );
201 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
203 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
204 [VLCApplication sharedApplication];
206 o_appLock = [[NSLock alloc] init];
208 [[VLCMain sharedInstance] setIntf: p_intf];
209 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
212 [[VLCMain sharedInstance] applicationWillTerminate:nil];
218 #pragma mark Variables Callback
220 /*****************************************************************************
221 * MsgCallback: Callback triggered by the core once a new debug message is
222 * ready to be displayed. We store everything in a NSArray in our Cocoa part
224 *****************************************************************************/
225 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
227 int canc = vlc_savecancel();
230 if (vasprintf( &str, format, ap ) == -1)
232 vlc_restorecancel( canc );
236 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
237 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
240 vlc_restorecancel( canc );
244 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
245 vlc_value_t oldval, vlc_value_t new_val, void *param )
247 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
248 switch (new_val.i_int) {
249 case INPUT_EVENT_STATE:
250 [[VLCMain sharedInstance] playbackStatusUpdated];
252 case INPUT_EVENT_RATE:
253 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
255 case INPUT_EVENT_POSITION:
256 [[VLCMain sharedInstance] updatePlaybackPosition];
258 case INPUT_EVENT_TITLE:
259 case INPUT_EVENT_CHAPTER:
260 [[VLCMain sharedInstance] updateMainMenu];
262 case INPUT_EVENT_CACHE:
263 [[VLCMain sharedInstance] updateMainWindow];
265 case INPUT_EVENT_STATISTICS:
266 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
270 case INPUT_EVENT_TELETEXT:
272 case INPUT_EVENT_AOUT:
274 case INPUT_EVENT_VOUT:
276 case INPUT_EVENT_ITEM_META:
277 case INPUT_EVENT_ITEM_INFO:
278 [[VLCMain sharedInstance] updateMainMenu];
279 [[VLCMain sharedInstance] updateName];
280 [[VLCMain sharedInstance] updateInfoandMetaPanel];
282 case INPUT_EVENT_BOOKMARK:
284 case INPUT_EVENT_RECORD:
285 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
287 case INPUT_EVENT_PROGRAM:
288 [[VLCMain sharedInstance] updateMainMenu];
290 case INPUT_EVENT_ITEM_EPG:
292 case INPUT_EVENT_SIGNAL:
295 case INPUT_EVENT_ITEM_NAME:
296 [[VLCMain sharedInstance] updateName];
297 [[VLCMain sharedInstance] playlistUpdated];
300 case INPUT_EVENT_AUDIO_DELAY:
301 case INPUT_EVENT_SUBTITLE_DELAY:
302 [[VLCMain sharedInstance] updateDelays];
305 case INPUT_EVENT_DEAD:
306 [[VLCMain sharedInstance] updateName];
307 [[VLCMain sharedInstance] updatePlaybackPosition];
310 case INPUT_EVENT_ABORT:
311 [[VLCMain sharedInstance] updateName];
312 [[VLCMain sharedInstance] updatePlaybackPosition];
316 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
324 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
325 vlc_value_t oldval, vlc_value_t new_val, void *param )
327 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
328 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
334 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
335 vlc_value_t oldval, vlc_value_t new_val, void *param )
337 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
338 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
344 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
345 vlc_value_t oldval, vlc_value_t new_val, void *param )
347 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
348 [[VLCMain sharedInstance] playbackModeUpdated];
354 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
355 vlc_value_t oldval, vlc_value_t new_val, void *param )
357 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
358 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
364 /*****************************************************************************
365 * ShowController: Callback triggered by the show-intf playlist variable
366 * through the ShowIntf-control-intf, to let us show the controller-win;
367 * usually when in fullscreen-mode
368 *****************************************************************************/
369 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
370 vlc_value_t old_val, vlc_value_t new_val, void *param )
372 intf_thread_t * p_intf = VLCIntf;
373 if( p_intf && p_intf->p_sys )
375 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
380 /*****************************************************************************
381 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
382 * variable, to let the intf update the controller.
383 *****************************************************************************/
384 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
385 vlc_value_t old_val, vlc_value_t new_val, void *param )
387 intf_thread_t * p_intf = VLCIntf;
390 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
391 [[VLCMain sharedInstance] fullscreenChanged];
397 /*****************************************************************************
398 * DialogCallback: Callback triggered by the "dialog-*" variables
399 * to let the intf display error and interaction dialogs
400 *****************************************************************************/
401 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
403 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
404 VLCMain *interface = (VLCMain *)data;
406 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
408 /* the progress panel needs to update itself and therefore wants special treatment within this context */
409 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
411 p_dialog->pf_update = updateProgressPanel;
412 p_dialog->pf_check = checkProgressPanel;
413 p_dialog->pf_destroy = destroyProgressPanel;
414 p_dialog->p_sys = VLCIntf->p_libvlc;
417 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
418 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
424 void updateProgressPanel (void *priv, const char *text, float value)
426 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
430 o_txt = [NSString stringWithUTF8String: text];
434 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
439 void destroyProgressPanel (void *priv)
441 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
442 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
446 bool checkProgressPanel (void *priv)
448 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
449 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
456 input_thread_t *getInput(void)
458 intf_thread_t *p_intf = VLCIntf;
461 return pl_CurrentInput(p_intf);
464 vout_thread_t *getVout(void)
466 input_thread_t *p_input = getInput();
469 vout_thread_t *p_vout = input_GetVout(p_input);
470 vlc_object_release(p_input);
474 audio_output_t *getAout(void)
476 input_thread_t *p_input = getInput();
479 audio_output_t *p_aout = input_GetAout(p_input);
480 vlc_object_release(p_input);
487 @interface VLCMain ()
488 - (void)_removeOldPreferences;
491 /*****************************************************************************
492 * VLCMain implementation
493 *****************************************************************************/
494 @implementation VLCMain
497 #pragma mark Initialization
499 static VLCMain *_o_sharedMainInstance = nil;
501 + (VLCMain *)sharedInstance
503 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
508 if( _o_sharedMainInstance)
511 return _o_sharedMainInstance;
514 _o_sharedMainInstance = [super init];
518 o_msg_lock = [[NSLock alloc] init];
519 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
521 o_open = [[VLCOpen alloc] init];
522 //o_embedded_list = [[VLCEmbeddedList alloc] init];
523 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
524 o_info = [[VLCInfo alloc] init];
525 o_mainmenu = [[VLCMainMenu alloc] init];
526 o_coreinteraction = [[VLCCoreInteraction alloc] init];
527 o_eyetv = [[VLCEyeTVController alloc] init];
528 o_mainwindow = [[VLCMainWindow alloc] init];
530 /* announce our launch to a potential eyetv plugin */
531 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
532 object: @"VLCEyeTVSupport"
534 deliverImmediately: YES];
535 return _o_sharedMainInstance;
538 - (void)setIntf: (intf_thread_t *)p_mainintf {
542 - (intf_thread_t *)intf {
548 playlist_t *p_playlist;
550 if( !p_intf ) return;
551 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
553 /* Check if we already did this once. Opening the other nibs calls it too,
554 because VLCMain is the owner */
555 if( nib_main_loaded ) return;
557 [o_msgs_panel setExcludedFromWindowsMenu: YES];
558 [o_msgs_panel setDelegate: self];
560 p_playlist = pl_Get( p_intf );
564 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
565 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
566 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
567 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
568 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
569 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
570 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
571 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
572 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
573 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
574 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
575 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
576 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
580 if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
581 var_SetBool( p_playlist, "fullscreen", YES );
584 /* load our Core Dialogs nib */
585 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
587 /* subscribe to various interactive dialogues */
588 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
589 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
590 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
591 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
592 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
593 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
594 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
595 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
596 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
597 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
598 dialog_Register( p_intf );
600 [self playbackModeUpdated];
602 /* init Apple Remote support */
603 o_remote = [[AppleRemote alloc] init];
604 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
605 [o_remote setDelegate: _o_sharedMainInstance];
607 /* yeah, we are done */
608 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
609 nib_main_loaded = TRUE;
612 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
614 if( !p_intf ) return;
616 /* init media key support */
617 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
618 if( b_mediaKeySupport )
620 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
621 [o_mediaKeyController startWatchingMediaKeys];
622 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
623 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
626 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
628 [self _removeOldPreferences];
630 [o_mainwindow updateWindow];
631 [o_mainwindow updateTimeSlider];
632 [o_mainwindow updateVolumeSlider];
633 [o_mainwindow makeKeyAndOrderFront: self];
635 /* Handle sleep notification */
636 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
637 name:NSWorkspaceWillSleepNotification object:nil];
639 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
644 if( !p_intf ) return;
647 [o_msgs_panel setTitle: _NS("Messages")];
648 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
649 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
651 /* crash reporter panel */
652 [o_crashrep_send_btn setTitle: _NS("Send")];
653 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
654 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
655 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
656 [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, ...")];
657 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
658 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
662 #pragma mark Termination
664 - (void)applicationWillTerminate:(NSNotification *)notification
666 playlist_t * p_playlist;
667 vout_thread_t * p_vout;
668 int returnedValue = 0;
674 config_SaveConfigFile( p_intf );
676 // don't allow a double termination call. If the user has
677 // already invoked the quit then simply return this time.
678 int isTerminating = false;
681 isTerminating = (f_appExit++ > 0 ? 1 : 0);
687 msg_Dbg( p_intf, "Terminating" );
689 /* Make sure the intf object is getting killed */
690 vlc_object_kill( p_intf );
691 p_playlist = pl_Get( p_intf );
693 /* unsubscribe from the interactive dialogues */
694 dialog_Unregister( p_intf );
695 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
696 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
697 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
698 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
699 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
700 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
701 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
702 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
703 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
704 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
705 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
706 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
707 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
708 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
709 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
710 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
711 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
712 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
714 /* remove global observer watching for vout device changes correctly */
715 [[NSNotificationCenter defaultCenter] removeObserver: self];
717 /* release some other objects here, because it isn't sure whether dealloc
718 * will be called later on */
733 [crashLogURLConnection cancel];
734 [crashLogURLConnection release];
736 [o_embedded_list release];
737 [o_coredialogs release];
739 [o_mainwindow release];
741 /* unsubscribe from libvlc's debug messages */
742 vlc_Unsubscribe( p_intf->p_sys->p_sub );
744 [o_msg_arr removeAllObjects];
747 [o_msg_lock release];
749 /* write cached user defaults to disk */
750 [[NSUserDefaults standardUserDefaults] synchronize];
752 /* Make sure the Menu doesn't have any references to vlc objects anymore */
753 //FIXME: this should be moved to VLCMainMenu
754 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
755 [o_mainmenu release];
757 /* Kill the playlist, so that it doesn't accept new request
758 * such as the play request from vlc.c (we are a blocking interface). */
759 vlc_object_kill( p_playlist );
760 libvlc_Quit( p_intf->p_libvlc );
765 #ifdef HAVE_SPARKLE_H
767 #pragma mark Sparkle delegate
768 /* received directly before the update gets installed, so let's shut down a bit */
769 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
771 [NSApp activateIgnoringOtherApps:YES];
772 [o_remote stopListening: self];
773 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
778 #pragma mark Media Key support
780 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
782 if( b_mediaKeySupport )
784 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
786 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
787 int keyFlags = ([event data1] & 0x0000FFFF);
788 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
789 int keyRepeat = (keyFlags & 0x1);
791 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
792 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
794 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
796 if( keyState == 0 && keyRepeat == 0 )
797 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
798 else if( keyRepeat == 1 )
800 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
801 b_mediakeyJustJumped = YES;
802 [self performSelector:@selector(resetMediaKeyJump)
808 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
810 if( keyState == 0 && keyRepeat == 0 )
811 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
812 else if( keyRepeat == 1 )
814 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
815 b_mediakeyJustJumped = YES;
816 [self performSelector:@selector(resetMediaKeyJump)
825 #pragma mark Other notification
827 /* Listen to the remote in exclusive mode, only when VLC is the active
829 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
831 if( !p_intf ) return;
832 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
833 [o_remote startListening: self];
835 - (void)applicationDidResignActive:(NSNotification *)aNotification
837 if( !p_intf ) return;
838 [o_remote stopListening: self];
841 /* Triggered when the computer goes to sleep */
842 - (void)computerWillSleep: (NSNotification *)notification
844 input_thread_t * p_input;
846 p_input = pl_CurrentInput( p_intf );
849 int state = var_GetInteger( p_input, "state" );
850 if( state == PLAYING_S )
851 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
852 vlc_object_release( p_input );
857 #pragma mark File opening
859 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
861 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
862 char *psz_uri = make_URI([o_filename UTF8String], "file" );
866 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
871 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
873 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
878 /* When user click in the Dock icon our double click in the finder */
879 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
881 if(!hasVisibleWindows)
882 [o_mainwindow makeKeyAndOrderFront:self];
888 #pragma mark Apple Remote Control
890 /* Helper method for the remote control interface in order to trigger forward/backward and volume
891 increase/decrease as long as the user holds the left/right, plus/minus button */
892 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
894 if(b_remote_button_hold)
896 switch([buttonIdentifierNumber intValue])
898 case kRemoteButtonRight_Hold:
899 [[VLCCoreInteraction sharedInstance] forward];
901 case kRemoteButtonLeft_Hold:
902 [[VLCCoreInteraction sharedInstance] backward];
904 case kRemoteButtonVolume_Plus_Hold:
905 [[VLCCoreInteraction sharedInstance] volumeUp];
907 case kRemoteButtonVolume_Minus_Hold:
908 [[VLCCoreInteraction sharedInstance] volumeDown];
911 if(b_remote_button_hold)
914 [self performSelector:@selector(executeHoldActionForRemoteButton:)
915 withObject:buttonIdentifierNumber
921 /* Apple Remote callback */
922 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
923 pressedDown: (BOOL) pressedDown
924 clickCount: (unsigned int) count
926 switch( buttonIdentifier )
928 case k2009RemoteButtonFullscreen:
929 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
931 case k2009RemoteButtonPlay:
932 [[VLCCoreInteraction sharedInstance] play];
934 case kRemoteButtonPlay:
936 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
938 [[VLCCoreInteraction sharedInstance] play];
941 case kRemoteButtonVolume_Plus:
942 [[VLCCoreInteraction sharedInstance] volumeUp];
944 case kRemoteButtonVolume_Minus:
945 [[VLCCoreInteraction sharedInstance] volumeDown];
947 case kRemoteButtonRight:
948 [[VLCCoreInteraction sharedInstance] next];
950 case kRemoteButtonLeft:
951 [[VLCCoreInteraction sharedInstance] previous];
953 case kRemoteButtonRight_Hold:
954 case kRemoteButtonLeft_Hold:
955 case kRemoteButtonVolume_Plus_Hold:
956 case kRemoteButtonVolume_Minus_Hold:
957 /* simulate an event as long as the user holds the button */
958 b_remote_button_hold = pressedDown;
961 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
962 [self performSelector:@selector(executeHoldActionForRemoteButton:)
963 withObject:buttonIdentifierNumber];
966 case kRemoteButtonMenu:
967 [o_controls showPosition: self]; //FIXME
970 /* Add here whatever you want other buttons to do */
976 #pragma mark String utility
977 // FIXME: this has nothing to do here
979 - (NSString *)localizedString:(const char *)psz
981 NSString * o_str = nil;
985 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
989 msg_Err( VLCIntf, "could not translate: %s", psz );
995 msg_Warn( VLCIntf, "can't translate empty strings" );
1004 - (char *)delocalizeString:(NSString *)id
1006 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1007 allowLossyConversion: NO];
1012 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1013 allowLossyConversion: YES];
1014 psz_string = malloc( [o_data length] + 1 );
1015 [o_data getBytes: psz_string];
1016 psz_string[ [o_data length] ] = '\0';
1017 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1022 psz_string = malloc( [o_data length] + 1 );
1023 [o_data getBytes: psz_string];
1024 psz_string[ [o_data length] ] = '\0';
1030 /* i_width is in pixels */
1031 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1033 NSMutableString *o_wrapped;
1034 NSString *o_out_string;
1035 NSRange glyphRange, effectiveRange, charRange;
1036 NSRect lineFragmentRect;
1037 unsigned glyphIndex, breaksInserted = 0;
1039 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1040 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1041 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1042 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1043 NSTextContainer *o_container = [[NSTextContainer alloc]
1044 initWithContainerSize: NSMakeSize(i_width, 2000)];
1046 [o_layout_manager addTextContainer: o_container];
1047 [o_container release];
1048 [o_storage addLayoutManager: o_layout_manager];
1049 [o_layout_manager release];
1051 o_wrapped = [o_in_string mutableCopy];
1052 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1054 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1055 glyphIndex += effectiveRange.length) {
1056 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1057 effectiveRange: &effectiveRange];
1058 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1059 actualGlyphRange: &effectiveRange];
1060 if([o_wrapped lineRangeForRange:
1061 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1062 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1066 o_out_string = [NSString stringWithString: o_wrapped];
1067 [o_wrapped release];
1068 [o_storage release];
1070 return o_out_string;
1075 #pragma mark Key Shortcuts
1080 unsigned int i_vlckey;
1081 } nskeys_to_vlckeys[] =
1083 { NSUpArrowFunctionKey, KEY_UP },
1084 { NSDownArrowFunctionKey, KEY_DOWN },
1085 { NSLeftArrowFunctionKey, KEY_LEFT },
1086 { NSRightArrowFunctionKey, KEY_RIGHT },
1087 { NSF1FunctionKey, KEY_F1 },
1088 { NSF2FunctionKey, KEY_F2 },
1089 { NSF3FunctionKey, KEY_F3 },
1090 { NSF4FunctionKey, KEY_F4 },
1091 { NSF5FunctionKey, KEY_F5 },
1092 { NSF6FunctionKey, KEY_F6 },
1093 { NSF7FunctionKey, KEY_F7 },
1094 { NSF8FunctionKey, KEY_F8 },
1095 { NSF9FunctionKey, KEY_F9 },
1096 { NSF10FunctionKey, KEY_F10 },
1097 { NSF11FunctionKey, KEY_F11 },
1098 { NSF12FunctionKey, KEY_F12 },
1099 { NSInsertFunctionKey, KEY_INSERT },
1100 { NSHomeFunctionKey, KEY_HOME },
1101 { NSEndFunctionKey, KEY_END },
1102 { NSPageUpFunctionKey, KEY_PAGEUP },
1103 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1104 { NSMenuFunctionKey, KEY_MENU },
1105 { NSTabCharacter, KEY_TAB },
1106 { NSCarriageReturnCharacter, KEY_ENTER },
1107 { NSEnterCharacter, KEY_ENTER },
1108 { NSBackspaceCharacter, KEY_BACKSPACE },
1109 { NSDeleteCharacter, KEY_DELETE },
1113 unsigned int CocoaKeyToVLC( unichar i_key )
1117 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1119 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1121 return nskeys_to_vlckeys[i].i_vlckey;
1124 return (unsigned int)i_key;
1127 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1129 unsigned int new = 0;
1131 if([theString rangeOfString:@"Command"].location != NSNotFound)
1132 new |= NSCommandKeyMask;
1133 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1134 new |= NSAlternateKeyMask;
1135 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1136 new |= NSShiftKeyMask;
1137 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1138 new |= NSControlKeyMask;
1142 - (NSString *)VLCKeyToString:(NSString *)theString
1144 if (![theString isEqualToString:@""]) {
1145 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1146 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1149 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1150 theString = [NSString stringWithFormat:@"%@+", theString];
1152 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1153 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1156 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1157 theString = [NSString stringWithFormat:@"%@-", theString];
1159 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1160 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1161 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1162 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1164 if ([theString length] > 1)
1166 if([theString rangeOfString:@"Up"].location != NSNotFound)
1167 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1168 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1169 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1170 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1171 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1172 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1173 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1174 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1175 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1176 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1177 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1178 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1179 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1180 else if([theString rangeOfString:@"End"].location != NSNotFound)
1181 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1182 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1183 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1184 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1185 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1186 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1187 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1188 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1189 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1190 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1191 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1192 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1193 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1194 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1195 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1196 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1197 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1198 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1199 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1200 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1201 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1202 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1203 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1204 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1205 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1206 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1207 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1208 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1209 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1210 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1211 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1212 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1213 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1214 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1215 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1216 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1217 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1218 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1225 /*****************************************************************************
1226 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1227 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1228 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1229 *****************************************************************************/
1230 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1234 unsigned int i_pressed_modifiers = 0;
1235 const struct hotkey *p_hotkeys;
1237 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1238 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1241 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1243 i_pressed_modifiers = [o_event modifierFlags];
1245 if( i_pressed_modifiers & NSShiftKeyMask ) {
1246 val.i_int |= KEY_MODIFIER_SHIFT;
1247 [tempString appendString:@"Shift-"];
1248 [tempStringPlus appendString:@"Shift+"];
1250 if( i_pressed_modifiers & NSControlKeyMask ) {
1251 val.i_int |= KEY_MODIFIER_CTRL;
1252 [tempString appendString:@"Ctrl-"];
1253 [tempStringPlus appendString:@"Ctrl+"];
1255 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1256 val.i_int |= KEY_MODIFIER_ALT;
1257 [tempString appendString:@"Alt-"];
1258 [tempStringPlus appendString:@"Alt+"];
1260 if( i_pressed_modifiers & NSCommandKeyMask ) {
1261 val.i_int |= KEY_MODIFIER_COMMAND;
1262 [tempString appendString:@"Command-"];
1263 [tempStringPlus appendString:@"Command+"];
1266 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1267 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1269 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1273 case NSDeleteCharacter:
1274 case NSDeleteFunctionKey:
1275 case NSDeleteCharFunctionKey:
1276 case NSBackspaceCharacter:
1277 case NSUpArrowFunctionKey:
1278 case NSDownArrowFunctionKey:
1279 case NSRightArrowFunctionKey:
1280 case NSLeftArrowFunctionKey:
1281 case NSEnterCharacter:
1282 case NSCarriageReturnCharacter:
1286 if( key == 0x0020 ) // space key
1288 [[VLCCoreInteraction sharedInstance] play];
1292 val.i_int |= CocoaKeyToVLC( key );
1294 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1296 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1303 - (void)updateCurrentlyUsedHotkeys
1305 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1306 /* Get the main Module */
1307 module_t *p_main = module_get_main();
1310 module_config_t *p_config;
1312 p_config = module_config_get (p_main, &confsize);
1314 for (size_t i = 0; i < confsize; i++)
1316 module_config_t *p_item = p_config + i;
1318 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1319 && !strncmp( p_item->psz_name , "key-", 4 )
1320 && !EMPTY_STR( p_item->psz_text ) )
1322 if (p_item->value.psz)
1323 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1326 module_config_free (p_config);
1327 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1331 #pragma mark Interface updaters
1332 - (void)fullscreenChanged
1334 playlist_t * p_playlist = pl_Get( VLCIntf );
1335 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1337 if (OSX_LION && b_nativeFullscreenMode)
1339 [o_mainwindow toggleFullScreen: self];
1341 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1343 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1347 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1349 if( p_input != NULL )
1352 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1354 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1355 vlc_object_release( p_input );
1360 - (void)PlaylistItemChanged
1362 input_thread_t * p_input;
1364 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1365 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1367 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1368 [o_mainmenu setRateControlsEnabled: YES];
1369 vlc_object_release( p_input );
1372 [o_mainmenu setRateControlsEnabled: NO];
1374 [o_playlist updateRowSelection];
1375 [o_mainwindow updateWindow];
1376 [self updateMainMenu];
1379 - (void)updateMainMenu
1381 [o_mainmenu setupMenus];
1382 [o_mainmenu updatePlaybackRate];
1385 - (void)updateMainWindow
1387 [o_mainwindow updateWindow];
1390 - (void)showFullscreenController
1392 [o_mainwindow showFullscreenController];
1395 - (void)updateDelays
1397 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1402 [o_mainwindow updateName];
1405 - (void)updatePlaybackPosition
1407 [o_mainwindow updateTimeSlider];
1409 input_thread_t * p_input;
1410 p_input = pl_CurrentInput( p_intf );
1413 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1414 UpdateSystemActivity( UsrActivity );
1415 vlc_object_release( p_input );
1419 - (void)updateVolume
1421 [o_mainwindow updateVolumeSlider];
1424 - (void)playlistUpdated
1426 [self playbackStatusUpdated];
1427 [o_playlist playlistUpdated];
1428 [o_mainwindow updateWindow];
1429 [o_mainwindow updateName];
1432 - (void)updateRecordState: (BOOL)b_value
1434 [o_mainmenu updateRecordState:b_value];
1437 - (void)updateInfoandMetaPanel
1439 [o_playlist outlineViewSelectionDidChange:nil];
1442 - (void)playbackStatusUpdated
1444 input_thread_t * p_input;
1446 p_input = pl_CurrentInput( p_intf );
1449 int state = var_GetInteger( p_input, "state" );
1450 if( state == PLAYING_S )
1452 [[self mainMenu] setPause];
1453 [o_mainwindow setPause];
1458 [o_mainmenu setSubmenusEnabled: FALSE];
1459 [[self mainMenu] setPlay];
1460 [o_mainwindow setPlay];
1462 vlc_object_release( p_input );
1466 - (void)playbackModeUpdated
1468 vlc_value_t looping,repeating;
1469 playlist_t * p_playlist = pl_Get( VLCIntf );
1471 bool loop = var_GetBool( p_playlist, "loop" );
1472 bool repeat = var_GetBool( p_playlist, "repeat" );
1474 [o_mainwindow setRepeatOne];
1475 [o_mainmenu setRepeatOne];
1477 [o_mainwindow setRepeatAll];
1478 [o_mainmenu setRepeatAll];
1480 [o_mainwindow setRepeatOff];
1481 [o_mainmenu setRepeatOff];
1484 [o_mainwindow setShuffle];
1485 [o_mainmenu setShuffle];
1489 #pragma mark Other objects getters
1507 o_bookmarks = [[VLCBookmarks alloc] init];
1509 if( !nib_bookmarks_loaded )
1510 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1520 if (!nib_open_loaded)
1521 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1526 - (id)simplePreferences
1529 o_sprefs = [[VLCSimplePrefs alloc] init];
1531 if (!nib_prefs_loaded)
1532 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1540 o_prefs = [[VLCPrefs alloc] init];
1542 if( !nib_prefs_loaded )
1543 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1558 if(! nib_info_loaded )
1559 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1570 o_wizard = [[VLCWizard alloc] init];
1572 if( !nib_wizard_loaded )
1574 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1575 [o_wizard initStrings];
1580 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1582 id videoView = [o_mainwindow videoView];
1583 NSRect videoRect = [videoView frame];
1584 int i_x = (int)videoRect.origin.x;
1585 int i_y = (int)videoRect.origin.y;
1586 unsigned int i_width = (int)videoRect.size.width;
1587 unsigned int i_height = (int)videoRect.size.height;
1590 pi_width = (unsigned int*)i_width;
1591 pi_height = (unsigned int*)i_height;
1592 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1596 - (void)setNativeVideoSize:(NSSize)size
1598 [o_mainwindow setNativeVideoSize:size];
1603 if( o_embedded_list )
1604 return o_embedded_list;
1609 - (id)coreDialogProvider
1612 return o_coredialogs;
1617 - (id)eyeTVController
1625 - (id)appleRemoteController
1630 - (void)setActiveVideoPlayback:(BOOL)b_value
1632 b_active_videoplayback = b_value;
1633 [o_mainwindow setVideoplayEnabled];
1634 [o_mainwindow togglePlaylist:nil];
1637 - (BOOL)activeVideoPlayback
1639 return b_active_videoplayback;
1643 #pragma mark Crash Log
1644 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1646 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1647 NSURL *url = [NSURL URLWithString:urlStr];
1649 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1650 [req setHTTPMethod:@"POST"];
1653 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1655 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1656 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1657 email = [emails valueAtIndex:[emails indexForIdentifier:
1658 [emails primaryIdentifier]]];
1661 email = [NSString string];
1664 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1665 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1666 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1667 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1669 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1671 /* Released from delegate */
1672 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1675 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1677 [crashLogURLConnection release];
1678 crashLogURLConnection = nil;
1681 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1683 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1684 [crashLogURLConnection release];
1685 crashLogURLConnection = nil;
1688 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1690 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1691 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1693 NSString * latestLog = nil;
1694 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1695 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1696 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1697 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1699 while (fname = [direnum nextObject])
1701 [direnum skipDescendents];
1702 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1704 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1705 if( [compo count] < 3 ) continue;
1706 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1707 if( [compo count] < 4 ) continue;
1710 if( year < [[compo objectAtIndex:0] intValue] ||
1711 (year ==[[compo objectAtIndex:0] intValue] &&
1712 (month < [[compo objectAtIndex:1] intValue] ||
1713 (month ==[[compo objectAtIndex:1] intValue] &&
1714 (day < [[compo objectAtIndex:2] intValue] ||
1715 (day ==[[compo objectAtIndex:2] intValue] &&
1716 hours < [[compo objectAtIndex:3] intValue] ))))))
1718 year = [[compo objectAtIndex:0] intValue];
1719 month = [[compo objectAtIndex:1] intValue];
1720 day = [[compo objectAtIndex:2] intValue];
1721 hours = [[compo objectAtIndex:3] intValue];
1722 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1727 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1730 if( !previouslySeen )
1732 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1733 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1734 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1735 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1740 - (NSString *)latestCrashLogPath
1742 return [self latestCrashLogPathPreviouslySeen:YES];
1745 - (void)lookForCrashLog
1747 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1748 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1749 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1750 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1751 if( latestLog && !areCrashLogsTooOld )
1752 [NSApp runModalForWindow: o_crashrep_win];
1756 - (IBAction)crashReporterAction:(id)sender
1758 if( sender == o_crashrep_send_btn )
1759 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1762 [o_crashrep_win orderOut: sender];
1765 - (IBAction)openCrashLog:(id)sender
1767 NSString * latestLog = [self latestCrashLogPath];
1770 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1774 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.") );
1779 #pragma mark Remove old prefs
1781 - (void)_removeOldPreferences
1783 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1784 static const int kCurrentPreferencesVersion = 1;
1785 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1786 if( version >= kCurrentPreferencesVersion ) return;
1788 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1789 NSUserDomainMask, YES);
1790 if( !libraries || [libraries count] == 0) return;
1791 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1793 /* File not found, don't attempt anything */
1794 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1795 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1797 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1801 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1802 _NS("We just found an older version of VLC's preferences files."),
1803 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1804 if( res != NSOKButton )
1806 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1810 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1812 /* Move the file to trash so that user can find them later */
1813 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1815 /* really reset the defaults from now on */
1816 [NSUserDefaults resetStandardUserDefaults];
1818 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1819 [[NSUserDefaults standardUserDefaults] synchronize];
1822 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1824 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1830 execl(path, path, NULL);
1834 #pragma mark Errors, warnings and messages
1835 - (IBAction)showMessagesPanel:(id)sender
1837 [o_msgs_panel makeKeyAndOrderFront: sender];
1840 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1842 if( [o_notification object] == o_msgs_panel )
1843 [self updateMessageDisplay];
1846 - (void)updateMessageDisplay
1848 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1851 NSEnumerator * o_enum;
1853 [o_messages setString: @""];
1857 o_enum = [o_msg_arr objectEnumerator];
1859 while( ( o_msg = [o_enum nextObject] ) != nil )
1861 [o_messages insertText: o_msg];
1864 b_msg_arr_changed = NO;
1865 [o_msg_lock unlock];
1869 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1871 NSColor *o_white = [NSColor whiteColor];
1872 NSColor *o_red = [NSColor redColor];
1873 NSColor *o_yellow = [NSColor yellowColor];
1874 NSColor *o_gray = [NSColor grayColor];
1876 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1877 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1879 NSDictionary *o_attr;
1880 NSAttributedString *o_msg_color;
1884 if( [o_msg_arr count] + 2 > 600 )
1886 [o_msg_arr removeObjectAtIndex: 0];
1887 [o_msg_arr removeObjectAtIndex: 1];
1890 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1891 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1892 [o_msg_arr addObject: [o_msg_color autorelease]];
1894 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1895 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1896 [o_msg_arr addObject: [o_msg_color autorelease]];
1898 b_msg_arr_changed = YES;
1899 [o_msg_lock unlock];
1901 [self updateMessageDisplay];
1904 - (IBAction)saveDebugLog:(id)sender
1906 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1908 [saveFolderPanel setCanSelectHiddenExtension: NO];
1909 [saveFolderPanel setCanCreateDirectories: YES];
1910 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1911 [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];
1914 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1917 if( returnCode == NSOKButton )
1919 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1921 msg_Warn( p_intf, "Error while saving the debug log" );
1926 #pragma mark Playlist toggling
1928 - (void)updateTogglePlaylistState
1930 [[self playlist] outlineViewSelectionDidChange: NULL];
1937 @implementation VLCMain (Internal)
1939 - (void)handlePortMessage:(NSPortMessage *)o_msg
1944 NSInvocation * o_inv;
1945 NSConditionLock * o_lock;
1947 o_data = [[o_msg components] lastObject];
1948 o_inv = *((NSInvocation **)[o_data bytes]);
1949 [o_inv getArgument: &o_value atIndex: 2];
1950 val = (id **)[o_value pointerValue];
1951 [o_inv setArgument: val[1] atIndex: 2];
1956 [o_lock unlockWithCondition: 1];
1958 - (void)resetMediaKeyJump
1960 b_mediakeyJustJumped = NO;
1962 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1964 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1965 if (b_mediaKeySupport) {
1966 if (!o_mediaKeyController)
1967 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1968 [o_mediaKeyController startWatchingMediaKeys];
1970 else if (!b_mediaKeySupport && o_mediaKeyController)
1972 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1973 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1974 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1975 if( returnedValue == NSOKButton )
1978 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1980 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1986 execl(path, path, NULL);
1993 /*****************************************************************************
1994 * VLCApplication interface
1995 *****************************************************************************/
1997 @implementation VLCApplication
1998 // when user selects the quit menu from dock it sends a terminate:
1999 // but we need to send a stop: to properly exits libvlc.
2000 // However, we are not able to change the action-method sent by this standard menu item.
2001 // thus we override terminat: to send a stop:
2002 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2003 - (void)terminate:(id)sender
2005 [self activateIgnoringOtherApps:YES];