]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
84de1543babfdfd7794abba8c802a233e67c3146
[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                  cachedInputState == BUFFERING_S )
1511             {
1512                 b_buffering = YES;
1513             }
1514                  
1515             /* seekable streams */
1516             b_seekable = var_GetBool( p_input, "seekable" );
1517
1518             /* check whether slow/fast motion is possible */
1519             b_control = p_input->b_can_pace_control;
1520
1521             /* chapters & titles */
1522             //b_chapters = p_input->stream.i_area_nb > 1;
1523             vlc_object_release( p_input );
1524         }
1525         pl_Release( p_intf );
1526
1527         if( b_buffering )
1528         {
1529             [o_main_pgbar startAnimation:self];
1530             [o_main_pgbar setIndeterminate:YES];
1531             [o_main_pgbar setHidden:NO];
1532         }
1533         else
1534         {
1535             [o_main_pgbar stopAnimation:self];
1536             [o_main_pgbar setHidden:YES];
1537         }
1538
1539         [o_btn_stop setEnabled: b_input];
1540         [o_btn_ff setEnabled: b_seekable];
1541         [o_btn_rewind setEnabled: b_seekable];
1542         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1543         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1544
1545         [o_timeslider setFloatValue: 0.0];
1546         [o_timeslider setEnabled: b_seekable];
1547         [o_timefield setStringValue: @"00:00"];
1548         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1549         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1550
1551         [o_embedded_window setSeekable: b_seekable];
1552
1553         p_intf->p_sys->b_current_title_update = true;
1554         
1555         p_intf->p_sys->b_intf_update = false;
1556     }
1557
1558     if( p_intf->p_sys->b_playmode_update )
1559     {
1560         [o_playlist playModeUpdated];
1561         p_intf->p_sys->b_playmode_update = false;
1562     }
1563     if( p_intf->p_sys->b_playlist_update )
1564     {
1565         [o_playlist playlistUpdated];
1566         p_intf->p_sys->b_playlist_update = false;
1567     }
1568
1569     if( p_intf->p_sys->b_fullscreen_update )
1570     {
1571         p_intf->p_sys->b_fullscreen_update = false;
1572     }
1573
1574     if( p_intf->p_sys->b_intf_show )
1575     {
1576         [o_window makeKeyAndOrderFront: self];
1577
1578         p_intf->p_sys->b_intf_show = false;
1579     }
1580
1581     p_input = pl_CurrentInput( p_intf );
1582     if( p_input && vlc_object_alive (p_input) )
1583     {
1584         vlc_value_t val;
1585
1586         if( p_intf->p_sys->b_current_title_update )
1587         {
1588             NSString *aString;
1589             input_item_t * p_item = input_GetItem( p_input );
1590             char * name = input_item_GetNowPlaying( p_item );
1591
1592             if( !name )
1593                 name = input_item_GetName( p_item );
1594
1595             aString = [NSString stringWithUTF8String:name];
1596
1597             free(name);
1598
1599             [self setScrollField: aString stopAfter:-1];
1600             [[[self getControls] getFSPanel] setStreamTitle: aString];
1601
1602             [[o_controls getVoutView] updateTitle];
1603  
1604             [o_playlist updateRowSelection];
1605             p_intf->p_sys->b_current_title_update = FALSE;
1606         }
1607
1608         if( [o_timeslider isEnabled] )
1609         {
1610             /* Update the slider */
1611             vlc_value_t time;
1612             NSString * o_time;
1613             vlc_value_t pos;
1614             char psz_time[MSTRTIME_MAX_SIZE];
1615             float f_updated;
1616
1617             var_Get( p_input, "position", &pos );
1618             f_updated = 10000. * pos.f_float;
1619             [o_timeslider setFloatValue: f_updated];
1620
1621             var_Get( p_input, "time", &time );
1622
1623             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1624
1625             [o_timefield setStringValue: o_time];
1626             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1627             [o_embedded_window setTime: o_time position: f_updated];
1628         }
1629
1630         /* Manage Playing status */
1631         var_Get( p_input, "state", &val );
1632         if( p_intf->p_sys->i_play_status != val.i_int )
1633         {
1634             p_intf->p_sys->i_play_status = val.i_int;
1635             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1636             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1637         }
1638         vlc_object_release( p_input );
1639     }
1640     else if( p_input )
1641     {
1642         vlc_object_release( p_input );
1643     }
1644     else
1645     {
1646         p_intf->p_sys->i_play_status = END_S;
1647         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1648         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1649         [self setSubmenusEnabled: FALSE];
1650     }
1651
1652     if( p_intf->p_sys->b_volume_update )
1653     {
1654         NSString *o_text;
1655         int i_volume_step = 0;
1656         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1657         if( i_lastShownVolume != -1 )
1658         [self setScrollField:o_text stopAfter:1000000];
1659         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1660         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1661         [o_volumeslider setEnabled: TRUE];
1662         [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1663         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1664         p_intf->p_sys->b_volume_update = FALSE;
1665     }
1666
1667 end:
1668     [self updateMessageArray];
1669
1670     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1671         [self resetScrollField];
1672
1673     [interfaceTimer autorelease];
1674
1675     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1676         target: self selector: @selector(manageIntf:)
1677         userInfo: nil repeats: FALSE] retain];
1678 }
1679
1680 #pragma mark -
1681 #pragma mark Interface update
1682
1683 - (void)setupMenus
1684 {
1685     playlist_t * p_playlist = pl_Hold( p_intf );
1686     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1687     if( p_input != NULL )
1688     {
1689         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1690             var: "program" selector: @selector(toggleVar:)];
1691
1692         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1693             var: "title" selector: @selector(toggleVar:)];
1694
1695         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1696             var: "chapter" selector: @selector(toggleVar:)];
1697
1698         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1699             var: "audio-es" selector: @selector(toggleVar:)];
1700
1701         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1702             var: "video-es" selector: @selector(toggleVar:)];
1703
1704         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1705             var: "spu-es" selector: @selector(toggleVar:)];
1706
1707         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1708                                                     FIND_ANYWHERE );
1709         if( p_aout != NULL )
1710         {
1711             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1712                 var: "audio-channels" selector: @selector(toggleVar:)];
1713
1714             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1715                 var: "audio-device" selector: @selector(toggleVar:)];
1716
1717             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1718                 var: "visual" selector: @selector(toggleVar:)];
1719             vlc_object_release( (vlc_object_t *)p_aout );
1720         }
1721
1722         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1723                                                             FIND_ANYWHERE );
1724
1725         if( p_vout != NULL )
1726         {
1727             vlc_object_t * p_dec_obj;
1728
1729             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1730                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1731
1732             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1733                 var: "crop" selector: @selector(toggleVar:)];
1734
1735             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1736                 var: "video-device" selector: @selector(toggleVar:)];
1737
1738             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1739                 var: "deinterlace" selector: @selector(toggleVar:)];
1740
1741             p_dec_obj = (vlc_object_t *)vlc_object_find(
1742                                                  (vlc_object_t *)p_vout,
1743                                                  VLC_OBJECT_DECODER,
1744                                                  FIND_PARENT );
1745             if( p_dec_obj != NULL )
1746             {
1747                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1748                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1749                     @selector(toggleVar:)];
1750
1751                 vlc_object_release(p_dec_obj);
1752             }
1753             vlc_object_release( (vlc_object_t *)p_vout );
1754         }
1755         vlc_object_release( p_input );
1756     }
1757     pl_Release( p_intf );
1758 }
1759
1760 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1761 {
1762     int x,y = 0;
1763     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1764                                               FIND_ANYWHERE );
1765  
1766     if(! p_vout )
1767         return;
1768  
1769     /* clean the menu before adding new entries */
1770     if( [o_mi_screen hasSubmenu] )
1771     {
1772         y = [[o_mi_screen submenu] numberOfItems] - 1;
1773         msg_Dbg( VLCIntf, "%i items in submenu", y );
1774         while( x != y )
1775         {
1776             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1777             [[o_mi_screen submenu] removeItemAtIndex: x];
1778             x++;
1779         }
1780     }
1781
1782     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1783                              var: "video-device" selector: @selector(toggleVar:)];
1784     vlc_object_release( (vlc_object_t *)p_vout );
1785 }
1786
1787 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1788 {
1789     if( timeout != -1 )
1790         i_end_scroll = mdate() + timeout;
1791     else
1792         i_end_scroll = -1;
1793     [o_scrollfield setStringValue: o_string];
1794 }
1795
1796 - (void)resetScrollField
1797 {
1798     playlist_t * p_playlist = pl_Hold( p_intf );
1799     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1800
1801     i_end_scroll = -1;
1802     if( p_input && vlc_object_alive (p_input) )
1803     {
1804         NSString *o_temp;
1805         if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1806             o_temp = [NSString stringWithUTF8String: 
1807                 input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1808         else
1809             o_temp = [NSString stringWithUTF8String:
1810                 p_playlist->status.p_item->p_input->psz_name];
1811         [self setScrollField: o_temp stopAfter:-1];
1812         [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1813         vlc_object_release( p_input );
1814         pl_Release( p_intf );
1815         return;
1816     }
1817     pl_Release( p_intf );
1818     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1819 }
1820
1821 - (void)playStatusUpdated:(int)i_status
1822 {
1823     if( i_status == PLAYING_S )
1824     {
1825         [[[self getControls] getFSPanel] setPause];
1826         [o_btn_play setImage: o_img_pause];
1827         [o_btn_play setAlternateImage: o_img_pause_pressed];
1828         [o_btn_play setToolTip: _NS("Pause")];
1829         [o_mi_play setTitle: _NS("Pause")];
1830         [o_dmi_play setTitle: _NS("Pause")];
1831         [o_vmi_play setTitle: _NS("Pause")];
1832     }
1833     else
1834     {
1835         [[[self getControls] getFSPanel] setPlay];
1836         [o_btn_play setImage: o_img_play];
1837         [o_btn_play setAlternateImage: o_img_play_pressed];
1838         [o_btn_play setToolTip: _NS("Play")];
1839         [o_mi_play setTitle: _NS("Play")];
1840         [o_dmi_play setTitle: _NS("Play")];
1841         [o_vmi_play setTitle: _NS("Play")];
1842     }
1843 }
1844
1845 - (void)setSubmenusEnabled:(BOOL)b_enabled
1846 {
1847     [o_mi_program setEnabled: b_enabled];
1848     [o_mi_title setEnabled: b_enabled];
1849     [o_mi_chapter setEnabled: b_enabled];
1850     [o_mi_audiotrack setEnabled: b_enabled];
1851     [o_mi_visual setEnabled: b_enabled];
1852     [o_mi_videotrack setEnabled: b_enabled];
1853     [o_mi_subtitle setEnabled: b_enabled];
1854     [o_mi_channels setEnabled: b_enabled];
1855     [o_mi_deinterlace setEnabled: b_enabled];
1856     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1857     [o_mi_device setEnabled: b_enabled];
1858     [o_mi_screen setEnabled: b_enabled];
1859     [o_mi_aspect_ratio setEnabled: b_enabled];
1860     [o_mi_crop setEnabled: b_enabled];
1861 }
1862
1863 - (IBAction)timesliderUpdate:(id)sender
1864 {
1865     float f_updated;
1866     playlist_t * p_playlist;
1867     input_thread_t * p_input;
1868
1869     switch( [[NSApp currentEvent] type] )
1870     {
1871         case NSLeftMouseUp:
1872         case NSLeftMouseDown:
1873         case NSLeftMouseDragged:
1874             f_updated = [sender floatValue];
1875             break;
1876
1877         default:
1878             return;
1879     }
1880     p_playlist = pl_Hold( p_intf );
1881     p_input = playlist_CurrentInput( p_playlist );
1882     if( p_input != NULL )
1883     {
1884         vlc_value_t time;
1885         vlc_value_t pos;
1886         NSString * o_time;
1887         char psz_time[MSTRTIME_MAX_SIZE];
1888
1889         pos.f_float = f_updated / 10000.;
1890         var_Set( p_input, "position", pos );
1891         [o_timeslider setFloatValue: f_updated];
1892
1893         var_Get( p_input, "time", &time );
1894
1895         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1896         [o_timefield setStringValue: o_time];
1897         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1898         [o_embedded_window setTime: o_time position: f_updated];
1899         vlc_object_release( p_input );
1900     }
1901     pl_Release( p_intf );
1902 }
1903
1904 #pragma mark -
1905 #pragma mark Recent Items
1906
1907 - (IBAction)clearRecentItems:(id)sender
1908 {
1909     [[NSDocumentController sharedDocumentController]
1910                           clearRecentDocuments: nil];
1911 }
1912
1913 - (void)openRecentItem:(id)sender
1914 {
1915     [self application: nil openFile: [sender title]];
1916 }
1917
1918 #pragma mark -
1919 #pragma mark Panels
1920
1921 - (IBAction)intfOpenFile:(id)sender
1922 {
1923     if( !nib_open_loaded )
1924     {
1925         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1926         [o_open awakeFromNib];
1927         [o_open openFile];
1928     } else {
1929         [o_open openFile];
1930     }
1931 }
1932
1933 - (IBAction)intfOpenFileGeneric:(id)sender
1934 {
1935     if( !nib_open_loaded )
1936     {
1937         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1938         [o_open awakeFromNib];
1939         [o_open openFileGeneric];
1940     } else {
1941         [o_open openFileGeneric];
1942     }
1943 }
1944
1945 - (IBAction)intfOpenDisc:(id)sender
1946 {
1947     if( !nib_open_loaded )
1948     {
1949         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1950         [o_open awakeFromNib];
1951         [o_open openDisc];
1952     } else {
1953         [o_open openDisc];
1954     }
1955 }
1956
1957 - (IBAction)intfOpenNet:(id)sender
1958 {
1959     if( !nib_open_loaded )
1960     {
1961         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1962         [o_open awakeFromNib];
1963         [o_open openNet];
1964     } else {
1965         [o_open openNet];
1966     }
1967 }
1968
1969 - (IBAction)intfOpenCapture:(id)sender
1970 {
1971     if( !nib_open_loaded )
1972     {
1973         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1974         [o_open awakeFromNib];
1975         [o_open openCapture];
1976     } else {
1977         [o_open openCapture];
1978     }
1979 }
1980
1981 - (IBAction)showWizard:(id)sender
1982 {
1983     if( !nib_wizard_loaded )
1984     {
1985         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1986         [o_wizard initStrings];
1987         [o_wizard resetWizard];
1988         [o_wizard showWizard];
1989     } else {
1990         [o_wizard resetWizard];
1991         [o_wizard showWizard];
1992     }
1993 }
1994
1995 - (IBAction)showVLM:(id)sender
1996 {
1997     if( !nib_vlm_loaded )
1998         nib_vlm_loaded = [NSBundle loadNibNamed:@"VLM" owner:self];
1999
2000     [o_vlm showVLMWindow];
2001 }
2002
2003 - (IBAction)showExtended:(id)sender
2004 {
2005     if( o_extended == nil )
2006         o_extended = [[VLCExtended alloc] init];
2007
2008     if( !nib_extended_loaded )
2009         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
2010
2011     [o_extended showPanel];
2012 }
2013
2014 - (IBAction)showBookmarks:(id)sender
2015 {
2016     /* we need the wizard-nib for the bookmarks's extract functionality */
2017     if( !nib_wizard_loaded )
2018     {
2019         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
2020         [o_wizard initStrings];
2021     }
2022  
2023     if( !nib_bookmarks_loaded )
2024         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
2025
2026     [o_bookmarks showBookmarks];
2027 }
2028
2029 - (IBAction)viewPreferences:(id)sender
2030 {
2031     if( !nib_prefs_loaded )
2032     {
2033         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
2034         o_sprefs = [[VLCSimplePrefs alloc] init];
2035         o_prefs= [[VLCPrefs alloc] init];
2036     }
2037
2038     [o_sprefs showSimplePrefs];
2039 }
2040
2041 #pragma mark -
2042 #pragma mark Update
2043
2044 - (IBAction)checkForUpdate:(id)sender
2045 {
2046 #ifdef UPDATE_CHECK
2047     if( !nib_update_loaded )
2048         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
2049     [o_update showUpdateWindow];
2050 #else
2051     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
2052     intf_UserFatal( VLCIntf, false, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
2053 #endif
2054 }
2055
2056 #pragma mark -
2057 #pragma mark Help and Docs
2058
2059 - (IBAction)viewAbout:(id)sender
2060 {
2061     if( !nib_about_loaded )
2062         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2063
2064     [o_about showAbout];
2065 }
2066
2067 - (IBAction)showLicense:(id)sender
2068 {
2069     if( !nib_about_loaded )
2070         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2071
2072     [o_about showGPL: sender];
2073 }
2074     
2075 - (IBAction)viewHelp:(id)sender
2076 {
2077     if( !nib_about_loaded )
2078     {
2079         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
2080         [o_about showHelp];
2081     }
2082     else
2083         [o_about showHelp];
2084 }
2085
2086 - (IBAction)openReadMe:(id)sender
2087 {
2088     NSString * o_path = [[NSBundle mainBundle]
2089         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2090
2091     [[NSWorkspace sharedWorkspace] openFile: o_path
2092                                    withApplication: @"TextEdit"];
2093 }
2094
2095 - (IBAction)openDocumentation:(id)sender
2096 {
2097     NSURL * o_url = [NSURL URLWithString:
2098         @"http://www.videolan.org/doc/"];
2099
2100     [[NSWorkspace sharedWorkspace] openURL: o_url];
2101 }
2102
2103 - (IBAction)openWebsite:(id)sender
2104 {
2105     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2106
2107     [[NSWorkspace sharedWorkspace] openURL: o_url];
2108 }
2109
2110 - (IBAction)openForum:(id)sender
2111 {
2112     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2113
2114     [[NSWorkspace sharedWorkspace] openURL: o_url];
2115 }
2116
2117 - (IBAction)openDonate:(id)sender
2118 {
2119     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2120
2121     [[NSWorkspace sharedWorkspace] openURL: o_url];
2122 }
2123
2124 #pragma mark -
2125 #pragma mark Crash Log
2126 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2127 {
2128     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2129     NSURL *url = [NSURL URLWithString:urlStr];
2130
2131     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2132     [req setHTTPMethod:@"POST"];
2133
2134     NSString * email;
2135     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2136     {
2137         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2138         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2139         email = [emails valueAtIndex:[emails indexForIdentifier:
2140                     [emails primaryIdentifier]]];
2141     }
2142     else
2143         email = [NSString string];
2144
2145     NSString *postBody;
2146     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2147             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2148             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2149             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2150
2151     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2152
2153     /* Released from delegate */
2154     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2155 }
2156
2157 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2158 {
2159     NSRunInformationalAlertPanel(_NS("Crash Report successfully sent"),
2160                 _NS("Thanks for your report!"),
2161                 _NS("OK"), nil, nil, nil);
2162     [crashLogURLConnection release];
2163     crashLogURLConnection = nil;
2164 }
2165
2166 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2167 {
2168     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2169     [crashLogURLConnection release];
2170     crashLogURLConnection = nil;
2171 }
2172
2173 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2174 {
2175     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2176     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2177     NSString *fname;
2178     NSString * latestLog = nil;
2179     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2180     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2181     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2182     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2183
2184     while (fname = [direnum nextObject])
2185     {
2186         [direnum skipDescendents];
2187         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2188         {
2189             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2190             if( [compo count] < 3 ) continue;
2191             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2192             if( [compo count] < 4 ) continue;
2193
2194             // Dooh. ugly.
2195             if( year < [[compo objectAtIndex:0] intValue] ||
2196                 (year ==[[compo objectAtIndex:0] intValue] && 
2197                  (month < [[compo objectAtIndex:1] intValue] ||
2198                   (month ==[[compo objectAtIndex:1] intValue] &&
2199                    (day   < [[compo objectAtIndex:2] intValue] ||
2200                     (day   ==[[compo objectAtIndex:2] intValue] &&
2201                       hours < [[compo objectAtIndex:3] intValue] ))))))
2202             {
2203                 year  = [[compo objectAtIndex:0] intValue];
2204                 month = [[compo objectAtIndex:1] intValue];
2205                 day   = [[compo objectAtIndex:2] intValue];
2206                 hours = [[compo objectAtIndex:3] intValue];
2207                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2208             }
2209         }
2210     }
2211
2212     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2213         return nil;
2214
2215     if( !previouslySeen )
2216     {
2217         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2218         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2219         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2220         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2221     }
2222     return latestLog;
2223 }
2224
2225 - (NSString *)latestCrashLogPath
2226 {
2227     return [self latestCrashLogPathPreviouslySeen:YES];
2228 }
2229
2230 - (void)lookForCrashLog
2231 {
2232     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2233     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2234     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2235     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2236     if( latestLog && !areCrashLogsTooOld )
2237         [NSApp runModalForWindow: o_crashrep_win];
2238     [o_pool release];
2239 }
2240
2241 - (IBAction)crashReporterAction:(id)sender
2242 {
2243     if( sender == o_crashrep_send_btn )
2244         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath]] withUserComment: [o_crashrep_fld string]];
2245
2246     [NSApp stopModal];
2247     [o_crashrep_win orderOut: sender];
2248 }
2249
2250 - (IBAction)openCrashLog:(id)sender
2251 {
2252     NSString * latestLog = [self latestCrashLogPath];
2253     if( latestLog )
2254     {
2255         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2256     }
2257     else
2258     {
2259         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.") );
2260     }
2261 }
2262
2263 #pragma mark -
2264 #pragma mark Remove old prefs
2265
2266 - (void)_removeOldPreferences
2267 {
2268     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2269     static const int kCurrentPreferencesVersion = 1;
2270     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2271     if( version >= kCurrentPreferencesVersion ) return;
2272
2273     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
2274         NSUserDomainMask, YES);
2275     if( !libraries || [libraries count] == 0) return;
2276     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2277
2278     /* File not found, don't attempt anything */
2279     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2280        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2281     {
2282         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2283         return;
2284     }
2285
2286     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2287                 _NS("We just found an older version of VLC's preferences files."),
2288                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2289     if( res != NSOKButton )
2290     {
2291         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2292         return;
2293     }
2294
2295     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2296
2297     /* Move the file to trash so that user can find them later */
2298     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2299
2300     /* really reset the defaults from now on */
2301     [NSUserDefaults resetStandardUserDefaults];
2302
2303     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2304     [[NSUserDefaults standardUserDefaults] synchronize];
2305
2306     /* Relaunch now */
2307     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2308
2309     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2310     if(fork() != 0)
2311     {
2312         exit(0);
2313         return;
2314     }
2315     execl(path, path, NULL);
2316 }
2317
2318 #pragma mark -
2319 #pragma mark Errors, warnings and messages
2320
2321 - (IBAction)viewErrorsAndWarnings:(id)sender
2322 {
2323     [[[self getInteractionList] getErrorPanel] showPanel];
2324 }
2325
2326 - (IBAction)showMessagesPanel:(id)sender
2327 {
2328     [o_msgs_panel makeKeyAndOrderFront: sender];
2329 }
2330
2331 - (IBAction)showInformationPanel:(id)sender
2332 {
2333     if(! nib_info_loaded )
2334         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: self];
2335     
2336     [o_info initPanel];
2337 }
2338
2339 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2340 {
2341     if( [o_notification object] == o_msgs_panel )
2342     {
2343         id o_msg;
2344         NSEnumerator * o_enum;
2345
2346         [o_messages setString: @""];
2347
2348         [o_msg_lock lock];
2349
2350         o_enum = [o_msg_arr objectEnumerator];
2351
2352         while( ( o_msg = [o_enum nextObject] ) != nil )
2353         {
2354             [o_messages insertText: o_msg];
2355         }
2356
2357         [o_msg_lock unlock];
2358     }
2359 }
2360
2361 - (void)updateMessageArray
2362 {
2363     int i_start, i_stop;
2364
2365     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
2366     i_stop = *p_intf->p_sys->p_sub->pi_stop;
2367     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
2368
2369     if( p_intf->p_sys->p_sub->i_start != i_stop )
2370     {
2371         NSColor *o_white = [NSColor whiteColor];
2372         NSColor *o_red = [NSColor redColor];
2373         NSColor *o_yellow = [NSColor yellowColor];
2374         NSColor *o_gray = [NSColor grayColor];
2375
2376         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2377         static const char * ppsz_type[4] = { ": ", " error: ",
2378                                              " warning: ", " debug: " };
2379
2380         for( i_start = p_intf->p_sys->p_sub->i_start;
2381              i_start != i_stop;
2382              i_start = (i_start+1) % VLC_MSG_QSIZE )
2383         {
2384             NSString *o_msg;
2385             NSDictionary *o_attr;
2386             NSAttributedString *o_msg_color;
2387
2388             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
2389
2390             [o_msg_lock lock];
2391
2392             if( [o_msg_arr count] + 2 > 400 )
2393             {
2394                 unsigned rid[] = { 0, 1 };
2395                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
2396                            numIndices: sizeof(rid)/sizeof(rid[0])];
2397             }
2398
2399             o_attr = [NSDictionary dictionaryWithObject: o_gray
2400                 forKey: NSForegroundColorAttributeName];
2401             o_msg = [NSString stringWithFormat: @"%s%s",
2402                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
2403                 ppsz_type[i_type]];
2404             o_msg_color = [[NSAttributedString alloc]
2405                 initWithString: o_msg attributes: o_attr];
2406             [o_msg_arr addObject: [o_msg_color autorelease]];
2407
2408             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2409                 forKey: NSForegroundColorAttributeName];
2410             o_msg = [[NSString stringWithUTF8String: p_intf->p_sys->p_sub->p_msg[i_start].psz_msg] stringByAppendingString: @"\n"];
2411             o_msg_color = [[NSAttributedString alloc]
2412                 initWithString: o_msg attributes: o_attr];
2413             [o_msg_arr addObject: [o_msg_color autorelease]];
2414
2415             [o_msg_lock unlock];
2416         }
2417
2418         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
2419         p_intf->p_sys->p_sub->i_start = i_start;
2420         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
2421     }
2422 }
2423
2424 #pragma mark -
2425 #pragma mark Playlist toggling
2426
2427 - (IBAction)togglePlaylist:(id)sender
2428 {
2429     NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2430     NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2431     /*First, check if the playlist is visible*/
2432     if( contentRect.size.height <= 169. )
2433     {
2434         o_restore_rect = contentRect;
2435         b_restore_size = true;
2436         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2437
2438         /* make large */
2439         if( o_size_with_playlist.height > 169. )
2440             o_rect.size.height = o_size_with_playlist.height;
2441         else
2442             o_rect.size.height = 500.;
2443  
2444         if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2445             o_rect.size.width = o_size_with_playlist.width;
2446         else
2447             o_rect.size.width = [o_window contentMinSize].width;
2448
2449         o_rect.origin.x = contentRect.origin.x;
2450         o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2451             [o_window contentMinSize].height;
2452
2453         o_rect = [o_window frameRectForContentRect:o_rect];
2454
2455         NSRect screenRect = [[o_window screen] visibleFrame];
2456         if( !NSContainsRect( screenRect, o_rect ) ) {
2457             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2458                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2459             if( NSMinY(o_rect) < NSMinY(screenRect) )
2460                 o_rect.origin.y = ( NSMinY(screenRect) );
2461         }
2462
2463         [o_btn_playlist setState: YES];
2464     }
2465     else
2466     {
2467         NSSize curSize = o_rect.size;
2468         if( b_restore_size )
2469         {
2470             o_rect = o_restore_rect;
2471             if( o_rect.size.height < [o_window contentMinSize].height )
2472                 o_rect.size.height = [o_window contentMinSize].height;
2473             if( o_rect.size.width < [o_window contentMinSize].width )
2474                 o_rect.size.width = [o_window contentMinSize].width;
2475         }
2476         else
2477         {
2478             NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2479             /* make small */
2480             o_rect.size.height = [o_window contentMinSize].height;
2481             o_rect.size.width = [o_window contentMinSize].width;
2482             o_rect.origin.x = contentRect.origin.x;
2483             /* Calculate the position of the lower right corner after resize */
2484             o_rect.origin.y = contentRect.origin.y +
2485                 contentRect.size.height - [o_window contentMinSize].height;
2486         }
2487
2488         [o_playlist_view setAutoresizesSubviews: NO];
2489         [o_playlist_view removeFromSuperview];
2490         [o_btn_playlist setState: NO];
2491         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2492         o_rect = [o_window frameRectForContentRect:o_rect];
2493     }
2494
2495     [o_window setFrame: o_rect display:YES animate: YES];
2496 }
2497
2498 - (void)updateTogglePlaylistState
2499 {
2500     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2501     {
2502         [o_btn_playlist setState: NO];
2503     }
2504     else
2505     {
2506         [o_btn_playlist setState: YES];
2507     }
2508 }
2509
2510 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2511 {
2512
2513     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2514
2515    /*Stores the size the controller one resize, to be able to restore it when
2516      toggling the playlist*/
2517     o_size_with_playlist = proposedFrameSize;
2518
2519     NSRect rect;
2520     rect.size = proposedFrameSize;
2521     if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2522     {
2523         if( b_small_window == NO )
2524         {
2525             /* if large and going to small then hide */
2526             b_small_window = YES;
2527             [o_playlist_view setAutoresizesSubviews: NO];
2528             [o_playlist_view removeFromSuperview];
2529         }
2530         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2531     }
2532     return proposedFrameSize;
2533 }
2534
2535 - (void)windowDidMove:(NSNotification *)notif
2536 {
2537     b_restore_size = false;
2538 }
2539
2540 - (void)windowDidResize:(NSNotification *)notif
2541 {
2542     if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2543     {
2544         /* If large and coming from small then show */
2545         [o_playlist_view setAutoresizesSubviews: YES];
2546         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2547         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2548         [o_playlist_view setNeedsDisplay:YES];
2549         [[o_window contentView] addSubview: o_playlist_view];
2550         b_small_window = NO;
2551     }
2552     [self updateTogglePlaylistState];
2553 }
2554
2555 #pragma mark -
2556
2557 @end
2558
2559 @implementation VLCMain (NSMenuValidation)
2560
2561 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2562 {
2563     NSString *o_title = [o_mi title];
2564     BOOL bEnabled = TRUE;
2565
2566     /* Recent Items Menu */
2567     if( [o_title isEqualToString: _NS("Clear Menu")] )
2568     {
2569         NSMenu * o_menu = [o_mi_open_recent submenu];
2570         int i_nb_items = [o_menu numberOfItems];
2571         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2572                                                        recentDocumentURLs];
2573         UInt32 i_nb_docs = [o_docs count];
2574
2575         if( i_nb_items > 1 )
2576         {
2577             while( --i_nb_items )
2578             {
2579                 [o_menu removeItemAtIndex: 0];
2580             }
2581         }
2582
2583         if( i_nb_docs > 0 )
2584         {
2585             NSURL * o_url;
2586             NSString * o_doc;
2587
2588             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2589
2590             while( TRUE )
2591             {
2592                 i_nb_docs--;
2593
2594                 o_url = [o_docs objectAtIndex: i_nb_docs];
2595
2596                 if( [o_url isFileURL] )
2597                 {
2598                     o_doc = [o_url path];
2599                 }
2600                 else
2601                 {
2602                     o_doc = [o_url absoluteString];
2603                 }
2604
2605                 [o_menu insertItemWithTitle: o_doc
2606                     action: @selector(openRecentItem:)
2607                     keyEquivalent: @"" atIndex: 0];
2608
2609                 if( i_nb_docs == 0 )
2610                 {
2611                     break;
2612                 }
2613             }
2614         }
2615         else
2616         {
2617             bEnabled = FALSE;
2618         }
2619     }
2620     return( bEnabled );
2621 }
2622
2623 @end
2624
2625 @implementation VLCMain (Internal)
2626
2627 - (void)handlePortMessage:(NSPortMessage *)o_msg
2628 {
2629     id ** val;
2630     NSData * o_data;
2631     NSValue * o_value;
2632     NSInvocation * o_inv;
2633     NSConditionLock * o_lock;
2634
2635     o_data = [[o_msg components] lastObject];
2636     o_inv = *((NSInvocation **)[o_data bytes]);
2637     [o_inv getArgument: &o_value atIndex: 2];
2638     val = (id **)[o_value pointerValue];
2639     [o_inv setArgument: val[1] atIndex: 2];
2640     o_lock = *(val[0]);
2641
2642     [o_lock lock];
2643     [o_inv invoke];
2644     [o_lock unlockWithCondition: 1];
2645 }
2646
2647 @end