]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: Do NOT call config_SaveConfigFile() if you don't intend to save ALL the optio...
[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
663     /* save the prefs if they were changed in the extended panel */
664     if(o_extended && [o_extended getConfigChanged])
665     {
666         [o_extended savePrefs];
667     }
668  
669     p_intf->b_interaction = false;
670     var_DelCallback( p_intf, "interaction", InteractCallback, self );
671
672     /* remove global observer watching for vout device changes correctly */
673     [[NSNotificationCenter defaultCenter] removeObserver: self];
674
675     /* release some other objects here, because it isn't sure whether dealloc
676      * will be called later on */
677
678     if( nib_about_loaded )
679         [o_about release];
680
681     if( nib_prefs_loaded )
682     {
683         [o_sprefs release];
684         [o_prefs release];
685     }
686
687     if( nib_open_loaded )
688         [o_open release];
689
690     if( nib_extended_loaded )
691     {
692         [o_extended release];
693     }
694
695     if( nib_bookmarks_loaded )
696         [o_bookmarks release];
697
698     if( o_info )
699     {
700         [o_info stopTimers];
701         [o_info release];
702     }
703
704     if( nib_wizard_loaded )
705         [o_wizard release];
706
707     [crashLogURLConnection cancel];
708     [crashLogURLConnection release];
709  
710     [o_embedded_list release];
711     [o_interaction_list release];
712     [o_eyetv release];
713
714     [o_img_pause_pressed release];
715     [o_img_play_pressed release];
716     [o_img_pause release];
717     [o_img_play release];
718
719     [o_msg_arr removeAllObjects];
720     [o_msg_arr release];
721
722     [o_msg_lock release];
723
724     /* write cached user defaults to disk */
725     [[NSUserDefaults standardUserDefaults] synchronize];
726
727     /* Kill the playlist, so that it doesn't accept new request
728      * such as the play request from vlc.c (we are a blocking interface). */
729     p_playlist = pl_Yield( p_intf );
730     vlc_object_kill( p_playlist );
731     pl_Release( p_intf );
732
733     vlc_object_kill( p_intf->p_libvlc );
734
735     [self setIntf:nil];
736
737     /* Go back to Run() and make libvlc exit properly */
738     if( jmpbuffer )
739         longjmp( jmpbuffer, 1 );
740     /* not reached */
741 }
742
743 #pragma mark -
744 #pragma mark Toolbar delegate
745
746 /* Our item identifiers */
747 static NSString * VLCToolbarMediaControl     = @"VLCToolbarMediaControl";
748
749 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
750 {
751     return [NSArray arrayWithObjects:
752 //                        NSToolbarCustomizeToolbarItemIdentifier,
753 //                        NSToolbarFlexibleSpaceItemIdentifier,
754 //                        NSToolbarSpaceItemIdentifier,
755 //                        NSToolbarSeparatorItemIdentifier,
756                         VLCToolbarMediaControl,
757                         nil ];
758 }
759
760 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
761 {
762     return [NSArray arrayWithObjects:
763                         VLCToolbarMediaControl,
764                         nil ];
765 }
766
767 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
768 {
769     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
770
771  
772     if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
773     {
774         [toolbarItem setLabel:@"Media Controls"];
775         [toolbarItem setPaletteLabel:@"Media Controls"];
776
777         NSSize size = toolbarMediaControl.frame.size;
778         [toolbarItem setView:toolbarMediaControl];
779         [toolbarItem setMinSize:size];
780         size.width += 1000.;
781         [toolbarItem setMaxSize:size];
782
783         // Hack: For some reason we need to make sure
784         // that the those element are on top
785         // Add them again will put them frontmost
786         [toolbarMediaControl addSubview:o_scrollfield];
787         [toolbarMediaControl addSubview:o_timeslider];
788         [toolbarMediaControl addSubview:o_timefield];
789         [toolbarMediaControl addSubview:o_main_pgbar];
790
791         /* TODO: setup a menu */
792     }
793     else
794     {
795         /* itemIdentifier referred to a toolbar item that is not
796          * provided or supported by us or Cocoa
797          * Returning nil will inform the toolbar
798          * that this kind of item is not supported */
799         toolbarItem = nil;
800     }
801     return toolbarItem;
802 }
803
804 #pragma mark -
805 #pragma mark Other notification
806
807 - (void)controlTintChanged
808 {
809     BOOL b_playing = NO;
810     
811     if( [o_btn_play alternateImage] == o_img_play_pressed )
812         b_playing = YES;
813     
814     if( [NSColor currentControlTint] == NSGraphiteControlTint )
815     {
816         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
817         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
818         
819         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
820         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
821         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
822         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
823         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
824         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
825         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
826         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
827     }
828     else
829     {
830         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
831         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
832         
833         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
834         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
835         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
836         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
837         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
838         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
839         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
840         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
841     }
842     
843     if( b_playing )
844         [o_btn_play setAlternateImage: o_img_play_pressed];
845     else
846         [o_btn_play setAlternateImage: o_img_pause_pressed];
847 }
848
849 /* Listen to the remote in exclusive mode, only when VLC is the active
850    application */
851 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
852 {
853     [o_remote startListening: self];
854 }
855 - (void)applicationDidResignActive:(NSNotification *)aNotification
856 {
857     [o_remote stopListening: self];
858 }
859
860 /* Triggered when the computer goes to sleep */
861 - (void)computerWillSleep: (NSNotification *)notification
862 {
863     /* Pause */
864     if( p_intf->p_sys->i_play_status == PLAYING_S )
865     {
866         vlc_value_t val;
867         val.i_int = config_GetInt( p_intf, "key-play-pause" );
868         var_Set( p_intf->p_libvlc, "key-pressed", val );
869     }
870 }
871
872 #pragma mark -
873 #pragma mark File opening
874
875 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
876 {
877     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
878     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
879     if( b_autoplay )
880         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
881     else
882         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
883
884     return( TRUE );
885 }
886
887 /* When user click in the Dock icon our double click in the finder */
888 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
889 {    
890     if(!hasVisibleWindows)
891         [o_window makeKeyAndOrderFront:self];
892
893     return YES;
894 }
895
896 #pragma mark -
897 #pragma mark Apple Remote Control
898
899 /* Helper method for the remote control interface in order to trigger forward/backward and volume
900    increase/decrease as long as the user holds the left/right, plus/minus button */
901 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
902 {
903     if(b_remote_button_hold)
904     {
905         switch([buttonIdentifierNumber intValue])
906         {
907             case kRemoteButtonRight_Hold:
908                   [o_controls forward: self];
909             break;
910             case kRemoteButtonLeft_Hold:
911                   [o_controls backward: self];
912             break;
913             case kRemoteButtonVolume_Plus_Hold:
914                 [o_controls volumeUp: self];
915             break;
916             case kRemoteButtonVolume_Minus_Hold:
917                 [o_controls volumeDown: self];
918             break;
919         }
920         if(b_remote_button_hold)
921         {
922             /* trigger event */
923             [self performSelector:@selector(executeHoldActionForRemoteButton:)
924                          withObject:buttonIdentifierNumber
925                          afterDelay:0.25];
926         }
927     }
928 }
929
930 /* Apple Remote callback */
931 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
932                pressedDown: (BOOL) pressedDown
933                 clickCount: (unsigned int) count
934 {
935     switch( buttonIdentifier )
936     {
937         case kRemoteButtonPlay:
938             if(count >= 2) {
939                 [o_controls toogleFullscreen:self];
940             } else {
941                 [o_controls play: self];
942             }
943             break;
944         case kRemoteButtonVolume_Plus:
945             [o_controls volumeUp: self];
946             break;
947         case kRemoteButtonVolume_Minus:
948             [o_controls volumeDown: self];
949             break;
950         case kRemoteButtonRight:
951             [o_controls next: self];
952             break;
953         case kRemoteButtonLeft:
954             [o_controls prev: self];
955             break;
956         case kRemoteButtonRight_Hold:
957         case kRemoteButtonLeft_Hold:
958         case kRemoteButtonVolume_Plus_Hold:
959         case kRemoteButtonVolume_Minus_Hold:
960             /* simulate an event as long as the user holds the button */
961             b_remote_button_hold = pressedDown;
962             if( pressedDown )
963             {
964                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
965                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
966                            withObject:buttonIdentifierNumber];
967             }
968             break;
969         case kRemoteButtonMenu:
970             [o_controls showPosition: self];
971             break;
972         default:
973             /* Add here whatever you want other buttons to do */
974             break;
975     }
976 }
977
978 #pragma mark -
979 #pragma mark String utility
980 // FIXME: this has nothing to do here
981
982 - (NSString *)localizedString:(const char *)psz
983 {
984     NSString * o_str = nil;
985
986     if( psz != NULL )
987     {
988         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
989
990         if( o_str == NULL )
991         {
992             msg_Err( VLCIntf, "could not translate: %s", psz );
993             return( @"" );
994         }
995     }
996     else
997     {
998         msg_Warn( VLCIntf, "can't translate empty strings" );
999         return( @"" );
1000     }
1001
1002     return( o_str );
1003 }
1004
1005
1006
1007 - (char *)delocalizeString:(NSString *)id
1008 {
1009     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1010                           allowLossyConversion: NO];
1011     char * psz_string;
1012
1013     if( o_data == nil )
1014     {
1015         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1016                      allowLossyConversion: YES];
1017         psz_string = malloc( [o_data length] + 1 );
1018         [o_data getBytes: psz_string];
1019         psz_string[ [o_data length] ] = '\0';
1020         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1021                  psz_string );
1022     }
1023     else
1024     {
1025         psz_string = malloc( [o_data length] + 1 );
1026         [o_data getBytes: psz_string];
1027         psz_string[ [o_data length] ] = '\0';
1028     }
1029
1030     return psz_string;
1031 }
1032
1033 /* i_width is in pixels */
1034 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1035 {
1036     NSMutableString *o_wrapped;
1037     NSString *o_out_string;
1038     NSRange glyphRange, effectiveRange, charRange;
1039     NSRect lineFragmentRect;
1040     unsigned glyphIndex, breaksInserted = 0;
1041
1042     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1043         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1044         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1045     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1046     NSTextContainer *o_container = [[NSTextContainer alloc]
1047         initWithContainerSize: NSMakeSize(i_width, 2000)];
1048
1049     [o_layout_manager addTextContainer: o_container];
1050     [o_container release];
1051     [o_storage addLayoutManager: o_layout_manager];
1052     [o_layout_manager release];
1053
1054     o_wrapped = [o_in_string mutableCopy];
1055     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1056
1057     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1058             glyphIndex += effectiveRange.length) {
1059         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1060                                             effectiveRange: &effectiveRange];
1061         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1062                                     actualGlyphRange: &effectiveRange];
1063         if([o_wrapped lineRangeForRange:
1064                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1065             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1066             breaksInserted++;
1067         }
1068     }
1069     o_out_string = [NSString stringWithString: o_wrapped];
1070     [o_wrapped release];
1071     [o_storage release];
1072
1073     return o_out_string;
1074 }
1075
1076
1077 #pragma mark -
1078 #pragma mark Key Shortcuts
1079
1080 static struct
1081 {
1082     unichar i_nskey;
1083     unsigned int i_vlckey;
1084 } nskeys_to_vlckeys[] =
1085 {
1086     { NSUpArrowFunctionKey, KEY_UP },
1087     { NSDownArrowFunctionKey, KEY_DOWN },
1088     { NSLeftArrowFunctionKey, KEY_LEFT },
1089     { NSRightArrowFunctionKey, KEY_RIGHT },
1090     { NSF1FunctionKey, KEY_F1 },
1091     { NSF2FunctionKey, KEY_F2 },
1092     { NSF3FunctionKey, KEY_F3 },
1093     { NSF4FunctionKey, KEY_F4 },
1094     { NSF5FunctionKey, KEY_F5 },
1095     { NSF6FunctionKey, KEY_F6 },
1096     { NSF7FunctionKey, KEY_F7 },
1097     { NSF8FunctionKey, KEY_F8 },
1098     { NSF9FunctionKey, KEY_F9 },
1099     { NSF10FunctionKey, KEY_F10 },
1100     { NSF11FunctionKey, KEY_F11 },
1101     { NSF12FunctionKey, KEY_F12 },
1102     { NSInsertFunctionKey, KEY_INSERT },
1103     { NSHomeFunctionKey, KEY_HOME },
1104     { NSEndFunctionKey, KEY_END },
1105     { NSPageUpFunctionKey, KEY_PAGEUP },
1106     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1107     { NSMenuFunctionKey, KEY_MENU },
1108     { NSTabCharacter, KEY_TAB },
1109     { NSCarriageReturnCharacter, KEY_ENTER },
1110     { NSEnterCharacter, KEY_ENTER },
1111     { NSBackspaceCharacter, KEY_BACKSPACE },
1112     { (unichar) ' ', KEY_SPACE },
1113     { (unichar) 0x1b, KEY_ESC },
1114     {0,0}
1115 };
1116
1117 static unichar VLCKeyToCocoa( unsigned int i_key )
1118 {
1119     unsigned int i;
1120
1121     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
1122     {
1123         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
1124         {
1125             return nskeys_to_vlckeys[i].i_nskey;
1126         }
1127     }
1128     return (unichar)(i_key & ~KEY_MODIFIER);
1129 }
1130
1131 unsigned int CocoaKeyToVLC( unichar i_key )
1132 {
1133     unsigned int i;
1134
1135     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1136     {
1137         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1138         {
1139             return nskeys_to_vlckeys[i].i_vlckey;
1140         }
1141     }
1142     return (unsigned int)i_key;
1143 }
1144
1145 static unsigned int VLCModifiersToCocoa( unsigned int i_key )
1146 {
1147     unsigned int new = 0;
1148     if( i_key & KEY_MODIFIER_COMMAND )
1149         new |= NSCommandKeyMask;
1150     if( i_key & KEY_MODIFIER_ALT )
1151         new |= NSAlternateKeyMask;
1152     if( i_key & KEY_MODIFIER_SHIFT )
1153         new |= NSShiftKeyMask;
1154     if( i_key & KEY_MODIFIER_CTRL )
1155         new |= NSControlKeyMask;
1156     return new;
1157 }
1158
1159 /*****************************************************************************
1160  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1161  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1162  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1163  *****************************************************************************/
1164 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1165 {
1166     unichar key = 0;
1167     vlc_value_t val;
1168     unsigned int i_pressed_modifiers = 0;
1169     struct hotkey *p_hotkeys;
1170     int i;
1171
1172     val.i_int = 0;
1173     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1174
1175     i_pressed_modifiers = [o_event modifierFlags];
1176
1177     if( i_pressed_modifiers & NSShiftKeyMask )
1178         val.i_int |= KEY_MODIFIER_SHIFT;
1179     if( i_pressed_modifiers & NSControlKeyMask )
1180         val.i_int |= KEY_MODIFIER_CTRL;
1181     if( i_pressed_modifiers & NSAlternateKeyMask )
1182         val.i_int |= KEY_MODIFIER_ALT;
1183     if( i_pressed_modifiers & NSCommandKeyMask )
1184         val.i_int |= KEY_MODIFIER_COMMAND;
1185
1186     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1187
1188     switch( key )
1189     {
1190         case NSDeleteCharacter:
1191         case NSDeleteFunctionKey:
1192         case NSDeleteCharFunctionKey:
1193         case NSBackspaceCharacter:
1194         case NSUpArrowFunctionKey:
1195         case NSDownArrowFunctionKey:
1196         case NSRightArrowFunctionKey:
1197         case NSLeftArrowFunctionKey:
1198         case NSEnterCharacter:
1199         case NSCarriageReturnCharacter:
1200             return NO;
1201     }
1202
1203     val.i_int |= CocoaKeyToVLC( key );
1204
1205     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1206     {
1207         if( p_hotkeys[i].i_key == val.i_int )
1208         {
1209             var_Set( p_intf->p_libvlc, "key-pressed", val );
1210             return YES;
1211         }
1212     }
1213
1214     return NO;
1215 }
1216
1217 #pragma mark -
1218 #pragma mark Other objects getters
1219 // FIXME: this is ugly and does not respect cocoa naming scheme
1220
1221 - (id)getControls
1222 {
1223     if( o_controls )
1224         return o_controls;
1225
1226     return nil;
1227 }
1228
1229 - (id)getSimplePreferences
1230 {
1231     if( !o_sprefs )
1232         return nil;
1233
1234     if( !nib_prefs_loaded )
1235         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1236
1237     return o_sprefs;
1238 }
1239
1240 - (id)getPreferences
1241 {
1242     if( !o_prefs )
1243         return nil;
1244
1245     if( !nib_prefs_loaded )
1246         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1247
1248     return o_prefs;
1249 }
1250
1251 - (id)getPlaylist
1252 {
1253     if( o_playlist )
1254         return o_playlist;
1255
1256     return nil;
1257 }
1258
1259 - (id)getInfo
1260 {
1261     if( o_info )
1262         return o_info;
1263
1264     return nil;
1265 }
1266
1267 - (id)getWizard
1268 {
1269     if( o_wizard )
1270         return o_wizard;
1271
1272     return nil;
1273 }
1274
1275 - (id)getBookmarks
1276 {
1277     if( o_bookmarks )
1278         return o_bookmarks;
1279
1280     return nil;
1281 }
1282
1283 - (id)getEmbeddedList
1284 {
1285     if( o_embedded_list )
1286         return o_embedded_list;
1287
1288     return nil;
1289 }
1290
1291 - (id)getInteractionList
1292 {
1293     if( o_interaction_list )
1294         return o_interaction_list;
1295
1296     return nil;
1297 }
1298
1299 - (id)getMainIntfPgbar
1300 {
1301     if( o_main_pgbar )
1302         return o_main_pgbar;
1303
1304     return nil;
1305 }
1306
1307 - (id)getControllerWindow
1308 {
1309     if( o_window )
1310         return o_window;
1311     return nil;
1312 }
1313
1314 - (id)getVoutMenu
1315 {
1316     return o_vout_menu;
1317 }
1318
1319 - (id)getEyeTVController
1320 {
1321     if( o_eyetv )
1322         return o_eyetv;
1323
1324     return nil;
1325 }
1326
1327 #pragma mark -
1328 #pragma mark Polling
1329
1330 /*****************************************************************************
1331  * ManageThread: An ugly thread that polls
1332  *****************************************************************************/
1333 static void * ManageThread( void *user_data )
1334 {
1335     id self = user_data;
1336
1337     [self manage];
1338
1339     return NULL;
1340 }
1341
1342 - (void)manage
1343 {
1344     playlist_t * p_playlist;
1345     input_thread_t * p_input = NULL;
1346
1347     /* new thread requires a new pool */
1348     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
1349
1350     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1351
1352     p_playlist = pl_Yield( p_intf );
1353
1354     var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1355     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1356     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1357     var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
1358     var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1359
1360     pl_Release( p_intf );
1361
1362     vlc_object_lock( p_intf );
1363
1364     while( vlc_object_alive( p_intf ) )
1365     {
1366         vlc_mutex_lock( &p_intf->change_lock );
1367
1368         if( !p_input )
1369         {
1370             p_input = playlist_CurrentInput( p_playlist );
1371
1372             /* Refresh the interface */
1373             if( p_input )
1374             {
1375                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1376                 p_intf->p_sys->b_input_update = true;
1377             }
1378         }
1379         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1380         {
1381             /* input stopped */
1382             p_intf->p_sys->b_intf_update = true;
1383             p_intf->p_sys->i_play_status = END_S;
1384             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1385             vlc_object_release( p_input );
1386             p_input = NULL;
1387         }
1388         else if( cachedInputState != input_GetState( p_input ) )
1389         {
1390             p_intf->p_sys->b_intf_update = true;
1391         }
1392
1393         /* Manage volume status */
1394         [self manageVolumeSlider];
1395
1396         vlc_mutex_unlock( &p_intf->change_lock );
1397
1398         vlc_object_timedwait( p_intf, 100000 + mdate());
1399     }
1400     vlc_object_unlock( p_intf );
1401     [o_pool release];
1402
1403     if( p_input ) vlc_object_release( p_input );
1404
1405     var_DelCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1406     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1407     var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1408     var_DelCallback( p_playlist, "item-append", PlaylistChanged, self );
1409     var_DelCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1410
1411     pthread_testcancel(); /* If we were cancelled stop here */
1412
1413     msg_Dbg( p_intf, "Killing the Mac OS X module" );
1414
1415     /* We are dead, terminate */
1416     [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1417 }
1418
1419 - (void)manageVolumeSlider
1420 {
1421     audio_volume_t i_volume;
1422     aout_VolumeGet( p_intf, &i_volume );
1423
1424     if( i_volume != i_lastShownVolume )
1425     {
1426         i_lastShownVolume = i_volume;
1427         p_intf->p_sys->b_volume_update = TRUE;
1428     }
1429 }
1430
1431 - (void)manageIntf:(NSTimer *)o_timer
1432 {
1433     vlc_value_t val;
1434     playlist_t * p_playlist;
1435     input_thread_t * p_input;
1436
1437     if( p_intf->p_sys->b_input_update )
1438     {
1439         /* Called when new input is opened */
1440         p_intf->p_sys->b_current_title_update = true;
1441         p_intf->p_sys->b_intf_update = true;
1442         p_intf->p_sys->b_input_update = false;
1443         [self setupMenus]; /* Make sure input menu is up to date */
1444     }
1445     if( p_intf->p_sys->b_intf_update )
1446     {
1447         bool b_input = false;
1448         bool b_plmul = false;
1449         bool b_control = false;
1450         bool b_seekable = false;
1451         bool b_chapters = false;
1452
1453         playlist_t * p_playlist = pl_Yield( p_intf );
1454     /* TODO: fix i_size use */
1455         b_plmul = p_playlist->items.i_size > 1;
1456
1457         p_input = playlist_CurrentInput( p_playlist );
1458         bool b_buffering = NO;
1459     
1460         if( ( b_input = ( p_input != NULL ) ) )
1461         {
1462             /* seekable streams */
1463             cachedInputState = input_GetState( p_input );
1464             if ( cachedInputState == INIT_S ||
1465                  cachedInputState == OPENING_S ||
1466                  cachedInputState == BUFFERING_S )
1467             {
1468                 b_buffering = YES;
1469             }
1470                  
1471             /* seekable streams */
1472             b_seekable = var_GetBool( p_input, "seekable" );
1473
1474             /* check whether slow/fast motion is possible */
1475             b_control = p_input->b_can_pace_control;
1476
1477             /* chapters & titles */
1478             //b_chapters = p_input->stream.i_area_nb > 1;
1479             vlc_object_release( p_input );
1480         }
1481         pl_Release( p_intf );
1482
1483         if( b_buffering )
1484         {
1485             [o_main_pgbar startAnimation:self];
1486             [o_main_pgbar setIndeterminate:YES];
1487             [o_main_pgbar setHidden:NO];
1488         }
1489         else
1490         {
1491             [o_main_pgbar stopAnimation:self];
1492             [o_main_pgbar setHidden:YES];
1493         }
1494
1495         [o_btn_stop setEnabled: b_input];
1496         [o_btn_ff setEnabled: b_seekable];
1497         [o_btn_rewind setEnabled: b_seekable];
1498         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1499         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1500
1501         [o_timeslider setFloatValue: 0.0];
1502         [o_timeslider setEnabled: b_seekable];
1503         [o_timefield setStringValue: @"00:00"];
1504         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1505         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1506
1507         [o_embedded_window setSeekable: b_seekable];
1508
1509         p_intf->p_sys->b_current_title_update = true;
1510         
1511         p_intf->p_sys->b_intf_update = false;
1512     }
1513
1514     if( p_intf->p_sys->b_playmode_update )
1515     {
1516         [o_playlist playModeUpdated];
1517         p_intf->p_sys->b_playmode_update = false;
1518     }
1519     if( p_intf->p_sys->b_playlist_update )
1520     {
1521         [o_playlist playlistUpdated];
1522         p_intf->p_sys->b_playlist_update = false;
1523     }
1524
1525     if( p_intf->p_sys->b_fullscreen_update )
1526     {
1527         p_intf->p_sys->b_fullscreen_update = false;
1528     }
1529
1530     if( p_intf->p_sys->b_intf_show )
1531     {
1532         [o_window makeKeyAndOrderFront: self];
1533
1534         p_intf->p_sys->b_intf_show = false;
1535     }
1536
1537     p_input = pl_CurrentInput( p_intf );
1538     if( p_input && vlc_object_alive (p_input) )
1539     {
1540         vlc_value_t val;
1541
1542         if( p_intf->p_sys->b_current_title_update )
1543         {
1544             NSString *aString;
1545             input_item_t * p_item = input_GetItem( p_input );
1546             char * name = input_item_GetNowPlaying( p_item );
1547
1548             if( !name )
1549                 name = input_item_GetName( p_item );
1550
1551             aString = [NSString stringWithUTF8String:name];
1552
1553             free(name);
1554
1555             [self setScrollField: aString stopAfter:-1];
1556             [[[self getControls] getFSPanel] setStreamTitle: aString];
1557
1558             [[o_controls getVoutView] updateTitle];
1559  
1560             [o_playlist updateRowSelection];
1561             p_intf->p_sys->b_current_title_update = FALSE;
1562         }
1563
1564         if( [o_timeslider isEnabled] )
1565         {
1566             /* Update the slider */
1567             vlc_value_t time;
1568             NSString * o_time;
1569             vlc_value_t pos;
1570             char psz_time[MSTRTIME_MAX_SIZE];
1571             float f_updated;
1572
1573             var_Get( p_input, "position", &pos );
1574             f_updated = 10000. * pos.f_float;
1575             [o_timeslider setFloatValue: f_updated];
1576
1577             var_Get( p_input, "time", &time );
1578
1579             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1580
1581             [o_timefield setStringValue: o_time];
1582             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1583             [o_embedded_window setTime: o_time position: f_updated];
1584         }
1585
1586         /* Manage Playing status */
1587         var_Get( p_input, "state", &val );
1588         if( p_intf->p_sys->i_play_status != val.i_int )
1589         {
1590             p_intf->p_sys->i_play_status = val.i_int;
1591             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1592             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1593         }
1594         vlc_object_release( p_input );
1595     }
1596     else if( p_input )
1597     {
1598         vlc_object_release( p_input );
1599     }
1600     else
1601     {
1602         p_intf->p_sys->i_play_status = END_S;
1603         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1604         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1605         [self setSubmenusEnabled: FALSE];
1606     }
1607
1608     if( p_intf->p_sys->b_volume_update )
1609     {
1610         NSString *o_text;
1611         int i_volume_step = 0;
1612         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1613         if( i_lastShownVolume != -1 )
1614         [self setScrollField:o_text stopAfter:1000000];
1615         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1616         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1617         [o_volumeslider setEnabled: TRUE];
1618         [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1619         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1620         p_intf->p_sys->b_volume_update = FALSE;
1621     }
1622
1623 end:
1624     [self updateMessageArray];
1625
1626     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1627         [self resetScrollField];
1628
1629     [interfaceTimer autorelease];
1630
1631     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1632         target: self selector: @selector(manageIntf:)
1633         userInfo: nil repeats: FALSE] retain];
1634 }
1635
1636 #pragma mark -
1637 #pragma mark Interface update
1638
1639 - (void)setupMenus
1640 {
1641     playlist_t * p_playlist = pl_Yield( p_intf );
1642     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1643     if( p_input != NULL )
1644     {
1645         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1646             var: "program" selector: @selector(toggleVar:)];
1647
1648         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1649             var: "title" selector: @selector(toggleVar:)];
1650
1651         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1652             var: "chapter" selector: @selector(toggleVar:)];
1653
1654         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1655             var: "audio-es" selector: @selector(toggleVar:)];
1656
1657         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1658             var: "video-es" selector: @selector(toggleVar:)];
1659
1660         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1661             var: "spu-es" selector: @selector(toggleVar:)];
1662
1663         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1664                                                     FIND_ANYWHERE );
1665         if( p_aout != NULL )
1666         {
1667             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1668                 var: "audio-channels" selector: @selector(toggleVar:)];
1669
1670             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1671                 var: "audio-device" selector: @selector(toggleVar:)];
1672
1673             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1674                 var: "visual" selector: @selector(toggleVar:)];
1675             vlc_object_release( (vlc_object_t *)p_aout );
1676         }
1677
1678         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1679                                                             FIND_ANYWHERE );
1680
1681         if( p_vout != NULL )
1682         {
1683             vlc_object_t * p_dec_obj;
1684
1685             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1686                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1687
1688             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1689                 var: "crop" selector: @selector(toggleVar:)];
1690
1691             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1692                 var: "video-device" selector: @selector(toggleVar:)];
1693
1694             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1695                 var: "deinterlace" selector: @selector(toggleVar:)];
1696
1697             p_dec_obj = (vlc_object_t *)vlc_object_find(
1698                                                  (vlc_object_t *)p_vout,
1699                                                  VLC_OBJECT_DECODER,
1700                                                  FIND_PARENT );
1701             if( p_dec_obj != NULL )
1702             {
1703                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1704                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1705                     @selector(toggleVar:)];
1706
1707                 vlc_object_release(p_dec_obj);
1708             }
1709             vlc_object_release( (vlc_object_t *)p_vout );
1710         }
1711         vlc_object_release( p_input );
1712     }
1713     pl_Release( p_intf );
1714 }
1715
1716 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1717 {
1718     int x,y = 0;
1719     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1720                                               FIND_ANYWHERE );
1721  
1722     if(! p_vout )
1723         return;
1724  
1725     /* clean the menu before adding new entries */
1726     if( [o_mi_screen hasSubmenu] )
1727     {
1728         y = [[o_mi_screen submenu] numberOfItems] - 1;
1729         msg_Dbg( VLCIntf, "%i items in submenu", y );
1730         while( x != y )
1731         {
1732             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1733             [[o_mi_screen submenu] removeItemAtIndex: x];
1734             x++;
1735         }
1736     }
1737
1738     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1739                              var: "video-device" selector: @selector(toggleVar:)];
1740     vlc_object_release( (vlc_object_t *)p_vout );
1741 }
1742
1743 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1744 {
1745     if( timeout != -1 )
1746         i_end_scroll = mdate() + timeout;
1747     else
1748         i_end_scroll = -1;
1749     [o_scrollfield setStringValue: o_string];
1750 }
1751
1752 - (void)resetScrollField
1753 {
1754     playlist_t * p_playlist = pl_Yield( p_intf );
1755     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1756
1757     i_end_scroll = -1;
1758     if( p_input && vlc_object_alive (p_input) )
1759     {
1760         NSString *o_temp;
1761         if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1762             o_temp = [NSString stringWithUTF8String: 
1763                 input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1764         else
1765             o_temp = [NSString stringWithUTF8String:
1766                 p_playlist->status.p_item->p_input->psz_name];
1767         [self setScrollField: o_temp stopAfter:-1];
1768         [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1769         vlc_object_release( p_input );
1770         pl_Release( p_intf );
1771         return;
1772     }
1773     pl_Release( p_intf );
1774     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1775 }
1776
1777 - (void)playStatusUpdated:(int)i_status
1778 {
1779     if( i_status == PLAYING_S )
1780     {
1781         [[[self getControls] getFSPanel] setPause];
1782         [o_btn_play setImage: o_img_pause];
1783         [o_btn_play setAlternateImage: o_img_pause_pressed];
1784         [o_btn_play setToolTip: _NS("Pause")];
1785         [o_mi_play setTitle: _NS("Pause")];
1786         [o_dmi_play setTitle: _NS("Pause")];
1787         [o_vmi_play setTitle: _NS("Pause")];
1788     }
1789     else
1790     {
1791         [[[self getControls] getFSPanel] setPlay];
1792         [o_btn_play setImage: o_img_play];
1793         [o_btn_play setAlternateImage: o_img_play_pressed];
1794         [o_btn_play setToolTip: _NS("Play")];
1795         [o_mi_play setTitle: _NS("Play")];
1796         [o_dmi_play setTitle: _NS("Play")];
1797         [o_vmi_play setTitle: _NS("Play")];
1798     }
1799 }
1800
1801 - (void)setSubmenusEnabled:(BOOL)b_enabled
1802 {
1803     [o_mi_program setEnabled: b_enabled];
1804     [o_mi_title setEnabled: b_enabled];
1805     [o_mi_chapter setEnabled: b_enabled];
1806     [o_mi_audiotrack setEnabled: b_enabled];
1807     [o_mi_visual setEnabled: b_enabled];
1808     [o_mi_videotrack setEnabled: b_enabled];
1809     [o_mi_subtitle setEnabled: b_enabled];
1810     [o_mi_channels setEnabled: b_enabled];
1811     [o_mi_deinterlace setEnabled: b_enabled];
1812     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1813     [o_mi_device setEnabled: b_enabled];
1814     [o_mi_screen setEnabled: b_enabled];
1815     [o_mi_aspect_ratio setEnabled: b_enabled];
1816     [o_mi_crop setEnabled: b_enabled];
1817 }
1818
1819 - (IBAction)timesliderUpdate:(id)sender
1820 {
1821     float f_updated;
1822     playlist_t * p_playlist;
1823     input_thread_t * p_input;
1824
1825     switch( [[NSApp currentEvent] type] )
1826     {
1827         case NSLeftMouseUp:
1828         case NSLeftMouseDown:
1829         case NSLeftMouseDragged:
1830             f_updated = [sender floatValue];
1831             break;
1832
1833         default:
1834             return;
1835     }
1836     p_playlist = pl_Yield( p_intf );
1837     p_input = playlist_CurrentInput( p_playlist );
1838     if( p_input != NULL )
1839     {
1840         vlc_value_t time;
1841         vlc_value_t pos;
1842         NSString * o_time;
1843         char psz_time[MSTRTIME_MAX_SIZE];
1844
1845         pos.f_float = f_updated / 10000.;
1846         var_Set( p_input, "position", pos );
1847         [o_timeslider setFloatValue: f_updated];
1848
1849         var_Get( p_input, "time", &time );
1850
1851         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1852         [o_timefield setStringValue: o_time];
1853         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1854         [o_embedded_window setTime: o_time position: f_updated];
1855         vlc_object_release( p_input );
1856     }
1857     pl_Release( p_intf );
1858 }
1859
1860 #pragma mark -
1861 #pragma mark Recent Items
1862
1863 - (IBAction)clearRecentItems:(id)sender
1864 {
1865     [[NSDocumentController sharedDocumentController]
1866                           clearRecentDocuments: nil];
1867 }
1868
1869 - (void)openRecentItem:(id)sender
1870 {
1871     [self application: nil openFile: [sender title]];
1872 }
1873
1874 #pragma mark -
1875 #pragma mark Panels
1876
1877 - (IBAction)intfOpenFile:(id)sender
1878 {
1879     if( !nib_open_loaded )
1880     {
1881         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1882         [o_open awakeFromNib];
1883         [o_open openFile];
1884     } else {
1885         [o_open openFile];
1886     }
1887 }
1888
1889 - (IBAction)intfOpenFileGeneric:(id)sender
1890 {
1891     if( !nib_open_loaded )
1892     {
1893         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1894         [o_open awakeFromNib];
1895         [o_open openFileGeneric];
1896     } else {
1897         [o_open openFileGeneric];
1898     }
1899 }
1900
1901 - (IBAction)intfOpenDisc:(id)sender
1902 {
1903     if( !nib_open_loaded )
1904     {
1905         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1906         [o_open awakeFromNib];
1907         [o_open openDisc];
1908     } else {
1909         [o_open openDisc];
1910     }
1911 }
1912
1913 - (IBAction)intfOpenNet:(id)sender
1914 {
1915     if( !nib_open_loaded )
1916     {
1917         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1918         [o_open awakeFromNib];
1919         [o_open openNet];
1920     } else {
1921         [o_open openNet];
1922     }
1923 }
1924
1925 - (IBAction)intfOpenCapture:(id)sender
1926 {
1927     if( !nib_open_loaded )
1928     {
1929         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1930         [o_open awakeFromNib];
1931         [o_open openCapture];
1932     } else {
1933         [o_open openCapture];
1934     }
1935 }
1936
1937 - (IBAction)showWizard:(id)sender
1938 {
1939     if( !nib_wizard_loaded )
1940     {
1941         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1942         [o_wizard initStrings];
1943         [o_wizard resetWizard];
1944         [o_wizard showWizard];
1945     } else {
1946         [o_wizard resetWizard];
1947         [o_wizard showWizard];
1948     }
1949 }
1950
1951 - (IBAction)showExtended:(id)sender
1952 {
1953     if( o_extended == nil )
1954         o_extended = [[VLCExtended alloc] init];
1955
1956     if( !nib_extended_loaded )
1957         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
1958
1959     [o_extended showPanel];
1960 }
1961
1962 - (IBAction)showBookmarks:(id)sender
1963 {
1964     /* we need the wizard-nib for the bookmarks's extract functionality */
1965     if( !nib_wizard_loaded )
1966     {
1967         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1968         [o_wizard initStrings];
1969     }
1970  
1971     if( !nib_bookmarks_loaded )
1972         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
1973
1974     [o_bookmarks showBookmarks];
1975 }
1976
1977 - (IBAction)viewPreferences:(id)sender
1978 {
1979     if( !nib_prefs_loaded )
1980     {
1981         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1982         o_sprefs = [[VLCSimplePrefs alloc] init];
1983         o_prefs= [[VLCPrefs alloc] init];
1984     }
1985
1986     [o_sprefs showSimplePrefs];
1987 }
1988
1989 #pragma mark -
1990 #pragma mark Update
1991
1992 - (IBAction)checkForUpdate:(id)sender
1993 {
1994 #ifdef UPDATE_CHECK
1995     if( !nib_update_loaded )
1996         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
1997     [o_update showUpdateWindow];
1998 #else
1999     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2000     intf_UserFatal( VLCIntf, false, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2001 #endif
2002 }
2003
2004 #pragma mark -
2005 #pragma mark Help and Docs
2006
2007 - (IBAction)viewAbout:(id)sender
2008 {
2009     if( !nib_about_loaded )
2010         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2011
2012     [o_about showAbout];
2013 }
2014
2015 - (IBAction)showLicense:(id)sender
2016 {
2017     if( !nib_about_loaded )
2018         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2019
2020     [o_about showGPL: sender];
2021 }
2022     
2023 - (IBAction)viewHelp:(id)sender
2024 {
2025     if( !nib_about_loaded )
2026     {
2027         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2028         [o_about showHelp];
2029     }
2030     else
2031         [o_about showHelp];
2032 }
2033
2034 - (IBAction)openReadMe:(id)sender
2035 {
2036     NSString * o_path = [[NSBundle mainBundle]
2037         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2038
2039     [[NSWorkspace sharedWorkspace] openFile: o_path
2040                                    withApplication: @"TextEdit"];
2041 }
2042
2043 - (IBAction)openDocumentation:(id)sender
2044 {
2045     NSURL * o_url = [NSURL URLWithString:
2046         @"http://www.videolan.org/doc/"];
2047
2048     [[NSWorkspace sharedWorkspace] openURL: o_url];
2049 }
2050
2051 - (IBAction)openWebsite:(id)sender
2052 {
2053     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2054
2055     [[NSWorkspace sharedWorkspace] openURL: o_url];
2056 }
2057
2058 - (IBAction)openForum:(id)sender
2059 {
2060     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2061
2062     [[NSWorkspace sharedWorkspace] openURL: o_url];
2063 }
2064
2065 - (IBAction)openDonate:(id)sender
2066 {
2067     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2068
2069     [[NSWorkspace sharedWorkspace] openURL: o_url];
2070 }
2071
2072 #pragma mark -
2073 #pragma mark Crash Log
2074 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2075 {
2076     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2077     NSURL *url = [NSURL URLWithString:urlStr];
2078
2079     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2080     [req setHTTPMethod:@"POST"];
2081
2082     ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2083
2084     ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2085     NSString * email = [emails valueAtIndex:[emails indexForIdentifier:
2086                 [emails primaryIdentifier]]];
2087
2088     NSString *postBody;
2089     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2090             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2091             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2092             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2093
2094     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2095
2096     /* Released from delegate */
2097     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2098 }
2099
2100 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2101 {
2102     NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2103                 _NS("Thanks for your report!"),
2104                 _NS("OK"), nil, nil, nil);
2105     [crashLogURLConnection release];
2106     crashLogURLConnection = nil;
2107 }
2108
2109 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2110 {
2111     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2112     [crashLogURLConnection release];
2113     crashLogURLConnection = nil;
2114 }
2115
2116 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2117 {
2118     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2119     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2120     NSString *fname;
2121     NSString * latestLog = nil;
2122     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2123     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2124     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2125     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2126
2127     while (fname = [direnum nextObject])
2128     {
2129         [direnum skipDescendents];
2130         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2131         {
2132             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2133             if( [compo count] < 3 ) continue;
2134             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2135             if( [compo count] < 4 ) continue;
2136
2137             // Dooh. ugly.
2138             if( year < [[compo objectAtIndex:0] intValue] ||
2139                 (year ==[[compo objectAtIndex:0] intValue] && 
2140                  (month < [[compo objectAtIndex:1] intValue] ||
2141                   (month ==[[compo objectAtIndex:1] intValue] &&
2142                    (day   < [[compo objectAtIndex:2] intValue] ||
2143                     (day   ==[[compo objectAtIndex:2] intValue] &&
2144                       hours < [[compo objectAtIndex:3] intValue] ))))))
2145             {
2146                 year  = [[compo objectAtIndex:0] intValue];
2147                 month = [[compo objectAtIndex:1] intValue];
2148                 day   = [[compo objectAtIndex:2] intValue];
2149                 hours = [[compo objectAtIndex:3] intValue];
2150                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2151             }
2152         }
2153     }
2154
2155     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2156         return nil;
2157
2158     if( !previouslySeen )
2159     {
2160         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2161         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2162         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2163         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2164     }
2165     return latestLog;
2166 }
2167
2168 - (NSString *)latestCrashLogPath
2169 {
2170     return [self latestCrashLogPathPreviouslySeen:YES];
2171 }
2172
2173 - (void)lookForCrashLog
2174 {
2175     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2176     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2177     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2178     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2179     if( latestLog && !areCrashLogsTooOld )
2180         [NSApp runModalForWindow: o_crashrep_win];
2181     [o_pool release];
2182 }
2183
2184 - (IBAction)crashReporterAction:(id)sender
2185 {
2186     if( sender == o_crashrep_send_btn )
2187         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath]] withUserComment: [o_crashrep_fld string]];
2188
2189     [NSApp stopModal];
2190     [o_crashrep_win orderOut: sender];
2191 }
2192
2193 - (IBAction)openCrashLog:(id)sender
2194 {
2195     NSString * latestLog = [self latestCrashLogPath];
2196     if( latestLog )
2197     {
2198         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2199     }
2200     else
2201     {
2202         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.") );
2203     }
2204 }
2205
2206 #pragma mark -
2207 #pragma mark Errors, warnings and messages
2208
2209 - (IBAction)viewErrorsAndWarnings:(id)sender
2210 {
2211     [[[self getInteractionList] getErrorPanel] showPanel];
2212 }
2213
2214 - (IBAction)showMessagesPanel:(id)sender
2215 {
2216     [o_msgs_panel makeKeyAndOrderFront: sender];
2217 }
2218
2219 - (IBAction)showInformationPanel:(id)sender
2220 {
2221     if(! nib_info_loaded )
2222         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: self];
2223     
2224     [o_info initPanel];
2225 }
2226
2227 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2228 {
2229     if( [o_notification object] == o_msgs_panel )
2230     {
2231         id o_msg;
2232         NSEnumerator * o_enum;
2233
2234         [o_messages setString: @""];
2235
2236         [o_msg_lock lock];
2237
2238         o_enum = [o_msg_arr objectEnumerator];
2239
2240         while( ( o_msg = [o_enum nextObject] ) != nil )
2241         {
2242             [o_messages insertText: o_msg];
2243         }
2244
2245         [o_msg_lock unlock];
2246     }
2247 }
2248
2249 - (void)updateMessageArray
2250 {
2251     int i_start, i_stop;
2252
2253     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
2254     i_stop = *p_intf->p_sys->p_sub->pi_stop;
2255     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
2256
2257     if( p_intf->p_sys->p_sub->i_start != i_stop )
2258     {
2259         NSColor *o_white = [NSColor whiteColor];
2260         NSColor *o_red = [NSColor redColor];
2261         NSColor *o_yellow = [NSColor yellowColor];
2262         NSColor *o_gray = [NSColor grayColor];
2263
2264         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2265         static const char * ppsz_type[4] = { ": ", " error: ",
2266                                              " warning: ", " debug: " };
2267
2268         for( i_start = p_intf->p_sys->p_sub->i_start;
2269              i_start != i_stop;
2270              i_start = (i_start+1) % VLC_MSG_QSIZE )
2271         {
2272             NSString *o_msg;
2273             NSDictionary *o_attr;
2274             NSAttributedString *o_msg_color;
2275
2276             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
2277
2278             [o_msg_lock lock];
2279
2280             if( [o_msg_arr count] + 2 > 400 )
2281             {
2282                 unsigned rid[] = { 0, 1 };
2283                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
2284                            numIndices: sizeof(rid)/sizeof(rid[0])];
2285             }
2286
2287             o_attr = [NSDictionary dictionaryWithObject: o_gray
2288                 forKey: NSForegroundColorAttributeName];
2289             o_msg = [NSString stringWithFormat: @"%s%s",
2290                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
2291                 ppsz_type[i_type]];
2292             o_msg_color = [[NSAttributedString alloc]
2293                 initWithString: o_msg attributes: o_attr];
2294             [o_msg_arr addObject: [o_msg_color autorelease]];
2295
2296             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2297                 forKey: NSForegroundColorAttributeName];
2298             o_msg = [[NSString stringWithUTF8String: p_intf->p_sys->p_sub->p_msg[i_start].psz_msg] stringByAppendingString: @"\n"];
2299             o_msg_color = [[NSAttributedString alloc]
2300                 initWithString: o_msg attributes: o_attr];
2301             [o_msg_arr addObject: [o_msg_color autorelease]];
2302
2303             [o_msg_lock unlock];
2304         }
2305
2306         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
2307         p_intf->p_sys->p_sub->i_start = i_start;
2308         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
2309     }
2310 }
2311
2312 #pragma mark -
2313 #pragma mark Playlist toggling
2314
2315 - (IBAction)togglePlaylist:(id)sender
2316 {
2317     NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2318     NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2319     /*First, check if the playlist is visible*/
2320     if( contentRect.size.height <= 169. )
2321     {
2322         o_restore_rect = contentRect;
2323         b_restore_size = true;
2324         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2325
2326         /* make large */
2327         if( o_size_with_playlist.height > 169. )
2328             o_rect.size.height = o_size_with_playlist.height;
2329         else
2330             o_rect.size.height = 500.;
2331  
2332         if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2333             o_rect.size.width = o_size_with_playlist.width;
2334         else
2335             o_rect.size.width = [o_window contentMinSize].width;
2336
2337         o_rect.origin.x = contentRect.origin.x;
2338         o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2339             [o_window contentMinSize].height;
2340
2341         o_rect = [o_window frameRectForContentRect:o_rect];
2342
2343         NSRect screenRect = [[o_window screen] visibleFrame];
2344         if( !NSContainsRect( screenRect, o_rect ) ) {
2345             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2346                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2347             if( NSMinY(o_rect) < NSMinY(screenRect) )
2348                 o_rect.origin.y = ( NSMinY(screenRect) );
2349         }
2350
2351         [o_btn_playlist setState: YES];
2352     }
2353     else
2354     {
2355         NSSize curSize = o_rect.size;
2356         if( b_restore_size )
2357         {
2358             o_rect = o_restore_rect;
2359             if( o_rect.size.height < [o_window contentMinSize].height )
2360                 o_rect.size.height = [o_window contentMinSize].height;
2361             if( o_rect.size.width < [o_window contentMinSize].width )
2362                 o_rect.size.width = [o_window contentMinSize].width;
2363         }
2364         else
2365         {
2366             NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2367             /* make small */
2368             o_rect.size.height = [o_window contentMinSize].height;
2369             o_rect.size.width = [o_window contentMinSize].width;
2370             o_rect.origin.x = contentRect.origin.x;
2371             /* Calculate the position of the lower right corner after resize */
2372             o_rect.origin.y = contentRect.origin.y +
2373                 contentRect.size.height - [o_window contentMinSize].height;
2374         }
2375
2376         [o_playlist_view setAutoresizesSubviews: NO];
2377         [o_playlist_view removeFromSuperview];
2378         [o_btn_playlist setState: NO];
2379         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2380         o_rect = [o_window frameRectForContentRect:o_rect];
2381     }
2382
2383     [o_window setFrame: o_rect display:YES animate: YES];
2384 }
2385
2386 - (void)updateTogglePlaylistState
2387 {
2388     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2389     {
2390         [o_btn_playlist setState: NO];
2391     }
2392     else
2393     {
2394         [o_btn_playlist setState: YES];
2395     }
2396 }
2397
2398 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2399 {
2400
2401     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2402
2403    /*Stores the size the controller one resize, to be able to restore it when
2404      toggling the playlist*/
2405     o_size_with_playlist = proposedFrameSize;
2406
2407     NSRect rect;
2408     rect.size = proposedFrameSize;
2409     if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2410     {
2411         if( b_small_window == NO )
2412         {
2413             /* if large and going to small then hide */
2414             b_small_window = YES;
2415             [o_playlist_view setAutoresizesSubviews: NO];
2416             [o_playlist_view removeFromSuperview];
2417         }
2418         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2419     }
2420     return proposedFrameSize;
2421 }
2422
2423 - (void)windowDidMove:(NSNotification *)notif
2424 {
2425     b_restore_size = false;
2426 }
2427
2428 - (void)windowDidResize:(NSNotification *)notif
2429 {
2430     if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2431     {
2432         /* If large and coming from small then show */
2433         [o_playlist_view setAutoresizesSubviews: YES];
2434         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2435         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2436         [o_playlist_view setNeedsDisplay:YES];
2437         [[o_window contentView] addSubview: o_playlist_view];
2438         b_small_window = NO;
2439     }
2440     [self updateTogglePlaylistState];
2441 }
2442
2443 #pragma mark -
2444
2445 @end
2446
2447 @implementation VLCMain (NSMenuValidation)
2448
2449 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2450 {
2451     NSString *o_title = [o_mi title];
2452     BOOL bEnabled = TRUE;
2453
2454     /* Recent Items Menu */
2455     if( [o_title isEqualToString: _NS("Clear Menu")] )
2456     {
2457         NSMenu * o_menu = [o_mi_open_recent submenu];
2458         int i_nb_items = [o_menu numberOfItems];
2459         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2460                                                        recentDocumentURLs];
2461         UInt32 i_nb_docs = [o_docs count];
2462
2463         if( i_nb_items > 1 )
2464         {
2465             while( --i_nb_items )
2466             {
2467                 [o_menu removeItemAtIndex: 0];
2468             }
2469         }
2470
2471         if( i_nb_docs > 0 )
2472         {
2473             NSURL * o_url;
2474             NSString * o_doc;
2475
2476             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2477
2478             while( TRUE )
2479             {
2480                 i_nb_docs--;
2481
2482                 o_url = [o_docs objectAtIndex: i_nb_docs];
2483
2484                 if( [o_url isFileURL] )
2485                 {
2486                     o_doc = [o_url path];
2487                 }
2488                 else
2489                 {
2490                     o_doc = [o_url absoluteString];
2491                 }
2492
2493                 [o_menu insertItemWithTitle: o_doc
2494                     action: @selector(openRecentItem:)
2495                     keyEquivalent: @"" atIndex: 0];
2496
2497                 if( i_nb_docs == 0 )
2498                 {
2499                     break;
2500                 }
2501             }
2502         }
2503         else
2504         {
2505             bEnabled = FALSE;
2506         }
2507     }
2508     return( bEnabled );
2509 }
2510
2511 @end
2512
2513 @implementation VLCMain (Internal)
2514
2515 - (void)handlePortMessage:(NSPortMessage *)o_msg
2516 {
2517     id ** val;
2518     NSData * o_data;
2519     NSValue * o_value;
2520     NSInvocation * o_inv;
2521     NSConditionLock * o_lock;
2522
2523     o_data = [[o_msg components] lastObject];
2524     o_inv = *((NSInvocation **)[o_data bytes]);
2525     [o_inv getArgument: &o_value atIndex: 2];
2526     val = (id **)[o_value pointerValue];
2527     [o_inv setArgument: val[1] atIndex: 2];
2528     o_lock = *(val[0]);
2529
2530     [o_lock lock];
2531     [o_inv invoke];
2532     [o_lock unlockWithCondition: 1];
2533 }
2534
2535 @end