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