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