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