]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: Fix crash log and remove some unneeded NSLog.
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2008 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_keys.h>
34
35 #ifdef HAVE_CONFIG_H
36 #   include "config.h"
37 #endif
38
39 #import "intf.h"
40 #import "fspanel.h"
41 #import "vout.h"
42 #import "prefs.h"
43 #import "playlist.h"
44 #import "playlistinfo.h"
45 #import "controls.h"
46 #import "about.h"
47 #import "open.h"
48 #import "wizard.h"
49 #import "extended.h"
50 #import "bookmarks.h"
51 #import "interaction.h"
52 #import "embeddedwindow.h"
53 #import "update.h"
54 #import "AppleRemote.h"
55 #import "eyetv.h"
56 #import "simple_prefs.h"
57
58 #import <vlc_input.h>
59 #import <vlc_interface.h>
60
61 /*****************************************************************************
62  * Local prototypes.
63  *****************************************************************************/
64 static void Run ( intf_thread_t *p_intf );
65
66 /* Quick hack */
67 /*****************************************************************************
68  * VLCApplication implementation (this hack is really disgusting now,
69  *                                feel free to fix.)
70  *****************************************************************************/
71 @interface VLCApplication : NSApplication
72 {
73    libvlc_int_t *o_libvlc;
74 }
75 - (void)setVLC: (libvlc_int_t *)p_libvlc;
76 @end
77
78
79 @implementation VLCApplication
80 - (void)setVLC: (libvlc_int_t *) p_libvlc
81 {
82     o_libvlc = p_libvlc;
83 }
84 - (void)terminate: (id)sender
85 {
86     vlc_object_kill( o_libvlc );
87     [super terminate: sender];
88 }
89 @end
90
91 /*****************************************************************************
92  * OpenIntf: initialize interface
93  *****************************************************************************/
94 int OpenIntf ( vlc_object_t *p_this )
95 {
96     intf_thread_t *p_intf = (intf_thread_t*) p_this;
97
98     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
99     if( p_intf->p_sys == NULL )
100     {
101         return( 1 );
102     }
103
104     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
105
106     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
107
108     p_intf->p_sys->p_sub = msg_Subscribe( p_intf );
109     p_intf->pf_run = Run;
110     p_intf->b_should_run_on_first_thread = true;
111
112     return( 0 );
113 }
114
115 /*****************************************************************************
116  * CloseIntf: destroy interface
117  *****************************************************************************/
118 void CloseIntf ( vlc_object_t *p_this )
119 {
120     intf_thread_t *p_intf = (intf_thread_t*) p_this;
121
122     [[VLCMain sharedInstance] setIntf: nil];
123     
124     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
125
126     [p_intf->p_sys->o_pool release];
127
128     free( p_intf->p_sys );
129 }
130
131 /*****************************************************************************
132  * Run: main loop
133  *****************************************************************************/
134 jmp_buf jmpbuffer;
135
136 static void Run( intf_thread_t *p_intf )
137 {
138     sigset_t set;
139
140     /* Do it again - for some unknown reason, vlc_thread_create() often
141      * fails to go to real-time priority with the first launched thread
142      * (???) --Meuuh */
143     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
144
145     /* Make sure the "force quit" menu item does quit instantly.
146      * VLC overrides SIGTERM which is sent by the "force quit"
147      * menu item to make sure deamon mode quits gracefully, so
148      * we un-override SIGTERM here. */
149     sigemptyset( &set );
150     sigaddset( &set, SIGTERM );
151     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
152
153     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
154
155     /* Install a jmpbuffer to where we can go back before the NSApp exit
156      * see applicationWillTerminate: */
157     /* We need that code to run on main thread */
158     [VLCApplication sharedApplication];
159     [NSApp setVLC: p_intf->p_libvlc];
160
161     [[VLCMain sharedInstance] setIntf: p_intf];
162     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
163
164     /* Install a jmpbuffer to where we can go back before the NSApp exit
165      * see applicationWillTerminate: */
166     if(setjmp(jmpbuffer) == 0)
167         [NSApp run];
168
169     [o_pool release];
170 }
171
172 /*****************************************************************************
173  * ManageThread: An ugly thread that polls
174  *****************************************************************************/
175 static void * ManageThread( void *user_data )
176 {
177     id self = user_data;
178
179     [self manage];
180
181     return NULL;
182 }
183
184 /*****************************************************************************
185  * playlistChanged: Callback triggered by the intf-change playlist
186  * variable, to let the intf update the playlist.
187  *****************************************************************************/
188 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
189                      vlc_value_t old_val, vlc_value_t new_val, void *param )
190 {
191     intf_thread_t * p_intf = VLCIntf;
192     p_intf->p_sys->b_intf_update = true;
193     p_intf->p_sys->b_playlist_update = true;
194     p_intf->p_sys->b_playmode_update = true;
195     p_intf->p_sys->b_current_title_update = true;
196     return VLC_SUCCESS;
197 }
198
199 /*****************************************************************************
200  * ShowController: Callback triggered by the show-intf playlist variable
201  * through the ShowIntf-control-intf, to let us show the controller-win;
202  * usually when in fullscreen-mode
203  *****************************************************************************/
204 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
205                      vlc_value_t old_val, vlc_value_t new_val, void *param )
206 {
207     intf_thread_t * p_intf = VLCIntf;
208     p_intf->p_sys->b_intf_show = true;
209     return VLC_SUCCESS;
210 }
211
212 /*****************************************************************************
213  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
214  * variable, to let the intf update the controller.
215  *****************************************************************************/
216 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
217                      vlc_value_t old_val, vlc_value_t new_val, void *param )
218 {
219     intf_thread_t * p_intf = VLCIntf;
220     p_intf->p_sys->b_fullscreen_update = true;
221     return VLC_SUCCESS;
222 }
223
224 /*****************************************************************************
225  * InteractCallback: Callback triggered by the interaction
226  * variable, to let the intf display error and interaction dialogs
227  *****************************************************************************/
228 static int InteractCallback( vlc_object_t *p_this, const char *psz_variable,
229                      vlc_value_t old_val, vlc_value_t new_val, void *param )
230 {
231     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
232     VLCMain *interface = (VLCMain *)param;
233     interaction_dialog_t *p_dialog = (interaction_dialog_t *)(new_val.p_address);
234     NSValue *o_value = [NSValue valueWithPointer:p_dialog];
235  
236     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewInteractionEventNotification" object:[interface getInteractionList]
237      userInfo:[NSDictionary dictionaryWithObject:o_value forKey:@"VLCDialogPointer"]];
238  
239     [o_pool release];
240     return VLC_SUCCESS;
241 }
242
243 static struct
244 {
245     unichar i_nskey;
246     unsigned int i_vlckey;
247 } nskeys_to_vlckeys[] =
248 {
249     { NSUpArrowFunctionKey, KEY_UP },
250     { NSDownArrowFunctionKey, KEY_DOWN },
251     { NSLeftArrowFunctionKey, KEY_LEFT },
252     { NSRightArrowFunctionKey, KEY_RIGHT },
253     { NSF1FunctionKey, KEY_F1 },
254     { NSF2FunctionKey, KEY_F2 },
255     { NSF3FunctionKey, KEY_F3 },
256     { NSF4FunctionKey, KEY_F4 },
257     { NSF5FunctionKey, KEY_F5 },
258     { NSF6FunctionKey, KEY_F6 },
259     { NSF7FunctionKey, KEY_F7 },
260     { NSF8FunctionKey, KEY_F8 },
261     { NSF9FunctionKey, KEY_F9 },
262     { NSF10FunctionKey, KEY_F10 },
263     { NSF11FunctionKey, KEY_F11 },
264     { NSF12FunctionKey, KEY_F12 },
265     { NSHomeFunctionKey, KEY_HOME },
266     { NSEndFunctionKey, KEY_END },
267     { NSPageUpFunctionKey, KEY_PAGEUP },
268     { NSPageDownFunctionKey, KEY_PAGEDOWN },
269     { NSTabCharacter, KEY_TAB },
270     { NSCarriageReturnCharacter, KEY_ENTER },
271     { NSEnterCharacter, KEY_ENTER },
272     { NSBackspaceCharacter, KEY_BACKSPACE },
273     { (unichar) ' ', KEY_SPACE },
274     { (unichar) 0x1b, KEY_ESC },
275     {0,0}
276 };
277
278 unichar VLCKeyToCocoa( unsigned int i_key )
279 {
280     unsigned int i;
281
282     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
283     {
284         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
285         {
286             return nskeys_to_vlckeys[i].i_nskey;
287         }
288     }
289     return (unichar)(i_key & ~KEY_MODIFIER);
290 }
291
292 unsigned int CocoaKeyToVLC( unichar i_key )
293 {
294     unsigned int i;
295
296     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
297     {
298         if( nskeys_to_vlckeys[i].i_nskey == i_key )
299         {
300             return nskeys_to_vlckeys[i].i_vlckey;
301         }
302     }
303     return (unsigned int)i_key;
304 }
305
306 unsigned int VLCModifiersToCocoa( unsigned int i_key )
307 {
308     unsigned int new = 0;
309     if( i_key & KEY_MODIFIER_COMMAND )
310         new |= NSCommandKeyMask;
311     if( i_key & KEY_MODIFIER_ALT )
312         new |= NSAlternateKeyMask;
313     if( i_key & KEY_MODIFIER_SHIFT )
314         new |= NSShiftKeyMask;
315     if( i_key & KEY_MODIFIER_CTRL )
316         new |= NSControlKeyMask;
317     return new;
318 }
319
320 /*****************************************************************************
321  * VLCMain implementation
322  *****************************************************************************/
323 @implementation VLCMain
324
325 static VLCMain *_o_sharedMainInstance = nil;
326
327 + (VLCMain *)sharedInstance
328 {
329     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
330 }
331
332 - (id)init
333 {
334     if( _o_sharedMainInstance) 
335     {
336         [self dealloc];
337         return _o_sharedMainInstance;
338     } 
339     else
340         _o_sharedMainInstance = [super init];
341
342     o_about = [[VLAboutBox alloc] init];
343     o_prefs = nil;
344     o_open = [[VLCOpen alloc] init];
345     o_wizard = [[VLCWizard alloc] init];
346     o_extended = nil;
347     o_bookmarks = [[VLCBookmarks alloc] init];
348     o_embedded_list = [[VLCEmbeddedList alloc] init];
349     o_interaction_list = [[VLCInteractionList alloc] init];
350     o_info = [[VLCInfo alloc] init];
351 #ifdef UPDATE_CHECK
352     o_update = [[VLCUpdate alloc] init];
353 #endif
354
355     i_lastShownVolume = -1;
356
357     o_remote = [[AppleRemote alloc] init];
358     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
359     [o_remote setDelegate: _o_sharedMainInstance];
360
361     o_eyetv = [[VLCEyeTVController alloc] init];
362
363     /* announce our launch to a potential eyetv plugin */
364     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
365                                                                    object: @"VLCEyeTVSupport"
366                                                                  userInfo: NULL
367                                                        deliverImmediately: YES];
368
369     return _o_sharedMainInstance;
370 }
371
372 - (void)setIntf: (intf_thread_t *)p_mainintf {
373     p_intf = p_mainintf;
374 }
375
376 - (intf_thread_t *)getIntf {
377     return p_intf;
378 }
379
380 - (void)awakeFromNib
381 {
382     unsigned int i_key = 0;
383     playlist_t *p_playlist;
384     vlc_value_t val;
385
386     /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
387     if( nib_main_loaded ) return;
388
389     [self initStrings];
390
391     [o_window setExcludedFromWindowsMenu: YES];
392     [o_msgs_panel setExcludedFromWindowsMenu: YES];
393     [o_msgs_panel setDelegate: self];
394
395     i_key = config_GetInt( p_intf, "key-quit" );
396     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
397     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
398     i_key = config_GetInt( p_intf, "key-play-pause" );
399     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
400     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
401     i_key = config_GetInt( p_intf, "key-stop" );
402     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
403     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
404     i_key = config_GetInt( p_intf, "key-faster" );
405     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
406     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
407     i_key = config_GetInt( p_intf, "key-slower" );
408     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
409     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
410     i_key = config_GetInt( p_intf, "key-prev" );
411     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
412     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
413     i_key = config_GetInt( p_intf, "key-next" );
414     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
415     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
416     i_key = config_GetInt( p_intf, "key-jump+short" );
417     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
418     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
419     i_key = config_GetInt( p_intf, "key-jump-short" );
420     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
421     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
422     i_key = config_GetInt( p_intf, "key-jump+medium" );
423     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
424     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
425     i_key = config_GetInt( p_intf, "key-jump-medium" );
426     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
427     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
428     i_key = config_GetInt( p_intf, "key-jump+long" );
429     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
430     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
431     i_key = config_GetInt( p_intf, "key-jump-long" );
432     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
433     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
434     i_key = config_GetInt( p_intf, "key-vol-up" );
435     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
436     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
437     i_key = config_GetInt( p_intf, "key-vol-down" );
438     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
439     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
440     i_key = config_GetInt( p_intf, "key-vol-mute" );
441     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
442     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
443     i_key = config_GetInt( p_intf, "key-fullscreen" );
444     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
445     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
446     i_key = config_GetInt( p_intf, "key-snapshot" );
447     [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
448     [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
449
450     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
451
452     [self setSubmenusEnabled: FALSE];
453     [o_volumeslider setEnabled: YES];
454     [self manageVolumeSlider];
455     [o_window setDelegate: self];
456  
457     b_restore_size = false;
458     if( [o_window frame].size.height <= 200 )
459     {
460         b_small_window = YES;
461         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
462             [o_window frame].origin.y, [o_window frame].size.width,
463             [o_window minSize].height ) display: YES animate:YES];
464         [o_playlist_view setAutoresizesSubviews: NO];
465     }
466     else
467     {
468         b_small_window = NO;
469         [o_playlist_view setFrame: NSMakeRect( 0, 0, [o_window frame].size.width, [o_window frame].size.height - 95 )];
470         [o_playlist_view setNeedsDisplay:YES];
471         [o_playlist_view setAutoresizesSubviews: YES];
472         [[o_window contentView] addSubview: o_playlist_view];
473     }
474     [self updateTogglePlaylistState];
475
476     o_size_with_playlist = [o_window frame].size;
477
478     p_playlist = pl_Yield( p_intf );
479
480     var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
481     val.b_bool = false;
482
483     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
484     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
485
486     pl_Release( p_intf );
487  
488     var_Create( p_intf, "interaction", VLC_VAR_ADDRESS );
489     var_AddCallback( p_intf, "interaction", InteractCallback, self );
490     p_intf->b_interaction = true;
491
492     /* update the playmode stuff */
493     p_intf->p_sys->b_playmode_update = true;
494
495     [[NSNotificationCenter defaultCenter] addObserver: self
496                                              selector: @selector(refreshVoutDeviceMenu:)
497                                                  name: NSApplicationDidChangeScreenParametersNotification
498                                                object: nil];
499
500     o_img_play = [NSImage imageNamed: @"play"];
501     o_img_pause = [NSImage imageNamed: @"pause"];    
502     
503     [self controlTintChanged];
504
505     [[NSNotificationCenter defaultCenter] addObserver: self
506                                              selector: @selector( controlTintChanged )
507                                                  name: NSControlTintDidChangeNotification
508                                                object: nil];
509     
510     nib_main_loaded = TRUE;
511 }
512
513 #pragma mark Toolbar delegate
514 /* Our item identifiers */
515 static NSString * VLCToolbarMediaControl     = @"VLCToolbarMediaControl";
516
517 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
518 {
519     return [NSArray arrayWithObjects:
520 //                        NSToolbarCustomizeToolbarItemIdentifier,
521 //                        NSToolbarFlexibleSpaceItemIdentifier,
522 //                        NSToolbarSpaceItemIdentifier,
523 //                        NSToolbarSeparatorItemIdentifier,
524                         VLCToolbarMediaControl,
525                         nil ];
526 }
527
528 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
529 {
530     return [NSArray arrayWithObjects:
531                         VLCToolbarMediaControl,
532                         nil ];
533 }
534
535 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
536 {
537     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
538
539  
540     if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
541     {
542         [toolbarItem setLabel:@"Media Controls"];
543         [toolbarItem setPaletteLabel:@"Media Controls"];
544
545         NSSize size = toolbarMediaControl.frame.size;
546         [toolbarItem setView:toolbarMediaControl];
547         [toolbarItem setMinSize:size];
548         size.width += 1000.;
549         [toolbarItem setMaxSize:size];
550
551         // Hack: For some reason we need to make sure
552         // that the those element are on top
553         // Add them again will put them frontmost
554         [toolbarMediaControl addSubview:o_scrollfield];
555         [toolbarMediaControl addSubview:o_timeslider];
556         [toolbarMediaControl addSubview:o_timefield];
557         [toolbarMediaControl addSubview:o_main_pgbar];
558
559         /* TODO: setup a menu */
560     }
561     else
562     {
563         /* itemIdentifier referred to a toolbar item that is not
564          * provided or supported by us or Cocoa
565          * Returning nil will inform the toolbar
566          * that this kind of item is not supported */
567         toolbarItem = nil;
568     }
569     return toolbarItem;
570 }
571
572 #pragma mark -
573
574 - (void)controlTintChanged
575 {
576     BOOL b_playing = NO;
577     
578     if( [o_btn_play alternateImage] == o_img_play_pressed )
579         b_playing = YES;
580     
581     if( [NSColor currentControlTint] == NSGraphiteControlTint )
582     {
583         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
584         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
585         
586         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
587         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
588         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
589         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
590         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
591         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
592         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
593         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
594     }
595     else
596     {
597         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
598         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
599         
600         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
601         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
602         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
603         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
604         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
605         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
606         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
607         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
608     }
609     
610     if( b_playing )
611         [o_btn_play setAlternateImage: o_img_play_pressed];
612     else
613         [o_btn_play setAlternateImage: o_img_pause_pressed];
614 }
615
616 - (void)initStrings
617 {
618     [o_window setTitle: _NS("VLC")];
619     [self setScrollField:_NS("VLC media player") stopAfter:-1];
620
621     /* button controls */
622     [o_btn_prev setToolTip: _NS("Previous")];
623     [o_btn_rewind setToolTip: _NS("Rewind")];
624     [o_btn_play setToolTip: _NS("Play")];
625     [o_btn_stop setToolTip: _NS("Stop")];
626     [o_btn_ff setToolTip: _NS("Fast Forward")];
627     [o_btn_next setToolTip: _NS("Next")];
628     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
629     [o_volumeslider setToolTip: _NS("Volume")];
630     [o_timeslider setToolTip: _NS("Position")];
631     [o_btn_playlist setToolTip: _NS("Playlist")];
632
633     /* messages panel */
634     [o_msgs_panel setTitle: _NS("Messages")];
635     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog...")];
636
637     /* main menu */
638     [o_mi_about setTitle: [_NS("About VLC media player") \
639         stringByAppendingString: @"..."]];
640     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
641     [o_mi_prefs setTitle: _NS("Preferences...")];
642     [o_mi_add_intf setTitle: _NS("Add Interface")];
643     [o_mu_add_intf setTitle: _NS("Add Interface")];
644     [o_mi_services setTitle: _NS("Services")];
645     [o_mi_hide setTitle: _NS("Hide VLC")];
646     [o_mi_hide_others setTitle: _NS("Hide Others")];
647     [o_mi_show_all setTitle: _NS("Show All")];
648     [o_mi_quit setTitle: _NS("Quit VLC")];
649
650     [o_mu_file setTitle: _ANS("1:File")];
651     [o_mi_open_generic setTitle: _NS("Open File...")];
652     [o_mi_open_file setTitle: _NS("Quick Open File...")];
653     [o_mi_open_disc setTitle: _NS("Open Disc...")];
654     [o_mi_open_net setTitle: _NS("Open Network...")];
655     [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
656     [o_mi_open_recent setTitle: _NS("Open Recent")];
657     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
658     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
659
660     [o_mu_edit setTitle: _NS("Edit")];
661     [o_mi_cut setTitle: _NS("Cut")];
662     [o_mi_copy setTitle: _NS("Copy")];
663     [o_mi_paste setTitle: _NS("Paste")];
664     [o_mi_clear setTitle: _NS("Clear")];
665     [o_mi_select_all setTitle: _NS("Select All")];
666
667     [o_mu_controls setTitle: _NS("Playback")];
668     [o_mi_play setTitle: _NS("Play")];
669     [o_mi_stop setTitle: _NS("Stop")];
670     [o_mi_faster setTitle: _NS("Faster")];
671     [o_mi_slower setTitle: _NS("Slower")];
672     [o_mi_previous setTitle: _NS("Previous")];
673     [o_mi_next setTitle: _NS("Next")];
674     [o_mi_random setTitle: _NS("Random")];
675     [o_mi_repeat setTitle: _NS("Repeat One")];
676     [o_mi_loop setTitle: _NS("Repeat All")];
677     [o_mi_fwd setTitle: _NS("Step Forward")];
678     [o_mi_bwd setTitle: _NS("Step Backward")];
679
680     [o_mi_program setTitle: _NS("Program")];
681     [o_mu_program setTitle: _NS("Program")];
682     [o_mi_title setTitle: _NS("Title")];
683     [o_mu_title setTitle: _NS("Title")];
684     [o_mi_chapter setTitle: _NS("Chapter")];
685     [o_mu_chapter setTitle: _NS("Chapter")];
686
687     [o_mu_audio setTitle: _NS("Audio")];
688     [o_mi_vol_up setTitle: _NS("Volume Up")];
689     [o_mi_vol_down setTitle: _NS("Volume Down")];
690     [o_mi_mute setTitle: _NS("Mute")];
691     [o_mi_audiotrack setTitle: _NS("Audio Track")];
692     [o_mu_audiotrack setTitle: _NS("Audio Track")];
693     [o_mi_channels setTitle: _NS("Audio Channels")];
694     [o_mu_channels setTitle: _NS("Audio Channels")];
695     [o_mi_device setTitle: _NS("Audio Device")];
696     [o_mu_device setTitle: _NS("Audio Device")];
697     [o_mi_visual setTitle: _NS("Visualizations")];
698     [o_mu_visual setTitle: _NS("Visualizations")];
699
700     [o_mu_video setTitle: _NS("Video")];
701     [o_mi_half_window setTitle: _NS("Half Size")];
702     [o_mi_normal_window setTitle: _NS("Normal Size")];
703     [o_mi_double_window setTitle: _NS("Double Size")];
704     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
705     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
706     [o_mi_floatontop setTitle: _NS("Float on Top")];
707     [o_mi_snapshot setTitle: _NS("Snapshot")];
708     [o_mi_videotrack setTitle: _NS("Video Track")];
709     [o_mu_videotrack setTitle: _NS("Video Track")];
710     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
711     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
712     [o_mi_crop setTitle: _NS("Crop")];
713     [o_mu_crop setTitle: _NS("Crop")];
714     [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
715     [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
716     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
717     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
718     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
719     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
720     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
721     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
722
723     [o_mu_window setTitle: _NS("Window")];
724     [o_mi_minimize setTitle: _NS("Minimize Window")];
725     [o_mi_close_window setTitle: _NS("Close Window")];
726     [o_mi_controller setTitle: _NS("Controller...")];
727     [o_mi_equalizer setTitle: _NS("Equalizer...")];
728     [o_mi_extended setTitle: _NS("Extended Controls...")];
729     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
730     [o_mi_playlist setTitle: _NS("Playlist...")];
731     [o_mi_info setTitle: _NS("Media Information...")];
732     [o_mi_messages setTitle: _NS("Messages...")];
733     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
734
735     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
736
737     [o_mu_help setTitle: _NS("Help")];
738     [o_mi_help setTitle: _NS("VLC media player Help...")];
739     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
740     [o_mi_license setTitle: _NS("License")];
741     [o_mi_documentation setTitle: _NS("Online Documentation...")];
742     [o_mi_website setTitle: _NS("VideoLAN Website...")];
743     [o_mi_donation setTitle: _NS("Make a donation...")];
744     [o_mi_forum setTitle: _NS("Online Forum...")];
745
746     /* dock menu */
747     [o_dmi_play setTitle: _NS("Play")];
748     [o_dmi_stop setTitle: _NS("Stop")];
749     [o_dmi_next setTitle: _NS("Next")];
750     [o_dmi_previous setTitle: _NS("Previous")];
751     [o_dmi_mute setTitle: _NS("Mute")];
752  
753     /* vout menu */
754     [o_vmi_play setTitle: _NS("Play")];
755     [o_vmi_stop setTitle: _NS("Stop")];
756     [o_vmi_prev setTitle: _NS("Previous")];
757     [o_vmi_next setTitle: _NS("Next")];
758     [o_vmi_volup setTitle: _NS("Volume Up")];
759     [o_vmi_voldown setTitle: _NS("Volume Down")];
760     [o_vmi_mute setTitle: _NS("Mute")];
761     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
762     [o_vmi_snapshot setTitle: _NS("Snapshot")];
763 }
764
765 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
766 {
767     o_msg_lock = [[NSLock alloc] init];
768     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
769
770     /* FIXME: don't poll */
771     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
772                                      target: self selector: @selector(manageIntf:)
773                                    userInfo: nil repeats: FALSE] retain];
774
775     /* Note: we use the pthread API to support pre-10.5 */
776     pthread_create( &manage_thread, NULL, ManageThread, self );
777
778     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
779         var: "intf-add" selector: @selector(toggleVar:)];
780
781     /* check whether the user runs a valid version of OSX; alert is auto-released */
782     if( MACOS_VERSION < 10.4f )
783     {
784         NSAlert *ourAlert;
785         int i_returnValue;
786         ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is not supported")
787                         defaultButton: _NS("Quit")
788                       alternateButton: NULL
789                           otherButton: NULL
790             informativeTextWithFormat: _NS("VLC media player requires Mac OS X 10.4 or higher.")];
791         [ourAlert setAlertStyle: NSCriticalAlertStyle];
792         i_returnValue = [ourAlert runModal];
793         [NSApp terminate: self];
794     }
795
796     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
797 }
798
799 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
800 {
801     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
802     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
803     if( b_autoplay )
804         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
805     else
806         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
807
808     return( TRUE );
809 }
810
811 - (NSString *)localizedString:(const char *)psz
812 {
813     NSString * o_str = nil;
814
815     if( psz != NULL )
816     {
817         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
818
819         if( o_str == NULL )
820         {
821             msg_Err( VLCIntf, "could not translate: %s", psz );
822             return( @"" );
823         }
824     }
825     else
826     {
827         msg_Warn( VLCIntf, "can't translate empty strings" );
828         return( @"" );
829     }
830
831     return( o_str );
832 }
833
834 /* When user click in the Dock icon our double click in the finder */
835 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
836 {    
837     if(!hasVisibleWindows)
838         [o_window makeKeyAndOrderFront:self];
839
840     return YES;
841 }
842
843 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
844 {
845 #ifdef UPDATE_CHECK
846     /* Check for update silently on startup */
847     if( !nib_update_loaded )
848         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
849
850     if([o_update shouldCheckForUpdate])
851         [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:NULL];
852 #endif
853
854     /* Handle sleep notification */
855     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
856            name:NSWorkspaceWillSleepNotification object:nil];
857
858     [self performSelectorInBackground:@selector(lookForCrashLog) withObject:NULL];
859 }
860
861 /* Listen to the remote in exclusive mode, only when VLC is the active
862    application */
863 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
864 {
865     [o_remote startListening: self];
866 }
867 - (void)applicationDidResignActive:(NSNotification *)aNotification
868 {
869     [o_remote stopListening: self];
870 }
871
872 /* Triggered when the computer goes to sleep */
873 - (void)computerWillSleep: (NSNotification *)notification
874 {
875     /* Pause */
876     if( p_intf->p_sys->i_play_status == PLAYING_S )
877     {
878         vlc_value_t val;
879         val.i_int = config_GetInt( p_intf, "key-play-pause" );
880         var_Set( p_intf->p_libvlc, "key-pressed", val );
881     }
882 }
883
884 /* Helper method for the remote control interface in order to trigger forward/backward and volume
885    increase/decrease as long as the user holds the left/right, plus/minus button */
886 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
887 {
888     if(b_remote_button_hold)
889     {
890         switch([buttonIdentifierNumber intValue])
891         {
892             case kRemoteButtonRight_Hold:
893                   [o_controls forward: self];
894             break;
895             case kRemoteButtonLeft_Hold:
896                   [o_controls backward: self];
897             break;
898             case kRemoteButtonVolume_Plus_Hold:
899                 [o_controls volumeUp: self];
900             break;
901             case kRemoteButtonVolume_Minus_Hold:
902                 [o_controls volumeDown: self];
903             break;
904         }
905         if(b_remote_button_hold)
906         {
907             /* trigger event */
908             [self performSelector:@selector(executeHoldActionForRemoteButton:)
909                          withObject:buttonIdentifierNumber
910                          afterDelay:0.25];
911         }
912     }
913 }
914
915 /* Apple Remote callback */
916 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
917                pressedDown: (BOOL) pressedDown
918                 clickCount: (unsigned int) count
919 {
920     switch( buttonIdentifier )
921     {
922         case kRemoteButtonPlay:
923             if(count >= 2) {
924                 [o_controls toogleFullscreen:self];
925             } else {
926                 [o_controls play: self];
927             }
928             break;
929         case kRemoteButtonVolume_Plus:
930             [o_controls volumeUp: self];
931             break;
932         case kRemoteButtonVolume_Minus:
933             [o_controls volumeDown: self];
934             break;
935         case kRemoteButtonRight:
936             [o_controls next: self];
937             break;
938         case kRemoteButtonLeft:
939             [o_controls prev: self];
940             break;
941         case kRemoteButtonRight_Hold:
942         case kRemoteButtonLeft_Hold:
943         case kRemoteButtonVolume_Plus_Hold:
944         case kRemoteButtonVolume_Minus_Hold:
945             /* simulate an event as long as the user holds the button */
946             b_remote_button_hold = pressedDown;
947             if( pressedDown )
948             {
949                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
950                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
951                            withObject:buttonIdentifierNumber];
952             }
953             break;
954         case kRemoteButtonMenu:
955             [o_controls showPosition: self];
956             break;
957         default:
958             /* Add here whatever you want other buttons to do */
959             break;
960     }
961 }
962
963 - (char *)delocalizeString:(NSString *)id
964 {
965     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
966                           allowLossyConversion: NO];
967     char * psz_string;
968
969     if( o_data == nil )
970     {
971         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
972                      allowLossyConversion: YES];
973         psz_string = malloc( [o_data length] + 1 );
974         [o_data getBytes: psz_string];
975         psz_string[ [o_data length] ] = '\0';
976         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
977                  psz_string );
978     }
979     else
980     {
981         psz_string = malloc( [o_data length] + 1 );
982         [o_data getBytes: psz_string];
983         psz_string[ [o_data length] ] = '\0';
984     }
985
986     return psz_string;
987 }
988
989 /* i_width is in pixels */
990 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
991 {
992     NSMutableString *o_wrapped;
993     NSString *o_out_string;
994     NSRange glyphRange, effectiveRange, charRange;
995     NSRect lineFragmentRect;
996     unsigned glyphIndex, breaksInserted = 0;
997
998     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
999         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1000         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1001     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1002     NSTextContainer *o_container = [[NSTextContainer alloc]
1003         initWithContainerSize: NSMakeSize(i_width, 2000)];
1004
1005     [o_layout_manager addTextContainer: o_container];
1006     [o_container release];
1007     [o_storage addLayoutManager: o_layout_manager];
1008     [o_layout_manager release];
1009
1010     o_wrapped = [o_in_string mutableCopy];
1011     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1012
1013     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1014             glyphIndex += effectiveRange.length) {
1015         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1016                                             effectiveRange: &effectiveRange];
1017         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1018                                     actualGlyphRange: &effectiveRange];
1019         if([o_wrapped lineRangeForRange:
1020                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1021             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1022             breaksInserted++;
1023         }
1024     }
1025     o_out_string = [NSString stringWithString: o_wrapped];
1026     [o_wrapped release];
1027     [o_storage release];
1028
1029     return o_out_string;
1030 }
1031
1032
1033 /*****************************************************************************
1034  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1035  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1036  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1037  *****************************************************************************/
1038 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1039 {
1040     unichar key = 0;
1041     vlc_value_t val;
1042     unsigned int i_pressed_modifiers = 0;
1043     struct hotkey *p_hotkeys;
1044     int i;
1045
1046     val.i_int = 0;
1047     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1048
1049     i_pressed_modifiers = [o_event modifierFlags];
1050
1051     if( i_pressed_modifiers & NSShiftKeyMask )
1052         val.i_int |= KEY_MODIFIER_SHIFT;
1053     if( i_pressed_modifiers & NSControlKeyMask )
1054         val.i_int |= KEY_MODIFIER_CTRL;
1055     if( i_pressed_modifiers & NSAlternateKeyMask )
1056         val.i_int |= KEY_MODIFIER_ALT;
1057     if( i_pressed_modifiers & NSCommandKeyMask )
1058         val.i_int |= KEY_MODIFIER_COMMAND;
1059
1060     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1061
1062     switch( key )
1063     {
1064         case NSDeleteCharacter:
1065         case NSDeleteFunctionKey:
1066         case NSDeleteCharFunctionKey:
1067         case NSBackspaceCharacter:
1068         case NSUpArrowFunctionKey:
1069         case NSDownArrowFunctionKey:
1070         case NSRightArrowFunctionKey:
1071         case NSLeftArrowFunctionKey:
1072         case NSEnterCharacter:
1073         case NSCarriageReturnCharacter:
1074             return NO;
1075     }
1076
1077     val.i_int |= CocoaKeyToVLC( key );
1078
1079     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1080     {
1081         if( p_hotkeys[i].i_key == val.i_int )
1082         {
1083             var_Set( p_intf->p_libvlc, "key-pressed", val );
1084             return YES;
1085         }
1086     }
1087
1088     return NO;
1089 }
1090
1091 - (id)getControls
1092 {
1093     if( o_controls )
1094         return o_controls;
1095
1096     return nil;
1097 }
1098
1099 - (id)getSimplePreferences
1100 {
1101     if( !o_sprefs )
1102         return nil;
1103
1104     if( !nib_prefs_loaded )
1105         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1106
1107     return o_sprefs;
1108 }
1109
1110 - (id)getPreferences
1111 {
1112     if( !o_prefs )
1113         return nil;
1114
1115     if( !nib_prefs_loaded )
1116         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1117
1118     return o_prefs;
1119 }
1120
1121 - (id)getPlaylist
1122 {
1123     if( o_playlist )
1124         return o_playlist;
1125
1126     return nil;
1127 }
1128
1129 - (id)getInfo
1130 {
1131     if( o_info )
1132         return o_info;
1133
1134     return nil;
1135 }
1136
1137 - (id)getWizard
1138 {
1139     if( o_wizard )
1140         return o_wizard;
1141
1142     return nil;
1143 }
1144
1145 - (id)getBookmarks
1146 {
1147     if( o_bookmarks )
1148         return o_bookmarks;
1149
1150     return nil;
1151 }
1152
1153 - (id)getEmbeddedList
1154 {
1155     if( o_embedded_list )
1156         return o_embedded_list;
1157
1158     return nil;
1159 }
1160
1161 - (id)getInteractionList
1162 {
1163     if( o_interaction_list )
1164         return o_interaction_list;
1165
1166     return nil;
1167 }
1168
1169 - (id)getMainIntfPgbar
1170 {
1171     if( o_main_pgbar )
1172         return o_main_pgbar;
1173
1174     return nil;
1175 }
1176
1177 - (id)getControllerWindow
1178 {
1179     if( o_window )
1180         return o_window;
1181     return nil;
1182 }
1183
1184 - (id)getVoutMenu
1185 {
1186     return o_vout_menu;
1187 }
1188
1189 - (id)getEyeTVController
1190 {
1191     if( o_eyetv )
1192         return o_eyetv;
1193
1194     return nil;
1195 }
1196
1197 - (void)manage
1198 {
1199     playlist_t * p_playlist;
1200     input_thread_t * p_input = NULL;
1201
1202     /* new thread requires a new pool */
1203     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
1204
1205     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1206
1207     p_playlist = pl_Yield( p_intf );
1208
1209     var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1210     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1211     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1212     var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
1213     var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1214
1215     pl_Release( p_intf );
1216
1217     vlc_object_lock( p_intf );
1218     while( vlc_object_alive( p_intf ) )
1219     {
1220         vlc_mutex_lock( &p_intf->change_lock );
1221
1222         if( !p_input )
1223         {
1224             p_input = playlist_CurrentInput( p_playlist );
1225
1226             /* Refresh the interface */
1227             if( p_input )
1228             {
1229                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1230                 p_intf->p_sys->b_input_update = true;
1231             }
1232         }
1233         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1234         {
1235             /* input stopped */
1236             p_intf->p_sys->b_intf_update = true;
1237             p_intf->p_sys->i_play_status = END_S;
1238             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1239             vlc_object_release( p_input );
1240             p_input = NULL;
1241         }
1242
1243         /* Manage volume status */
1244         [self manageVolumeSlider];
1245
1246         vlc_mutex_unlock( &p_intf->change_lock );
1247
1248         vlc_object_timedwait( p_intf, 100000 + mdate());
1249     }
1250     vlc_object_unlock( p_intf );
1251     [o_pool release];
1252
1253     if( p_input ) vlc_object_release( p_input );
1254
1255     var_DelCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1256     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1257     var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1258     var_DelCallback( p_playlist, "item-append", PlaylistChanged, self );
1259     var_DelCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1260
1261     pthread_testcancel(); /* If we were cancelled stop here */
1262
1263     msg_Dbg( p_intf, "Killing the Mac OS X module" );
1264
1265     /* We are dead, terminate */
1266     [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1267 }
1268
1269 - (void)manageIntf:(NSTimer *)o_timer
1270 {
1271     vlc_value_t val;
1272     playlist_t * p_playlist;
1273     input_thread_t * p_input;
1274
1275     if( p_intf->p_sys->b_input_update )
1276     {
1277         /* Called when new input is opened */
1278         p_intf->p_sys->b_current_title_update = true;
1279         p_intf->p_sys->b_intf_update = true;
1280         p_intf->p_sys->b_input_update = false;
1281         [self setupMenus]; /* Make sure input menu is up to date */
1282     }
1283     if( p_intf->p_sys->b_intf_update )
1284     {
1285         bool b_input = false;
1286         bool b_plmul = false;
1287         bool b_control = false;
1288         bool b_seekable = false;
1289         bool b_chapters = false;
1290
1291         playlist_t * p_playlist = pl_Yield( p_intf );
1292     /* TODO: fix i_size use */
1293         b_plmul = p_playlist->items.i_size > 1;
1294
1295         p_input = playlist_CurrentInput( p_playlist );
1296         bool b_buffering = NO;
1297     
1298         if( ( b_input = ( p_input != NULL ) ) )
1299         {
1300             /* seekable streams */
1301             int state = input_GetState( p_input );
1302             if ( state == INIT_S ||
1303                  state == OPENING_S ||
1304                  state == BUFFERING_S )
1305             {
1306                 b_buffering = YES;
1307             }
1308                  
1309             /* seekable streams */
1310             b_seekable = var_GetBool( p_input, "seekable" );
1311
1312             /* check whether slow/fast motion is possible */
1313             b_control = p_input->b_can_pace_control;
1314
1315             /* chapters & titles */
1316             //b_chapters = p_input->stream.i_area_nb > 1;
1317             vlc_object_release( p_input );
1318         }
1319         pl_Release( p_intf );
1320
1321         if( b_buffering )
1322         {
1323             [o_main_pgbar startAnimation:self];
1324             [o_main_pgbar setIndeterminate:YES];
1325             [o_main_pgbar setHidden:NO];
1326         }
1327         else
1328         {
1329             [o_main_pgbar stopAnimation:self];
1330             [o_main_pgbar setHidden:YES];
1331         }
1332
1333         [o_btn_stop setEnabled: b_input];
1334         [o_btn_ff setEnabled: b_seekable];
1335         [o_btn_rewind setEnabled: b_seekable];
1336         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1337         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1338
1339         [o_timeslider setFloatValue: 0.0];
1340         [o_timeslider setEnabled: b_seekable];
1341         [o_timefield setStringValue: @"00:00"];
1342         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1343         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1344
1345         [o_embedded_window setSeekable: b_seekable];
1346
1347         p_intf->p_sys->b_current_title_update = true;
1348         
1349         p_intf->p_sys->b_intf_update = false;
1350     }
1351
1352     if( p_intf->p_sys->b_playmode_update )
1353     {
1354         [o_playlist playModeUpdated];
1355         p_intf->p_sys->b_playmode_update = false;
1356     }
1357     if( p_intf->p_sys->b_playlist_update )
1358     {
1359         [o_playlist playlistUpdated];
1360         p_intf->p_sys->b_playlist_update = false;
1361     }
1362
1363     if( p_intf->p_sys->b_fullscreen_update )
1364     {
1365         p_intf->p_sys->b_fullscreen_update = false;
1366     }
1367
1368     if( p_intf->p_sys->b_intf_show )
1369     {
1370         [o_window makeKeyAndOrderFront: self];
1371
1372         p_intf->p_sys->b_intf_show = false;
1373     }
1374
1375     p_input = pl_CurrentInput( p_intf );
1376     if( p_input && vlc_object_alive (p_input) )
1377     {
1378         vlc_value_t val;
1379
1380         if( p_intf->p_sys->b_current_title_update )
1381         {
1382             NSString *aString;
1383             input_item_t * p_item = input_GetItem( p_input );
1384             char * name = input_item_GetNowPlaying( p_item );
1385
1386             if( !name )
1387                 name = input_item_GetName( p_item );
1388
1389             aString = [NSString stringWithUTF8String:name];
1390
1391             free(name);
1392
1393             [self setScrollField: aString stopAfter:-1];
1394             [[[self getControls] getFSPanel] setStreamTitle: aString];
1395
1396             [[o_controls getVoutView] updateTitle];
1397  
1398             [o_playlist updateRowSelection];
1399             p_intf->p_sys->b_current_title_update = FALSE;
1400         }
1401
1402         if( [o_timeslider isEnabled] )
1403         {
1404             /* Update the slider */
1405             vlc_value_t time;
1406             NSString * o_time;
1407             vlc_value_t pos;
1408             char psz_time[MSTRTIME_MAX_SIZE];
1409             float f_updated;
1410
1411             var_Get( p_input, "position", &pos );
1412             f_updated = 10000. * pos.f_float;
1413             [o_timeslider setFloatValue: f_updated];
1414
1415             var_Get( p_input, "time", &time );
1416
1417             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1418
1419             [o_timefield setStringValue: o_time];
1420             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1421             [o_embedded_window setTime: o_time position: f_updated];
1422         }
1423
1424         /* Manage Playing status */
1425         var_Get( p_input, "state", &val );
1426         if( p_intf->p_sys->i_play_status != val.i_int )
1427         {
1428             p_intf->p_sys->i_play_status = val.i_int;
1429             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1430             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1431         }
1432         vlc_object_release( p_input );
1433     }
1434     else if( p_input )
1435     {
1436         vlc_object_release( p_input );
1437     }
1438     else
1439     {
1440         p_intf->p_sys->i_play_status = END_S;
1441         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1442         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1443         [self setSubmenusEnabled: FALSE];
1444     }
1445
1446     if( p_intf->p_sys->b_volume_update )
1447     {
1448         NSString *o_text;
1449         int i_volume_step = 0;
1450         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1451         if( i_lastShownVolume != -1 )
1452         [self setScrollField:o_text stopAfter:1000000];
1453         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1454         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1455         [o_volumeslider setEnabled: TRUE];
1456         [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1457         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1458         p_intf->p_sys->b_volume_update = FALSE;
1459     }
1460
1461 end:
1462     [self updateMessageArray];
1463
1464     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1465         [self resetScrollField];
1466
1467     [interfaceTimer autorelease];
1468
1469     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1470         target: self selector: @selector(manageIntf:)
1471         userInfo: nil repeats: FALSE] retain];
1472 }
1473
1474 - (void)setupMenus
1475 {
1476     playlist_t * p_playlist = pl_Yield( p_intf );
1477     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1478     if( p_input != NULL )
1479     {
1480         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1481             var: "program" selector: @selector(toggleVar:)];
1482
1483         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1484             var: "title" selector: @selector(toggleVar:)];
1485
1486         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1487             var: "chapter" selector: @selector(toggleVar:)];
1488
1489         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1490             var: "audio-es" selector: @selector(toggleVar:)];
1491
1492         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1493             var: "video-es" selector: @selector(toggleVar:)];
1494
1495         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1496             var: "spu-es" selector: @selector(toggleVar:)];
1497
1498         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1499                                                     FIND_ANYWHERE );
1500         if( p_aout != NULL )
1501         {
1502             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1503                 var: "audio-channels" selector: @selector(toggleVar:)];
1504
1505             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1506                 var: "audio-device" selector: @selector(toggleVar:)];
1507
1508             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1509                 var: "visual" selector: @selector(toggleVar:)];
1510             vlc_object_release( (vlc_object_t *)p_aout );
1511         }
1512
1513         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1514                                                             FIND_ANYWHERE );
1515
1516         if( p_vout != NULL )
1517         {
1518             vlc_object_t * p_dec_obj;
1519
1520             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1521                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1522
1523             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1524                 var: "crop" selector: @selector(toggleVar:)];
1525
1526             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1527                 var: "video-device" selector: @selector(toggleVar:)];
1528
1529             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1530                 var: "deinterlace" selector: @selector(toggleVar:)];
1531
1532             p_dec_obj = (vlc_object_t *)vlc_object_find(
1533                                                  (vlc_object_t *)p_vout,
1534                                                  VLC_OBJECT_DECODER,
1535                                                  FIND_PARENT );
1536             if( p_dec_obj != NULL )
1537             {
1538                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1539                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1540                     @selector(toggleVar:)];
1541
1542                 vlc_object_release(p_dec_obj);
1543             }
1544             vlc_object_release( (vlc_object_t *)p_vout );
1545         }
1546         vlc_object_release( p_input );
1547     }
1548     pl_Release( p_intf );
1549 }
1550
1551 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1552 {
1553     int x,y = 0;
1554     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1555                                               FIND_ANYWHERE );
1556  
1557     if(! p_vout )
1558         return;
1559  
1560     /* clean the menu before adding new entries */
1561     if( [o_mi_screen hasSubmenu] )
1562     {
1563         y = [[o_mi_screen submenu] numberOfItems] - 1;
1564         msg_Dbg( VLCIntf, "%i items in submenu", y );
1565         while( x != y )
1566         {
1567             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1568             [[o_mi_screen submenu] removeItemAtIndex: x];
1569             x++;
1570         }
1571     }
1572
1573     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1574                              var: "video-device" selector: @selector(toggleVar:)];
1575     vlc_object_release( (vlc_object_t *)p_vout );
1576 }
1577
1578 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1579 {
1580     if( timeout != -1 )
1581         i_end_scroll = mdate() + timeout;
1582     else
1583         i_end_scroll = -1;
1584     [o_scrollfield setStringValue: o_string];
1585 }
1586
1587 - (void)resetScrollField
1588 {
1589     playlist_t * p_playlist = pl_Yield( p_intf );
1590     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1591
1592     i_end_scroll = -1;
1593     if( p_input && vlc_object_alive (p_input) )
1594     {
1595         NSString *o_temp;
1596         if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1597             o_temp = [NSString stringWithUTF8String: 
1598                 input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1599         else
1600             o_temp = [NSString stringWithUTF8String:
1601                 p_playlist->status.p_item->p_input->psz_name];
1602         [self setScrollField: o_temp stopAfter:-1];
1603         [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1604         vlc_object_release( p_input );
1605         pl_Release( p_intf );
1606         return;
1607     }
1608     pl_Release( p_intf );
1609     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1610 }
1611
1612 - (void)updateMessageArray
1613 {
1614     int i_start, i_stop;
1615
1616     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1617     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1618     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1619
1620     if( p_intf->p_sys->p_sub->i_start != i_stop )
1621     {
1622         NSColor *o_white = [NSColor whiteColor];
1623         NSColor *o_red = [NSColor redColor];
1624         NSColor *o_yellow = [NSColor yellowColor];
1625         NSColor *o_gray = [NSColor grayColor];
1626
1627         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1628         static const char * ppsz_type[4] = { ": ", " error: ",
1629                                              " warning: ", " debug: " };
1630
1631         for( i_start = p_intf->p_sys->p_sub->i_start;
1632              i_start != i_stop;
1633              i_start = (i_start+1) % VLC_MSG_QSIZE )
1634         {
1635             NSString *o_msg;
1636             NSDictionary *o_attr;
1637             NSAttributedString *o_msg_color;
1638
1639             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1640
1641             [o_msg_lock lock];
1642
1643             if( [o_msg_arr count] + 2 > 400 )
1644             {
1645                 unsigned rid[] = { 0, 1 };
1646                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1647                            numIndices: sizeof(rid)/sizeof(rid[0])];
1648             }
1649
1650             o_attr = [NSDictionary dictionaryWithObject: o_gray
1651                 forKey: NSForegroundColorAttributeName];
1652             o_msg = [NSString stringWithFormat: @"%s%s",
1653                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1654                 ppsz_type[i_type]];
1655             o_msg_color = [[NSAttributedString alloc]
1656                 initWithString: o_msg attributes: o_attr];
1657             [o_msg_arr addObject: [o_msg_color autorelease]];
1658
1659             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1660                 forKey: NSForegroundColorAttributeName];
1661             o_msg = [NSString stringWithFormat: @"%s\n",
1662                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1663             o_msg_color = [[NSAttributedString alloc]
1664                 initWithString: o_msg attributes: o_attr];
1665             [o_msg_arr addObject: [o_msg_color autorelease]];
1666
1667             [o_msg_lock unlock];
1668         }
1669
1670         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1671         p_intf->p_sys->p_sub->i_start = i_start;
1672         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1673     }
1674 }
1675
1676 - (void)playStatusUpdated:(int)i_status
1677 {
1678     if( i_status == PLAYING_S )
1679     {
1680         [[[self getControls] getFSPanel] setPause];
1681         [o_btn_play setImage: o_img_pause];
1682         [o_btn_play setAlternateImage: o_img_pause_pressed];
1683         [o_btn_play setToolTip: _NS("Pause")];
1684         [o_mi_play setTitle: _NS("Pause")];
1685         [o_dmi_play setTitle: _NS("Pause")];
1686         [o_vmi_play setTitle: _NS("Pause")];
1687     }
1688     else
1689     {
1690         [[[self getControls] getFSPanel] setPlay];
1691         [o_btn_play setImage: o_img_play];
1692         [o_btn_play setAlternateImage: o_img_play_pressed];
1693         [o_btn_play setToolTip: _NS("Play")];
1694         [o_mi_play setTitle: _NS("Play")];
1695         [o_dmi_play setTitle: _NS("Play")];
1696         [o_vmi_play setTitle: _NS("Play")];
1697     }
1698 }
1699
1700 - (void)setSubmenusEnabled:(BOOL)b_enabled
1701 {
1702     [o_mi_program setEnabled: b_enabled];
1703     [o_mi_title setEnabled: b_enabled];
1704     [o_mi_chapter setEnabled: b_enabled];
1705     [o_mi_audiotrack setEnabled: b_enabled];
1706     [o_mi_visual setEnabled: b_enabled];
1707     [o_mi_videotrack setEnabled: b_enabled];
1708     [o_mi_subtitle setEnabled: b_enabled];
1709     [o_mi_channels setEnabled: b_enabled];
1710     [o_mi_deinterlace setEnabled: b_enabled];
1711     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1712     [o_mi_device setEnabled: b_enabled];
1713     [o_mi_screen setEnabled: b_enabled];
1714     [o_mi_aspect_ratio setEnabled: b_enabled];
1715     [o_mi_crop setEnabled: b_enabled];
1716 }
1717
1718 - (void)manageVolumeSlider
1719 {
1720     audio_volume_t i_volume;
1721     aout_VolumeGet( p_intf, &i_volume );
1722
1723     if( i_volume != i_lastShownVolume )
1724     {
1725         i_lastShownVolume = i_volume;
1726         p_intf->p_sys->b_volume_update = TRUE;
1727     }
1728 }
1729
1730 - (IBAction)timesliderUpdate:(id)sender
1731 {
1732     float f_updated;
1733     playlist_t * p_playlist;
1734     input_thread_t * p_input;
1735
1736     switch( [[NSApp currentEvent] type] )
1737     {
1738         case NSLeftMouseUp:
1739         case NSLeftMouseDown:
1740         case NSLeftMouseDragged:
1741             f_updated = [sender floatValue];
1742             break;
1743
1744         default:
1745             return;
1746     }
1747     p_playlist = pl_Yield( p_intf );
1748     p_input = playlist_CurrentInput( p_playlist );
1749     if( p_input != NULL )
1750     {
1751         vlc_value_t time;
1752         vlc_value_t pos;
1753         NSString * o_time;
1754         char psz_time[MSTRTIME_MAX_SIZE];
1755
1756         pos.f_float = f_updated / 10000.;
1757         var_Set( p_input, "position", pos );
1758         [o_timeslider setFloatValue: f_updated];
1759
1760         var_Get( p_input, "time", &time );
1761
1762         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1763         [o_timefield setStringValue: o_time];
1764         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1765         [o_embedded_window setTime: o_time position: f_updated];
1766         vlc_object_release( p_input );
1767     }
1768     pl_Release( p_intf );
1769 }
1770
1771 - (void)applicationWillTerminate:(NSNotification *)notification
1772 {
1773     playlist_t * p_playlist;
1774     vout_thread_t * p_vout;
1775     int returnedValue = 0;
1776  
1777     msg_Dbg( p_intf, "Terminating" );
1778
1779     /* Make sure the manage_thread won't call -terminate: again */
1780     pthread_cancel( manage_thread );
1781
1782     /* Make sure the intf object is getting killed */
1783     vlc_object_kill( p_intf );
1784
1785     /* Make sure our manage_thread ends */
1786     pthread_join( manage_thread, NULL );
1787
1788     /* Make sure the interfaceTimer is destroyed */
1789     [interfaceTimer invalidate];
1790     [interfaceTimer release];
1791     interfaceTimer = nil;
1792
1793     /* make sure that the current volume is saved */
1794     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
1795     returnedValue = config_SaveConfigFile( p_intf->p_libvlc, "main" );
1796     if( returnedValue != 0 )
1797         msg_Err( p_intf,
1798                  "error while saving volume in osx's terminate method (%i)",
1799                  returnedValue );
1800
1801     /* save the prefs if they were changed in the extended panel */
1802     if(o_extended && [o_extended getConfigChanged])
1803     {
1804         [o_extended savePrefs];
1805     }
1806  
1807     p_intf->b_interaction = false;
1808     var_DelCallback( p_intf, "interaction", InteractCallback, self );
1809
1810     /* remove global observer watching for vout device changes correctly */
1811     [[NSNotificationCenter defaultCenter] removeObserver: self];
1812
1813     /* release some other objects here, because it isn't sure whether dealloc
1814      * will be called later on */
1815
1816     if( nib_about_loaded )
1817         [o_about release];
1818
1819     if( nib_prefs_loaded )
1820     {
1821         [o_sprefs release];
1822         [o_prefs release];
1823     }
1824
1825     if( nib_open_loaded )
1826         [o_open release];
1827
1828     if( nib_extended_loaded )
1829     {
1830         [o_extended release];
1831     }
1832
1833     if( nib_bookmarks_loaded )
1834         [o_bookmarks release];
1835
1836     if( o_info )
1837     {
1838         [o_info stopTimers];
1839         [o_info release];
1840     }
1841
1842     if( nib_wizard_loaded )
1843         [o_wizard release];
1844  
1845     [o_embedded_list release];
1846     [o_interaction_list release];
1847     [o_eyetv release];
1848
1849     [o_img_pause_pressed release];
1850     [o_img_play_pressed release];
1851     [o_img_pause release];
1852     [o_img_play release];
1853
1854     [o_msg_arr removeAllObjects];
1855     [o_msg_arr release];
1856
1857     [o_msg_lock release];
1858
1859     /* write cached user defaults to disk */
1860     [[NSUserDefaults standardUserDefaults] synchronize];
1861
1862     /* Kill the playlist, so that it doesn't accept new request
1863      * such as the play request from vlc.c (we are a blocking interface). */
1864     p_playlist = pl_Yield( p_intf );
1865     vlc_object_kill( p_playlist );
1866     pl_Release( p_intf );
1867
1868     vlc_object_kill( p_intf->p_libvlc );
1869
1870     /* Go back to Run() and make libvlc exit properly */
1871     if( jmpbuffer )
1872         longjmp( jmpbuffer, 1 );
1873     /* not reached */
1874 }
1875
1876
1877 - (IBAction)clearRecentItems:(id)sender
1878 {
1879     [[NSDocumentController sharedDocumentController]
1880                           clearRecentDocuments: nil];
1881 }
1882
1883 - (void)openRecentItem:(id)sender
1884 {
1885     [self application: nil openFile: [sender title]];
1886 }
1887
1888 - (IBAction)intfOpenFile:(id)sender
1889 {
1890     if( !nib_open_loaded )
1891     {
1892         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1893         [o_open awakeFromNib];
1894         [o_open openFile];
1895     } else {
1896         [o_open openFile];
1897     }
1898 }
1899
1900 - (IBAction)intfOpenFileGeneric:(id)sender
1901 {
1902     if( !nib_open_loaded )
1903     {
1904         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1905         [o_open awakeFromNib];
1906         [o_open openFileGeneric];
1907     } else {
1908         [o_open openFileGeneric];
1909     }
1910 }
1911
1912 - (IBAction)intfOpenDisc:(id)sender
1913 {
1914     if( !nib_open_loaded )
1915     {
1916         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1917         [o_open awakeFromNib];
1918         [o_open openDisc];
1919     } else {
1920         [o_open openDisc];
1921     }
1922 }
1923
1924 - (IBAction)intfOpenNet:(id)sender
1925 {
1926     if( !nib_open_loaded )
1927     {
1928         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1929         [o_open awakeFromNib];
1930         [o_open openNet];
1931     } else {
1932         [o_open openNet];
1933     }
1934 }
1935
1936 - (IBAction)intfOpenCapture:(id)sender
1937 {
1938     if( !nib_open_loaded )
1939     {
1940         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1941         [o_open awakeFromNib];
1942         [o_open openCapture];
1943     } else {
1944         [o_open openCapture];
1945     }
1946 }
1947
1948 - (IBAction)showWizard:(id)sender
1949 {
1950     if( !nib_wizard_loaded )
1951     {
1952         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1953         [o_wizard initStrings];
1954         [o_wizard resetWizard];
1955         [o_wizard showWizard];
1956     } else {
1957         [o_wizard resetWizard];
1958         [o_wizard showWizard];
1959     }
1960 }
1961
1962 - (IBAction)showExtended:(id)sender
1963 {
1964     if( o_extended == nil )
1965         o_extended = [[VLCExtended alloc] init];
1966
1967     if( !nib_extended_loaded )
1968         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
1969
1970     [o_extended showPanel];
1971 }
1972
1973 - (IBAction)showBookmarks:(id)sender
1974 {
1975     /* we need the wizard-nib for the bookmarks's extract functionality */
1976     if( !nib_wizard_loaded )
1977     {
1978         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1979         [o_wizard initStrings];
1980     }
1981  
1982     if( !nib_bookmarks_loaded )
1983         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
1984
1985     [o_bookmarks showBookmarks];
1986 }
1987
1988 - (IBAction)viewAbout:(id)sender
1989 {
1990     if( !nib_about_loaded )
1991         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1992
1993     [o_about showAbout];
1994 }
1995
1996 - (IBAction)showLicense:(id)sender
1997 {
1998     if( !nib_about_loaded )
1999         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2000
2001     [o_about showGPL: sender];
2002 }
2003     
2004 - (IBAction)viewPreferences:(id)sender
2005 {
2006     if( !nib_prefs_loaded )
2007     {
2008         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
2009         o_sprefs = [[VLCSimplePrefs alloc] init];
2010         o_prefs= [[VLCPrefs alloc] init];
2011     }
2012
2013     [o_sprefs showSimplePrefs];
2014 }
2015
2016 - (IBAction)checkForUpdate:(id)sender
2017 {
2018 #ifdef UPDATE_CHECK
2019     if( !nib_update_loaded )
2020         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
2021     [o_update showUpdateWindow];
2022 #else
2023     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2024     intf_UserFatal( VLCIntf, false, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2025 #endif
2026 }
2027
2028 - (IBAction)viewHelp:(id)sender
2029 {
2030     if( !nib_about_loaded )
2031     {
2032         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2033         [o_about showHelp];
2034     }
2035     else
2036         [o_about showHelp];
2037 }
2038
2039 - (IBAction)openReadMe:(id)sender
2040 {
2041     NSString * o_path = [[NSBundle mainBundle]
2042         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2043
2044     [[NSWorkspace sharedWorkspace] openFile: o_path
2045                                    withApplication: @"TextEdit"];
2046 }
2047
2048 - (IBAction)openDocumentation:(id)sender
2049 {
2050     NSURL * o_url = [NSURL URLWithString:
2051         @"http://www.videolan.org/doc/"];
2052
2053     [[NSWorkspace sharedWorkspace] openURL: o_url];
2054 }
2055
2056 - (IBAction)openWebsite:(id)sender
2057 {
2058     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2059
2060     [[NSWorkspace sharedWorkspace] openURL: o_url];
2061 }
2062
2063 - (IBAction)openForum:(id)sender
2064 {
2065     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2066
2067     [[NSWorkspace sharedWorkspace] openURL: o_url];
2068 }
2069
2070 - (IBAction)openDonate:(id)sender
2071 {
2072     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2073
2074     [[NSWorkspace sharedWorkspace] openURL: o_url];
2075 }
2076
2077 #pragma mark Crash Log
2078 - (void)mailCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2079 {
2080     static char mail[] =
2081         "From: vlcuser <vlcuser@videolan.org>\n"
2082         "To: VideoLAN Crash Report <apple-bugreport@videolan.org>\n"
2083         "Subject: %@\n"
2084         "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\n"
2085         "Content-Transfer-Encoding: 7bit\n"
2086         "\n"
2087         "%@\n\n"
2088         "User Comment:\n%@\n--------------\n"
2089         "\n"
2090         "Crash log:\n%@\n--------------\n"
2091         "\n"
2092         "\n";
2093     NSString * mailPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"vlc_crash_mail.eml"];
2094     NSString * mailContent = [NSString stringWithFormat:[NSString stringWithUTF8String:mail],
2095         _NS("Crash Report (Type Command-shift-D and hit send)"),
2096         _NS("Type Command-shift-D (or in Menu \"Message\">\"Send Again\") and hit the \"Send Mail\" button."),
2097         userComment, crashLog];
2098     BOOL ret = [mailContent writeToFile:mailPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
2099     if( !ret )
2100     {
2101         NSRunAlertPanel(_NS("Error when generating crash report mail."), _NS("Can't prepare crash log mail"), _NS("OK"), nil, nil, nil );
2102         return;
2103     }
2104
2105     [[NSWorkspace sharedWorkspace] openFile:mailPath];
2106 }
2107
2108
2109 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2110 {
2111     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2112     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2113     NSString *fname;
2114     NSString * latestLog = nil;
2115     NSInteger year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2116     NSInteger month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2117     NSInteger day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2118     NSInteger hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2119
2120     while (fname = [direnum nextObject])
2121     {
2122         [direnum skipDescendents];
2123         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2124         {
2125             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2126             if( [compo count] < 3 ) continue;
2127             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2128             if( [compo count] < 4 ) continue;
2129
2130             // Dooh. ugly.
2131             if( year < [[compo objectAtIndex:0] intValue] ||
2132                 (year ==[[compo objectAtIndex:0] intValue] && 
2133                  (month < [[compo objectAtIndex:1] intValue] ||
2134                   (month ==[[compo objectAtIndex:1] intValue] &&
2135                    (day   < [[compo objectAtIndex:2] intValue] ||
2136                     (day   ==[[compo objectAtIndex:2] intValue] &&
2137                       hours < [[compo objectAtIndex:3] intValue] ))))))
2138             {
2139                 year  = [[compo objectAtIndex:0] intValue];
2140                 month = [[compo objectAtIndex:1] intValue];
2141                 day   = [[compo objectAtIndex:2] intValue];
2142                 hours = [[compo objectAtIndex:3] intValue];
2143                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2144             }
2145         }
2146     }
2147
2148     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2149         return nil;
2150
2151     if( !previouslySeen )
2152     {
2153         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2154         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2155         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2156         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2157     }
2158     return latestLog;
2159 }
2160
2161 - (NSString *)latestCrashLogPath
2162 {
2163     return [self latestCrashLogPathPreviouslySeen:YES];
2164 }
2165
2166 - (void)lookForCrashLog
2167 {
2168     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2169
2170     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2171     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2172     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2173     if( latestLog && !areCrashLogsTooOld )
2174         [self performSelectorOnMainThread:@selector(notifyCrashLogToUser:) withObject:latestLog waitUntilDone:NO];
2175
2176     [pool release];
2177 }
2178
2179 - (void)notifyCrashLogToUser:(NSString *)crashLogPath
2180 {
2181     int ret = NSRunInformationalAlertPanel(_NS("VLC has previously crashed"),
2182                 _NS("VLC has previously crashed, do you want to send an email with the crash to VLC's team?"),
2183                 _NS("Send"), _NS("Don't Send"), nil, nil);
2184     if( ret == NSAlertDefaultReturn )
2185     {
2186         [self mailCrashLog:[NSString stringWithContentsOfFile:crashLogPath] withUserComment:_NS("<Explain here what you were doing when VLC crashed, with possibly a link to the failing video>")];
2187     }
2188 }
2189
2190 - (IBAction)openCrashLog:(id)sender
2191 {
2192     NSString * latestLog = [self latestCrashLogPath];
2193     if( latestLog )
2194     {
2195         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2196     }
2197     else
2198     {
2199         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.") );
2200     }
2201 }
2202
2203 #pragma mark -
2204
2205 - (IBAction)viewErrorsAndWarnings:(id)sender
2206 {
2207     [[[self getInteractionList] getErrorPanel] showPanel];
2208 }
2209
2210 - (IBAction)showMessagesPanel:(id)sender
2211 {
2212     [o_msgs_panel makeKeyAndOrderFront: sender];
2213 }
2214
2215 - (IBAction)showInformationPanel:(id)sender
2216 {
2217     if(! nib_info_loaded )
2218         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: self];
2219     
2220     [o_info initPanel];
2221 }
2222
2223 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2224 {
2225     if( [o_notification object] == o_msgs_panel )
2226     {
2227         id o_msg;
2228         NSEnumerator * o_enum;
2229
2230         [o_messages setString: @""];
2231
2232         [o_msg_lock lock];
2233
2234         o_enum = [o_msg_arr objectEnumerator];
2235
2236         while( ( o_msg = [o_enum nextObject] ) != nil )
2237         {
2238             [o_messages insertText: o_msg];
2239         }
2240
2241         [o_msg_lock unlock];
2242     }
2243 }
2244
2245 - (IBAction)togglePlaylist:(id)sender
2246 {
2247     NSRect o_rect = [o_window frame];
2248     /*First, check if the playlist is visible*/
2249     if( o_rect.size.height <= 200 )
2250     {
2251         o_restore_rect = o_rect;
2252         b_restore_size = true;
2253         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2254         /* make large */
2255         if( o_size_with_playlist.height > 200 )
2256         {
2257             o_rect.size.height = o_size_with_playlist.height;
2258         } else {
2259             o_rect.size.height = 500;
2260         }
2261  
2262         if( o_size_with_playlist.width > [o_window minSize].width )
2263         {
2264             o_rect.size.width = o_size_with_playlist.width;
2265         } else {
2266             o_rect.size.width = 500;
2267         }
2268  
2269         o_rect.size.height = (o_size_with_playlist.height > 200) ?
2270             o_size_with_playlist.height : 500;
2271         o_rect.origin.x = [o_window frame].origin.x;
2272         o_rect.origin.y = [o_window frame].origin.y - o_rect.size.height +
2273                                                 [o_window minSize].height;
2274
2275         NSRect screenRect = [[o_window screen] visibleFrame];
2276         if( !NSContainsRect( screenRect, o_rect ) ) {
2277             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2278                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2279             if( NSMinY(o_rect) < NSMinY(screenRect) )
2280                 o_rect.origin.y = ( NSMinY(screenRect) );
2281         }
2282
2283         [o_btn_playlist setState: YES];
2284     }
2285     else
2286     {
2287         NSSize curSize = o_rect.size;
2288         /* make small */
2289         o_rect.size.height = [o_window minSize].height;
2290         o_rect.size.width = [o_window minSize].width;
2291         o_rect.origin.x = [o_window frame].origin.x;
2292         /* Calculate the position of the lower right corner after resize */
2293         o_rect.origin.y = [o_window frame].origin.y +
2294             [o_window frame].size.height - [o_window minSize].height;
2295
2296         if( b_restore_size )
2297             o_rect = o_restore_rect;
2298
2299         [o_playlist_view setAutoresizesSubviews: NO];
2300         [o_playlist_view removeFromSuperview];
2301         [o_btn_playlist setState: NO];
2302         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2303     }
2304
2305     [o_window setFrame: o_rect display:YES animate: YES];
2306 }
2307
2308 - (void)updateTogglePlaylistState
2309 {
2310     if( [o_window frame].size.height <= 200 )
2311     {
2312         [o_btn_playlist setState: NO];
2313     }
2314     else
2315     {
2316         [o_btn_playlist setState: YES];
2317     }
2318 }
2319
2320 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2321 {
2322     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2323
2324    /*Stores the size the controller one resize, to be able to restore it when
2325      toggling the playlist*/
2326     o_size_with_playlist = proposedFrameSize;
2327
2328     if( proposedFrameSize.height <= 200 )
2329     {
2330         if( b_small_window == NO )
2331         {
2332             /* if large and going to small then hide */
2333             b_small_window = YES;
2334             [o_playlist_view setAutoresizesSubviews: NO];
2335             [o_playlist_view removeFromSuperview];
2336         }
2337         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2338     }
2339     return proposedFrameSize;
2340 }
2341
2342 - (void)windowDidMove:(NSNotification *)notif
2343 {
2344     b_restore_size = false;
2345 }
2346
2347 - (void)windowDidResize:(NSNotification *)notif
2348 {
2349     if( [o_window frame].size.height > 200 && b_small_window )
2350     {
2351         /* If large and coming from small then show */
2352         [o_playlist_view setAutoresizesSubviews: YES];
2353         [o_playlist_view setFrame: NSMakeRect( 0, 0, [o_window frame].size.width, [o_window frame].size.height - [o_window minSize].height )];
2354         [o_playlist_view setNeedsDisplay:YES];
2355         [[o_window contentView] addSubview: o_playlist_view];
2356         b_small_window = NO;
2357     }
2358     [self updateTogglePlaylistState];
2359 }
2360
2361 @end
2362
2363 @implementation VLCMain (NSMenuValidation)
2364
2365 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2366 {
2367     NSString *o_title = [o_mi title];
2368     BOOL bEnabled = TRUE;
2369
2370     /* Recent Items Menu */
2371     if( [o_title isEqualToString: _NS("Clear Menu")] )
2372     {
2373         NSMenu * o_menu = [o_mi_open_recent submenu];
2374         int i_nb_items = [o_menu numberOfItems];
2375         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2376                                                        recentDocumentURLs];
2377         UInt32 i_nb_docs = [o_docs count];
2378
2379         if( i_nb_items > 1 )
2380         {
2381             while( --i_nb_items )
2382             {
2383                 [o_menu removeItemAtIndex: 0];
2384             }
2385         }
2386
2387         if( i_nb_docs > 0 )
2388         {
2389             NSURL * o_url;
2390             NSString * o_doc;
2391
2392             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2393
2394             while( TRUE )
2395             {
2396                 i_nb_docs--;
2397
2398                 o_url = [o_docs objectAtIndex: i_nb_docs];
2399
2400                 if( [o_url isFileURL] )
2401                 {
2402                     o_doc = [o_url path];
2403                 }
2404                 else
2405                 {
2406                     o_doc = [o_url absoluteString];
2407                 }
2408
2409                 [o_menu insertItemWithTitle: o_doc
2410                     action: @selector(openRecentItem:)
2411                     keyEquivalent: @"" atIndex: 0];
2412
2413                 if( i_nb_docs == 0 )
2414                 {
2415                     break;
2416                 }
2417             }
2418         }
2419         else
2420         {
2421             bEnabled = FALSE;
2422         }
2423     }
2424     return( bEnabled );
2425 }
2426
2427 @end
2428
2429 @implementation VLCMain (Internal)
2430
2431 - (void)handlePortMessage:(NSPortMessage *)o_msg
2432 {
2433     id ** val;
2434     NSData * o_data;
2435     NSValue * o_value;
2436     NSInvocation * o_inv;
2437     NSConditionLock * o_lock;
2438
2439     o_data = [[o_msg components] lastObject];
2440     o_inv = *((NSInvocation **)[o_data bytes]);
2441     [o_inv getArgument: &o_value atIndex: 2];
2442     val = (id **)[o_value pointerValue];
2443     [o_inv setArgument: val[1] atIndex: 2];
2444     o_lock = *(val[0]);
2445
2446     [o_lock lock];
2447     [o_inv invoke];
2448     [o_lock unlockWithCondition: 1];
2449 }
2450
2451 @end