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