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