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