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