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