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