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