1 /*****************************************************************************
2 * intf.m: MacOS X interface module
3 *****************************************************************************
4 * Copyright (C) 2002-2011 the VideoLAN team
7 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8 * Christophe Massiot <massiot@via.ecp.fr>
9 * Derk-Jan Hartman <hartman at videolan.org>
10 * Felix Paul Kühne <fkuehne at videolan dot org>
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
30 #include <stdlib.h> /* malloc(), free() */
31 #include <sys/param.h> /* for MAXPATHLEN */
33 #include <vlc_common.h>
35 #include <vlc_dialog.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
44 #import "MainWindow.h"
48 #import "playlistinfo.h"
53 #import "coredialogs.h"
54 #import "embeddedwindow.h"
55 #import "AppleRemote.h"
57 #import "simple_prefs.h"
58 #import "CoreInteraction.h"
59 #import "TrackSynchronization.h"
61 #import <AddressBook/AddressBook.h> /* for crashlog send mechanism */
62 #import <Sparkle/Sparkle.h> /* we're the update delegate */
64 /*****************************************************************************
66 *****************************************************************************/
67 static void Run ( intf_thread_t *p_intf );
69 static void updateProgressPanel (void *, const char *, float);
70 static bool checkProgressPanel (void *);
71 static void destroyProgressPanel (void *);
73 static void MsgCallback( msg_cb_data_t *, const msg_item_t * );
75 static int InputEvent( vlc_object_t *, const char *,
76 vlc_value_t, vlc_value_t, void * );
77 static int PLItemChanged( vlc_object_t *, const char *,
78 vlc_value_t, vlc_value_t, void * );
79 static int PlaylistUpdated( vlc_object_t *, const char *,
80 vlc_value_t, vlc_value_t, void * );
81 static int PlaybackModeUpdated( vlc_object_t *, const char *,
82 vlc_value_t, vlc_value_t, void * );
83 static int VolumeUpdated( vlc_object_t *, const char *,
84 vlc_value_t, vlc_value_t, void * );
87 #pragma mark VLC Interface Object Callbacks
89 /*****************************************************************************
90 * OpenIntf: initialize interface
91 *****************************************************************************/
92 int OpenIntf ( vlc_object_t *p_this )
94 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
95 [VLCApplication sharedApplication];
96 intf_thread_t *p_intf = (intf_thread_t*) p_this;
98 p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
99 if( p_intf->p_sys == NULL )
102 memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
104 /* subscribe to LibVLCCore's messages */
105 p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
106 p_intf->pf_run = Run;
107 p_intf->b_should_run_on_first_thread = true;
113 /*****************************************************************************
114 * CloseIntf: destroy interface
115 *****************************************************************************/
116 void CloseIntf ( vlc_object_t *p_this )
118 intf_thread_t *p_intf = (intf_thread_t*) p_this;
120 free( p_intf->p_sys );
123 static int WindowControl( vout_window_t *, int i_query, va_list );
125 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
127 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
128 intf_thread_t *p_intf = VLCIntf;
130 msg_Err( p_wnd, "Mac OS X interface not found" );
136 unsigned i_width = cfg->width;
137 unsigned i_height = cfg->height;
138 p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
140 if ( !p_wnd->handle.nsobject ) {
141 msg_Err( p_wnd, "got no video view from the interface" );
146 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
147 [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
148 p_wnd->control = WindowControl;
149 p_wnd->sys = (vout_window_sys_t *)VLCIntf;
154 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
157 if( i_query == VOUT_WINDOW_SET_STATE )
158 NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
159 else if( i_query == VOUT_WINDOW_SET_SIZE )
161 NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
162 unsigned int i_width = va_arg( args, unsigned int );
163 unsigned int i_height = va_arg( args, unsigned int );
164 [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
166 else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
167 NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
169 NSLog( @"WindowControl: unknown query" );
173 void WindowClose( vout_window_t *p_wnd )
175 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
176 [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
177 NSLog( @"Window Close" );
178 // tell the interface to get rid of the video, TODO
182 /*****************************************************************************
184 *****************************************************************************/
185 static NSLock * o_appLock = nil; // controls access to f_appExit
186 static int f_appExit = 0; // set to 1 when application termination signaled
188 static void Run( intf_thread_t *p_intf )
192 /* Make sure the "force quit" menu item does quit instantly.
193 * VLC overrides SIGTERM which is sent by the "force quit"
194 * menu item to make sure daemon mode quits gracefully, so
195 * we un-override SIGTERM here. */
197 sigaddset( &set, SIGTERM );
198 pthread_sigmask( SIG_UNBLOCK, &set, NULL );
200 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
201 [VLCApplication sharedApplication];
203 o_appLock = [[NSLock alloc] init];
205 [[VLCMain sharedInstance] setIntf: p_intf];
206 [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
209 [[VLCMain sharedInstance] applicationWillTerminate:nil];
215 #pragma mark Variables Callback
217 /*****************************************************************************
218 * MsgCallback: Callback triggered by the core once a new debug message is
219 * ready to be displayed. We store everything in a NSArray in our Cocoa part
221 *****************************************************************************/
222 static void MsgCallback( msg_cb_data_t *data, const msg_item_t *item )
224 int canc = vlc_savecancel();
226 /* this may happen from time to time, let's bail out as info would be useless anyway */
227 if( !item->psz_module || !item->psz_msg )
230 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
231 [[VLCMain sharedInstance] processReceivedlibvlcMessage: item];
234 vlc_restorecancel( canc );
237 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
238 vlc_value_t oldval, vlc_value_t new_val, void *param )
240 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
241 switch (new_val.i_int) {
242 case INPUT_EVENT_STATE:
243 [[VLCMain sharedInstance] playbackStatusUpdated];
245 case INPUT_EVENT_RATE:
246 [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
248 case INPUT_EVENT_POSITION:
249 [[VLCMain sharedInstance] updatePlaybackPosition];
251 case INPUT_EVENT_TITLE:
252 case INPUT_EVENT_CHAPTER:
254 case INPUT_EVENT_CACHE:
255 [[VLCMain sharedInstance] updateMainWindow];
257 case INPUT_EVENT_STATISTICS:
258 [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
262 case INPUT_EVENT_TELETEXT:
263 NSLog( @"teletext" );
265 case INPUT_EVENT_AOUT:
267 case INPUT_EVENT_VOUT:
269 case INPUT_EVENT_ITEM_META:
270 case INPUT_EVENT_ITEM_INFO:
271 [[VLCMain sharedInstance] updateName];
272 [[VLCMain sharedInstance] updateInfoandMetaPanel];
274 case INPUT_EVENT_BOOKMARK:
276 case INPUT_EVENT_RECORD:
278 case INPUT_EVENT_PROGRAM:
280 case INPUT_EVENT_ITEM_EPG:
282 case INPUT_EVENT_SIGNAL:
285 case INPUT_EVENT_ITEM_NAME:
286 [[VLCMain sharedInstance] updateName];
287 [[VLCMain sharedInstance] playlistUpdated];
290 case INPUT_EVENT_AUDIO_DELAY:
291 case INPUT_EVENT_SUBTITLE_DELAY:
292 [[VLCMain sharedInstance] updateDelays];
295 case INPUT_EVENT_DEAD:
296 [[VLCMain sharedInstance] updateName];
297 [[VLCMain sharedInstance] updatePlaybackPosition];
300 case INPUT_EVENT_ABORT:
301 //NSLog( @"input stopped by user" );
305 //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
313 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
314 vlc_value_t oldval, vlc_value_t new_val, void *param )
316 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
317 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
323 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
324 vlc_value_t oldval, vlc_value_t new_val, void *param )
326 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
327 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
333 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
334 vlc_value_t oldval, vlc_value_t new_val, void *param )
336 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
337 [[VLCMain sharedInstance] playbackModeUpdated];
343 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
344 vlc_value_t oldval, vlc_value_t new_val, void *param )
346 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
347 [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
353 /*****************************************************************************
354 * ShowController: Callback triggered by the show-intf playlist variable
355 * through the ShowIntf-control-intf, to let us show the controller-win;
356 * usually when in fullscreen-mode
357 *****************************************************************************/
358 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
359 vlc_value_t old_val, vlc_value_t new_val, void *param )
361 intf_thread_t * p_intf = VLCIntf;
362 if( p_intf && p_intf->p_sys )
364 // [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
369 /*****************************************************************************
370 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
371 * variable, to let the intf update the controller.
372 *****************************************************************************/
373 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
374 vlc_value_t old_val, vlc_value_t new_val, void *param )
376 intf_thread_t * p_intf = VLCIntf;
379 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
380 [[VLCMain sharedInstance] fullscreenChanged];
386 /*****************************************************************************
387 * DialogCallback: Callback triggered by the "dialog-*" variables
388 * to let the intf display error and interaction dialogs
389 *****************************************************************************/
390 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
392 NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
393 VLCMain *interface = (VLCMain *)data;
395 if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
397 /* the progress panel needs to update itself and therefore wants special treatment within this context */
398 dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
400 p_dialog->pf_update = updateProgressPanel;
401 p_dialog->pf_check = checkProgressPanel;
402 p_dialog->pf_destroy = destroyProgressPanel;
403 p_dialog->p_sys = VLCIntf->p_libvlc;
406 NSValue *o_value = [NSValue valueWithPointer:value.p_address];
407 [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
413 void updateProgressPanel (void *priv, const char *text, float value)
415 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
419 o_txt = [NSString stringWithUTF8String: text];
423 [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
428 void destroyProgressPanel (void *priv)
430 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
431 [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
435 bool checkProgressPanel (void *priv)
437 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
438 return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
445 input_thread_t *getInput(void)
447 intf_thread_t *p_intf = VLCIntf;
450 return pl_CurrentInput(p_intf);
453 vout_thread_t *getVout(void)
455 input_thread_t *p_input = getInput();
458 vout_thread_t *p_vout = input_GetVout(p_input);
459 vlc_object_release(p_input);
463 audio_output_t *getAout(void)
465 input_thread_t *p_input = getInput();
468 audio_output_t *p_aout = input_GetAout(p_input);
469 vlc_object_release(p_input);
476 @interface VLCMain ()
477 - (void)_removeOldPreferences;
480 /*****************************************************************************
481 * VLCMain implementation
482 *****************************************************************************/
483 @implementation VLCMain
486 #pragma mark Initialization
488 static VLCMain *_o_sharedMainInstance = nil;
490 + (VLCMain *)sharedInstance
492 return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
497 if( _o_sharedMainInstance)
500 return _o_sharedMainInstance;
503 _o_sharedMainInstance = [super init];
507 o_msg_lock = [[NSLock alloc] init];
508 o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
510 o_open = [[VLCOpen alloc] init];
511 //o_embedded_list = [[VLCEmbeddedList alloc] init];
512 o_coredialogs = [[VLCCoreDialogProvider alloc] init];
513 o_info = [[VLCInfo alloc] init];
514 o_mainmenu = [[VLCMainMenu alloc] init];
515 o_coreinteraction = [[VLCCoreInteraction alloc] init];
516 o_eyetv = [[VLCEyeTVController alloc] init];
517 o_mainwindow = [[VLCMainWindow alloc] init];
519 /* announce our launch to a potential eyetv plugin */
520 [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
521 object: @"VLCEyeTVSupport"
523 deliverImmediately: YES];
524 return _o_sharedMainInstance;
527 - (void)setIntf: (intf_thread_t *)p_mainintf {
531 - (intf_thread_t *)intf {
537 playlist_t *p_playlist;
539 if( !p_intf ) return;
540 var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
542 /* Check if we already did this once. Opening the other nibs calls it too,
543 because VLCMain is the owner */
544 if( nib_main_loaded ) return;
546 [o_msgs_panel setExcludedFromWindowsMenu: YES];
547 [o_msgs_panel setDelegate: self];
549 p_playlist = pl_Get( p_intf );
553 var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
554 var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
555 // var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
556 var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
557 var_AddCallback(p_playlist, "activity", PLItemChanged, self);
558 var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
559 var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
560 var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
561 var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
562 var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
563 var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
564 var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
565 var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
567 /* load our Core Dialogs nib */
568 nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
570 /* subscribe to various interactive dialogues */
571 var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
572 var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
573 var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
574 var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
575 var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
576 var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
577 var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
578 var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
579 var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
580 var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
581 dialog_Register( p_intf );
583 [self playbackModeUpdated];
585 /* init Apple Remote support */
586 o_remote = [[AppleRemote alloc] init];
587 [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
588 [o_remote setDelegate: _o_sharedMainInstance];
590 /* yeah, we are done */
591 nib_main_loaded = TRUE;
594 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
596 if( !p_intf ) return;
598 /* init media key support */
599 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
600 if( b_mediaKeySupport )
602 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
603 [o_mediaKeyController startWatchingMediaKeys];
604 [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
605 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
608 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
610 [self _removeOldPreferences];
612 [o_mainwindow makeKeyAndOrderFront: self];
614 /* Handle sleep notification */
615 [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
616 name:NSWorkspaceWillSleepNotification object:nil];
618 [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
623 if( !p_intf ) return;
626 [o_msgs_panel setTitle: _NS("Messages")];
627 [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
628 [o_msgs_save_btn setTitle: _NS("Save this Log...")];
630 /* crash reporter panel */
631 [o_crashrep_send_btn setTitle: _NS("Send")];
632 [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
633 [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
634 [o_crashrep_win setTitle: _NS("VLC crashed previously")];
635 [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, ...")];
636 [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
637 [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
641 #pragma mark Termination
643 - (void)applicationWillTerminate:(NSNotification *)notification
645 playlist_t * p_playlist;
646 vout_thread_t * p_vout;
647 int returnedValue = 0;
652 // don't allow a double termination call. If the user has
653 // already invoked the quit then simply return this time.
654 int isTerminating = false;
657 isTerminating = (f_appExit++ > 0 ? 1 : 0);
663 msg_Dbg( p_intf, "Terminating" );
665 /* Make sure the intf object is getting killed */
666 vlc_object_kill( p_intf );
667 p_playlist = pl_Get( p_intf );
669 /* unsubscribe from the interactive dialogues */
670 dialog_Unregister( p_intf );
671 var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
672 var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
673 var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
674 var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
675 var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
676 //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
677 var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
678 var_DelCallback(p_playlist, "activity", PLItemChanged, self);
679 var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
680 var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
681 var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
682 var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
683 var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
684 var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
685 var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
686 var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
688 /* remove global observer watching for vout device changes correctly */
689 [[NSNotificationCenter defaultCenter] removeObserver: self];
691 /* release some other objects here, because it isn't sure whether dealloc
692 * will be called later on */
707 [crashLogURLConnection cancel];
708 [crashLogURLConnection release];
710 [o_embedded_list release];
711 [o_coredialogs release];
713 [o_mainwindow release];
715 /* unsubscribe from libvlc's debug messages */
716 msg_Unsubscribe( p_intf->p_sys->p_sub );
718 [o_msg_arr removeAllObjects];
721 [o_msg_lock release];
723 /* write cached user defaults to disk */
724 [[NSUserDefaults standardUserDefaults] synchronize];
726 /* Make sure the Menu doesn't have any references to vlc objects anymore */
727 //FIXME: this should be moved to VLCMainMenu
728 [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
729 [o_mainmenu release];
731 /* Kill the playlist, so that it doesn't accept new request
732 * such as the play request from vlc.c (we are a blocking interface). */
733 vlc_object_kill( p_playlist );
734 libvlc_Quit( p_intf->p_libvlc );
740 #pragma mark Sparkle delegate
741 /* received directly before the update gets installed, so let's shut down a bit */
742 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
744 [NSApp activateIgnoringOtherApps:YES];
745 [o_remote stopListening: self];
746 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
750 #pragma mark Media Key support
752 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
754 if( b_mediaKeySupport )
756 assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
758 int keyCode = (([event data1] & 0xFFFF0000) >> 16);
759 int keyFlags = ([event data1] & 0x0000FFFF);
760 int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
761 int keyRepeat = (keyFlags & 0x1);
763 if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
764 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
766 if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
768 if( keyState == 0 && keyRepeat == 0 )
769 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
770 else if( keyRepeat == 1 )
772 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
773 b_mediakeyJustJumped = YES;
774 [self performSelector:@selector(resetMediaKeyJump)
780 if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
782 if( keyState == 0 && keyRepeat == 0 )
783 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
784 else if( keyRepeat == 1 )
786 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
787 b_mediakeyJustJumped = YES;
788 [self performSelector:@selector(resetMediaKeyJump)
797 #pragma mark Other notification
799 /* Listen to the remote in exclusive mode, only when VLC is the active
801 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
803 if( !p_intf ) return;
804 if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
805 [o_remote startListening: self];
807 - (void)applicationDidResignActive:(NSNotification *)aNotification
809 if( !p_intf ) return;
810 [o_remote stopListening: self];
813 /* Triggered when the computer goes to sleep */
814 - (void)computerWillSleep: (NSNotification *)notification
816 input_thread_t * p_input;
818 p_input = pl_CurrentInput( p_intf );
821 int state = var_GetInteger( p_input, "state" );
822 if( state == PLAYING_S )
823 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
824 vlc_object_release( p_input );
829 #pragma mark File opening
831 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
833 BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
834 char *psz_uri = make_URI([o_filename UTF8String], "file" );
838 NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
843 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
845 [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
850 /* When user click in the Dock icon our double click in the finder */
851 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
853 if(!hasVisibleWindows)
854 [o_mainwindow makeKeyAndOrderFront:self];
860 #pragma mark Apple Remote Control
862 /* Helper method for the remote control interface in order to trigger forward/backward and volume
863 increase/decrease as long as the user holds the left/right, plus/minus button */
864 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
866 if(b_remote_button_hold)
868 switch([buttonIdentifierNumber intValue])
870 case kRemoteButtonRight_Hold:
871 [[VLCCoreInteraction sharedInstance] forward];
873 case kRemoteButtonLeft_Hold:
874 [[VLCCoreInteraction sharedInstance] backward];
876 case kRemoteButtonVolume_Plus_Hold:
877 [[VLCCoreInteraction sharedInstance] volumeUp];
879 case kRemoteButtonVolume_Minus_Hold:
880 [[VLCCoreInteraction sharedInstance] volumeDown];
883 if(b_remote_button_hold)
886 [self performSelector:@selector(executeHoldActionForRemoteButton:)
887 withObject:buttonIdentifierNumber
893 /* Apple Remote callback */
894 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
895 pressedDown: (BOOL) pressedDown
896 clickCount: (unsigned int) count
898 switch( buttonIdentifier )
900 case k2009RemoteButtonFullscreen:
901 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
903 case k2009RemoteButtonPlay:
904 [[VLCCoreInteraction sharedInstance] play];
906 case kRemoteButtonPlay:
908 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
910 [[VLCCoreInteraction sharedInstance] play];
913 case kRemoteButtonVolume_Plus:
914 [[VLCCoreInteraction sharedInstance] volumeUp];
916 case kRemoteButtonVolume_Minus:
917 [[VLCCoreInteraction sharedInstance] volumeDown];
919 case kRemoteButtonRight:
920 [[VLCCoreInteraction sharedInstance] next];
922 case kRemoteButtonLeft:
923 [[VLCCoreInteraction sharedInstance] previous];
925 case kRemoteButtonRight_Hold:
926 case kRemoteButtonLeft_Hold:
927 case kRemoteButtonVolume_Plus_Hold:
928 case kRemoteButtonVolume_Minus_Hold:
929 /* simulate an event as long as the user holds the button */
930 b_remote_button_hold = pressedDown;
933 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
934 [self performSelector:@selector(executeHoldActionForRemoteButton:)
935 withObject:buttonIdentifierNumber];
938 case kRemoteButtonMenu:
939 [o_controls showPosition: self]; //FIXME
942 /* Add here whatever you want other buttons to do */
948 #pragma mark String utility
949 // FIXME: this has nothing to do here
951 - (NSString *)localizedString:(const char *)psz
953 NSString * o_str = nil;
957 o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
961 msg_Err( VLCIntf, "could not translate: %s", psz );
967 msg_Warn( VLCIntf, "can't translate empty strings" );
976 - (char *)delocalizeString:(NSString *)id
978 NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
979 allowLossyConversion: NO];
984 o_data = [id dataUsingEncoding: NSUTF8StringEncoding
985 allowLossyConversion: YES];
986 psz_string = malloc( [o_data length] + 1 );
987 [o_data getBytes: psz_string];
988 psz_string[ [o_data length] ] = '\0';
989 msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
994 psz_string = malloc( [o_data length] + 1 );
995 [o_data getBytes: psz_string];
996 psz_string[ [o_data length] ] = '\0';
1002 /* i_width is in pixels */
1003 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1005 NSMutableString *o_wrapped;
1006 NSString *o_out_string;
1007 NSRange glyphRange, effectiveRange, charRange;
1008 NSRect lineFragmentRect;
1009 unsigned glyphIndex, breaksInserted = 0;
1011 NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1012 attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1013 [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1014 NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1015 NSTextContainer *o_container = [[NSTextContainer alloc]
1016 initWithContainerSize: NSMakeSize(i_width, 2000)];
1018 [o_layout_manager addTextContainer: o_container];
1019 [o_container release];
1020 [o_storage addLayoutManager: o_layout_manager];
1021 [o_layout_manager release];
1023 o_wrapped = [o_in_string mutableCopy];
1024 glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1026 for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1027 glyphIndex += effectiveRange.length) {
1028 lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1029 effectiveRange: &effectiveRange];
1030 charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1031 actualGlyphRange: &effectiveRange];
1032 if([o_wrapped lineRangeForRange:
1033 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1034 [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1038 o_out_string = [NSString stringWithString: o_wrapped];
1039 [o_wrapped release];
1040 [o_storage release];
1042 return o_out_string;
1047 #pragma mark Key Shortcuts
1052 unsigned int i_vlckey;
1053 } nskeys_to_vlckeys[] =
1055 { NSUpArrowFunctionKey, KEY_UP },
1056 { NSDownArrowFunctionKey, KEY_DOWN },
1057 { NSLeftArrowFunctionKey, KEY_LEFT },
1058 { NSRightArrowFunctionKey, KEY_RIGHT },
1059 { NSF1FunctionKey, KEY_F1 },
1060 { NSF2FunctionKey, KEY_F2 },
1061 { NSF3FunctionKey, KEY_F3 },
1062 { NSF4FunctionKey, KEY_F4 },
1063 { NSF5FunctionKey, KEY_F5 },
1064 { NSF6FunctionKey, KEY_F6 },
1065 { NSF7FunctionKey, KEY_F7 },
1066 { NSF8FunctionKey, KEY_F8 },
1067 { NSF9FunctionKey, KEY_F9 },
1068 { NSF10FunctionKey, KEY_F10 },
1069 { NSF11FunctionKey, KEY_F11 },
1070 { NSF12FunctionKey, KEY_F12 },
1071 { NSInsertFunctionKey, KEY_INSERT },
1072 { NSHomeFunctionKey, KEY_HOME },
1073 { NSEndFunctionKey, KEY_END },
1074 { NSPageUpFunctionKey, KEY_PAGEUP },
1075 { NSPageDownFunctionKey, KEY_PAGEDOWN },
1076 { NSMenuFunctionKey, KEY_MENU },
1077 { NSTabCharacter, KEY_TAB },
1078 { NSCarriageReturnCharacter, KEY_ENTER },
1079 { NSEnterCharacter, KEY_ENTER },
1080 { NSBackspaceCharacter, KEY_BACKSPACE },
1084 unsigned int CocoaKeyToVLC( unichar i_key )
1088 for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1090 if( nskeys_to_vlckeys[i].i_nskey == i_key )
1092 return nskeys_to_vlckeys[i].i_vlckey;
1095 return (unsigned int)i_key;
1098 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1100 unsigned int new = 0;
1102 if([theString rangeOfString:@"Command"].location != NSNotFound)
1103 new |= NSCommandKeyMask;
1104 if([theString rangeOfString:@"Alt"].location != NSNotFound)
1105 new |= NSAlternateKeyMask;
1106 if([theString rangeOfString:@"Shift"].location != NSNotFound)
1107 new |= NSShiftKeyMask;
1108 if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1109 new |= NSControlKeyMask;
1113 - (NSString *)VLCKeyToString:(NSString *)theString
1115 if (![theString isEqualToString:@""]) {
1116 theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1117 theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1118 theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1119 theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1120 theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1121 theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1127 /*****************************************************************************
1128 * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1129 * shortcut key. If it is, pass it off to VLC for handling and return YES,
1130 * otherwise ignore it and return NO (where it will get handled by Cocoa).
1131 *****************************************************************************/
1132 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1136 unsigned int i_pressed_modifiers = 0;
1137 const struct hotkey *p_hotkeys;
1139 NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1140 NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1143 p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1145 i_pressed_modifiers = [o_event modifierFlags];
1147 if( i_pressed_modifiers & NSShiftKeyMask ) {
1148 val.i_int |= KEY_MODIFIER_SHIFT;
1149 [tempString appendString:@"Shift-"];
1150 [tempStringPlus appendString:@"Shift+"];
1152 if( i_pressed_modifiers & NSControlKeyMask ) {
1153 val.i_int |= KEY_MODIFIER_CTRL;
1154 [tempString appendString:@"Ctrl-"];
1155 [tempStringPlus appendString:@"Ctrl+"];
1157 if( i_pressed_modifiers & NSAlternateKeyMask ) {
1158 val.i_int |= KEY_MODIFIER_ALT;
1159 [tempString appendString:@"Alt-"];
1160 [tempStringPlus appendString:@"Alt+"];
1162 if( i_pressed_modifiers & NSCommandKeyMask ) {
1163 val.i_int |= KEY_MODIFIER_COMMAND;
1164 [tempString appendString:@"Command-"];
1165 [tempStringPlus appendString:@"Command+"];
1168 [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1169 [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1171 key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1175 case NSDeleteCharacter:
1176 case NSDeleteFunctionKey:
1177 case NSDeleteCharFunctionKey:
1178 case NSBackspaceCharacter:
1179 case NSUpArrowFunctionKey:
1180 case NSDownArrowFunctionKey:
1181 case NSRightArrowFunctionKey:
1182 case NSLeftArrowFunctionKey:
1183 case NSEnterCharacter:
1184 case NSCarriageReturnCharacter:
1188 val.i_int |= CocoaKeyToVLC( key );
1190 if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1192 var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1199 - (void)updateCurrentlyUsedHotkeys
1201 NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1202 /* Get the main Module */
1203 module_t *p_main = module_get_main();
1206 module_config_t *p_config;
1208 p_config = module_config_get (p_main, &confsize);
1210 for (size_t i = 0; i < confsize; i++)
1212 module_config_t *p_item = p_config + i;
1214 if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1215 && !strncmp( p_item->psz_name , "key-", 4 )
1216 && !EMPTY_STR( p_item->psz_text ) )
1218 if (p_item->value.psz)
1219 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1222 module_config_free (p_config);
1223 module_release (p_main);
1224 o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1228 #pragma mark Interface updaters
1229 - (void)fullscreenChanged
1231 if(! [o_mainwindow isFullscreen] )
1232 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1234 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1237 - (void)PlaylistItemChanged
1239 input_thread_t * p_input;
1241 p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1242 if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1244 var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1245 [o_mainmenu setRateControlsEnabled: YES];
1246 vlc_object_release( p_input );
1249 [o_mainmenu setRateControlsEnabled: NO];
1251 [o_playlist updateRowSelection];
1252 [o_mainwindow updateWindow];
1253 [o_mainmenu setupMenus];
1254 [o_mainmenu updatePlaybackRate];
1257 - (void)updateMainWindow
1259 [o_mainwindow updateWindow];
1262 - (void)updateDelays
1264 [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1269 [o_mainwindow updateName];
1272 - (void)updatePlaybackPosition
1274 [o_mainwindow updateTimeSlider];
1276 input_thread_t * p_input;
1277 p_input = pl_CurrentInput( p_intf );
1280 if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1281 UpdateSystemActivity( UsrActivity );
1282 vlc_object_release( p_input );
1286 - (void)updateVolume
1288 [o_mainwindow updateVolumeSlider];
1291 - (void)playlistUpdated
1293 [self playbackStatusUpdated];
1294 [o_playlist playlistUpdated];
1295 [o_mainwindow updateWindow];
1298 - (void)updateInfoandMetaPanel
1300 [o_playlist outlineViewSelectionDidChange:nil];
1303 - (void)playbackStatusUpdated
1305 input_thread_t * p_input;
1307 p_input = pl_CurrentInput( p_intf );
1310 int state = var_GetInteger( p_input, "state" );
1311 if( state == PLAYING_S )
1313 [[self mainMenu] setPause];
1314 [o_mainwindow setPause];
1319 [o_mainmenu setSubmenusEnabled: FALSE];
1320 [[self mainMenu] setPlay];
1321 [o_mainwindow setPlay];
1323 vlc_object_release( p_input );
1327 - (void)playbackModeUpdated
1329 vlc_value_t looping,repeating;
1330 playlist_t * p_playlist = pl_Get( VLCIntf );
1332 bool loop = var_GetBool( p_playlist, "loop" );
1333 bool repeat = var_GetBool( p_playlist, "repeat" );
1335 [o_mainwindow setRepeatOne];
1336 [o_mainmenu setRepeatOne];
1338 [o_mainwindow setRepeatAll];
1339 [o_mainmenu setRepeatAll];
1341 [o_mainwindow setRepeatOff];
1342 [o_mainmenu setRepeatOff];
1345 [o_mainwindow setShuffle];
1346 [o_mainmenu setShuffle];
1350 #pragma mark Other objects getters
1368 o_bookmarks = [[VLCBookmarks alloc] init];
1370 if( !nib_bookmarks_loaded )
1371 nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1381 if (!nib_open_loaded)
1382 nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1387 - (id)simplePreferences
1390 o_sprefs = [[VLCSimplePrefs alloc] init];
1392 if (!nib_prefs_loaded)
1393 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1401 o_prefs = [[VLCPrefs alloc] init];
1403 if( !nib_prefs_loaded )
1404 nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1419 if(! nib_info_loaded )
1420 nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1431 o_wizard = [[VLCWizard alloc] init];
1433 if( !nib_wizard_loaded )
1435 nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1436 [o_wizard initStrings];
1441 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1443 id videoView = [o_mainwindow videoView];
1444 NSRect videoRect = [videoView frame];
1445 int i_x = (int)videoRect.origin.x;
1446 int i_y = (int)videoRect.origin.y;
1447 unsigned int i_width = (int)videoRect.size.width;
1448 unsigned int i_height = (int)videoRect.size.height;
1451 pi_width = (unsigned int*)i_width;
1452 pi_height = (unsigned int*)i_height;
1453 msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1457 - (void)setNativeVideoSize:(NSSize)size
1459 [o_mainwindow setNativeVideoSize:size];
1464 if( o_embedded_list )
1465 return o_embedded_list;
1470 - (id)coreDialogProvider
1473 return o_coredialogs;
1478 - (id)eyeTVController
1486 - (id)appleRemoteController
1491 - (void)setActiveVideoPlayback:(BOOL)b_value
1493 b_active_videoplayback = b_value;
1494 [o_mainwindow setVideoplayEnabled];
1495 [o_mainwindow togglePlaylist:nil];
1498 - (BOOL)activeVideoPlayback
1500 return b_active_videoplayback;
1504 #pragma mark Crash Log
1505 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1507 NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1508 NSURL *url = [NSURL URLWithString:urlStr];
1510 NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1511 [req setHTTPMethod:@"POST"];
1514 if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1516 ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1517 ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1518 email = [emails valueAtIndex:[emails indexForIdentifier:
1519 [emails primaryIdentifier]]];
1522 email = [NSString string];
1525 postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1526 [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1527 [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1528 [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1530 [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1532 /* Released from delegate */
1533 crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1536 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1538 [crashLogURLConnection release];
1539 crashLogURLConnection = nil;
1542 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1544 NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1545 [crashLogURLConnection release];
1546 crashLogURLConnection = nil;
1549 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1551 NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1552 NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1554 NSString * latestLog = nil;
1555 int year = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1556 int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1557 int day = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"] : 0;
1558 int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1560 while (fname = [direnum nextObject])
1562 [direnum skipDescendents];
1563 if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1565 NSArray * compo = [fname componentsSeparatedByString:@"_"];
1566 if( [compo count] < 3 ) continue;
1567 compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1568 if( [compo count] < 4 ) continue;
1571 if( year < [[compo objectAtIndex:0] intValue] ||
1572 (year ==[[compo objectAtIndex:0] intValue] &&
1573 (month < [[compo objectAtIndex:1] intValue] ||
1574 (month ==[[compo objectAtIndex:1] intValue] &&
1575 (day < [[compo objectAtIndex:2] intValue] ||
1576 (day ==[[compo objectAtIndex:2] intValue] &&
1577 hours < [[compo objectAtIndex:3] intValue] ))))))
1579 year = [[compo objectAtIndex:0] intValue];
1580 month = [[compo objectAtIndex:1] intValue];
1581 day = [[compo objectAtIndex:2] intValue];
1582 hours = [[compo objectAtIndex:3] intValue];
1583 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1588 if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1591 if( !previouslySeen )
1593 [[NSUserDefaults standardUserDefaults] setInteger:year forKey:@"LatestCrashReportYear"];
1594 [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1595 [[NSUserDefaults standardUserDefaults] setInteger:day forKey:@"LatestCrashReportDay"];
1596 [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1601 - (NSString *)latestCrashLogPath
1603 return [self latestCrashLogPathPreviouslySeen:YES];
1606 - (void)lookForCrashLog
1608 NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1609 // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1610 BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1611 NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1612 if( latestLog && !areCrashLogsTooOld )
1613 [NSApp runModalForWindow: o_crashrep_win];
1617 - (IBAction)crashReporterAction:(id)sender
1619 if( sender == o_crashrep_send_btn )
1620 [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1623 [o_crashrep_win orderOut: sender];
1626 - (IBAction)openCrashLog:(id)sender
1628 NSString * latestLog = [self latestCrashLogPath];
1631 [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1635 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.") );
1640 #pragma mark Remove old prefs
1642 - (void)_removeOldPreferences
1644 static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1645 static const int kCurrentPreferencesVersion = 1;
1646 int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1647 if( version >= kCurrentPreferencesVersion ) return;
1649 NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1650 NSUserDomainMask, YES);
1651 if( !libraries || [libraries count] == 0) return;
1652 NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1654 /* File not found, don't attempt anything */
1655 if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1656 ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1658 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1662 int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1663 _NS("We just found an older version of VLC's preferences files."),
1664 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1665 if( res != NSOKButton )
1667 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1671 NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1673 /* Move the file to trash so that user can find them later */
1674 [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1676 /* really reset the defaults from now on */
1677 [NSUserDefaults resetStandardUserDefaults];
1679 [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1680 [[NSUserDefaults standardUserDefaults] synchronize];
1683 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1685 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1691 execl(path, path, NULL);
1695 #pragma mark Errors, warnings and messages
1696 - (IBAction)showMessagesPanel:(id)sender
1698 [o_msgs_panel makeKeyAndOrderFront: sender];
1701 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1703 if( [o_notification object] == o_msgs_panel )
1704 [self updateMessageDisplay];
1707 - (void)updateMessageDisplay
1709 if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1712 NSEnumerator * o_enum;
1714 [o_messages setString: @""];
1718 o_enum = [o_msg_arr objectEnumerator];
1720 while( ( o_msg = [o_enum nextObject] ) != nil )
1722 [o_messages insertText: o_msg];
1725 b_msg_arr_changed = NO;
1726 [o_msg_lock unlock];
1730 - (void)processReceivedlibvlcMessage:(const msg_item_t *)item
1732 NSColor *o_white = [NSColor whiteColor];
1733 NSColor *o_red = [NSColor redColor];
1734 NSColor *o_yellow = [NSColor yellowColor];
1735 NSColor *o_gray = [NSColor grayColor];
1737 NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1738 static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1740 NSDictionary *o_attr;
1741 NSAttributedString *o_msg_color;
1743 int i_type = item->i_type;
1747 if( [o_msg_arr count] + 2 > 600 )
1749 [o_msg_arr removeObjectAtIndex: 0];
1750 [o_msg_arr removeObjectAtIndex: 1];
1753 o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1754 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1755 [o_msg_arr addObject: [o_msg_color autorelease]];
1757 o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1758 o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", item->psz_msg] attributes: o_attr];
1759 [o_msg_arr addObject: [o_msg_color autorelease]];
1761 b_msg_arr_changed = YES;
1762 [o_msg_lock unlock];
1764 [self updateMessageDisplay];
1767 - (IBAction)saveDebugLog:(id)sender
1769 NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1771 [saveFolderPanel setCanSelectHiddenExtension: NO];
1772 [saveFolderPanel setCanCreateDirectories: YES];
1773 [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1774 [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];
1777 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1780 if( returnCode == NSOKButton )
1782 b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1784 msg_Warn( p_intf, "Error while saving the debug log" );
1789 #pragma mark Playlist toggling
1791 - (void)updateTogglePlaylistState
1793 [[self playlist] outlineViewSelectionDidChange: NULL];
1800 @implementation VLCMain (Internal)
1802 - (void)handlePortMessage:(NSPortMessage *)o_msg
1807 NSInvocation * o_inv;
1808 NSConditionLock * o_lock;
1810 o_data = [[o_msg components] lastObject];
1811 o_inv = *((NSInvocation **)[o_data bytes]);
1812 [o_inv getArgument: &o_value atIndex: 2];
1813 val = (id **)[o_value pointerValue];
1814 [o_inv setArgument: val[1] atIndex: 2];
1819 [o_lock unlockWithCondition: 1];
1821 - (void)resetMediaKeyJump
1823 b_mediakeyJustJumped = NO;
1825 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1827 b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1828 if (b_mediaKeySupport) {
1829 if (!o_mediaKeyController)
1830 o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1831 [o_mediaKeyController startWatchingMediaKeys];
1833 else if (!b_mediaKeySupport && o_mediaKeyController)
1835 int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1836 _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1837 _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1838 if( returnedValue == NSOKButton )
1841 const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1843 /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1849 execl(path, path, NULL);
1856 /*****************************************************************************
1857 * VLCApplication interface
1858 *****************************************************************************/
1860 @implementation VLCApplication
1861 // when user selects the quit menu from dock it sends a terminate:
1862 // but we need to send a stop: to properly exits libvlc.
1863 // However, we are not able to change the action-method sent by this standard menu item.
1864 // thus we override terminat: to send a stop:
1865 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1866 - (void)terminate:(id)sender
1868 [self activateIgnoringOtherApps:YES];