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