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