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