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