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