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