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