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