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