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