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