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