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