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