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