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