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