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