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