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