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