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