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