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