]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: fixed corner case, which could lead to an empty main window in case the video...
[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 <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         // we already have our playlist "fullscreen" callback, do not repeat the same call here
174         //[[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject: nil 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     /* yeah, we are done */
620     b_nativeFullscreenMode = NO;
621 #ifdef MAC_OS_X_VERSION_10_7
622     if( OSX_LION )
623         b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
624 #endif
625
626     /* recover stored audio device, if set
627      * in case it was unplugged in the meantime, auhal will fall back on the default */
628     int i_value = config_GetInt( p_intf, "macosx-audio-device" );
629     if (i_value > 0)
630         var_SetInteger( pl_Get( VLCIntf ), "audio-device", i_value );
631
632     if (config_GetInt( VLCIntf, "macosx-icon-change"))
633     {
634         /* After day 354 of the year, the usual VLC cone is replaced by another cone
635          * wearing a Father Xmas hat.
636          * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
637          */
638         NSCalendar *gregorian =
639         [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
640         NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
641         [gregorian release];
642
643         if (dayOfYear >= 354)
644             [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
645     }
646
647     nib_main_loaded = TRUE;
648 }
649
650 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
651 {
652     if( !p_intf ) return;
653
654     [o_mainwindow updateWindow];
655     [o_mainwindow updateTimeSlider];
656     [o_mainwindow updateVolumeSlider];
657     [o_mainwindow makeKeyAndOrderFront: self];
658
659     /* init media key support */
660     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
661     if( b_mediaKeySupport )
662     {
663         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
664         [o_mediaKeyController startWatchingMediaKeys];
665         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
666                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
667                                                                  nil]];
668     }
669     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
670
671     [self _removeOldPreferences];
672
673     /* Handle sleep notification */
674     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
675            name:NSWorkspaceWillSleepNotification object:nil];
676
677     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
678
679     /* we will need this, so let's load it here so the interface appears to be more responsive */
680     nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
681     [self initStrings];
682 }
683
684 - (void)initStrings
685 {
686     if( !p_intf ) return;
687
688     /* messages panel */
689     [o_msgs_panel setTitle: _NS("Messages")];
690     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
691     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
692
693     /* crash reporter panel */
694     [o_crashrep_send_btn setTitle: _NS("Send")];
695     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
696     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
697     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
698     [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, ...")];
699     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
700     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
701 }
702
703 #pragma mark -
704 #pragma mark Termination
705
706 - (void)applicationWillTerminate:(NSNotification *)notification
707 {
708     /* don't allow a double termination call. If the user has
709      * already invoked the quit then simply return this time. */
710     static bool f_appExit = false;
711     bool isTerminating;
712
713     [o_appLock lock];
714     isTerminating = f_appExit;
715     f_appExit = true;
716     [o_appLock unlock];
717
718     if (isTerminating)
719         return;
720
721     if (notification == nil)
722         [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
723
724     playlist_t * p_playlist = pl_Get( p_intf );
725     int returnedValue = 0;
726
727     /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
728     if (b_nativeFullscreenMode)
729     {
730         [o_mainwindow toggleFullScreen: self];
731         [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
732     }
733
734     /* Save some interface state in configuration, at module quit */
735     config_PutInt( p_intf, "random", var_GetBool( p_playlist, "random" ) );
736     config_PutInt( p_intf, "loop", var_GetBool( p_playlist, "loop" ) );
737     config_PutInt( p_intf, "repeat", var_GetBool( p_playlist, "repeat" ) );
738
739     msg_Dbg( p_intf, "Terminating" );
740
741     /* unsubscribe from the interactive dialogues */
742     dialog_Unregister( p_intf );
743     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
744     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
745     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
746     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
747     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
748     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
749     var_DelCallback(p_playlist, "item-current", PLItemChanged, self);
750     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
751     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
752     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
753     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
754     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
755     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
756     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
757     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
758     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
759     var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
760     var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
761     var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
762
763     if( p_current_input )
764     {
765         var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
766         vlc_object_release( p_current_input );
767         p_current_input = NULL;
768     }
769
770     /* remove global observer watching for vout device changes correctly */
771     [[NSNotificationCenter defaultCenter] removeObserver: self];
772
773     /* release some other objects here, because it isn't sure whether dealloc
774      * will be called later on */
775     if( o_sprefs )
776         [o_sprefs release];
777
778     if( o_prefs )
779         [o_prefs release];
780
781     [o_open release];
782
783     if( o_info )
784         [o_info release];
785
786     if( o_wizard )
787         [o_wizard release];
788
789     [crashLogURLConnection cancel];
790     [crashLogURLConnection release];
791
792     [o_embedded_list release];
793     [o_coredialogs release];
794     [o_eyetv release];
795
796     /* unsubscribe from libvlc's debug messages */
797     vlc_Unsubscribe( &p_intf->p_sys->sub );
798
799     [o_msg_arr removeAllObjects];
800     [o_msg_arr release];
801     o_msg_arr = NULL;
802
803     [o_msg_lock release];
804
805     /* write cached user defaults to disk */
806     [[NSUserDefaults standardUserDefaults] synchronize];
807
808     /* Make sure the Menu doesn't have any references to vlc objects anymore */
809     //FIXME: this should be moved to VLCMainMenu
810     [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
811     [o_mainmenu release];
812
813     libvlc_Quit( p_intf->p_libvlc );
814
815     [o_mainwindow release];
816     o_mainwindow = NULL;
817
818     [self setIntf:nil];
819 }
820
821 #pragma mark -
822 #pragma mark Sparkle delegate
823 /* received directly before the update gets installed, so let's shut down a bit */
824 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
825 {
826     [NSApp activateIgnoringOtherApps:YES];
827     [o_remote stopListening: self];
828     [[VLCCoreInteraction sharedInstance] stop];
829 }
830
831 #pragma mark -
832 #pragma mark Media Key support
833
834 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
835 {
836     if( b_mediaKeySupport )
837        {
838         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
839
840         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
841         int keyFlags = ([event data1] & 0x0000FFFF);
842         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
843         int keyRepeat = (keyFlags & 0x1);
844
845         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
846             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
847
848         if( (keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped )
849         {
850             if( keyState == 0 && keyRepeat == 0 )
851                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
852             else if( keyRepeat == 1 )
853             {
854                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
855                 b_mediakeyJustJumped = YES;
856                 [self performSelector:@selector(resetMediaKeyJump)
857                            withObject: NULL
858                            afterDelay:0.25];
859             }
860         }
861
862         if( (keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped )
863         {
864             if( keyState == 0 && keyRepeat == 0 )
865                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
866             else if( keyRepeat == 1 )
867             {
868                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
869                 b_mediakeyJustJumped = YES;
870                 [self performSelector:@selector(resetMediaKeyJump)
871                            withObject: NULL
872                            afterDelay:0.25];
873             }
874         }
875     }
876 }
877
878 #pragma mark -
879 #pragma mark Other notification
880
881 /* Listen to the remote in exclusive mode, only when VLC is the active
882    application */
883 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
884 {
885     if( !p_intf ) return;
886     if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
887         [o_remote startListening: self];
888 }
889 - (void)applicationDidResignActive:(NSNotification *)aNotification
890 {
891     if( !p_intf ) return;
892     [o_remote stopListening: self];
893 }
894
895 /* Triggered when the computer goes to sleep */
896 - (void)computerWillSleep: (NSNotification *)notification
897 {
898     [[VLCCoreInteraction sharedInstance] pause];
899 }
900
901 #pragma mark -
902 #pragma mark File opening
903
904 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
905 {
906     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
907     char *psz_uri = make_URI([o_filename UTF8String], "file" );
908     if( !psz_uri )
909         return( FALSE );
910
911     input_thread_t * p_input = pl_CurrentInput( VLCIntf );
912     BOOL b_returned = NO;
913
914     if (p_input)
915     {
916         b_returned = input_AddSubtitle( p_input, psz_uri, true );
917         vlc_object_release( p_input );
918         if(!b_returned)
919         {
920             free( psz_uri );
921             return YES;
922         }
923     }
924     else if( p_input )
925         vlc_object_release( p_input );
926
927     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
928
929     free( psz_uri );
930
931     if( b_autoplay )
932         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
933     else
934         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
935
936     return( TRUE );
937 }
938
939 /* When user click in the Dock icon our double click in the finder */
940 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
941 {
942     if(!hasVisibleWindows)
943         [o_mainwindow makeKeyAndOrderFront:self];
944
945     return YES;
946 }
947
948 #pragma mark -
949 #pragma mark Apple Remote Control
950
951 /* Helper method for the remote control interface in order to trigger forward/backward and volume
952    increase/decrease as long as the user holds the left/right, plus/minus button */
953 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
954 {
955     if(b_remote_button_hold)
956     {
957         switch([buttonIdentifierNumber intValue])
958         {
959             case kRemoteButtonRight_Hold:
960                 [[VLCCoreInteraction sharedInstance] forward];
961             break;
962             case kRemoteButtonLeft_Hold:
963                 [[VLCCoreInteraction sharedInstance] backward];
964             break;
965             case kRemoteButtonVolume_Plus_Hold:
966                 [[VLCCoreInteraction sharedInstance] volumeUp];
967             break;
968             case kRemoteButtonVolume_Minus_Hold:
969                 [[VLCCoreInteraction sharedInstance] volumeDown];
970             break;
971         }
972         if(b_remote_button_hold)
973         {
974             /* trigger event */
975             [self performSelector:@selector(executeHoldActionForRemoteButton:)
976                          withObject:buttonIdentifierNumber
977                          afterDelay:0.25];
978         }
979     }
980 }
981
982 /* Apple Remote callback */
983 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
984                pressedDown: (BOOL) pressedDown
985                 clickCount: (unsigned int) count
986 {
987     switch( buttonIdentifier )
988     {
989         case k2009RemoteButtonFullscreen:
990             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
991             break;
992         case k2009RemoteButtonPlay:
993             [[VLCCoreInteraction sharedInstance] play];
994             break;
995         case kRemoteButtonPlay:
996             if(count >= 2) {
997                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
998             } else {
999                 [[VLCCoreInteraction sharedInstance] play];
1000             }
1001             break;
1002         case kRemoteButtonVolume_Plus:
1003             [[VLCCoreInteraction sharedInstance] volumeUp];
1004             break;
1005         case kRemoteButtonVolume_Minus:
1006             [[VLCCoreInteraction sharedInstance] volumeDown];
1007             break;
1008         case kRemoteButtonRight:
1009             [[VLCCoreInteraction sharedInstance] next];
1010             break;
1011         case kRemoteButtonLeft:
1012             [[VLCCoreInteraction sharedInstance] previous];
1013             break;
1014         case kRemoteButtonRight_Hold:
1015         case kRemoteButtonLeft_Hold:
1016         case kRemoteButtonVolume_Plus_Hold:
1017         case kRemoteButtonVolume_Minus_Hold:
1018             /* simulate an event as long as the user holds the button */
1019             b_remote_button_hold = pressedDown;
1020             if( pressedDown )
1021             {
1022                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1023                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1024                            withObject:buttonIdentifierNumber];
1025             }
1026             break;
1027         case kRemoteButtonMenu:
1028             [o_controls showPosition: self]; //FIXME
1029             break;
1030         default:
1031             /* Add here whatever you want other buttons to do */
1032             break;
1033     }
1034 }
1035
1036 #pragma mark -
1037 #pragma mark String utility
1038 // FIXME: this has nothing to do here
1039
1040 - (NSString *)localizedString:(const char *)psz
1041 {
1042     NSString * o_str = nil;
1043
1044     if( psz != NULL )
1045     {
1046         o_str = [NSString stringWithCString: _(psz) encoding:NSUTF8StringEncoding];
1047
1048         if( o_str == NULL )
1049         {
1050             msg_Err( VLCIntf, "could not translate: %s", psz );
1051             return( @"" );
1052         }
1053     }
1054     else
1055     {
1056         msg_Warn( VLCIntf, "can't translate empty strings" );
1057         return( @"" );
1058     }
1059
1060     return( o_str );
1061 }
1062
1063
1064
1065 - (char *)delocalizeString:(NSString *)id
1066 {
1067     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1068                           allowLossyConversion: NO];
1069     char * psz_string;
1070
1071     if( o_data == nil )
1072     {
1073         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1074                      allowLossyConversion: YES];
1075         psz_string = malloc( [o_data length] + 1 );
1076         [o_data getBytes: psz_string];
1077         psz_string[ [o_data length] ] = '\0';
1078         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1079                  psz_string );
1080     }
1081     else
1082     {
1083         psz_string = malloc( [o_data length] + 1 );
1084         [o_data getBytes: psz_string];
1085         psz_string[ [o_data length] ] = '\0';
1086     }
1087
1088     return psz_string;
1089 }
1090
1091 /* i_width is in pixels */
1092 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1093 {
1094     NSMutableString *o_wrapped;
1095     NSString *o_out_string;
1096     NSRange glyphRange, effectiveRange, charRange;
1097     NSRect lineFragmentRect;
1098     unsigned glyphIndex, breaksInserted = 0;
1099
1100     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1101         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1102         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1103     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1104     NSTextContainer *o_container = [[NSTextContainer alloc]
1105         initWithContainerSize: NSMakeSize(i_width, 2000)];
1106
1107     [o_layout_manager addTextContainer: o_container];
1108     [o_container release];
1109     [o_storage addLayoutManager: o_layout_manager];
1110     [o_layout_manager release];
1111
1112     o_wrapped = [o_in_string mutableCopy];
1113     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1114
1115     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1116             glyphIndex += effectiveRange.length) {
1117         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1118                                             effectiveRange: &effectiveRange];
1119         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1120                                     actualGlyphRange: &effectiveRange];
1121         if([o_wrapped lineRangeForRange:
1122                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1123             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1124             breaksInserted++;
1125         }
1126     }
1127     o_out_string = [NSString stringWithString: o_wrapped];
1128     [o_wrapped release];
1129     [o_storage release];
1130
1131     return o_out_string;
1132 }
1133
1134
1135 #pragma mark -
1136 #pragma mark Key Shortcuts
1137
1138 static struct
1139 {
1140     unichar i_nskey;
1141     unsigned int i_vlckey;
1142 } nskeys_to_vlckeys[] =
1143 {
1144     { NSUpArrowFunctionKey, KEY_UP },
1145     { NSDownArrowFunctionKey, KEY_DOWN },
1146     { NSLeftArrowFunctionKey, KEY_LEFT },
1147     { NSRightArrowFunctionKey, KEY_RIGHT },
1148     { NSF1FunctionKey, KEY_F1 },
1149     { NSF2FunctionKey, KEY_F2 },
1150     { NSF3FunctionKey, KEY_F3 },
1151     { NSF4FunctionKey, KEY_F4 },
1152     { NSF5FunctionKey, KEY_F5 },
1153     { NSF6FunctionKey, KEY_F6 },
1154     { NSF7FunctionKey, KEY_F7 },
1155     { NSF8FunctionKey, KEY_F8 },
1156     { NSF9FunctionKey, KEY_F9 },
1157     { NSF10FunctionKey, KEY_F10 },
1158     { NSF11FunctionKey, KEY_F11 },
1159     { NSF12FunctionKey, KEY_F12 },
1160     { NSInsertFunctionKey, KEY_INSERT },
1161     { NSHomeFunctionKey, KEY_HOME },
1162     { NSEndFunctionKey, KEY_END },
1163     { NSPageUpFunctionKey, KEY_PAGEUP },
1164     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1165     { NSMenuFunctionKey, KEY_MENU },
1166     { NSTabCharacter, KEY_TAB },
1167     { NSCarriageReturnCharacter, KEY_ENTER },
1168     { NSEnterCharacter, KEY_ENTER },
1169     { NSBackspaceCharacter, KEY_BACKSPACE },
1170     { NSDeleteCharacter, KEY_DELETE },
1171     {0,0}
1172 };
1173
1174 unsigned int CocoaKeyToVLC( unichar i_key )
1175 {
1176     unsigned int i;
1177
1178     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1179     {
1180         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1181         {
1182             return nskeys_to_vlckeys[i].i_vlckey;
1183         }
1184     }
1185     return (unsigned int)i_key;
1186 }
1187
1188 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1189 {
1190     unsigned int new = 0;
1191
1192     if([theString rangeOfString:@"Command"].location != NSNotFound)
1193         new |= NSCommandKeyMask;
1194     if([theString rangeOfString:@"Alt"].location != NSNotFound)
1195         new |= NSAlternateKeyMask;
1196     if([theString rangeOfString:@"Shift"].location != NSNotFound)
1197         new |= NSShiftKeyMask;
1198     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1199         new |= NSControlKeyMask;
1200     return new;
1201 }
1202
1203 - (NSString *)VLCKeyToString:(NSString *)theString
1204 {
1205     if (![theString isEqualToString:@""]) {
1206         if ([theString characterAtIndex:([theString length] - 1)] != 0x2b)
1207             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1208         else
1209         {
1210             theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1211             theString = [NSString stringWithFormat:@"%@+", theString];
1212         }
1213         if ([theString characterAtIndex:([theString length] - 1)] != 0x2d)
1214             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1215         else
1216         {
1217             theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1218             theString = [NSString stringWithFormat:@"%@-", theString];
1219         }
1220         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1221         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1222         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1223         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1224     }
1225     if ([theString length] > 1)
1226     {
1227         if([theString rangeOfString:@"Up"].location != NSNotFound)
1228             return [NSString stringWithFormat:@"%C", NSUpArrowFunctionKey];
1229         else if([theString rangeOfString:@"Down"].location != NSNotFound)
1230             return [NSString stringWithFormat:@"%C", NSDownArrowFunctionKey];
1231         else if([theString rangeOfString:@"Right"].location != NSNotFound)
1232             return [NSString stringWithFormat:@"%C", NSRightArrowFunctionKey];
1233         else if([theString rangeOfString:@"Left"].location != NSNotFound)
1234             return [NSString stringWithFormat:@"%C", NSLeftArrowFunctionKey];
1235         else if([theString rangeOfString:@"Enter"].location != NSNotFound)
1236             return [NSString stringWithFormat:@"%C", NSEnterCharacter]; // we treat NSCarriageReturnCharacter as aquivalent
1237         else if([theString rangeOfString:@"Insert"].location != NSNotFound)
1238             return [NSString stringWithFormat:@"%C", NSInsertFunctionKey];
1239         else if([theString rangeOfString:@"Home"].location != NSNotFound)
1240             return [NSString stringWithFormat:@"%C", NSHomeFunctionKey];
1241         else if([theString rangeOfString:@"End"].location != NSNotFound)
1242             return [NSString stringWithFormat:@"%C", NSEndFunctionKey];
1243         else if([theString rangeOfString:@"Pageup"].location != NSNotFound)
1244             return [NSString stringWithFormat:@"%C", NSPageUpFunctionKey];
1245         else if([theString rangeOfString:@"Pagedown"].location != NSNotFound)
1246             return [NSString stringWithFormat:@"%C", NSPageDownFunctionKey];
1247         else if([theString rangeOfString:@"Menu"].location != NSNotFound)
1248             return [NSString stringWithFormat:@"%C", NSMenuFunctionKey];
1249         else if([theString rangeOfString:@"Tab"].location != NSNotFound)
1250             return [NSString stringWithFormat:@"%C", NSTabCharacter];
1251         else if([theString rangeOfString:@"Backspace"].location != NSNotFound)
1252             return [NSString stringWithFormat:@"%C", NSBackspaceCharacter];
1253         else if([theString rangeOfString:@"Delete"].location != NSNotFound)
1254             return [NSString stringWithFormat:@"%C", NSDeleteCharacter];
1255         else if([theString rangeOfString:@"F12"].location != NSNotFound)
1256             return [NSString stringWithFormat:@"%C", NSF12FunctionKey];
1257         else if([theString rangeOfString:@"F11"].location != NSNotFound)
1258             return [NSString stringWithFormat:@"%C", NSF11FunctionKey];
1259         else if([theString rangeOfString:@"F10"].location != NSNotFound)
1260             return [NSString stringWithFormat:@"%C", NSF10FunctionKey];
1261         else if([theString rangeOfString:@"F9"].location != NSNotFound)
1262             return [NSString stringWithFormat:@"%C", NSF9FunctionKey];
1263         else if([theString rangeOfString:@"F8"].location != NSNotFound)
1264             return [NSString stringWithFormat:@"%C", NSF8FunctionKey];
1265         else if([theString rangeOfString:@"F7"].location != NSNotFound)
1266             return [NSString stringWithFormat:@"%C", NSF7FunctionKey];
1267         else if([theString rangeOfString:@"F6"].location != NSNotFound)
1268             return [NSString stringWithFormat:@"%C", NSF6FunctionKey];
1269         else if([theString rangeOfString:@"F5"].location != NSNotFound)
1270             return [NSString stringWithFormat:@"%C", NSF5FunctionKey];
1271         else if([theString rangeOfString:@"F4"].location != NSNotFound)
1272             return [NSString stringWithFormat:@"%C", NSF4FunctionKey];
1273         else if([theString rangeOfString:@"F3"].location != NSNotFound)
1274             return [NSString stringWithFormat:@"%C", NSF3FunctionKey];
1275         else if([theString rangeOfString:@"F2"].location != NSNotFound)
1276             return [NSString stringWithFormat:@"%C", NSF2FunctionKey];
1277         else if([theString rangeOfString:@"F1"].location != NSNotFound)
1278             return [NSString stringWithFormat:@"%C", NSF1FunctionKey];
1279         /* note that we don't support esc here, since it is reserved for leaving fullscreen */
1280     }
1281
1282     return theString;
1283 }
1284
1285
1286 /*****************************************************************************
1287  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1288  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1289  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1290  *****************************************************************************/
1291 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1292 {
1293     unichar key = 0;
1294     vlc_value_t val;
1295     unsigned int i_pressed_modifiers = 0;
1296     const struct hotkey *p_hotkeys;
1297     int i;
1298     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1299     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1300
1301     val.i_int = 0;
1302     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1303
1304     i_pressed_modifiers = [o_event modifierFlags];
1305
1306     if( i_pressed_modifiers & NSShiftKeyMask ) {
1307         val.i_int |= KEY_MODIFIER_SHIFT;
1308         [tempString appendString:@"Shift-"];
1309         [tempStringPlus appendString:@"Shift+"];
1310     }
1311     if( i_pressed_modifiers & NSControlKeyMask ) {
1312         val.i_int |= KEY_MODIFIER_CTRL;
1313         [tempString appendString:@"Ctrl-"];
1314         [tempStringPlus appendString:@"Ctrl+"];
1315     }
1316     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1317         val.i_int |= KEY_MODIFIER_ALT;
1318         [tempString appendString:@"Alt-"];
1319         [tempStringPlus appendString:@"Alt+"];
1320     }
1321     if( i_pressed_modifiers & NSCommandKeyMask ) {
1322         val.i_int |= KEY_MODIFIER_COMMAND;
1323         [tempString appendString:@"Command-"];
1324         [tempStringPlus appendString:@"Command+"];
1325     }
1326
1327     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1328     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1329
1330     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1331
1332     /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1333     if( key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask )
1334     {
1335         [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1336         return YES;
1337     }
1338
1339     switch( key )
1340     {
1341         case NSDeleteCharacter:
1342         case NSDeleteFunctionKey:
1343         case NSDeleteCharFunctionKey:
1344         case NSBackspaceCharacter:
1345         case NSUpArrowFunctionKey:
1346         case NSDownArrowFunctionKey:
1347         case NSRightArrowFunctionKey:
1348         case NSLeftArrowFunctionKey:
1349         case NSEnterCharacter:
1350         case NSCarriageReturnCharacter:
1351             return NO;
1352     }
1353
1354     if( key == 0x0020 ) // space key
1355     {
1356         [[VLCCoreInteraction sharedInstance] play];
1357         return YES;
1358     }
1359
1360     val.i_int |= CocoaKeyToVLC( key );
1361
1362     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1363     {
1364         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1365         return YES;
1366     }
1367
1368     return NO;
1369 }
1370
1371 - (void)updateCurrentlyUsedHotkeys
1372 {
1373     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1374     /* Get the main Module */
1375     module_t *p_main = module_get_main();
1376     assert( p_main );
1377     unsigned confsize;
1378     module_config_t *p_config;
1379
1380     p_config = module_config_get (p_main, &confsize);
1381
1382     for (size_t i = 0; i < confsize; i++)
1383     {
1384         module_config_t *p_item = p_config + i;
1385
1386         if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1387            && !strncmp( p_item->psz_name , "key-", 4 )
1388            && !EMPTY_STR( p_item->psz_text ) )
1389         {
1390             if (p_item->value.psz)
1391                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1392         }
1393     }
1394     module_config_free (p_config);
1395     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1396 }
1397
1398 #pragma mark -
1399 #pragma mark Interface updaters
1400 - (void)fullscreenChanged
1401 {
1402     playlist_t * p_playlist = pl_Get( VLCIntf );
1403     BOOL b_fullscreen = var_GetBool( p_playlist, "fullscreen" );
1404
1405     if (b_nativeFullscreenMode)
1406     {
1407         // this is called twice in certain situations, so only toogle if we really need to
1408         if( (  b_fullscreen && !([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) || 
1409             ( !b_fullscreen &&  ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen) ) )
1410             [o_mainwindow toggleFullScreen: self];
1411
1412         if(b_fullscreen)
1413             [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
1414         else
1415             [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
1416     }
1417     else
1418     {
1419         if( b_fullscreen )
1420         {
1421             input_thread_t * p_input = pl_CurrentInput( VLCIntf );
1422             if( p_input != NULL && [self activeVideoPlayback] )
1423             {
1424                 [o_mainwindow performSelectorOnMainThread:@selector(enterFullscreen) withObject:nil waitUntilDone:NO];
1425             }
1426             if (p_input)
1427                 vlc_object_release( p_input );
1428         }
1429         else
1430         {
1431             // leaving fullscreen is always allowed
1432             [o_mainwindow performSelectorOnMainThread:@selector(leaveFullscreen) withObject:nil waitUntilDone:NO];
1433         }
1434     }
1435 }
1436
1437 - (void)PlaylistItemChanged
1438 {
1439     if( p_current_input && ( p_current_input->b_dead || !vlc_object_alive( p_current_input ) ))
1440     {
1441         var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1442         vlc_object_release( p_current_input );
1443         p_current_input = NULL;
1444
1445         [o_mainmenu setRateControlsEnabled: NO];
1446     }
1447     else if( !p_current_input )
1448     {
1449         // object is hold here and released then it is dead
1450         p_current_input = playlist_CurrentInput( pl_Get( VLCIntf ));
1451         if( p_current_input )
1452         {
1453             var_AddCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
1454             [self playbackStatusUpdated];
1455             [o_mainmenu setRateControlsEnabled: YES];
1456             if ( [self activeVideoPlayback] && [[o_mainwindow videoView] isHidden] )
1457                 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1458         }
1459     }
1460
1461     [o_playlist updateRowSelection];
1462     [o_mainwindow updateWindow];
1463     [self updateDelays];
1464     [self updateMainMenu];
1465 }
1466
1467 - (void)updateMainMenu
1468 {
1469     [o_mainmenu setupMenus];
1470     [o_mainmenu updatePlaybackRate];
1471 }
1472
1473 - (void)updateMainWindow
1474 {
1475     [o_mainwindow updateWindow];
1476 }
1477
1478 - (void)showMainWindow
1479 {
1480     [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1481 }
1482
1483 - (void)showFullscreenController
1484 {
1485     [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1486 }
1487
1488 - (void)updateDelays
1489 {
1490     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1491 }
1492
1493 - (void)updateName
1494 {
1495     [o_mainwindow updateName];
1496 }
1497
1498 - (void)updatePlaybackPosition
1499 {
1500     [o_mainwindow updateTimeSlider];
1501
1502     input_thread_t * p_input;
1503     p_input = pl_CurrentInput( p_intf );
1504     if( p_input )
1505     {
1506         if( var_GetInteger( p_input, "state" ) == PLAYING_S && [self activeVideoPlayback] )
1507             UpdateSystemActivity( UsrActivity );
1508         vlc_object_release( p_input );
1509     }
1510 }
1511
1512 - (void)updateVolume
1513 {
1514     [o_mainwindow updateVolumeSlider];
1515 }
1516
1517 - (void)playlistUpdated
1518 {
1519     [self playbackStatusUpdated];
1520     [o_playlist playlistUpdated];
1521     [o_mainwindow updateWindow];
1522     [o_mainwindow updateName];
1523 }
1524
1525 - (void)updateRecordState: (BOOL)b_value
1526 {
1527     [o_mainmenu updateRecordState:b_value];
1528 }
1529
1530 - (void)updateInfoandMetaPanel
1531 {
1532     [o_playlist outlineViewSelectionDidChange:nil];
1533 }
1534
1535 - (void)playbackStatusUpdated
1536 {
1537     input_thread_t * p_input;
1538
1539     p_input = pl_CurrentInput( p_intf );
1540     if( p_input )
1541     {
1542         int state = var_GetInteger( p_input, "state" );
1543         if( state == PLAYING_S )
1544         {
1545             [[self mainMenu] setPause];
1546             [o_mainwindow setPause];
1547         }
1548         else
1549         {
1550             if (state == END_S)
1551                 [o_mainmenu setSubmenusEnabled: FALSE];
1552             [[self mainMenu] setPlay];
1553             [o_mainwindow setPlay];
1554         }
1555         vlc_object_release( p_input );
1556     }
1557
1558     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1559     [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1560 }
1561
1562 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1563 {
1564     [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1565                                                                    object:nil
1566                                                                  userInfo:nil
1567                                                        deliverImmediately:YES];
1568 }
1569
1570 - (void)playbackModeUpdated
1571 {
1572     vlc_value_t looping,repeating;
1573     playlist_t * p_playlist = pl_Get( VLCIntf );
1574
1575     bool loop = var_GetBool( p_playlist, "loop" );
1576     bool repeat = var_GetBool( p_playlist, "repeat" );
1577     if( repeat ) {
1578         [o_mainwindow setRepeatOne];
1579         [o_mainmenu setRepeatOne];
1580     } else if( loop ) {
1581         [o_mainwindow setRepeatAll];
1582         [o_mainmenu setRepeatAll];
1583     } else {
1584         [o_mainwindow setRepeatOff];
1585         [o_mainmenu setRepeatOff];
1586     }
1587
1588     [o_mainwindow setShuffle];
1589     [o_mainmenu setShuffle];
1590 }
1591
1592 #pragma mark -
1593 #pragma mark Other objects getters
1594
1595 - (id)mainMenu
1596 {
1597     return o_mainmenu;
1598 }
1599
1600 - (id)mainWindow
1601 {
1602     return o_mainwindow;
1603 }
1604
1605 - (id)controls
1606 {
1607     if( o_controls )
1608         return o_controls;
1609
1610     return nil;
1611 }
1612
1613 - (id)bookmarks
1614 {
1615     if (!o_bookmarks )
1616         o_bookmarks = [[VLCBookmarks alloc] init];
1617
1618     if( !nib_bookmarks_loaded )
1619         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1620
1621     return o_bookmarks;
1622 }
1623
1624 - (id)open
1625 {
1626     if (!o_open)
1627         return nil;
1628
1629     if (!nib_open_loaded)
1630         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1631
1632     return o_open;
1633 }
1634
1635 - (id)simplePreferences
1636 {
1637     if (!o_sprefs)
1638         o_sprefs = [[VLCSimplePrefs alloc] init];
1639
1640     if (!nib_prefs_loaded)
1641         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1642
1643     return o_sprefs;
1644 }
1645
1646 - (id)preferences
1647 {
1648     if( !o_prefs )
1649         o_prefs = [[VLCPrefs alloc] init];
1650
1651     if( !nib_prefs_loaded )
1652         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1653
1654     return o_prefs;
1655 }
1656
1657 - (id)playlist
1658 {
1659     if( o_playlist )
1660         return o_playlist;
1661
1662     return nil;
1663 }
1664
1665 - (id)info
1666 {
1667     if(! nib_info_loaded )
1668         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1669
1670     if( o_info )
1671         return o_info;
1672
1673     return nil;
1674 }
1675
1676 - (id)wizard
1677 {
1678     if( !o_wizard )
1679         o_wizard = [[VLCWizard alloc] init];
1680
1681     if( !nib_wizard_loaded )
1682     {
1683         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1684         [o_wizard initStrings];
1685     }
1686     return o_wizard;
1687 }
1688
1689 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1690 {
1691     id videoView = [o_mainwindow setupVideoView];
1692     NSRect videoRect = [videoView frame];
1693     int i_x = (int)videoRect.origin.x;
1694     int i_y = (int)videoRect.origin.y;
1695     unsigned int i_width = (int)videoRect.size.width;
1696     unsigned int i_height = (int)videoRect.size.height;
1697     pi_x = &i_x;
1698     pi_y = &i_y;
1699     pi_width = &i_width;
1700     pi_height = &i_height;
1701     msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1702     return videoView;
1703 }
1704
1705 - (void)setNativeVideoSize:(NSSize)size
1706 {
1707     [o_mainwindow setNativeVideoSize:size];
1708 }
1709
1710 - (id)embeddedList
1711 {
1712     if( o_embedded_list )
1713         return o_embedded_list;
1714
1715     return nil;
1716 }
1717
1718 - (id)coreDialogProvider
1719 {
1720     if( o_coredialogs )
1721         return o_coredialogs;
1722
1723     return nil;
1724 }
1725
1726 - (id)eyeTVController
1727 {
1728     if( o_eyetv )
1729         return o_eyetv;
1730
1731     return nil;
1732 }
1733
1734 - (id)appleRemoteController
1735 {
1736     return o_remote;
1737 }
1738
1739 - (void)setActiveVideoPlayback:(BOOL)b_value
1740 {
1741     b_active_videoplayback = b_value;
1742     if( o_mainwindow )
1743     {
1744         [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1745         [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1746     }
1747 }
1748
1749 - (BOOL)activeVideoPlayback
1750 {
1751     return b_active_videoplayback;
1752 }
1753
1754 #pragma mark -
1755 #pragma mark Crash Log
1756 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1757 {
1758     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1759     NSURL *url = [NSURL URLWithString:urlStr];
1760
1761     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1762     [req setHTTPMethod:@"POST"];
1763
1764     NSString * email;
1765     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1766     {
1767         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1768         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1769         email = [emails valueAtIndex:[emails indexForIdentifier:
1770                     [emails primaryIdentifier]]];
1771     }
1772     else
1773         email = [NSString string];
1774
1775     NSString *postBody;
1776     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1777             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1778             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1779             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1780
1781     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1782
1783     /* Released from delegate */
1784     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1785 }
1786
1787 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1788 {
1789     [crashLogURLConnection release];
1790     crashLogURLConnection = nil;
1791 }
1792
1793 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1794 {
1795     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1796     [crashLogURLConnection release];
1797     crashLogURLConnection = nil;
1798 }
1799
1800 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1801 {
1802     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1803     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1804     NSString *fname;
1805     NSString * latestLog = nil;
1806     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1807     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1808     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
1809     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1810
1811     while (fname = [direnum nextObject])
1812     {
1813         [direnum skipDescendents];
1814         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1815         {
1816             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1817             if( [compo count] < 3 ) continue;
1818             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1819             if( [compo count] < 4 ) continue;
1820
1821             // Dooh. ugly.
1822             if( year < [[compo objectAtIndex:0] intValue] ||
1823                 (year ==[[compo objectAtIndex:0] intValue] &&
1824                  (month < [[compo objectAtIndex:1] intValue] ||
1825                   (month ==[[compo objectAtIndex:1] intValue] &&
1826                    (day   < [[compo objectAtIndex:2] intValue] ||
1827                     (day   ==[[compo objectAtIndex:2] intValue] &&
1828                       hours < [[compo objectAtIndex:3] intValue] ))))))
1829             {
1830                 year  = [[compo objectAtIndex:0] intValue];
1831                 month = [[compo objectAtIndex:1] intValue];
1832                 day   = [[compo objectAtIndex:2] intValue];
1833                 hours = [[compo objectAtIndex:3] intValue];
1834                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1835             }
1836         }
1837     }
1838
1839     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1840         return nil;
1841
1842     if( !previouslySeen )
1843     {
1844         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
1845         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1846         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
1847         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1848     }
1849     return latestLog;
1850 }
1851
1852 - (NSString *)latestCrashLogPath
1853 {
1854     return [self latestCrashLogPathPreviouslySeen:YES];
1855 }
1856
1857 - (void)lookForCrashLog
1858 {
1859     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1860     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1861     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1862     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1863     if( latestLog && !areCrashLogsTooOld )
1864         [NSApp runModalForWindow: o_crashrep_win];
1865     [o_pool release];
1866 }
1867
1868 - (IBAction)crashReporterAction:(id)sender
1869 {
1870     if( sender == o_crashrep_send_btn )
1871         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1872
1873     [NSApp stopModal];
1874     [o_crashrep_win orderOut: sender];
1875 }
1876
1877 - (IBAction)openCrashLog:(id)sender
1878 {
1879     NSString * latestLog = [self latestCrashLogPath];
1880     if( latestLog )
1881     {
1882         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1883     }
1884     else
1885     {
1886         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.") );
1887     }
1888 }
1889
1890 #pragma mark -
1891 #pragma mark Remove old prefs
1892
1893 - (void)_removeOldPreferences
1894 {
1895     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1896     static const int kCurrentPreferencesVersion = 2;
1897     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1898     if( version >= kCurrentPreferencesVersion ) return;
1899
1900     if( version == 1 )
1901     {
1902         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1903         [[NSUserDefaults standardUserDefaults] synchronize];
1904
1905         if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1906             return;
1907         else
1908             config_SaveConfigFile( VLCIntf ); // we need to do manually, since we won't quit libvlc cleanly
1909     }
1910     else
1911     {
1912         NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1913             NSUserDomainMask, YES);
1914         if( !libraries || [libraries count] == 0) return;
1915         NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1916
1917         /* File not found, don't attempt anything */
1918         if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1919            ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1920         {
1921             [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1922             return;
1923         }
1924
1925         int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1926                     _NS("We just found an older version of VLC's preferences files."),
1927                     _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1928         if( res != NSOKButton )
1929         {
1930             [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1931             return;
1932         }
1933
1934         NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc", nil];
1935
1936         /* Move the file to trash so that user can find them later */
1937         [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1938
1939         /* really reset the defaults from now on */
1940         [NSUserDefaults resetStandardUserDefaults];
1941
1942         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1943         [[NSUserDefaults standardUserDefaults] synchronize];
1944     }
1945
1946     /* Relaunch now */
1947     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1948
1949     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1950     if(fork() != 0)
1951     {
1952         exit(0);
1953         return;
1954     }
1955     execl(path, path, NULL);
1956 }
1957
1958 #pragma mark -
1959 #pragma mark Errors, warnings and messages
1960 - (IBAction)updateMessagesPanel:(id)sender
1961 {
1962     [self windowDidBecomeKey:nil];
1963 }
1964
1965 - (IBAction)showMessagesPanel:(id)sender
1966 {
1967     [o_msgs_panel makeKeyAndOrderFront: sender];
1968 }
1969
1970 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1971 {
1972     [o_msgs_table reloadData];
1973     [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1974 }
1975
1976 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1977 {
1978     if (aTableView == o_msgs_table)
1979         return [o_msg_arr count];
1980     return 0; 
1981 }
1982
1983 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1984 {
1985     NSMutableAttributedString *result = NULL;
1986
1987     [o_msg_lock lock];
1988     if( rowIndex < [o_msg_arr count] )
1989         result = [o_msg_arr objectAtIndex: rowIndex];
1990     [o_msg_lock unlock];
1991
1992     if( result != NULL )
1993         return result;
1994     else
1995         return @"";
1996 }
1997
1998 - (void)processReceivedlibvlcMessage:(const msg_item_t *) item ofType: (int)i_type withStr: (char *)str
1999 {
2000     if (o_msg_arr)
2001     {
2002         NSColor *o_white = [NSColor whiteColor];
2003         NSColor *o_red = [NSColor redColor];
2004         NSColor *o_yellow = [NSColor yellowColor];
2005         NSColor *o_gray = [NSColor grayColor];
2006         NSString * firstString, * secondString;
2007
2008         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2009         static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
2010
2011         NSDictionary *o_attr;
2012         NSMutableAttributedString *o_msg_color;
2013
2014         [o_msg_lock lock];
2015
2016         if( [o_msg_arr count] + 2 > 600 )
2017         {
2018             [o_msg_arr removeObjectAtIndex: 0];
2019             [o_msg_arr removeObjectAtIndex: 1];
2020         }
2021         firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
2022         secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
2023
2024         o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]  forKey: NSForegroundColorAttributeName];
2025         o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
2026         o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
2027         [o_msg_color setAttributes: o_attr range: NSMakeRange( 0, [firstString length] )];
2028         [o_msg_arr addObject: [o_msg_color autorelease]];
2029
2030         b_msg_arr_changed = YES;
2031         [o_msg_lock unlock];
2032     }
2033 }
2034
2035 - (IBAction)saveDebugLog:(id)sender
2036 {
2037     NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
2038
2039     [saveFolderPanel setCanSelectHiddenExtension: NO];
2040     [saveFolderPanel setCanCreateDirectories: YES];
2041     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
2042     [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];
2043 }
2044
2045 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2046 {
2047     BOOL b_returned;
2048     if( returnCode == NSOKButton )
2049     {
2050         NSUInteger count = [o_msg_arr count];
2051         NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
2052         for (NSUInteger i = 0; i < count; i++)
2053         {
2054             [string appendAttributedString: [o_msg_arr objectAtIndex: i]];
2055         }
2056         b_returned = [[string RTFDFileWrapperFromRange:NSMakeRange( 0, [string length] ) documentAttributes:[NSDictionary dictionaryWithObject: NSRTFDTextDocumentType forKey: NSDocumentTypeDocumentAttribute]] writeToFile:[[sheet URL] path] atomically:YES updateFilenames:NO];
2057         [string release];
2058
2059         if(! b_returned )
2060             msg_Warn( p_intf, "Error while saving the debug log" );
2061     }
2062 }
2063
2064 #pragma mark -
2065 #pragma mark Playlist toggling
2066
2067 - (void)updateTogglePlaylistState
2068 {
2069     [[self playlist] outlineViewSelectionDidChange: NULL];
2070 }
2071
2072 #pragma mark -
2073
2074 @end
2075
2076 @implementation VLCMain (Internal)
2077
2078 - (void)handlePortMessage:(NSPortMessage *)o_msg
2079 {
2080     id ** val;
2081     NSData * o_data;
2082     NSValue * o_value;
2083     NSInvocation * o_inv;
2084     NSConditionLock * o_lock;
2085
2086     o_data = [[o_msg components] lastObject];
2087     o_inv = *((NSInvocation **)[o_data bytes]);
2088     [o_inv getArgument: &o_value atIndex: 2];
2089     val = (id **)[o_value pointerValue];
2090     [o_inv setArgument: val[1] atIndex: 2];
2091     o_lock = *(val[0]);
2092
2093     [o_lock lock];
2094     [o_inv invoke];
2095     [o_lock unlockWithCondition: 1];
2096 }
2097 - (void)resetMediaKeyJump
2098 {
2099     b_mediakeyJustJumped = NO;
2100 }
2101 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2102 {
2103     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2104     if (b_mediaKeySupport) {
2105         if (!o_mediaKeyController)
2106             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2107         [o_mediaKeyController startWatchingMediaKeys];
2108     }
2109     else if (!b_mediaKeySupport && o_mediaKeyController)
2110     {
2111         int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
2112                                                _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
2113                                                _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
2114         if( returnedValue == NSOKButton )
2115         {
2116             /* Relaunch now */
2117             const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2118
2119             /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2120             if(fork() != 0)
2121             {
2122                 exit(0);
2123                 return;
2124             }
2125             execl(path, path, NULL);
2126         }
2127     }
2128 }
2129
2130 @end
2131
2132 /*****************************************************************************
2133  * VLCApplication interface
2134  *****************************************************************************/
2135
2136 @implementation VLCApplication
2137 // when user selects the quit menu from dock it sends a terminate:
2138 // but we need to send a stop: to properly exits libvlc.
2139 // However, we are not able to change the action-method sent by this standard menu item.
2140 // thus we override terminat: to send a stop:
2141 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2142 - (void)terminate:(id)sender
2143 {
2144     [self activateIgnoringOtherApps:YES];
2145     [self stop:sender];
2146 }
2147
2148 @end