1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2012 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_plugin.h>
43 #include <vlc_aout_intf.h>
44 #include <vlc_vout_window.h>
45 #include <unistd.h> /* execl() */
47 #import "CompatibilityFixes.h"
53 #import "playlistinfo.h"
58 #import "coredialogs.h"
59 #import "AppleRemote.h"
61 #import "simple_prefs.h"
62 #import "CoreInteraction.h"
63 #import "TrackSynchronization.h"
65 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
66 #import <Sparkle/Sparkle.h> /* we're the update delegate */
68 /*****************************************************************************
70 *****************************************************************************/
71 static void Run ( intf_thread_t *p_intf );
73 static void updateProgressPanel (void *, const char *, float);
74 static bool checkProgressPanel (void *);
75 static void destroyProgressPanel (void *);
77 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
79 static int InputEvent( vlc_object_t *, const char *,
80 vlc_value_t, vlc_value_t, void * );
81 static int PLItemChanged( vlc_object_t *, const char *,
82 vlc_value_t, vlc_value_t, void * );
83 static int PlaylistUpdated( vlc_object_t *, const char *,
84 vlc_value_t, vlc_value_t, void * );
85 static int PlaybackModeUpdated( vlc_object_t *, const char *,
86 vlc_value_t, vlc_value_t, void * );
87 static int VolumeUpdated( vlc_object_t *, const char *,
88 vlc_value_t, vlc_value_t, void * );
91 #pragma mark VLC Interface Object Callbacks
93 /*****************************************************************************
94 * OpenIntf: initialize interface
95 *****************************************************************************/
96 int OpenIntf ( vlc_object_t *p_this )
98 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
99 [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 vlc_Subscribe( &p_intf->p_sys->sub, MsgCallback, NULL );
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 )
172 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
173 // we already have our playlist "fullscreen" callback, do not repeat the same call here
174 //[[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject: nil waitUntilDone: NO];
178 msg_Dbg( p_wnd, "WindowControl: unknown query" );
182 void WindowClose( vout_window_t *p_wnd )
184 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
185 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
190 /*****************************************************************************
192 *****************************************************************************/
193 static NSLock * o_appLock = nil; // controls access to f_appExit
195 static void Run( intf_thread_t *p_intf )
197 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
198 [VLCApplication sharedApplication];
200 o_appLock = [[NSLock alloc] init];
202 [[VLCMain sharedInstance] setIntf: p_intf];
203 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
206 [[VLCMain sharedInstance] applicationWillTerminate:nil];
214 #pragma mark Variables Callback
216 /*****************************************************************************
217 * MsgCallback: Callback triggered by the core once a new debug message is
218 * ready to be displayed. We store everything in a NSArray in our Cocoa part
220 *****************************************************************************/
221 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
223 int canc = vlc_savecancel();
226 if (vasprintf( &str, format, ap ) == -1)
228 vlc_restorecancel( canc );
232 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
233 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
236 vlc_restorecancel( canc );
240 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
241 vlc_value_t oldval, vlc_value_t new_val, void *param )
243 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
244 switch (new_val.i_int) {
245 case INPUT_EVENT_STATE:
246 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
248 case INPUT_EVENT_RATE:
249 [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
251 case INPUT_EVENT_POSITION:
252 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
254 case INPUT_EVENT_TITLE:
255 case INPUT_EVENT_CHAPTER:
256 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
258 case INPUT_EVENT_CACHE:
259 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
261 case INPUT_EVENT_STATISTICS:
262 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
266 case INPUT_EVENT_TELETEXT:
268 case INPUT_EVENT_AOUT:
270 case INPUT_EVENT_VOUT:
272 case INPUT_EVENT_ITEM_META:
273 case INPUT_EVENT_ITEM_INFO:
274 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
275 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
276 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
278 case INPUT_EVENT_BOOKMARK:
280 case INPUT_EVENT_RECORD:
281 [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
283 case INPUT_EVENT_PROGRAM:
284 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
286 case INPUT_EVENT_ITEM_EPG:
288 case INPUT_EVENT_SIGNAL:
291 case INPUT_EVENT_ITEM_NAME:
292 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
293 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
296 case INPUT_EVENT_AUDIO_DELAY:
297 case INPUT_EVENT_SUBTITLE_DELAY:
298 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
301 case INPUT_EVENT_DEAD:
302 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
303 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
306 case INPUT_EVENT_ABORT:
307 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
308 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
312 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
320 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
321 vlc_value_t oldval, vlc_value_t new_val, void *param )
323 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
324 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
330 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
331 vlc_value_t oldval, vlc_value_t new_val, void *param )
333 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
334 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
340 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
341 vlc_value_t oldval, vlc_value_t new_val, void *param )
343 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
344 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
350 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
351 vlc_value_t oldval, vlc_value_t new_val, void *param )
353 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
354 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
360 /*****************************************************************************
361 * ShowController: Callback triggered by the show-intf playlist variable
362 * through the ShowIntf-control-intf, to let us show the controller-win;
363 * usually when in fullscreen-mode
364 *****************************************************************************/
365 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
366 vlc_value_t old_val, vlc_value_t new_val, void *param )
368 intf_thread_t * p_intf = VLCIntf;
369 if( p_intf && p_intf->p_sys )
371 playlist_t * p_playlist = pl_Get( p_intf );
372 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
373 if( strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen )
375 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
379 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
385 /*****************************************************************************
386 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
387 * variable, to let the intf update the controller.
388 *****************************************************************************/
389 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
390 vlc_value_t old_val, vlc_value_t new_val, void *param )
392 intf_thread_t * p_intf = VLCIntf;
395 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
396 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
402 /*****************************************************************************
403 * DialogCallback: Callback triggered by the "dialog-*" variables
404 * to let the intf display error and interaction dialogs
405 *****************************************************************************/
406 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
408 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
409 VLCMain *interface = (VLCMain *)data;
411 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
413 /* the progress panel needs to update itself and therefore wants special treatment within this context */
414 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
416 p_dialog->pf_update = updateProgressPanel;
417 p_dialog->pf_check = checkProgressPanel;
418 p_dialog->pf_destroy = destroyProgressPanel;
419 p_dialog->p_sys = VLCIntf->p_libvlc;
422 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
423 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
429 void updateProgressPanel (void *priv, const char *text, float value)
431 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
435 o_txt = [NSString stringWithUTF8String: text];
439 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
444 void destroyProgressPanel (void *priv)
446 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
447 [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:NO];
451 bool checkProgressPanel (void *priv)
453 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
454 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
461 input_thread_t *getInput(void)
463 intf_thread_t *p_intf = VLCIntf;
466 return pl_CurrentInput(p_intf);
469 vout_thread_t *getVout(void)
471 input_thread_t *p_input = getInput();
474 vout_thread_t *p_vout = input_GetVout(p_input);
475 vlc_object_release(p_input);
479 audio_output_t *getAout(void)
481 input_thread_t *p_input = getInput();
484 audio_output_t *p_aout = input_GetAout(p_input);
485 vlc_object_release(p_input);
492 @interface VLCMain ()
493 - (void)_removeOldPreferences;
496 /*****************************************************************************
497 * VLCMain implementation
498 *****************************************************************************/
499 @implementation VLCMain
502 #pragma mark Initialization
504 static VLCMain *_o_sharedMainInstance = nil;
506 + (VLCMain *)sharedInstance
508 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
513 if( _o_sharedMainInstance)
516 return _o_sharedMainInstance;
519 _o_sharedMainInstance = [super init];
522 p_current_input = NULL;
524 o_msg_lock = [[NSLock alloc] init];
525 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
527 o_open = [[VLCOpen alloc] init];
528 //o_embedded_list = [[VLCEmbeddedList alloc] init];
529 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
530 o_info = [[VLCInfo alloc] init];
531 o_mainmenu = [[VLCMainMenu alloc] init];
532 o_coreinteraction = [[VLCCoreInteraction alloc] init];
533 o_eyetv = [[VLCEyeTVController alloc] init];
534 o_mainwindow = [[VLCMainWindow alloc] init];
536 /* announce our launch to a potential eyetv plugin */
537 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
538 object: @"VLCEyeTVSupport"
540 deliverImmediately: YES];
542 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
543 NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
544 [defaults registerDefaults:appDefaults];
546 return _o_sharedMainInstance;
549 - (void)setIntf: (intf_thread_t *)p_mainintf {
553 - (intf_thread_t *)intf {
559 playlist_t *p_playlist;
561 if( !p_intf ) return;
562 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
564 /* Check if we already did this once. Opening the other nibs calls it too,
565 because VLCMain is the owner */
566 if( nib_main_loaded ) return;
568 [o_msgs_panel setExcludedFromWindowsMenu: YES];
569 [o_msgs_panel setDelegate: self];
571 p_playlist = pl_Get( p_intf );
575 var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
576 var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
577 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
578 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
579 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
580 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
581 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
582 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
583 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
584 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
585 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
586 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
587 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
588 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
592 if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
593 var_SetBool( p_playlist, "fullscreen", YES );
596 /* load our Core Dialogs nib */
597 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
599 /* subscribe to various interactive dialogues */
600 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
601 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
602 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
603 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
604 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
605 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
606 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
607 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
608 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
609 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
610 dialog_Register( p_intf );
612 /* init Apple Remote support */
613 o_remote = [[AppleRemote alloc] init];
614 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
615 [o_remote setDelegate: _o_sharedMainInstance];
617 [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
619 /* yeah, we are done */
620 b_nativeFullscreenMode = NO;
621 #ifdef MAC_OS_X_VERSION_10_7
623 b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
626 /* recover stored audio device, if set
627 * in case it was unplugged in the meantime, auhal will fall back on the default */
628 int i_value = config_GetInt( p_intf, "macosx-audio-device" );
630 var_SetInteger( pl_Get( VLCIntf ), "audio-device", i_value );
632 if (config_GetInt( VLCIntf, "macosx-icon-change"))
634 /* After day 354 of the year, the usual VLC cone is replaced by another cone
635 * wearing a Father Xmas hat.
636 * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
638 NSCalendar *gregorian =
639 [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
640 NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
643 if (dayOfYear >= 354)
644 [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
647 nib_main_loaded = TRUE;
650 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
652 if( !p_intf ) return;
654 [o_mainwindow updateWindow];
655 [o_mainwindow updateTimeSlider];
656 [o_mainwindow updateVolumeSlider];
657 [o_mainwindow makeKeyAndOrderFront: self];
659 /* init media key support */
660 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
661 if( b_mediaKeySupport )
663 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
664 [o_mediaKeyController startWatchingMediaKeys];
665 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
666 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
669 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
671 [self _removeOldPreferences];
673 /* Handle sleep notification */
674 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
675 name:NSWorkspaceWillSleepNotification object:nil];
677 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
679 /* we will need this, so let's load it here so the interface appears to be more responsive */
680 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
686 if( !p_intf ) return;
689 [o_msgs_panel setTitle: _NS("Messages")];
690 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
691 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
693 /* crash reporter panel */
694 [o_crashrep_send_btn setTitle: _NS("Send")];
695 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
696 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
697 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
698 [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, ...")];
699 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
700 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
704 #pragma mark Termination
706 - (void)applicationWillTerminate:(NSNotification *)notification
708 /* don't allow a double termination call. If the user has
709 * already invoked the quit then simply return this time. */
710 static bool f_appExit = false;
714 isTerminating = f_appExit;
721 if (notification == nil)
722 [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
724 playlist_t * p_playlist = pl_Get( p_intf );
725 int returnedValue = 0;
727 /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
728 if (b_nativeFullscreenMode)
730 [o_mainwindow toggleFullScreen: self];
731 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
734 /* Save some interface state in configuration, at module quit */
735 config_PutInt( p_intf, "random", var_GetBool( p_playlist, "random" ) );
736 config_PutInt( p_intf, "loop", var_GetBool( p_playlist, "loop" ) );
737 config_PutInt( p_intf, "repeat", var_GetBool( p_playlist, "repeat" ) );
739 msg_Dbg( p_intf, "Terminating" );
741 /* unsubscribe from the interactive dialogues */
742 dialog_Unregister( p_intf );
743 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
744 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
745 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
746 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
747 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
748 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
749 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
750 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
751 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
752 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
753 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
754 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
755 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
756 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
757 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
758 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
759 var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
760 var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
761 var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
763 if( p_current_input )
765 var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
766 vlc_object_release( p_current_input );
767 p_current_input = NULL;
770 /* remove global observer watching for vout device changes correctly */
771 [[NSNotificationCenter defaultCenter] removeObserver: self];
773 /* release some other objects here, because it isn't sure whether dealloc
774 * will be called later on */
789 [crashLogURLConnection cancel];
790 [crashLogURLConnection release];
792 [o_embedded_list release];
793 [o_coredialogs release];
796 /* unsubscribe from libvlc's debug messages */
797 vlc_Unsubscribe( &p_intf->p_sys->sub );
799 [o_msg_arr removeAllObjects];
803 [o_msg_lock release];
805 /* write cached user defaults to disk */
806 [[NSUserDefaults standardUserDefaults] synchronize];
808 /* Make sure the Menu doesn't have any references to vlc objects anymore */
809 //FIXME: this should be moved to VLCMainMenu
810 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
811 [o_mainmenu release];
813 libvlc_Quit( p_intf->p_libvlc );
815 [o_mainwindow release];
822 #pragma mark Sparkle delegate
823 /* received directly before the update gets installed, so let's shut down a bit */
824 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
826 [NSApp activateIgnoringOtherApps:YES];
827 [o_remote stopListening: self];
828 [[VLCCoreInteraction sharedInstance] stop];
832 #pragma mark Media Key support
834 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
836 if( b_mediaKeySupport )
838 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
840 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
841 int keyFlags = ([event data1] & 0x0000FFFF);
842 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
843 int keyRepeat = (keyFlags & 0x1);
845 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
846 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
848 if( (keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped )
850 if( keyState == 0 && keyRepeat == 0 )
851 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
852 else if( keyRepeat == 1 )
854 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
855 b_mediakeyJustJumped = YES;
856 [self performSelector:@selector(resetMediaKeyJump)
862 if( (keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped )
864 if( keyState == 0 && keyRepeat == 0 )
865 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
866 else if( keyRepeat == 1 )
868 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
869 b_mediakeyJustJumped = YES;
870 [self performSelector:@selector(resetMediaKeyJump)
879 #pragma mark Other notification
881 /* Listen to the remote in exclusive mode, only when VLC is the active
883 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
885 if( !p_intf ) return;
886 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
887 [o_remote startListening: self];
889 - (void)applicationDidResignActive:(NSNotification *)aNotification
891 if( !p_intf ) return;
892 [o_remote stopListening: self];
895 /* Triggered when the computer goes to sleep */
896 - (void)computerWillSleep: (NSNotification *)notification
898 [[VLCCoreInteraction sharedInstance] pause];
902 #pragma mark File opening
904 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
906 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
907 char *psz_uri = make_URI([o_filename UTF8String], "file" );
911 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
912 BOOL b_returned = NO;
916 b_returned = input_AddSubtitle( p_input, psz_uri, true );
917 vlc_object_release( p_input );
925 vlc_object_release( p_input );
927 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
932 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
934 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
939 /* When user click in the Dock icon our double click in the finder */
940 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
942 if(!hasVisibleWindows)
943 [o_mainwindow makeKeyAndOrderFront:self];
949 #pragma mark Apple Remote Control
951 /* Helper method for the remote control interface in order to trigger forward/backward and volume
952 increase/decrease as long as the user holds the left/right, plus/minus button */
953 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
955 if(b_remote_button_hold)
957 switch([buttonIdentifierNumber intValue])
959 case kRemoteButtonRight_Hold:
960 [[VLCCoreInteraction sharedInstance] forward];
962 case kRemoteButtonLeft_Hold:
963 [[VLCCoreInteraction sharedInstance] backward];
965 case kRemoteButtonVolume_Plus_Hold:
966 [[VLCCoreInteraction sharedInstance] volumeUp];
968 case kRemoteButtonVolume_Minus_Hold:
969 [[VLCCoreInteraction sharedInstance] volumeDown];
972 if(b_remote_button_hold)
975 [self performSelector:@selector(executeHoldActionForRemoteButton:)
976 withObject:buttonIdentifierNumber
982 /* Apple Remote callback */
983 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
984 pressedDown: (BOOL) pressedDown
985 clickCount: (unsigned int) count
987 switch( buttonIdentifier )
989 case k2009RemoteButtonFullscreen:
990 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
992 case k2009RemoteButtonPlay:
993 [[VLCCoreInteraction sharedInstance] play];
995 case kRemoteButtonPlay:
997 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
999 [[VLCCoreInteraction sharedInstance] play];
1002 case kRemoteButtonVolume_Plus:
1003 [[VLCCoreInteraction sharedInstance] volumeUp];
1005 case kRemoteButtonVolume_Minus:
1006 [[VLCCoreInteraction sharedInstance] volumeDown];
1008 case kRemoteButtonRight:
1009 [[VLCCoreInteraction sharedInstance] next];
1011 case kRemoteButtonLeft:
1012 [[VLCCoreInteraction sharedInstance] previous];
1014 case kRemoteButtonRight_Hold:
1015 case kRemoteButtonLeft_Hold:
1016 case kRemoteButtonVolume_Plus_Hold:
1017 case kRemoteButtonVolume_Minus_Hold:
1018 /* simulate an event as long as the user holds the button */
1019 b_remote_button_hold = pressedDown;
1022 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1023 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1024 withObject:buttonIdentifierNumber];
1027 case kRemoteButtonMenu:
1028 [o_controls showPosition: self]; //FIXME
1031 /* Add here whatever you want other buttons to do */
1037 #pragma mark String utility
1038 // FIXME: this has nothing to do here
1040 - (NSString *)localizedString:(const char *)psz
1042 NSString * o_str = nil;
1046 o_str = [NSString stringWithCString: _(psz) encoding:NSUTF8StringEncoding];
1050 msg_Err( VLCIntf, "could not translate: %s", psz );
1056 msg_Warn( VLCIntf, "can't translate empty strings" );
1065 - (char *)delocalizeString:(NSString *)id
1067 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1068 allowLossyConversion: NO];
1073 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1074 allowLossyConversion: YES];
1075 psz_string = malloc( [o_data length] + 1 );
1076 [o_data getBytes: psz_string];
1077 psz_string[ [o_data length] ] = '\0';
1078 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1083 psz_string = malloc( [o_data length] + 1 );
1084 [o_data getBytes: psz_string];
1085 psz_string[ [o_data length] ] = '\0';
1091 /* i_width is in pixels */
1092 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1094 NSMutableString *o_wrapped;
1095 NSString *o_out_string;
1096 NSRange glyphRange, effectiveRange, charRange;
1097 NSRect lineFragmentRect;
1098 unsigned glyphIndex, breaksInserted = 0;
1100 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1101 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1102 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1103 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1104 NSTextContainer *o_container = [[NSTextContainer alloc]
1105 initWithContainerSize: NSMakeSize(i_width, 2000)];
1107 [o_layout_manager addTextContainer: o_container];
1108 [o_container release];
1109 [o_storage addLayoutManager: o_layout_manager];
1110 [o_layout_manager release];
1112 o_wrapped = [o_in_string mutableCopy];
1113 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1115 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1116 glyphIndex += effectiveRange.length) {
1117 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1118 effectiveRange: &effectiveRange];
1119 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1120 actualGlyphRange: &effectiveRange];
1121 if([o_wrapped lineRangeForRange:
1122 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1123 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1127 o_out_string = [NSString stringWithString: o_wrapped];
1128 [o_wrapped release];
1129 [o_storage release];
1131 return o_out_string;
1136 #pragma mark Key Shortcuts
1141 unsigned int i_vlckey;
1142 } nskeys_to_vlckeys[] =
1144 { NSUpArrowFunctionKey, KEY_UP },
1145 { NSDownArrowFunctionKey, KEY_DOWN },
1146 { NSLeftArrowFunctionKey, KEY_LEFT },
1147 { NSRightArrowFunctionKey, KEY_RIGHT },
1148 { NSF1FunctionKey, KEY_F1 },
1149 { NSF2FunctionKey, KEY_F2 },
1150 { NSF3FunctionKey, KEY_F3 },
1151 { NSF4FunctionKey, KEY_F4 },
1152 { NSF5FunctionKey, KEY_F5 },
1153 { NSF6FunctionKey, KEY_F6 },
1154 { NSF7FunctionKey, KEY_F7 },
1155 { NSF8FunctionKey, KEY_F8 },
1156 { NSF9FunctionKey, KEY_F9 },
1157 { NSF10FunctionKey, KEY_F10 },
1158 { NSF11FunctionKey, KEY_F11 },
1159 { NSF12FunctionKey, KEY_F12 },
1160 { NSInsertFunctionKey, KEY_INSERT },
1161 { NSHomeFunctionKey, KEY_HOME },
1162 { NSEndFunctionKey, KEY_END },
1163 { NSPageUpFunctionKey, KEY_PAGEUP },
1164 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1165 { NSMenuFunctionKey, KEY_MENU },
1166 { NSTabCharacter, KEY_TAB },
1167 { NSCarriageReturnCharacter, KEY_ENTER },
1168 { NSEnterCharacter, KEY_ENTER },
1169 { NSBackspaceCharacter, KEY_BACKSPACE },
1170 { NSDeleteCharacter, KEY_DELETE },
1174 unsigned int CocoaKeyToVLC( unichar i_key )
1178 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1180 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1182 return nskeys_to_vlckeys[i].i_vlckey;
1185 return (unsigned int)i_key;
1188 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1190 unsigned int new = 0;
1192 if([theString rangeOfString:@"Command"].location != NSNotFound)
1193 new |= NSCommandKeyMask;
1194 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1195 new |= NSAlternateKeyMask;
1196 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1197 new |= NSShiftKeyMask;
1198 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1199 new |= NSControlKeyMask;
1203 - (NSString *)VLCKeyToString:(NSString *)theString
1205 if (![theString isEqualToString:@""]) {
1206 if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1207 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1210 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1211 theString = [NSString stringWithFormat:@"%@+", theString];
1213 if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1214 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1217 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1218 theString = [NSString stringWithFormat:@"%@-", theString];
1220 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1221 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1222 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1223 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1225 if ([theString length] > 1)
1227 if([theString rangeOfString:@"Up"].location != NSNotFound)
1228 return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1229 else if([theString rangeOfString:@"Down"].location != NSNotFound)
1230 return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1231 else if([theString rangeOfString:@"Right"].location != NSNotFound)
1232 return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1233 else if([theString rangeOfString:@"Left"].location != NSNotFound)
1234 return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1235 else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1236 return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1237 else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1238 return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1239 else if([theString rangeOfString:@"Home"].location != NSNotFound)
1240 return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1241 else if([theString rangeOfString:@"End"].location != NSNotFound)
1242 return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1243 else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1244 return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1245 else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1246 return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1247 else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1248 return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1249 else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1250 return [NSString stringWithFormat:@"%C", NSTabCharacter];
1251 else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1252 return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1253 else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1254 return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1255 else if([theString rangeOfString:@"F12"].location != NSNotFound)
1256 return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1257 else if([theString rangeOfString:@"F11"].location != NSNotFound)
1258 return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1259 else if([theString rangeOfString:@"F10"].location != NSNotFound)
1260 return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1261 else if([theString rangeOfString:@"F9"].location != NSNotFound)
1262 return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1263 else if([theString rangeOfString:@"F8"].location != NSNotFound)
1264 return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1265 else if([theString rangeOfString:@"F7"].location != NSNotFound)
1266 return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1267 else if([theString rangeOfString:@"F6"].location != NSNotFound)
1268 return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1269 else if([theString rangeOfString:@"F5"].location != NSNotFound)
1270 return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1271 else if([theString rangeOfString:@"F4"].location != NSNotFound)
1272 return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1273 else if([theString rangeOfString:@"F3"].location != NSNotFound)
1274 return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1275 else if([theString rangeOfString:@"F2"].location != NSNotFound)
1276 return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1277 else if([theString rangeOfString:@"F1"].location != NSNotFound)
1278 return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1279 /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1286 /*****************************************************************************
1287 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1288 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1289 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1290 *****************************************************************************/
1291 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1295 unsigned int i_pressed_modifiers = 0;
1296 const struct hotkey *p_hotkeys;
1298 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1299 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1302 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1304 i_pressed_modifiers = [o_event modifierFlags];
1306 if( i_pressed_modifiers & NSShiftKeyMask ) {
1307 val.i_int |= KEY_MODIFIER_SHIFT;
1308 [tempString appendString:@"Shift-"];
1309 [tempStringPlus appendString:@"Shift+"];
1311 if( i_pressed_modifiers & NSControlKeyMask ) {
1312 val.i_int |= KEY_MODIFIER_CTRL;
1313 [tempString appendString:@"Ctrl-"];
1314 [tempStringPlus appendString:@"Ctrl+"];
1316 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1317 val.i_int |= KEY_MODIFIER_ALT;
1318 [tempString appendString:@"Alt-"];
1319 [tempStringPlus appendString:@"Alt+"];
1321 if( i_pressed_modifiers & NSCommandKeyMask ) {
1322 val.i_int |= KEY_MODIFIER_COMMAND;
1323 [tempString appendString:@"Command-"];
1324 [tempStringPlus appendString:@"Command+"];
1327 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1328 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1330 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1332 /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1333 if( key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask )
1335 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1341 case NSDeleteCharacter:
1342 case NSDeleteFunctionKey:
1343 case NSDeleteCharFunctionKey:
1344 case NSBackspaceCharacter:
1345 case NSUpArrowFunctionKey:
1346 case NSDownArrowFunctionKey:
1347 case NSRightArrowFunctionKey:
1348 case NSLeftArrowFunctionKey:
1349 case NSEnterCharacter:
1350 case NSCarriageReturnCharacter:
1354 if( key == 0x0020 ) // space key
1356 [[VLCCoreInteraction sharedInstance] play];
1360 val.i_int |= CocoaKeyToVLC( key );
1362 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1364 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1371 - (void)updateCurrentlyUsedHotkeys
1373 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1374 /* Get the main Module */
1375 module_t *p_main = module_get_main();
1378 module_config_t *p_config;
1380 p_config = module_config_get (p_main, &confsize);
1382 for (size_t i = 0; i < confsize; i++)
1384 module_config_t *p_item = p_config + i;
1386 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1387 && !strncmp( p_item->psz_name , "key-", 4 )
1388 && !EMPTY_STR( p_item->psz_text ) )
1390 if (p_item->value.psz)
1391 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1394 module_config_free (p_config);
1395 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1399 #pragma mark Interface updaters
1400 - (void)fullscreenChanged
1402 playlist_t * p_playlist = pl_Get( VLCIntf );
1403 BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1405 if (b_nativeFullscreenMode)
1407 // this is called twice in certain situations, so only toogle if we really need to
1408 if( ( b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) ||
1409 ( !b_fullscreen && ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) )
1410 [o_mainwindow toggleFullScreen: self];
1413 [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1415 [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1421 input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1422 if( p_input != NULL && [self activeVideoPlayback] )
1424 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1427 vlc_object_release( p_input );
1431 // leaving fullscreen is always allowed
1432 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1437 - (void)PlaylistItemChanged
1439 if( p_current_input && ( p_current_input->b_dead || !vlc_object_alive( p_current_input ) ))
1441 var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1442 vlc_object_release( p_current_input );
1443 p_current_input = NULL;
1445 [o_mainmenu setRateControlsEnabled: NO];
1447 else if( !p_current_input )
1449 // object is hold here and released then it is dead
1450 p_current_input = playlist_CurrentInput( pl_Get( VLCIntf ));
1451 if( p_current_input )
1453 var_AddCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1454 [self playbackStatusUpdated];
1455 [o_mainmenu setRateControlsEnabled: YES];
1456 if ( [self activeVideoPlayback] && [[o_mainwindow videoView] isHidden] )
1457 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1461 [o_playlist updateRowSelection];
1462 [o_mainwindow updateWindow];
1463 [self updateDelays];
1464 [self updateMainMenu];
1467 - (void)updateMainMenu
1469 [o_mainmenu setupMenus];
1470 [o_mainmenu updatePlaybackRate];
1473 - (void)updateMainWindow
1475 [o_mainwindow updateWindow];
1478 - (void)showMainWindow
1480 [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1483 - (void)showFullscreenController
1485 [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1488 - (void)updateDelays
1490 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1495 [o_mainwindow updateName];
1498 - (void)updatePlaybackPosition
1500 [o_mainwindow updateTimeSlider];
1502 input_thread_t * p_input;
1503 p_input = pl_CurrentInput( p_intf );
1506 if( var_GetInteger( p_input, "state" ) == PLAYING_S && [self activeVideoPlayback] )
1507 UpdateSystemActivity( UsrActivity );
1508 vlc_object_release( p_input );
1512 - (void)updateVolume
1514 [o_mainwindow updateVolumeSlider];
1517 - (void)playlistUpdated
1519 [self playbackStatusUpdated];
1520 [o_playlist playlistUpdated];
1521 [o_mainwindow updateWindow];
1522 [o_mainwindow updateName];
1525 - (void)updateRecordState: (BOOL)b_value
1527 [o_mainmenu updateRecordState:b_value];
1530 - (void)updateInfoandMetaPanel
1532 [o_playlist outlineViewSelectionDidChange:nil];
1535 - (void)playbackStatusUpdated
1537 input_thread_t * p_input;
1539 p_input = pl_CurrentInput( p_intf );
1542 int state = var_GetInteger( p_input, "state" );
1543 if( state == PLAYING_S )
1545 [[self mainMenu] setPause];
1546 [o_mainwindow setPause];
1551 [o_mainmenu setSubmenusEnabled: FALSE];
1552 [[self mainMenu] setPlay];
1553 [o_mainwindow setPlay];
1555 vlc_object_release( p_input );
1558 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1559 [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1562 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1564 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1567 deliverImmediately:YES];
1570 - (void)playbackModeUpdated
1572 vlc_value_t looping,repeating;
1573 playlist_t * p_playlist = pl_Get( VLCIntf );
1575 bool loop = var_GetBool( p_playlist, "loop" );
1576 bool repeat = var_GetBool( p_playlist, "repeat" );
1578 [o_mainwindow setRepeatOne];
1579 [o_mainmenu setRepeatOne];
1581 [o_mainwindow setRepeatAll];
1582 [o_mainmenu setRepeatAll];
1584 [o_mainwindow setRepeatOff];
1585 [o_mainmenu setRepeatOff];
1588 [o_mainwindow setShuffle];
1589 [o_mainmenu setShuffle];
1593 #pragma mark Other objects getters
1602 return o_mainwindow;
1616 o_bookmarks = [[VLCBookmarks alloc] init];
1618 if( !nib_bookmarks_loaded )
1619 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1629 if (!nib_open_loaded)
1630 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1635 - (id)simplePreferences
1638 o_sprefs = [[VLCSimplePrefs alloc] init];
1640 if (!nib_prefs_loaded)
1641 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1649 o_prefs = [[VLCPrefs alloc] init];
1651 if( !nib_prefs_loaded )
1652 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1667 if(! nib_info_loaded )
1668 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1679 o_wizard = [[VLCWizard alloc] init];
1681 if( !nib_wizard_loaded )
1683 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1684 [o_wizard initStrings];
1689 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1691 id videoView = [o_mainwindow setupVideoView];
1692 NSRect videoRect = [videoView frame];
1693 int i_x = (int)videoRect.origin.x;
1694 int i_y = (int)videoRect.origin.y;
1695 unsigned int i_width = (int)videoRect.size.width;
1696 unsigned int i_height = (int)videoRect.size.height;
1699 pi_width = &i_width;
1700 pi_height = &i_height;
1701 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1705 - (void)setNativeVideoSize:(NSSize)size
1707 [o_mainwindow setNativeVideoSize:size];
1712 if( o_embedded_list )
1713 return o_embedded_list;
1718 - (id)coreDialogProvider
1721 return o_coredialogs;
1726 - (id)eyeTVController
1734 - (id)appleRemoteController
1739 - (void)setActiveVideoPlayback:(BOOL)b_value
1741 b_active_videoplayback = b_value;
1744 [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1745 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1749 - (BOOL)activeVideoPlayback
1751 return b_active_videoplayback;
1755 #pragma mark Crash Log
1756 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1758 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1759 NSURL *url = [NSURL URLWithString:urlStr];
1761 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1762 [req setHTTPMethod:@"POST"];
1765 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1767 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1768 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1769 email = [emails valueAtIndex:[emails indexForIdentifier:
1770 [emails primaryIdentifier]]];
1773 email = [NSString string];
1776 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1777 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1778 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1779 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1781 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1783 /* Released from delegate */
1784 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1787 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1789 [crashLogURLConnection release];
1790 crashLogURLConnection = nil;
1793 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1795 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1796 [crashLogURLConnection release];
1797 crashLogURLConnection = nil;
1800 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1802 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1803 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1805 NSString * latestLog = nil;
1806 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1807 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1808 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1809 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1811 while (fname = [direnum nextObject])
1813 [direnum skipDescendents];
1814 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1816 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1817 if( [compo count] < 3 ) continue;
1818 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1819 if( [compo count] < 4 ) continue;
1822 if( year < [[compo objectAtIndex:0] intValue] ||
1823 (year ==[[compo objectAtIndex:0] intValue] &&
1824 (month < [[compo objectAtIndex:1] intValue] ||
1825 (month ==[[compo objectAtIndex:1] intValue] &&
1826 (day < [[compo objectAtIndex:2] intValue] ||
1827 (day ==[[compo objectAtIndex:2] intValue] &&
1828 hours < [[compo objectAtIndex:3] intValue] ))))))
1830 year = [[compo objectAtIndex:0] intValue];
1831 month = [[compo objectAtIndex:1] intValue];
1832 day = [[compo objectAtIndex:2] intValue];
1833 hours = [[compo objectAtIndex:3] intValue];
1834 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1839 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1842 if( !previouslySeen )
1844 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1845 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1846 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1847 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1852 - (NSString *)latestCrashLogPath
1854 return [self latestCrashLogPathPreviouslySeen:YES];
1857 - (void)lookForCrashLog
1859 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1860 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1861 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1862 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1863 if( latestLog && !areCrashLogsTooOld )
1864 [NSApp runModalForWindow: o_crashrep_win];
1868 - (IBAction)crashReporterAction:(id)sender
1870 if( sender == o_crashrep_send_btn )
1871 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1874 [o_crashrep_win orderOut: sender];
1877 - (IBAction)openCrashLog:(id)sender
1879 NSString * latestLog = [self latestCrashLogPath];
1882 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1886 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.") );
1891 #pragma mark Remove old prefs
1893 - (void)_removeOldPreferences
1895 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1896 static const int kCurrentPreferencesVersion = 2;
1897 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1898 if( version >= kCurrentPreferencesVersion ) return;
1902 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1903 [[NSUserDefaults standardUserDefaults] synchronize];
1905 if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1908 config_SaveConfigFile( VLCIntf ); // we need to do manually, since we won't quit libvlc cleanly
1912 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1913 NSUserDomainMask, YES);
1914 if( !libraries || [libraries count] == 0) return;
1915 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1917 /* File not found, don't attempt anything */
1918 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1919 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1921 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1925 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1926 _NS("We just found an older version of VLC's preferences files."),
1927 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1928 if( res != NSOKButton )
1930 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1934 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1936 /* Move the file to trash so that user can find them later */
1937 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1939 /* really reset the defaults from now on */
1940 [NSUserDefaults resetStandardUserDefaults];
1942 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1943 [[NSUserDefaults standardUserDefaults] synchronize];
1947 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1949 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1955 execl(path, path, NULL);
1959 #pragma mark Errors, warnings and messages
1960 - (IBAction)updateMessagesPanel:(id)sender
1962 [self windowDidBecomeKey:nil];
1965 - (IBAction)showMessagesPanel:(id)sender
1967 [o_msgs_panel makeKeyAndOrderFront: sender];
1970 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1972 [o_msgs_table reloadData];
1973 [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1976 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1978 if (aTableView == o_msgs_table)
1979 return [o_msg_arr count];
1983 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1985 NSMutableAttributedString *result = NULL;
1988 if( rowIndex < [o_msg_arr count] )
1989 result = [o_msg_arr objectAtIndex: rowIndex];
1990 [o_msg_lock unlock];
1992 if( result != NULL )
1998 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
2002 NSColor *o_white = [NSColor whiteColor];
2003 NSColor *o_red = [NSColor redColor];
2004 NSColor *o_yellow = [NSColor yellowColor];
2005 NSColor *o_gray = [NSColor grayColor];
2006 NSString * firstString, * secondString;
2008 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2009 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
2011 NSDictionary *o_attr;
2012 NSMutableAttributedString *o_msg_color;
2016 if( [o_msg_arr count] + 2 > 600 )
2018 [o_msg_arr removeObjectAtIndex: 0];
2019 [o_msg_arr removeObjectAtIndex: 1];
2021 firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
2022 secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
2024 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
2025 o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
2026 o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
2027 [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
2028 [o_msg_arr addObject: [o_msg_color autorelease]];
2030 b_msg_arr_changed = YES;
2031 [o_msg_lock unlock];
2035 - (IBAction)saveDebugLog:(id)sender
2037 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
2039 [saveFolderPanel setCanSelectHiddenExtension: NO];
2040 [saveFolderPanel setCanCreateDirectories: YES];
2041 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
2042 [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];
2045 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2048 if( returnCode == NSOKButton )
2050 NSUInteger count = [o_msg_arr count];
2051 NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
2052 for (NSUInteger i = 0; i < count; i++)
2054 [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
2056 b_returned = [[string RTFDFileWrapperFromRange:NSMakeRange( 0, [string length] ) documentAttributes:[NSDictionary dictionaryWithObject: NSRTFDTextDocumentType forKey: NSDocumentTypeDocumentAttribute]] writeToFile:[[sheet URL] path] atomically:YES updateFilenames:NO];
2060 msg_Warn( p_intf, "Error while saving the debug log" );
2065 #pragma mark Playlist toggling
2067 - (void)updateTogglePlaylistState
2069 [[self playlist] outlineViewSelectionDidChange: NULL];
2076 @implementation VLCMain (Internal)
2078 - (void)handlePortMessage:(NSPortMessage *)o_msg
2083 NSInvocation * o_inv;
2084 NSConditionLock * o_lock;
2086 o_data = [[o_msg components] lastObject];
2087 o_inv = *((NSInvocation **)[o_data bytes]);
2088 [o_inv getArgument: &o_value atIndex: 2];
2089 val = (id **)[o_value pointerValue];
2090 [o_inv setArgument: val[1] atIndex: 2];
2095 [o_lock unlockWithCondition: 1];
2097 - (void)resetMediaKeyJump
2099 b_mediakeyJustJumped = NO;
2101 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2103 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2104 if (b_mediaKeySupport) {
2105 if (!o_mediaKeyController)
2106 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2107 [o_mediaKeyController startWatchingMediaKeys];
2109 else if (!b_mediaKeySupport && o_mediaKeyController)
2111 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
2112 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
2113 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
2114 if( returnedValue == NSOKButton )
2117 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2119 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2125 execl(path, path, NULL);
2132 /*****************************************************************************
2133 * VLCApplication interface
2134 *****************************************************************************/
2136 @implementation VLCApplication
2137 // when user selects the quit menu from dock it sends a terminate:
2138 // but we need to send a stop: to properly exits libvlc.
2139 // However, we are not able to change the action-method sent by this standard menu item.
2140 // thus we override terminat: to send a stop:
2141 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2142 - (void)terminate:(id)sender
2144 [self activateIgnoringOtherApps:YES];