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