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