]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: replaced a few NSLog which sneaked in this summer
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2011 VLC authors and VideoLAN
5  * $Id$
6  *
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>
11  *
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.
16  *
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.
21  *
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  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>                                      /* malloc(), free() */
31 #include <sys/param.h>                                    /* for MAXPATHLEN */
32 #include <string.h>
33 #include <vlc_common.h>
34 #include <vlc_keys.h>
35 #include <vlc_dialog.h>
36 #include <vlc_url.h>
37 #include <vlc_modules.h>
38 #include <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
41
42 #import "CompatibilityFixes.h"
43 #import "intf.h"
44 #import "MainMenu.h"
45 #import "VideoView.h"
46 #import "prefs.h"
47 #import "playlist.h"
48 #import "playlistinfo.h"
49 #import "controls.h"
50 #import "open.h"
51 #import "wizard.h"
52 #import "bookmarks.h"
53 #import "coredialogs.h"
54 #import "AppleRemote.h"
55 #import "eyetv.h"
56 #import "simple_prefs.h"
57 #import "CoreInteraction.h"
58 #import "TrackSynchronization.h"
59
60 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
61 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
62
63 /*****************************************************************************
64  * Local prototypes.
65  *****************************************************************************/
66 static void Run ( intf_thread_t *p_intf );
67
68 static void updateProgressPanel (void *, const char *, float);
69 static bool checkProgressPanel (void *);
70 static void destroyProgressPanel (void *);
71
72 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap );
73
74 static int InputEvent( vlc_object_t *, const char *,
75                       vlc_value_t, vlc_value_t, void * );
76 static int PLItemChanged( vlc_object_t *, const char *,
77                          vlc_value_t, vlc_value_t, void * );
78 static int PlaylistUpdated( vlc_object_t *, const char *,
79                            vlc_value_t, vlc_value_t, void * );
80 static int PlaybackModeUpdated( vlc_object_t *, const char *,
81                                vlc_value_t, vlc_value_t, void * );
82 static int VolumeUpdated( vlc_object_t *, const char *,
83                          vlc_value_t, vlc_value_t, void * );
84
85 #pragma mark -
86 #pragma mark VLC Interface Object Callbacks
87
88 /*****************************************************************************
89  * OpenIntf: initialize interface
90  *****************************************************************************/
91 int OpenIntf ( vlc_object_t *p_this )
92 {
93     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
94     [VLCApplication sharedApplication];
95     intf_thread_t *p_intf = (intf_thread_t*) p_this;
96
97     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
98     if( p_intf->p_sys == NULL )
99         return VLC_ENOMEM;
100
101     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
102
103     /* subscribe to LibVLCCore's messages */
104     p_intf->p_sys->p_sub = vlc_Subscribe( MsgCallback, NULL );
105     p_intf->pf_run = Run;
106     p_intf->b_should_run_on_first_thread = true;
107
108     [o_pool release];
109     return VLC_SUCCESS;
110 }
111
112 /*****************************************************************************
113  * CloseIntf: destroy interface
114  *****************************************************************************/
115 void CloseIntf ( vlc_object_t *p_this )
116 {
117     intf_thread_t *p_intf = (intf_thread_t*) p_this;
118
119     free( p_intf->p_sys );
120 }
121
122 static int WindowControl( vout_window_t *, int i_query, va_list );
123
124 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
125 {
126     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
127     intf_thread_t *p_intf = VLCIntf;
128     if (!p_intf) {
129         msg_Err( p_wnd, "Mac OS X interface not found" );
130         return VLC_EGENERIC;
131     }
132
133     int i_x = cfg->x;
134     int i_y = cfg->y;
135     unsigned i_width = cfg->width;
136     unsigned i_height = cfg->height;
137     p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
138
139     if ( !p_wnd->handle.nsobject ) {
140         msg_Err( p_wnd, "got no video view from the interface" );
141         [o_pool release];
142         return VLC_EGENERIC;
143     }
144
145     [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
146     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
147     p_wnd->control = WindowControl;
148     p_wnd->sys = (vout_window_sys_t *)VLCIntf;
149     [o_pool release];
150     return VLC_SUCCESS;
151 }
152
153 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
154 {
155     /* TODO */
156     if( i_query == VOUT_WINDOW_SET_STATE )
157         msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
158     else if( i_query == VOUT_WINDOW_SET_SIZE )
159     {
160         unsigned int i_width  = va_arg( args, unsigned int );
161         unsigned int i_height = va_arg( args, unsigned int );
162         [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
163     }
164     else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
165         msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
166     else
167         msg_Dbg( p_wnd, "WindowControl: unknown query" );
168     return VLC_SUCCESS;
169 }
170
171 void WindowClose( vout_window_t *p_wnd )
172 {
173     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
174     [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
175
176     [o_pool release];
177 }
178
179 /*****************************************************************************
180  * Run: main loop
181  *****************************************************************************/
182 static NSLock * o_appLock = nil;    // controls access to f_appExit
183 static int f_appExit = 0;           // set to 1 when application termination signaled
184
185 static void Run( intf_thread_t *p_intf )
186 {
187     sigset_t set;
188
189     /* Make sure the "force quit" menu item does quit instantly.
190      * VLC overrides SIGTERM which is sent by the "force quit"
191      * menu item to make sure daemon mode quits gracefully, so
192      * we un-override SIGTERM here. */
193     sigemptyset( &set );
194     sigaddset( &set, SIGTERM );
195     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
196
197     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
198     [VLCApplication sharedApplication];
199
200     o_appLock = [[NSLock alloc] init];
201
202     [[VLCMain sharedInstance] setIntf: p_intf];
203     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
204
205     [NSApp run];
206     [[VLCMain sharedInstance] applicationWillTerminate:nil];
207     [o_appLock release];
208     [o_pool release];
209 }
210
211 #pragma mark -
212 #pragma mark Variables Callback
213
214 /*****************************************************************************
215  * MsgCallback: Callback triggered by the core once a new debug message is
216  * ready to be displayed. We store everything in a NSArray in our Cocoa part
217  * of this file.
218  *****************************************************************************/
219 static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
220 {
221     int canc = vlc_savecancel();
222     char *str;
223
224     if (vasprintf( &str, format, ap ) == -1)
225     {
226         vlc_restorecancel( canc );
227         return;
228     }
229
230     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
231     [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
232     [o_pool release];
233
234     vlc_restorecancel( canc );
235     free( str );
236 }
237
238 static int InputEvent( vlc_object_t *p_this, const char *psz_var,
239                        vlc_value_t oldval, vlc_value_t new_val, void *param )
240 {
241     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
242     switch (new_val.i_int) {
243         case INPUT_EVENT_STATE:
244             [[VLCMain sharedInstance] playbackStatusUpdated];
245             break;
246         case INPUT_EVENT_RATE:
247             [[VLCMainMenu sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
248             break;
249         case INPUT_EVENT_POSITION:
250             [[VLCMain sharedInstance] updatePlaybackPosition];
251             break;
252         case INPUT_EVENT_TITLE:
253         case INPUT_EVENT_CHAPTER:
254             [[VLCMain sharedInstance] updateMainMenu];
255             break;
256         case INPUT_EVENT_CACHE:
257             [[VLCMain sharedInstance] updateMainWindow];
258             break;
259         case INPUT_EVENT_STATISTICS:
260             [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
261             break;
262         case INPUT_EVENT_ES:
263             break;
264         case INPUT_EVENT_TELETEXT:
265             break;
266         case INPUT_EVENT_AOUT:
267             break;
268         case INPUT_EVENT_VOUT:
269             break;
270         case INPUT_EVENT_ITEM_META:
271         case INPUT_EVENT_ITEM_INFO:
272             [[VLCMain sharedInstance] updateMainMenu];
273             [[VLCMain sharedInstance] updateName];
274             [[VLCMain sharedInstance] updateInfoandMetaPanel];
275             break;
276         case INPUT_EVENT_BOOKMARK:
277             break;
278         case INPUT_EVENT_RECORD:
279             [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
280             break;
281         case INPUT_EVENT_PROGRAM:
282             [[VLCMain sharedInstance] updateMainMenu];
283             break;
284         case INPUT_EVENT_ITEM_EPG:
285             break;
286         case INPUT_EVENT_SIGNAL:
287             break;
288
289         case INPUT_EVENT_ITEM_NAME:
290             [[VLCMain sharedInstance] updateName];
291             [[VLCMain sharedInstance] playlistUpdated];
292             break;
293
294         case INPUT_EVENT_AUDIO_DELAY:
295         case INPUT_EVENT_SUBTITLE_DELAY:
296             [[VLCMain sharedInstance] updateDelays];
297             break;
298
299         case INPUT_EVENT_DEAD:
300             [[VLCMain sharedInstance] updateName];
301             [[VLCMain sharedInstance] updatePlaybackPosition];
302             break;
303
304         case INPUT_EVENT_ABORT:
305             [[VLCMain sharedInstance] updateName];
306             [[VLCMain sharedInstance] updatePlaybackPosition];
307             break;
308
309         default:
310             //msg_Warn( p_this, "unhandled input event (%lld)", new_val.i_int );
311             break;
312     }
313
314     [o_pool release];
315     return VLC_SUCCESS;
316 }
317
318 static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
319                          vlc_value_t oldval, vlc_value_t new_val, void *param )
320 {
321     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
322     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];
323
324     [o_pool release];
325     return VLC_SUCCESS;
326 }
327
328 static int PlaylistUpdated( vlc_object_t *p_this, const char *psz_var,
329                          vlc_value_t oldval, vlc_value_t new_val, void *param )
330 {
331     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
332     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
333
334     [o_pool release];
335     return VLC_SUCCESS;
336 }
337
338 static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
339                          vlc_value_t oldval, vlc_value_t new_val, void *param )
340 {
341     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
342     [[VLCMain sharedInstance] playbackModeUpdated];
343
344     [o_pool release];
345     return VLC_SUCCESS;
346 }
347
348 static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
349                          vlc_value_t oldval, vlc_value_t new_val, void *param )
350 {
351     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
352     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
353
354     [o_pool release];
355     return VLC_SUCCESS;
356 }
357
358 /*****************************************************************************
359  * ShowController: Callback triggered by the show-intf playlist variable
360  * through the ShowIntf-control-intf, to let us show the controller-win;
361  * usually when in fullscreen-mode
362  *****************************************************************************/
363 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
364                      vlc_value_t old_val, vlc_value_t new_val, void *param )
365 {
366     intf_thread_t * p_intf = VLCIntf;
367     if( p_intf && p_intf->p_sys )
368     {
369 //        [[[VLCMain sharedInstance] fspanel] makeKeyAndOrderFront: nil];
370     }
371     return VLC_SUCCESS;
372 }
373
374 /*****************************************************************************
375  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
376  * variable, to let the intf update the controller.
377  *****************************************************************************/
378 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
379                      vlc_value_t old_val, vlc_value_t new_val, void *param )
380 {
381     intf_thread_t * p_intf = VLCIntf;
382     if (p_intf)
383     {
384         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
385         [[VLCMain sharedInstance] fullscreenChanged];
386         [o_pool release];
387     }
388     return VLC_SUCCESS;
389 }
390
391 /*****************************************************************************
392  * DialogCallback: Callback triggered by the "dialog-*" variables
393  * to let the intf display error and interaction dialogs
394  *****************************************************************************/
395 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
396 {
397     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
398     VLCMain *interface = (VLCMain *)data;
399
400     if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
401     {
402         /* the progress panel needs to update itself and therefore wants special treatment within this context */
403         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
404
405         p_dialog->pf_update = updateProgressPanel;
406         p_dialog->pf_check = checkProgressPanel;
407         p_dialog->pf_destroy = destroyProgressPanel;
408         p_dialog->p_sys = VLCIntf->p_libvlc;
409     }
410
411     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
412     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
413
414     [o_pool release];
415     return VLC_SUCCESS;
416 }
417
418 void updateProgressPanel (void *priv, const char *text, float value)
419 {
420     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
421
422     NSString *o_txt;
423     if( text != NULL )
424         o_txt = [NSString stringWithUTF8String: text];
425     else
426         o_txt = @"";
427
428     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
429
430     [o_pool release];
431 }
432
433 void destroyProgressPanel (void *priv)
434 {
435     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
436     [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
437     [o_pool release];
438 }
439
440 bool checkProgressPanel (void *priv)
441 {
442     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
443     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
444     [o_pool release];
445 }
446
447 #pragma mark -
448 #pragma mark Helpers
449
450 input_thread_t *getInput(void)
451 {
452     intf_thread_t *p_intf = VLCIntf;
453     if (!p_intf)
454         return NULL;
455     return pl_CurrentInput(p_intf);
456 }
457
458 vout_thread_t *getVout(void)
459 {
460     input_thread_t *p_input = getInput();
461     if (!p_input)
462         return NULL;
463     vout_thread_t *p_vout = input_GetVout(p_input);
464     vlc_object_release(p_input);
465     return p_vout;
466 }
467
468 audio_output_t *getAout(void)
469 {
470     input_thread_t *p_input = getInput();
471     if (!p_input)
472         return NULL;
473     audio_output_t *p_aout = input_GetAout(p_input);
474     vlc_object_release(p_input);
475     return p_aout;
476 }
477
478 #pragma mark -
479 #pragma mark Private
480
481 @interface VLCMain ()
482 - (void)_removeOldPreferences;
483 @end
484
485 /*****************************************************************************
486  * VLCMain implementation
487  *****************************************************************************/
488 @implementation VLCMain
489
490 #pragma mark -
491 #pragma mark Initialization
492
493 static VLCMain *_o_sharedMainInstance = nil;
494
495 + (VLCMain *)sharedInstance
496 {
497     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
498 }
499
500 - (id)init
501 {
502     if( _o_sharedMainInstance)
503     {
504         [self dealloc];
505         return _o_sharedMainInstance;
506     }
507     else
508         _o_sharedMainInstance = [super init];
509
510     p_intf = NULL;
511
512     o_msg_lock = [[NSLock alloc] init];
513     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
514
515     o_open = [[VLCOpen alloc] init];
516     //o_embedded_list = [[VLCEmbeddedList alloc] init];
517     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
518     o_info = [[VLCInfo alloc] init];
519     o_mainmenu = [[VLCMainMenu alloc] init];
520     o_coreinteraction = [[VLCCoreInteraction alloc] init];
521     o_eyetv = [[VLCEyeTVController alloc] init];
522     o_mainwindow = [[VLCMainWindow alloc] init];
523
524     /* announce our launch to a potential eyetv plugin */
525     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
526                                                                    object: @"VLCEyeTVSupport"
527                                                                  userInfo: NULL
528                                                        deliverImmediately: YES];
529     return _o_sharedMainInstance;
530 }
531
532 - (void)setIntf: (intf_thread_t *)p_mainintf {
533     p_intf = p_mainintf;
534 }
535
536 - (intf_thread_t *)intf {
537     return p_intf;
538 }
539
540 - (void)awakeFromNib
541 {
542     playlist_t *p_playlist;
543     vlc_value_t val;
544     if( !p_intf ) return;
545     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
546
547     /* Check if we already did this once. Opening the other nibs calls it too,
548      because VLCMain is the owner */
549     if( nib_main_loaded ) return;
550
551     [o_msgs_panel setExcludedFromWindowsMenu: YES];
552     [o_msgs_panel setDelegate: self];
553
554     p_playlist = pl_Get( p_intf );
555
556     val.b_bool = false;
557
558     var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
559     var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
560 //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
561     var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
562     var_AddCallback(p_playlist, "activity", PLItemChanged, self);
563     var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
564     var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
565     var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
566     var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
567     var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
568     var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
569     var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
570     var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
571
572     if (OSX_LION)
573     {
574         if ([NSApp currentSystemPresentationOptions] == NSApplicationPresentationFullScreen)
575             var_SetBool( p_playlist, "fullscreen", YES );
576     }
577
578     /* load our Core Dialogs nib */
579     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
580
581     /* subscribe to various interactive dialogues */
582     var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
583     var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
584     var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
585     var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
586     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
587     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
588     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
589     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
590     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
591     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
592     dialog_Register( p_intf );
593
594     [self playbackModeUpdated];
595
596     /* init Apple Remote support */
597     o_remote = [[AppleRemote alloc] init];
598     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
599     [o_remote setDelegate: _o_sharedMainInstance];
600
601     /* yeah, we are done */
602     b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
603     nib_main_loaded = TRUE;
604 }
605
606 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
607 {
608     if( !p_intf ) return;
609
610     /* init media key support */
611     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
612     if( b_mediaKeySupport )
613     {
614         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
615         [o_mediaKeyController startWatchingMediaKeys];
616         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
617                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
618                                                                  nil]];
619     }
620     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
621
622     [self _removeOldPreferences];
623
624     [o_mainwindow updateWindow];
625     [o_mainwindow updateTimeSlider];
626     [o_mainwindow updateVolumeSlider];
627     [o_mainwindow makeKeyAndOrderFront: self];
628
629     /* Handle sleep notification */
630     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
631            name:NSWorkspaceWillSleepNotification object:nil];
632
633     [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
634 }
635
636 - (void)initStrings
637 {
638     if( !p_intf ) return;
639
640     /* messages panel */
641     [o_msgs_panel setTitle: _NS("Messages")];
642     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
643     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
644
645     /* crash reporter panel */
646     [o_crashrep_send_btn setTitle: _NS("Send")];
647     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
648     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
649     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
650     [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, ...")];
651     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
652     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
653 }
654
655 #pragma mark -
656 #pragma mark Termination
657
658 - (void)applicationWillTerminate:(NSNotification *)notification
659 {
660     playlist_t * p_playlist;
661     vout_thread_t * p_vout;
662     int returnedValue = 0;
663
664     if( !p_intf )
665         return;
666
667     // save stuff
668     config_SaveConfigFile( p_intf );
669
670     // don't allow a double termination call. If the user has
671     // already invoked the quit then simply return this time.
672     int isTerminating = false;
673
674     [o_appLock lock];
675     isTerminating = (f_appExit++ > 0 ? 1 : 0);
676     [o_appLock unlock];
677
678     if (isTerminating)
679         return;
680
681     msg_Dbg( p_intf, "Terminating" );
682
683     /* Make sure the intf object is getting killed */
684     vlc_object_kill( p_intf );
685     p_playlist = pl_Get( p_intf );
686
687     /* unsubscribe from the interactive dialogues */
688     dialog_Unregister( p_intf );
689     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
690     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
691     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
692     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
693     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
694     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
695     var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
696     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
697     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
698     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
699     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
700     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
701     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
702     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
703     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
704     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
705     var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
706     var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
707
708     /* remove global observer watching for vout device changes correctly */
709     [[NSNotificationCenter defaultCenter] removeObserver: self];
710
711     /* release some other objects here, because it isn't sure whether dealloc
712      * will be called later on */
713     if( o_sprefs )
714         [o_sprefs release];
715
716     if( o_prefs )
717         [o_prefs release];
718
719     [o_open release];
720
721     if( o_info )
722         [o_info release];
723
724     if( o_wizard )
725         [o_wizard release];
726
727     [crashLogURLConnection cancel];
728     [crashLogURLConnection release];
729
730     [o_embedded_list release];
731     [o_coredialogs release];
732     [o_eyetv release];
733     [o_mainwindow release];
734
735     /* unsubscribe from libvlc's debug messages */
736     vlc_Unsubscribe( p_intf->p_sys->p_sub );
737
738     [o_msg_arr removeAllObjects];
739     [o_msg_arr release];
740
741     [o_msg_lock release];
742
743     /* write cached user defaults to disk */
744     [[NSUserDefaults standardUserDefaults] synchronize];
745
746     /* Make sure the Menu doesn't have any references to vlc objects anymore */
747     //FIXME: this should be moved to VLCMainMenu
748     [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
749     [o_mainmenu release];
750
751     /* Kill the playlist, so that it doesn't accept new request
752      * such as the play request from vlc.c (we are a blocking interface). */
753     vlc_object_kill( p_playlist );
754     libvlc_Quit( p_intf->p_libvlc );
755
756     [self setIntf:nil];
757 }
758
759 #pragma mark -
760 #pragma mark Sparkle delegate
761 /* received directly before the update gets installed, so let's shut down a bit */
762 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
763 {
764     [NSApp activateIgnoringOtherApps:YES];
765     [o_remote stopListening: self];
766     var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
767 }
768
769 #pragma mark -
770 #pragma mark Media Key support
771
772 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
773 {
774     if( b_mediaKeySupport )
775        {
776         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
777
778         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
779         int keyFlags = ([event data1] & 0x0000FFFF);
780         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
781         int keyRepeat = (keyFlags & 0x1);
782
783         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
784             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
785
786         if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
787         {
788             if( keyState == 0 && keyRepeat == 0 )
789                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
790             else if( keyRepeat == 1 )
791             {
792                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
793                 b_mediakeyJustJumped = YES;
794                 [self performSelector:@selector(resetMediaKeyJump)
795                            withObject: NULL
796                            afterDelay:0.25];
797             }
798         }
799
800         if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
801         {
802             if( keyState == 0 && keyRepeat == 0 )
803                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
804             else if( keyRepeat == 1 )
805             {
806                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
807                 b_mediakeyJustJumped = YES;
808                 [self performSelector:@selector(resetMediaKeyJump)
809                            withObject: NULL
810                            afterDelay:0.25];
811             }
812         }
813     }
814 }
815
816 #pragma mark -
817 #pragma mark Other notification
818
819 /* Listen to the remote in exclusive mode, only when VLC is the active
820    application */
821 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
822 {
823     if( !p_intf ) return;
824         if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
825                 [o_remote startListening: self];
826 }
827 - (void)applicationDidResignActive:(NSNotification *)aNotification
828 {
829     if( !p_intf ) return;
830     [o_remote stopListening: self];
831 }
832
833 /* Triggered when the computer goes to sleep */
834 - (void)computerWillSleep: (NSNotification *)notification
835 {
836     input_thread_t * p_input;
837
838     p_input = pl_CurrentInput( p_intf );
839     if( p_input )
840     {
841         int state = var_GetInteger( p_input, "state" );
842         if( state == PLAYING_S )
843             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
844         vlc_object_release( p_input );
845     }
846 }
847
848 #pragma mark -
849 #pragma mark File opening
850
851 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
852 {
853     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
854     char *psz_uri = make_URI([o_filename UTF8String], "file" );
855     if( !psz_uri )
856         return( FALSE );
857
858     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
859
860     free( psz_uri );
861
862     if( b_autoplay )
863         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
864     else
865         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
866
867     return( TRUE );
868 }
869
870 /* When user click in the Dock icon our double click in the finder */
871 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
872 {
873     if(!hasVisibleWindows)
874         [o_mainwindow makeKeyAndOrderFront:self];
875
876     return YES;
877 }
878
879 #pragma mark -
880 #pragma mark Apple Remote Control
881
882 /* Helper method for the remote control interface in order to trigger forward/backward and volume
883    increase/decrease as long as the user holds the left/right, plus/minus button */
884 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
885 {
886     if(b_remote_button_hold)
887     {
888         switch([buttonIdentifierNumber intValue])
889         {
890             case kRemoteButtonRight_Hold:
891                 [[VLCCoreInteraction sharedInstance] forward];
892             break;
893             case kRemoteButtonLeft_Hold:
894                 [[VLCCoreInteraction sharedInstance] backward];
895             break;
896             case kRemoteButtonVolume_Plus_Hold:
897                 [[VLCCoreInteraction sharedInstance] volumeUp];
898             break;
899             case kRemoteButtonVolume_Minus_Hold:
900                 [[VLCCoreInteraction sharedInstance] volumeDown];
901             break;
902         }
903         if(b_remote_button_hold)
904         {
905             /* trigger event */
906             [self performSelector:@selector(executeHoldActionForRemoteButton:)
907                          withObject:buttonIdentifierNumber
908                          afterDelay:0.25];
909         }
910     }
911 }
912
913 /* Apple Remote callback */
914 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
915                pressedDown: (BOOL) pressedDown
916                 clickCount: (unsigned int) count
917 {
918     switch( buttonIdentifier )
919     {
920         case k2009RemoteButtonFullscreen:
921             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
922             break;
923         case k2009RemoteButtonPlay:
924             [[VLCCoreInteraction sharedInstance] play];
925             break;
926         case kRemoteButtonPlay:
927             if(count >= 2) {
928                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
929             } else {
930                 [[VLCCoreInteraction sharedInstance] play];
931             }
932             break;
933         case kRemoteButtonVolume_Plus:
934             [[VLCCoreInteraction sharedInstance] volumeUp];
935             break;
936         case kRemoteButtonVolume_Minus:
937             [[VLCCoreInteraction sharedInstance] volumeDown];
938             break;
939         case kRemoteButtonRight:
940             [[VLCCoreInteraction sharedInstance] next];
941             break;
942         case kRemoteButtonLeft:
943             [[VLCCoreInteraction sharedInstance] previous];
944             break;
945         case kRemoteButtonRight_Hold:
946         case kRemoteButtonLeft_Hold:
947         case kRemoteButtonVolume_Plus_Hold:
948         case kRemoteButtonVolume_Minus_Hold:
949             /* simulate an event as long as the user holds the button */
950             b_remote_button_hold = pressedDown;
951             if( pressedDown )
952             {
953                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
954                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
955                            withObject:buttonIdentifierNumber];
956             }
957             break;
958         case kRemoteButtonMenu:
959             [o_controls showPosition: self]; //FIXME
960             break;
961         default:
962             /* Add here whatever you want other buttons to do */
963             break;
964     }
965 }
966
967 #pragma mark -
968 #pragma mark String utility
969 // FIXME: this has nothing to do here
970
971 - (NSString *)localizedString:(const char *)psz
972 {
973     NSString * o_str = nil;
974
975     if( psz != NULL )
976     {
977         o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
978
979         if( o_str == NULL )
980         {
981             msg_Err( VLCIntf, "could not translate: %s", psz );
982             return( @"" );
983         }
984     }
985     else
986     {
987         msg_Warn( VLCIntf, "can't translate empty strings" );
988         return( @"" );
989     }
990
991     return( o_str );
992 }
993
994
995
996 - (char *)delocalizeString:(NSString *)id
997 {
998     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
999                           allowLossyConversion: NO];
1000     char * psz_string;
1001
1002     if( o_data == nil )
1003     {
1004         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1005                      allowLossyConversion: YES];
1006         psz_string = malloc( [o_data length] + 1 );
1007         [o_data getBytes: psz_string];
1008         psz_string[ [o_data length] ] = '\0';
1009         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1010                  psz_string );
1011     }
1012     else
1013     {
1014         psz_string = malloc( [o_data length] + 1 );
1015         [o_data getBytes: psz_string];
1016         psz_string[ [o_data length] ] = '\0';
1017     }
1018
1019     return psz_string;
1020 }
1021
1022 /* i_width is in pixels */
1023 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1024 {
1025     NSMutableString *o_wrapped;
1026     NSString *o_out_string;
1027     NSRange glyphRange, effectiveRange, charRange;
1028     NSRect lineFragmentRect;
1029     unsigned glyphIndex, breaksInserted = 0;
1030
1031     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1032         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1033         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1034     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1035     NSTextContainer *o_container = [[NSTextContainer alloc]
1036         initWithContainerSize: NSMakeSize(i_width, 2000)];
1037
1038     [o_layout_manager addTextContainer: o_container];
1039     [o_container release];
1040     [o_storage addLayoutManager: o_layout_manager];
1041     [o_layout_manager release];
1042
1043     o_wrapped = [o_in_string mutableCopy];
1044     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1045
1046     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1047             glyphIndex += effectiveRange.length) {
1048         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1049                                             effectiveRange: &effectiveRange];
1050         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1051                                     actualGlyphRange: &effectiveRange];
1052         if([o_wrapped lineRangeForRange:
1053                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1054             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1055             breaksInserted++;
1056         }
1057     }
1058     o_out_string = [NSString stringWithString: o_wrapped];
1059     [o_wrapped release];
1060     [o_storage release];
1061
1062     return o_out_string;
1063 }
1064
1065
1066 #pragma mark -
1067 #pragma mark Key Shortcuts
1068
1069 static struct
1070 {
1071     unichar i_nskey;
1072     unsigned int i_vlckey;
1073 } nskeys_to_vlckeys[] =
1074 {
1075     { NSUpArrowFunctionKey, KEY_UP },
1076     { NSDownArrowFunctionKey, KEY_DOWN },
1077     { NSLeftArrowFunctionKey, KEY_LEFT },
1078     { NSRightArrowFunctionKey, KEY_RIGHT },
1079     { NSF1FunctionKey, KEY_F1 },
1080     { NSF2FunctionKey, KEY_F2 },
1081     { NSF3FunctionKey, KEY_F3 },
1082     { NSF4FunctionKey, KEY_F4 },
1083     { NSF5FunctionKey, KEY_F5 },
1084     { NSF6FunctionKey, KEY_F6 },
1085     { NSF7FunctionKey, KEY_F7 },
1086     { NSF8FunctionKey, KEY_F8 },
1087     { NSF9FunctionKey, KEY_F9 },
1088     { NSF10FunctionKey, KEY_F10 },
1089     { NSF11FunctionKey, KEY_F11 },
1090     { NSF12FunctionKey, KEY_F12 },
1091     { NSInsertFunctionKey, KEY_INSERT },
1092     { NSHomeFunctionKey, KEY_HOME },
1093     { NSEndFunctionKey, KEY_END },
1094     { NSPageUpFunctionKey, KEY_PAGEUP },
1095     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1096     { NSMenuFunctionKey, KEY_MENU },
1097     { NSTabCharacter, KEY_TAB },
1098     { NSCarriageReturnCharacter, KEY_ENTER },
1099     { NSEnterCharacter, KEY_ENTER },
1100     { NSBackspaceCharacter, KEY_BACKSPACE },
1101     { NSDeleteCharacter, KEY_DELETE },
1102     {0,0}
1103 };
1104
1105 unsigned int CocoaKeyToVLC( unichar i_key )
1106 {
1107     unsigned int i;
1108
1109     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1110     {
1111         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1112         {
1113             return nskeys_to_vlckeys[i].i_vlckey;
1114         }
1115     }
1116     return (unsigned int)i_key;
1117 }
1118
1119 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1120 {
1121     unsigned int new = 0;
1122
1123     if([theString rangeOfString:@"Command"].location != NSNotFound)
1124         new |= NSCommandKeyMask;
1125     if([theString rangeOfString:@"Alt"].location != NSNotFound)
1126         new |= NSAlternateKeyMask;
1127     if([theString rangeOfString:@"Shift"].location != NSNotFound)
1128         new |= NSShiftKeyMask;
1129     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1130         new |= NSControlKeyMask;
1131     return new;
1132 }
1133
1134 - (NSString *)VLCKeyToString:(NSString *)theString
1135 {
1136     if (![theString isEqualToString:@""]) {
1137         if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1138             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1139         else
1140         {
1141             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1142             theString = [NSString stringWithFormat:@"%@+", theString];
1143         }
1144         if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1145             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1146         else
1147         {
1148             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1149             theString = [NSString stringWithFormat:@"%@-", theString];
1150         }
1151         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1152         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1153         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1154         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1155     }
1156     if ([theString length] > 1)
1157     {
1158         if([theString rangeOfString:@"Up"].location != NSNotFound)
1159             return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1160         else if([theString rangeOfString:@"Down"].location != NSNotFound)
1161             return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1162         else if([theString rangeOfString:@"Right"].location != NSNotFound)
1163             return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1164         else if([theString rangeOfString:@"Left"].location != NSNotFound)
1165             return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1166         else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1167             return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1168         else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1169             return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1170         else if([theString rangeOfString:@"Home"].location != NSNotFound)
1171             return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1172         else if([theString rangeOfString:@"End"].location != NSNotFound)
1173             return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1174         else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1175             return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1176         else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1177             return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1178         else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1179             return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1180         else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1181             return [NSString stringWithFormat:@"%C", NSTabCharacter];
1182         else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1183             return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1184         else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1185             return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1186         else if([theString rangeOfString:@"F12"].location != NSNotFound)
1187             return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1188         else if([theString rangeOfString:@"F11"].location != NSNotFound)
1189             return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1190         else if([theString rangeOfString:@"F10"].location != NSNotFound)
1191             return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1192         else if([theString rangeOfString:@"F9"].location != NSNotFound)
1193             return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1194         else if([theString rangeOfString:@"F8"].location != NSNotFound)
1195             return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1196         else if([theString rangeOfString:@"F7"].location != NSNotFound)
1197             return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1198         else if([theString rangeOfString:@"F6"].location != NSNotFound)
1199             return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1200         else if([theString rangeOfString:@"F5"].location != NSNotFound)
1201             return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1202         else if([theString rangeOfString:@"F4"].location != NSNotFound)
1203             return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1204         else if([theString rangeOfString:@"F3"].location != NSNotFound)
1205             return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1206         else if([theString rangeOfString:@"F2"].location != NSNotFound)
1207             return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1208         else if([theString rangeOfString:@"F1"].location != NSNotFound)
1209             return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1210         /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1211     }
1212
1213     return theString;
1214 }
1215
1216
1217 /*****************************************************************************
1218  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1219  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1220  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1221  *****************************************************************************/
1222 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1223 {
1224     unichar key = 0;
1225     vlc_value_t val;
1226     unsigned int i_pressed_modifiers = 0;
1227     const struct hotkey *p_hotkeys;
1228     int i;
1229     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1230     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1231
1232     val.i_int = 0;
1233     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1234
1235     i_pressed_modifiers = [o_event modifierFlags];
1236
1237     if( i_pressed_modifiers & NSShiftKeyMask ) {
1238         val.i_int |= KEY_MODIFIER_SHIFT;
1239         [tempString appendString:@"Shift-"];
1240         [tempStringPlus appendString:@"Shift+"];
1241     }
1242     if( i_pressed_modifiers & NSControlKeyMask ) {
1243         val.i_int |= KEY_MODIFIER_CTRL;
1244         [tempString appendString:@"Ctrl-"];
1245         [tempStringPlus appendString:@"Ctrl+"];
1246     }
1247     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1248         val.i_int |= KEY_MODIFIER_ALT;
1249         [tempString appendString:@"Alt-"];
1250         [tempStringPlus appendString:@"Alt+"];
1251     }
1252     if( i_pressed_modifiers & NSCommandKeyMask ) {
1253         val.i_int |= KEY_MODIFIER_COMMAND;
1254         [tempString appendString:@"Command-"];
1255         [tempStringPlus appendString:@"Command+"];
1256     }
1257
1258     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1259     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1260
1261     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1262
1263     switch( key )
1264     {
1265         case NSDeleteCharacter:
1266         case NSDeleteFunctionKey:
1267         case NSDeleteCharFunctionKey:
1268         case NSBackspaceCharacter:
1269         case NSUpArrowFunctionKey:
1270         case NSDownArrowFunctionKey:
1271         case NSRightArrowFunctionKey:
1272         case NSLeftArrowFunctionKey:
1273         case NSEnterCharacter:
1274         case NSCarriageReturnCharacter:
1275             return NO;
1276     }
1277
1278     if( key == 0x0020 ) // space key
1279     {
1280         [[VLCCoreInteraction sharedInstance] play];
1281         return YES;
1282     }
1283
1284     val.i_int |= CocoaKeyToVLC( key );
1285
1286     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1287     {
1288         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1289         return YES;
1290     }
1291
1292     return NO;
1293 }
1294
1295 - (void)updateCurrentlyUsedHotkeys
1296 {
1297     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1298     /* Get the main Module */
1299     module_t *p_main = module_get_main();
1300     assert( p_main );
1301     unsigned confsize;
1302     module_config_t *p_config;
1303
1304     p_config = module_config_get (p_main, &confsize);
1305
1306     for (size_t i = 0; i < confsize; i++)
1307     {
1308         module_config_t *p_item = p_config + i;
1309
1310         if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1311            && !strncmp( p_item->psz_name , "key-", 4 )
1312            && !EMPTY_STR( p_item->psz_text ) )
1313         {
1314             if (p_item->value.psz)
1315                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1316         }
1317     }
1318     module_config_free (p_config);
1319     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1320 }
1321
1322 #pragma mark -
1323 #pragma mark Interface updaters
1324 - (void)fullscreenChanged
1325 {
1326     playlist_t * p_playlist = pl_Get( VLCIntf );
1327     BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1328
1329     if (OSX_LION && b_nativeFullscreenMode)
1330     {
1331         [o_mainwindow toggleFullScreen: self];
1332         if(b_fullscreen)
1333             [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen)];
1334         else
1335             [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1336     }
1337     else
1338     {
1339         input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1340
1341         if( p_input != NULL )
1342         {
1343             if(b_fullscreen)
1344                 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1345             else
1346                 [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1347             vlc_object_release( p_input );
1348         }
1349     }
1350 }
1351
1352 - (void)PlaylistItemChanged
1353 {
1354     input_thread_t * p_input;
1355
1356     p_input = playlist_CurrentInput( pl_Get(VLCIntf) );
1357     if( p_input && !( p_input->b_dead || !vlc_object_alive(p_input) ) )
1358     {
1359         var_AddCallback( p_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1360         [o_mainmenu setRateControlsEnabled: YES];
1361         vlc_object_release( p_input );
1362     }
1363     else
1364         [o_mainmenu setRateControlsEnabled: NO];
1365
1366     [o_playlist updateRowSelection];
1367     [o_mainwindow updateWindow];
1368     [self updateMainMenu];
1369 }
1370
1371 - (void)updateMainMenu
1372 {
1373     [o_mainmenu setupMenus];
1374     [o_mainmenu updatePlaybackRate];
1375 }
1376
1377 - (void)updateMainWindow
1378 {
1379     [o_mainwindow updateWindow];
1380 }
1381
1382 - (void)showFullscreenController
1383 {
1384     [o_mainwindow showFullscreenController];
1385 }
1386
1387 - (void)updateDelays
1388 {
1389     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1390 }
1391
1392 - (void)updateName
1393 {
1394     [o_mainwindow updateName];
1395 }
1396
1397 - (void)updatePlaybackPosition
1398 {
1399     [o_mainwindow updateTimeSlider];
1400
1401     input_thread_t * p_input;
1402     p_input = pl_CurrentInput( p_intf );
1403     if( p_input )
1404     {
1405         if( var_GetInteger( p_input, "state" ) == PLAYING_S )
1406             UpdateSystemActivity( UsrActivity );
1407         vlc_object_release( p_input );
1408     }
1409 }
1410
1411 - (void)updateVolume
1412 {
1413     [o_mainwindow updateVolumeSlider];
1414 }
1415
1416 - (void)playlistUpdated
1417 {
1418     [self playbackStatusUpdated];
1419     [o_playlist playlistUpdated];
1420     [o_mainwindow updateWindow];
1421     [o_mainwindow updateName];
1422 }
1423
1424 - (void)updateRecordState: (BOOL)b_value
1425 {
1426     [o_mainmenu updateRecordState:b_value];
1427 }
1428
1429 - (void)updateInfoandMetaPanel
1430 {
1431     [o_playlist outlineViewSelectionDidChange:nil];
1432 }
1433
1434 - (void)playbackStatusUpdated
1435 {
1436     input_thread_t * p_input;
1437
1438     p_input = pl_CurrentInput( p_intf );
1439     if( p_input )
1440     {
1441         int state = var_GetInteger( p_input, "state" );
1442         if( state == PLAYING_S )
1443         {
1444             [[self mainMenu] setPause];
1445             [o_mainwindow setPause];
1446         }
1447         else
1448         {
1449             if (state == END_S)
1450                 [o_mainmenu setSubmenusEnabled: FALSE];
1451             [[self mainMenu] setPlay];
1452             [o_mainwindow setPlay];
1453         }
1454         vlc_object_release( p_input );
1455     }
1456 }
1457
1458 - (void)playbackModeUpdated
1459 {
1460     vlc_value_t looping,repeating;
1461     playlist_t * p_playlist = pl_Get( VLCIntf );
1462
1463     bool loop = var_GetBool( p_playlist, "loop" );
1464     bool repeat = var_GetBool( p_playlist, "repeat" );
1465     if( repeat ) {
1466         [o_mainwindow setRepeatOne];
1467         [o_mainmenu setRepeatOne];
1468     } else if( loop ) {
1469         [o_mainwindow setRepeatAll];
1470         [o_mainmenu setRepeatAll];
1471     } else {
1472         [o_mainwindow setRepeatOff];
1473         [o_mainmenu setRepeatOff];
1474     }
1475
1476     [o_mainwindow setShuffle];
1477     [o_mainmenu setShuffle];
1478 }
1479
1480 #pragma mark -
1481 #pragma mark Other objects getters
1482
1483 - (id)mainMenu
1484 {
1485     return o_mainmenu;
1486 }
1487
1488 - (id)controls
1489 {
1490     if( o_controls )
1491         return o_controls;
1492
1493     return nil;
1494 }
1495
1496 - (id)bookmarks
1497 {
1498     if (!o_bookmarks )
1499         o_bookmarks = [[VLCBookmarks alloc] init];
1500
1501     if( !nib_bookmarks_loaded )
1502         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1503
1504     return o_bookmarks;
1505 }
1506
1507 - (id)open
1508 {
1509     if (!o_open)
1510         return nil;
1511
1512     if (!nib_open_loaded)
1513         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1514
1515     return o_open;
1516 }
1517
1518 - (id)simplePreferences
1519 {
1520     if (!o_sprefs)
1521         o_sprefs = [[VLCSimplePrefs alloc] init];
1522
1523     if (!nib_prefs_loaded)
1524         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1525
1526     return o_sprefs;
1527 }
1528
1529 - (id)preferences
1530 {
1531     if( !o_prefs )
1532         o_prefs = [[VLCPrefs alloc] init];
1533
1534     if( !nib_prefs_loaded )
1535         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1536
1537     return o_prefs;
1538 }
1539
1540 - (id)playlist
1541 {
1542     if( o_playlist )
1543         return o_playlist;
1544
1545     return nil;
1546 }
1547
1548 - (id)info
1549 {
1550     if(! nib_info_loaded )
1551         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1552
1553     if( o_info )
1554         return o_info;
1555
1556     return nil;
1557 }
1558
1559 - (id)wizard
1560 {
1561     if( !o_wizard )
1562         o_wizard = [[VLCWizard alloc] init];
1563
1564     if( !nib_wizard_loaded )
1565     {
1566         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1567         [o_wizard initStrings];
1568     }
1569     return o_wizard;
1570 }
1571
1572 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1573 {
1574     id videoView = [o_mainwindow videoView];
1575     NSRect videoRect = [videoView frame];
1576     int i_x = (int)videoRect.origin.x;
1577     int i_y = (int)videoRect.origin.y;
1578     unsigned int i_width = (int)videoRect.size.width;
1579     unsigned int i_height = (int)videoRect.size.height;
1580     pi_x = (int *)i_x;
1581     pi_y = (int *)i_y;
1582     pi_width = (unsigned int*)i_width;
1583     pi_height = (unsigned int*)i_height;
1584     msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1585     return videoView;
1586 }
1587
1588 - (void)setNativeVideoSize:(NSSize)size
1589 {
1590     [o_mainwindow setNativeVideoSize:size];
1591 }
1592
1593 - (id)embeddedList
1594 {
1595     if( o_embedded_list )
1596         return o_embedded_list;
1597
1598     return nil;
1599 }
1600
1601 - (id)coreDialogProvider
1602 {
1603     if( o_coredialogs )
1604         return o_coredialogs;
1605
1606     return nil;
1607 }
1608
1609 - (id)eyeTVController
1610 {
1611     if( o_eyetv )
1612         return o_eyetv;
1613
1614     return nil;
1615 }
1616
1617 - (id)appleRemoteController
1618 {
1619         return o_remote;
1620 }
1621
1622 - (void)setActiveVideoPlayback:(BOOL)b_value
1623 {
1624     b_active_videoplayback = b_value;
1625     [o_mainwindow setVideoplayEnabled];
1626     [o_mainwindow togglePlaylist:nil];
1627 }
1628
1629 - (BOOL)activeVideoPlayback
1630 {
1631     return b_active_videoplayback;
1632 }
1633
1634 #pragma mark -
1635 #pragma mark Crash Log
1636 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1637 {
1638     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1639     NSURL *url = [NSURL URLWithString:urlStr];
1640
1641     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1642     [req setHTTPMethod:@"POST"];
1643
1644     NSString * email;
1645     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1646     {
1647         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1648         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1649         email = [emails valueAtIndex:[emails indexForIdentifier:
1650                     [emails primaryIdentifier]]];
1651     }
1652     else
1653         email = [NSString string];
1654
1655     NSString *postBody;
1656     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1657             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1658             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1659             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1660
1661     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1662
1663     /* Released from delegate */
1664     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1665 }
1666
1667 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1668 {
1669     [crashLogURLConnection release];
1670     crashLogURLConnection = nil;
1671 }
1672
1673 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1674 {
1675     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1676     [crashLogURLConnection release];
1677     crashLogURLConnection = nil;
1678 }
1679
1680 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1681 {
1682     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1683     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1684     NSString *fname;
1685     NSString * latestLog = nil;
1686     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1687     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1688     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
1689     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1690
1691     while (fname = [direnum nextObject])
1692     {
1693         [direnum skipDescendents];
1694         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1695         {
1696             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1697             if( [compo count] < 3 ) continue;
1698             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1699             if( [compo count] < 4 ) continue;
1700
1701             // Dooh. ugly.
1702             if( year < [[compo objectAtIndex:0] intValue] ||
1703                 (year ==[[compo objectAtIndex:0] intValue] &&
1704                  (month < [[compo objectAtIndex:1] intValue] ||
1705                   (month ==[[compo objectAtIndex:1] intValue] &&
1706                    (day   < [[compo objectAtIndex:2] intValue] ||
1707                     (day   ==[[compo objectAtIndex:2] intValue] &&
1708                       hours < [[compo objectAtIndex:3] intValue] ))))))
1709             {
1710                 year  = [[compo objectAtIndex:0] intValue];
1711                 month = [[compo objectAtIndex:1] intValue];
1712                 day   = [[compo objectAtIndex:2] intValue];
1713                 hours = [[compo objectAtIndex:3] intValue];
1714                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1715             }
1716         }
1717     }
1718
1719     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1720         return nil;
1721
1722     if( !previouslySeen )
1723     {
1724         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
1725         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1726         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
1727         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1728     }
1729     return latestLog;
1730 }
1731
1732 - (NSString *)latestCrashLogPath
1733 {
1734     return [self latestCrashLogPathPreviouslySeen:YES];
1735 }
1736
1737 - (void)lookForCrashLog
1738 {
1739     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1740     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1741     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1742     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1743     if( latestLog && !areCrashLogsTooOld )
1744         [NSApp runModalForWindow: o_crashrep_win];
1745     [o_pool release];
1746 }
1747
1748 - (IBAction)crashReporterAction:(id)sender
1749 {
1750     if( sender == o_crashrep_send_btn )
1751         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1752
1753     [NSApp stopModal];
1754     [o_crashrep_win orderOut: sender];
1755 }
1756
1757 - (IBAction)openCrashLog:(id)sender
1758 {
1759     NSString * latestLog = [self latestCrashLogPath];
1760     if( latestLog )
1761     {
1762         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1763     }
1764     else
1765     {
1766         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.") );
1767     }
1768 }
1769
1770 #pragma mark -
1771 #pragma mark Remove old prefs
1772
1773 - (void)_removeOldPreferences
1774 {
1775     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1776     static const int kCurrentPreferencesVersion = 1;
1777     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1778     if( version >= kCurrentPreferencesVersion ) return;
1779
1780     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1781         NSUserDomainMask, YES);
1782     if( !libraries || [libraries count] == 0) return;
1783     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1784
1785     /* File not found, don't attempt anything */
1786     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1787        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1788     {
1789         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1790         return;
1791     }
1792
1793     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1794                 _NS("We just found an older version of VLC's preferences files."),
1795                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1796     if( res != NSOKButton )
1797     {
1798         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1799         return;
1800     }
1801
1802     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1803
1804     /* Move the file to trash so that user can find them later */
1805     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1806
1807     /* really reset the defaults from now on */
1808     [NSUserDefaults resetStandardUserDefaults];
1809
1810     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1811     [[NSUserDefaults standardUserDefaults] synchronize];
1812
1813     /* Relaunch now */
1814     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1815
1816     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1817     if(fork() != 0)
1818     {
1819         exit(0);
1820         return;
1821     }
1822     execl(path, path, NULL);
1823 }
1824
1825 #pragma mark -
1826 #pragma mark Errors, warnings and messages
1827 - (IBAction)showMessagesPanel:(id)sender
1828 {
1829     [o_msgs_panel makeKeyAndOrderFront: sender];
1830 }
1831
1832 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1833 {
1834     if( [o_notification object] == o_msgs_panel )
1835         [self updateMessageDisplay];
1836 }
1837
1838 - (void)updateMessageDisplay
1839 {
1840     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1841     {
1842         id o_msg;
1843         NSEnumerator * o_enum;
1844
1845         [o_messages setString: @""];
1846
1847         [o_msg_lock lock];
1848
1849         o_enum = [o_msg_arr objectEnumerator];
1850
1851         while( ( o_msg = [o_enum nextObject] ) != nil )
1852         {
1853             [o_messages insertText: o_msg];
1854         }
1855
1856         b_msg_arr_changed = NO;
1857         [o_msg_lock unlock];
1858     }
1859 }
1860
1861 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1862 {
1863     NSColor *o_white = [NSColor whiteColor];
1864     NSColor *o_red = [NSColor redColor];
1865     NSColor *o_yellow = [NSColor yellowColor];
1866     NSColor *o_gray = [NSColor grayColor];
1867
1868     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1869     static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1870
1871     NSDictionary *o_attr;
1872     NSAttributedString *o_msg_color;
1873
1874     [o_msg_lock lock];
1875
1876     if( [o_msg_arr count] + 2 > 600 )
1877     {
1878         [o_msg_arr removeObjectAtIndex: 0];
1879         [o_msg_arr removeObjectAtIndex: 1];
1880     }
1881
1882     o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1883     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1884     [o_msg_arr addObject: [o_msg_color autorelease]];
1885
1886     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1887     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", str] attributes: o_attr];
1888     [o_msg_arr addObject: [o_msg_color autorelease]];
1889
1890     b_msg_arr_changed = YES;
1891     [o_msg_lock unlock];
1892
1893     [self updateMessageDisplay];
1894 }
1895
1896 - (IBAction)saveDebugLog:(id)sender
1897 {
1898     NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
1899
1900     [saveFolderPanel setCanSelectHiddenExtension: NO];
1901     [saveFolderPanel setCanCreateDirectories: YES];
1902     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1903     [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];
1904 }
1905
1906 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1907 {
1908     BOOL b_returned;
1909     if( returnCode == NSOKButton )
1910     {
1911         b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1912         if(! b_returned )
1913             msg_Warn( p_intf, "Error while saving the debug log" );
1914     }
1915 }
1916
1917 #pragma mark -
1918 #pragma mark Playlist toggling
1919
1920 - (void)updateTogglePlaylistState
1921 {
1922     [[self playlist] outlineViewSelectionDidChange: NULL];
1923 }
1924
1925 #pragma mark -
1926
1927 @end
1928
1929 @implementation VLCMain (Internal)
1930
1931 - (void)handlePortMessage:(NSPortMessage *)o_msg
1932 {
1933     id ** val;
1934     NSData * o_data;
1935     NSValue * o_value;
1936     NSInvocation * o_inv;
1937     NSConditionLock * o_lock;
1938
1939     o_data = [[o_msg components] lastObject];
1940     o_inv = *((NSInvocation **)[o_data bytes]);
1941     [o_inv getArgument: &o_value atIndex: 2];
1942     val = (id **)[o_value pointerValue];
1943     [o_inv setArgument: val[1] atIndex: 2];
1944     o_lock = *(val[0]);
1945
1946     [o_lock lock];
1947     [o_inv invoke];
1948     [o_lock unlockWithCondition: 1];
1949 }
1950 - (void)resetMediaKeyJump
1951 {
1952     b_mediakeyJustJumped = NO;
1953 }
1954 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1955 {
1956     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1957     if (b_mediaKeySupport) {
1958         if (!o_mediaKeyController)
1959             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1960         [o_mediaKeyController startWatchingMediaKeys];
1961     }
1962     else if (!b_mediaKeySupport && o_mediaKeyController)
1963     {
1964         int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1965                                                _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1966                                                _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1967         if( returnedValue == NSOKButton )
1968         {
1969             /* Relaunch now */
1970             const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1971
1972             /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1973             if(fork() != 0)
1974             {
1975                 exit(0);
1976                 return;
1977             }
1978             execl(path, path, NULL);
1979         }
1980     }
1981 }
1982
1983 @end
1984
1985 /*****************************************************************************
1986  * VLCApplication interface
1987  *****************************************************************************/
1988
1989 @implementation VLCApplication
1990 // when user selects the quit menu from dock it sends a terminate:
1991 // but we need to send a stop: to properly exits libvlc.
1992 // However, we are not able to change the action-method sent by this standard menu item.
1993 // thus we override terminat: to send a stop:
1994 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1995 - (void)terminate:(id)sender
1996 {
1997     [self activateIgnoringOtherApps:YES];
1998     [self stop:sender];
1999 }
2000
2001 @end