]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
c0c86f4c3fa3075edf1892afc2d17d3056612460
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2008 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_keys.h>
34
35 #ifdef HAVE_CONFIG_H
36 #   include "config.h"
37 #endif
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 "sfilters.h"
52 #import "interaction.h"
53 #import "embeddedwindow.h"
54 #import "update.h"
55 #import "AppleRemote.h"
56 #import "eyetv.h"
57 #import "simple_prefs.h"
58
59 #import <vlc_input.h>
60 #import <vlc_interface.h>
61
62 /*****************************************************************************
63  * Local prototypes.
64  *****************************************************************************/
65 static void Run ( intf_thread_t *p_intf );
66
67 /* Quick hack */
68 /*****************************************************************************
69  * VLCApplication implementation (this hack is really disgusting now,
70  *                                feel free to fix.)
71  *****************************************************************************/
72 @interface VLCApplication : NSApplication
73 {
74    libvlc_int_t *o_libvlc;
75 }
76 - (void)setVLC: (libvlc_int_t *)p_libvlc;
77 @end
78
79
80 @implementation VLCApplication
81 - (void)setVLC: (libvlc_int_t *) p_libvlc
82 {
83     o_libvlc = p_libvlc;
84 }
85 - (void)terminate: (id)sender
86 {
87     vlc_object_kill( o_libvlc );
88     [super terminate: sender];
89 }
90 @end
91
92 /*****************************************************************************
93  * OpenIntf: initialize interface
94  *****************************************************************************/
95 int OpenIntf ( vlc_object_t *p_this )
96 {
97     intf_thread_t *p_intf = (intf_thread_t*) p_this;
98
99     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
100     if( p_intf->p_sys == NULL )
101     {
102         return( 1 );
103     }
104
105     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
106
107     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
108
109     p_intf->p_sys->o_sendport = [[NSPort port] retain];
110     p_intf->p_sys->p_sub = msg_Subscribe( p_intf );
111     p_intf->pf_run = Run;
112     p_intf->b_should_run_on_first_thread = true;
113
114     return( 0 );
115 }
116
117 /*****************************************************************************
118  * CloseIntf: destroy interface
119  *****************************************************************************/
120 void CloseIntf ( vlc_object_t *p_this )
121 {
122     intf_thread_t *p_intf = (intf_thread_t*) p_this;
123
124     [[VLCMain sharedInstance] setIntf: nil];
125     
126     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
127
128     [p_intf->p_sys->o_sendport release];
129     [p_intf->p_sys->o_pool release];
130
131     free( p_intf->p_sys );
132 }
133
134 /*****************************************************************************
135  * Run: main loop
136  *****************************************************************************/
137 jmp_buf jmpbuffer;
138
139 static void Run( intf_thread_t *p_intf )
140 {
141     sigset_t set;
142
143     /* Do it again - for some unknown reason, vlc_thread_create() often
144      * fails to go to real-time priority with the first launched thread
145      * (???) --Meuuh */
146     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
147
148     /* Make sure the "force quit" menu item does quit instantly.
149      * VLC overrides SIGTERM which is sent by the "force quit"
150      * menu item to make sure deamon mode quits gracefully, so
151      * we un-override SIGTERM here. */
152     sigemptyset( &set );
153     sigaddset( &set, SIGTERM );
154     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
155
156     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
157
158     /* Install a jmpbuffer to where we can go back before the NSApp exit
159      * see applicationWillTerminate: */
160     /* We need that code to run on main thread */
161     [VLCApplication sharedApplication];
162     [NSApp setVLC: p_intf->p_libvlc];
163
164     [[VLCMain sharedInstance] setIntf: p_intf];
165     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
166
167     /* Install a jmpbuffer to where we can go back before the NSApp exit
168      * see applicationWillTerminate: */
169     if(setjmp(jmpbuffer) == 0)
170         [NSApp run];
171
172     [o_pool release];
173 }
174
175 /*****************************************************************************
176  * ManageThread: An ugly thread that polls
177  *****************************************************************************/
178 static void * ManageThread( void *user_data )
179 {
180     id self = user_data;
181
182     [self manage];
183
184     return NULL;
185 }
186
187 /*****************************************************************************
188  * playlistChanged: Callback triggered by the intf-change playlist
189  * variable, to let the intf update the playlist.
190  *****************************************************************************/
191 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
192                      vlc_value_t old_val, vlc_value_t new_val, void *param )
193 {
194     intf_thread_t * p_intf = VLCIntf;
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     return VLC_SUCCESS;
200 }
201
202 /*****************************************************************************
203  * ShowController: Callback triggered by the show-intf playlist variable
204  * through the ShowIntf-control-intf, to let us show the controller-win;
205  * usually when in fullscreen-mode
206  *****************************************************************************/
207 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
208                      vlc_value_t old_val, vlc_value_t new_val, void *param )
209 {
210     intf_thread_t * p_intf = VLCIntf;
211     p_intf->p_sys->b_intf_show = true;
212     return VLC_SUCCESS;
213 }
214
215 /*****************************************************************************
216  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
217  * variable, to let the intf update the controller.
218  *****************************************************************************/
219 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
220                      vlc_value_t old_val, vlc_value_t new_val, void *param )
221 {
222     intf_thread_t * p_intf = VLCIntf;
223     p_intf->p_sys->b_fullscreen_update = true;
224     return VLC_SUCCESS;
225 }
226
227 /*****************************************************************************
228  * InteractCallback: Callback triggered by the interaction
229  * variable, to let the intf display error and interaction dialogs
230  *****************************************************************************/
231 static int InteractCallback( vlc_object_t *p_this, const char *psz_variable,
232                      vlc_value_t old_val, vlc_value_t new_val, void *param )
233 {
234     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
235     VLCMain *interface = (VLCMain *)param;
236     interaction_dialog_t *p_dialog = (interaction_dialog_t *)(new_val.p_address);
237     NSValue *o_value = [NSValue valueWithPointer:p_dialog];
238  
239     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewInteractionEventNotification" object:[interface getInteractionList]
240      userInfo:[NSDictionary dictionaryWithObject:o_value forKey:@"VLCDialogPointer"]];
241  
242     [o_pool release];
243     return VLC_SUCCESS;
244 }
245
246 static struct
247 {
248     unichar i_nskey;
249     unsigned int i_vlckey;
250 } nskeys_to_vlckeys[] =
251 {
252     { NSUpArrowFunctionKey, KEY_UP },
253     { NSDownArrowFunctionKey, KEY_DOWN },
254     { NSLeftArrowFunctionKey, KEY_LEFT },
255     { NSRightArrowFunctionKey, KEY_RIGHT },
256     { NSF1FunctionKey, KEY_F1 },
257     { NSF2FunctionKey, KEY_F2 },
258     { NSF3FunctionKey, KEY_F3 },
259     { NSF4FunctionKey, KEY_F4 },
260     { NSF5FunctionKey, KEY_F5 },
261     { NSF6FunctionKey, KEY_F6 },
262     { NSF7FunctionKey, KEY_F7 },
263     { NSF8FunctionKey, KEY_F8 },
264     { NSF9FunctionKey, KEY_F9 },
265     { NSF10FunctionKey, KEY_F10 },
266     { NSF11FunctionKey, KEY_F11 },
267     { NSF12FunctionKey, KEY_F12 },
268     { NSHomeFunctionKey, KEY_HOME },
269     { NSEndFunctionKey, KEY_END },
270     { NSPageUpFunctionKey, KEY_PAGEUP },
271     { NSPageDownFunctionKey, KEY_PAGEDOWN },
272     { NSTabCharacter, KEY_TAB },
273     { NSCarriageReturnCharacter, KEY_ENTER },
274     { NSEnterCharacter, KEY_ENTER },
275     { NSBackspaceCharacter, KEY_BACKSPACE },
276     { (unichar) ' ', KEY_SPACE },
277     { (unichar) 0x1b, KEY_ESC },
278     {0,0}
279 };
280
281 unichar VLCKeyToCocoa( unsigned int i_key )
282 {
283     unsigned int i;
284
285     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
286     {
287         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
288         {
289             return nskeys_to_vlckeys[i].i_nskey;
290         }
291     }
292     return (unichar)(i_key & ~KEY_MODIFIER);
293 }
294
295 unsigned int CocoaKeyToVLC( unichar i_key )
296 {
297     unsigned int i;
298
299     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
300     {
301         if( nskeys_to_vlckeys[i].i_nskey == i_key )
302         {
303             return nskeys_to_vlckeys[i].i_vlckey;
304         }
305     }
306     return (unsigned int)i_key;
307 }
308
309 unsigned int VLCModifiersToCocoa( unsigned int i_key )
310 {
311     unsigned int new = 0;
312     if( i_key & KEY_MODIFIER_COMMAND )
313         new |= NSCommandKeyMask;
314     if( i_key & KEY_MODIFIER_ALT )
315         new |= NSAlternateKeyMask;
316     if( i_key & KEY_MODIFIER_SHIFT )
317         new |= NSShiftKeyMask;
318     if( i_key & KEY_MODIFIER_CTRL )
319         new |= NSControlKeyMask;
320     return new;
321 }
322
323 /*****************************************************************************
324  * VLCMain implementation
325  *****************************************************************************/
326 @implementation VLCMain
327
328 static VLCMain *_o_sharedMainInstance = nil;
329
330 + (VLCMain *)sharedInstance
331 {
332     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
333 }
334
335 - (id)init
336 {
337     if( _o_sharedMainInstance) 
338     {
339         [self dealloc];
340         return _o_sharedMainInstance;
341     } 
342     else
343         _o_sharedMainInstance = [super init];
344
345     o_about = [[VLAboutBox alloc] init];
346     o_prefs = nil;
347     o_open = [[VLCOpen alloc] init];
348     o_wizard = [[VLCWizard alloc] init];
349     o_extended = nil;
350     o_bookmarks = [[VLCBookmarks alloc] init];
351     o_embedded_list = [[VLCEmbeddedList alloc] init];
352     o_interaction_list = [[VLCInteractionList alloc] init];
353     o_info = [[VLCInfo alloc] init];
354     o_sfilters = nil;
355 #ifdef UPDATE_CHECK
356     o_update = [[VLCUpdate alloc] init];
357 #endif
358
359     i_lastShownVolume = -1;
360
361     o_remote = [[AppleRemote alloc] init];
362     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
363     [o_remote setDelegate: _o_sharedMainInstance];
364
365     o_eyetv = [[VLCEyeTVController alloc] init];
366
367     /* announce our launch to a potential eyetv plugin */
368     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
369                                                                    object: @"VLCEyeTVSupport"
370                                                                  userInfo: NULL
371                                                        deliverImmediately: YES];
372
373     return _o_sharedMainInstance;
374 }
375
376 - (void)setIntf: (intf_thread_t *)p_mainintf {
377     p_intf = p_mainintf;
378 }
379
380 - (intf_thread_t *)getIntf {
381     return p_intf;
382 }
383
384 - (void)awakeFromNib
385 {
386     unsigned int i_key = 0;
387     playlist_t *p_playlist;
388     vlc_value_t val;
389
390     /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
391     if( nib_main_loaded ) return;
392
393     [self initStrings];
394     [o_window setExcludedFromWindowsMenu: TRUE];
395     [o_msgs_panel setExcludedFromWindowsMenu: TRUE];
396     [o_msgs_panel setDelegate: self];
397
398     i_key = config_GetInt( p_intf, "key-quit" );
399     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
400     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
401     i_key = config_GetInt( p_intf, "key-play-pause" );
402     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
403     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
404     i_key = config_GetInt( p_intf, "key-stop" );
405     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
406     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
407     i_key = config_GetInt( p_intf, "key-faster" );
408     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
409     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
410     i_key = config_GetInt( p_intf, "key-slower" );
411     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
412     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
413     i_key = config_GetInt( p_intf, "key-prev" );
414     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
415     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
416     i_key = config_GetInt( p_intf, "key-next" );
417     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
418     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
419     i_key = config_GetInt( p_intf, "key-jump+short" );
420     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
421     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
422     i_key = config_GetInt( p_intf, "key-jump-short" );
423     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
424     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
425     i_key = config_GetInt( p_intf, "key-jump+medium" );
426     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
427     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
428     i_key = config_GetInt( p_intf, "key-jump-medium" );
429     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
430     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
431     i_key = config_GetInt( p_intf, "key-jump+long" );
432     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
433     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
434     i_key = config_GetInt( p_intf, "key-jump-long" );
435     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
436     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
437     i_key = config_GetInt( p_intf, "key-vol-up" );
438     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
439     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
440     i_key = config_GetInt( p_intf, "key-vol-down" );
441     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
442     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
443     i_key = config_GetInt( p_intf, "key-vol-mute" );
444     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
445     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
446     i_key = config_GetInt( p_intf, "key-fullscreen" );
447     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
448     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
449     i_key = config_GetInt( p_intf, "key-snapshot" );
450     [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
451     [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
452
453     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
454
455     [self setSubmenusEnabled: FALSE];
456     [self manageVolumeSlider];
457     [o_window setDelegate: self];
458  
459     b_restore_size = false;
460     if( [o_window frame].size.height <= 200 )
461     {
462         b_small_window = YES;
463         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
464             [o_window frame].origin.y, [o_window frame].size.width,
465             [o_window minSize].height ) display: YES animate:YES];
466         [o_playlist_view setAutoresizesSubviews: NO];
467     }
468     else
469     {
470         b_small_window = NO;
471         [o_playlist_view setFrame: NSMakeRect( 0, 0, [o_window frame].size.width, [o_window frame].size.height - 95 )];
472         [o_playlist_view setNeedsDisplay:YES];
473         [o_playlist_view setAutoresizesSubviews: YES];
474         [[o_window contentView] addSubview: o_playlist_view];
475     }
476     [self updateTogglePlaylistState];
477
478     o_size_with_playlist = [o_window frame].size;
479
480     p_playlist = pl_Yield( p_intf );
481
482     var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
483     val.b_bool = false;
484
485     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
486     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
487
488     vlc_object_release( p_playlist );
489  
490     var_Create( p_intf, "interaction", VLC_VAR_ADDRESS );
491     var_AddCallback( p_intf, "interaction", InteractCallback, self );
492     p_intf->b_interaction = true;
493
494     /* update the playmode stuff */
495     p_intf->p_sys->b_playmode_update = true;
496
497     [[NSNotificationCenter defaultCenter] addObserver: self
498                                              selector: @selector(refreshVoutDeviceMenu:)
499                                                  name: NSApplicationDidChangeScreenParametersNotification
500                                                object: nil];
501
502     o_img_play = [NSImage imageNamed: @"play"];
503     o_img_pause = [NSImage imageNamed: @"pause"];    
504     
505     [self controlTintChanged];
506
507     [[NSNotificationCenter defaultCenter] addObserver: self
508                                              selector: @selector( controlTintChanged )
509                                                  name: NSControlTintDidChangeNotification
510                                                object: nil];
511     
512     nib_main_loaded = TRUE;
513 }
514
515 - (void)controlTintChanged
516 {
517     BOOL b_playing = NO;
518     
519     if( [o_btn_play alternateImage] == o_img_play_pressed )
520         b_playing = YES;
521     
522     if( [NSColor currentControlTint] == NSGraphiteControlTint )
523     {
524         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
525         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
526         
527         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
528         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
529         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
530         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
531         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
532         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
533         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
534         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
535     }
536     else
537     {
538         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
539         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
540         
541         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
542         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
543         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
544         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
545         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
546         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
547         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
548         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
549     }
550     
551     if( b_playing )
552         [o_btn_play setAlternateImage: o_img_play_pressed];
553     else
554         [o_btn_play setAlternateImage: o_img_pause_pressed];
555 }
556
557 - (void)initStrings
558 {
559     [o_window setTitle: _NS("VLC - Controller")];
560     [self setScrollField:_NS("VLC media player") stopAfter:-1];
561
562     /* button controls */
563     [o_btn_prev setToolTip: _NS("Previous")];
564     [o_btn_rewind setToolTip: _NS("Rewind")];
565     [o_btn_play setToolTip: _NS("Play")];
566     [o_btn_stop setToolTip: _NS("Stop")];
567     [o_btn_ff setToolTip: _NS("Fast Forward")];
568     [o_btn_next setToolTip: _NS("Next")];
569     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
570     [o_volumeslider setToolTip: _NS("Volume")];
571     [o_timeslider setToolTip: _NS("Position")];
572     [o_btn_playlist setToolTip: _NS("Playlist")];
573
574     /* messages panel */
575     [o_msgs_panel setTitle: _NS("Messages")];
576     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog...")];
577
578     /* main menu */
579     [o_mi_about setTitle: [_NS("About VLC media player") \
580         stringByAppendingString: @"..."]];
581     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
582     [o_mi_prefs setTitle: _NS("Preferences...")];
583     [o_mi_add_intf setTitle: _NS("Add Interface")];
584     [o_mu_add_intf setTitle: _NS("Add Interface")];
585     [o_mi_services setTitle: _NS("Services")];
586     [o_mi_hide setTitle: _NS("Hide VLC")];
587     [o_mi_hide_others setTitle: _NS("Hide Others")];
588     [o_mi_show_all setTitle: _NS("Show All")];
589     [o_mi_quit setTitle: _NS("Quit VLC")];
590
591     [o_mu_file setTitle: _ANS("1:File")];
592     [o_mi_open_generic setTitle: _NS("Open File...")];
593     [o_mi_open_file setTitle: _NS("Quick Open File...")];
594     [o_mi_open_disc setTitle: _NS("Open Disc...")];
595     [o_mi_open_net setTitle: _NS("Open Network...")];
596     [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
597     [o_mi_open_recent setTitle: _NS("Open Recent")];
598     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
599     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
600
601     [o_mu_edit setTitle: _NS("Edit")];
602     [o_mi_cut setTitle: _NS("Cut")];
603     [o_mi_copy setTitle: _NS("Copy")];
604     [o_mi_paste setTitle: _NS("Paste")];
605     [o_mi_clear setTitle: _NS("Clear")];
606     [o_mi_select_all setTitle: _NS("Select All")];
607
608     [o_mu_controls setTitle: _NS("Playback")];
609     [o_mi_play setTitle: _NS("Play")];
610     [o_mi_stop setTitle: _NS("Stop")];
611     [o_mi_faster setTitle: _NS("Faster")];
612     [o_mi_slower setTitle: _NS("Slower")];
613     [o_mi_previous setTitle: _NS("Previous")];
614     [o_mi_next setTitle: _NS("Next")];
615     [o_mi_random setTitle: _NS("Random")];
616     [o_mi_repeat setTitle: _NS("Repeat One")];
617     [o_mi_loop setTitle: _NS("Repeat All")];
618     [o_mi_fwd setTitle: _NS("Step Forward")];
619     [o_mi_bwd setTitle: _NS("Step Backward")];
620
621     [o_mi_program setTitle: _NS("Program")];
622     [o_mu_program setTitle: _NS("Program")];
623     [o_mi_title setTitle: _NS("Title")];
624     [o_mu_title setTitle: _NS("Title")];
625     [o_mi_chapter setTitle: _NS("Chapter")];
626     [o_mu_chapter setTitle: _NS("Chapter")];
627
628     [o_mu_audio setTitle: _NS("Audio")];
629     [o_mi_vol_up setTitle: _NS("Volume Up")];
630     [o_mi_vol_down setTitle: _NS("Volume Down")];
631     [o_mi_mute setTitle: _NS("Mute")];
632     [o_mi_audiotrack setTitle: _NS("Audio Track")];
633     [o_mu_audiotrack setTitle: _NS("Audio Track")];
634     [o_mi_channels setTitle: _NS("Audio Channels")];
635     [o_mu_channels setTitle: _NS("Audio Channels")];
636     [o_mi_device setTitle: _NS("Audio Device")];
637     [o_mu_device setTitle: _NS("Audio Device")];
638     [o_mi_visual setTitle: _NS("Visualizations")];
639     [o_mu_visual setTitle: _NS("Visualizations")];
640
641     [o_mu_video setTitle: _NS("Video")];
642     [o_mi_half_window setTitle: _NS("Half Size")];
643     [o_mi_normal_window setTitle: _NS("Normal Size")];
644     [o_mi_double_window setTitle: _NS("Double Size")];
645     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
646     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
647     [o_mi_floatontop setTitle: _NS("Float on Top")];
648     [o_mi_snapshot setTitle: _NS("Snapshot")];
649     [o_mi_videotrack setTitle: _NS("Video Track")];
650     [o_mu_videotrack setTitle: _NS("Video Track")];
651     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
652     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
653     [o_mi_crop setTitle: _NS("Crop")];
654     [o_mu_crop setTitle: _NS("Crop")];
655     [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
656     [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
657     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
658     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
659     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
660     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
661     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
662     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
663
664     [o_mu_window setTitle: _NS("Window")];
665     [o_mi_minimize setTitle: _NS("Minimize Window")];
666     [o_mi_close_window setTitle: _NS("Close Window")];
667     [o_mi_controller setTitle: _NS("Controller...")];
668     [o_mi_equalizer setTitle: _NS("Equalizer...")];
669     [o_mi_extended setTitle: _NS("Extended Controls...")];
670     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
671     [o_mi_playlist setTitle: _NS("Playlist...")];
672     [o_mi_info setTitle: _NS("Media Information...")];
673     [o_mi_messages setTitle: _NS("Messages...")];
674     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
675
676     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
677
678     [o_mu_help setTitle: _NS("Help")];
679     [o_mi_help setTitle: _NS("VLC media player Help...")];
680     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
681     [o_mi_license setTitle: _NS("License")];
682     [o_mi_documentation setTitle: _NS("Online Documentation...")];
683     [o_mi_website setTitle: _NS("VideoLAN Website...")];
684     [o_mi_donation setTitle: _NS("Make a donation...")];
685     [o_mi_forum setTitle: _NS("Online Forum...")];
686
687     /* dock menu */
688     [o_dmi_play setTitle: _NS("Play")];
689     [o_dmi_stop setTitle: _NS("Stop")];
690     [o_dmi_next setTitle: _NS("Next")];
691     [o_dmi_previous setTitle: _NS("Previous")];
692     [o_dmi_mute setTitle: _NS("Mute")];
693  
694     /* vout menu */
695     [o_vmi_play setTitle: _NS("Play")];
696     [o_vmi_stop setTitle: _NS("Stop")];
697     [o_vmi_prev setTitle: _NS("Previous")];
698     [o_vmi_next setTitle: _NS("Next")];
699     [o_vmi_volup setTitle: _NS("Volume Up")];
700     [o_vmi_voldown setTitle: _NS("Volume Down")];
701     [o_vmi_mute setTitle: _NS("Mute")];
702     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
703     [o_vmi_snapshot setTitle: _NS("Snapshot")];
704 }
705
706 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
707 {
708     o_msg_lock = [[NSLock alloc] init];
709     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
710
711     [p_intf->p_sys->o_sendport setDelegate: self];
712     [[NSRunLoop currentRunLoop]
713         addPort: p_intf->p_sys->o_sendport
714         forMode: NSDefaultRunLoopMode];
715
716     /* FIXME: don't poll */
717     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
718                                      target: self selector: @selector(manageIntf:)
719                                    userInfo: nil repeats: FALSE] retain];
720
721     /* Note: we use the pthread API to support pre-10.5 */
722     pthread_create( &manage_thread, NULL, ManageThread, self );
723
724     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
725         var: "intf-add" selector: @selector(toggleVar:)];
726
727     /* check whether the user runs a valid version of OSX; alert is auto-released */
728     if( MACOS_VERSION < 10.4f )
729     {
730         NSAlert *ourAlert;
731         int i_returnValue;
732         ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is not supported")
733                         defaultButton: _NS("Quit")
734                       alternateButton: NULL
735                           otherButton: NULL
736             informativeTextWithFormat: _NS("VLC media player requires Mac OS X 10.4 or higher.")];
737         [ourAlert setAlertStyle: NSCriticalAlertStyle];
738         i_returnValue = [ourAlert runModal];
739         [NSApp terminate: self];
740     }
741
742     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
743 }
744
745 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
746 {
747     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
748     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
749     if( b_autoplay )
750         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
751     else
752         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
753
754     return( TRUE );
755 }
756
757 - (NSString *)localizedString:(const char *)psz
758 {
759     NSString * o_str = nil;
760
761     if( psz != NULL )
762     {
763         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
764
765         if( o_str == NULL )
766         {
767             msg_Err( VLCIntf, "could not translate: %s", psz );
768             return( @"" );
769         }
770     }
771     else
772     {
773         msg_Warn( VLCIntf, "can't translate empty strings" );
774         return( @"" );
775     }
776
777     return( o_str );
778 }
779
780 /* When user click in the Dock icon our double click in the finder */
781 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
782 {    
783     if(!hasVisibleWindows)
784         [o_window makeKeyAndOrderFront:self];
785
786     return YES;
787 }
788
789 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
790 {
791 #ifdef UPDATE_CHECK
792     /* Check for update silently on startup */
793     if( !nib_update_loaded )
794         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
795
796     if([o_update shouldCheckForUpdate])
797         [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:NULL];
798 #endif
799
800     /* Handle sleep notification */
801     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
802            name:NSWorkspaceWillSleepNotification object:nil];
803 }
804
805 /* Listen to the remote in exclusive mode, only when VLC is the active
806    application */
807 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
808 {
809     [o_remote startListening: self];
810 }
811 - (void)applicationDidResignActive:(NSNotification *)aNotification
812 {
813     [o_remote stopListening: self];
814 }
815
816 /* Triggered when the computer goes to sleep */
817 - (void)computerWillSleep: (NSNotification *)notification
818 {
819     /* Pause */
820     if( p_intf->p_sys->i_play_status == PLAYING_S )
821     {
822         vlc_value_t val;
823         val.i_int = config_GetInt( p_intf, "key-play-pause" );
824         var_Set( p_intf->p_libvlc, "key-pressed", val );
825     }
826 }
827
828 /* Helper method for the remote control interface in order to trigger forward/backward and volume
829    increase/decrease as long as the user holds the left/right, plus/minus button */
830 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
831 {
832     if(b_remote_button_hold)
833     {
834         switch([buttonIdentifierNumber intValue])
835         {
836             case kRemoteButtonRight_Hold:
837                   [o_controls forward: self];
838             break;
839             case kRemoteButtonLeft_Hold:
840                   [o_controls backward: self];
841             break;
842             case kRemoteButtonVolume_Plus_Hold:
843                 [o_controls volumeUp: self];
844             break;
845             case kRemoteButtonVolume_Minus_Hold:
846                 [o_controls volumeDown: self];
847             break;
848         }
849         if(b_remote_button_hold)
850         {
851             /* trigger event */
852             [self performSelector:@selector(executeHoldActionForRemoteButton:)
853                          withObject:buttonIdentifierNumber
854                          afterDelay:0.25];
855         }
856     }
857 }
858
859 /* Apple Remote callback */
860 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
861                pressedDown: (BOOL) pressedDown
862                 clickCount: (unsigned int) count
863 {
864     switch( buttonIdentifier )
865     {
866         case kRemoteButtonPlay:
867             if(count >= 2) {
868                 [o_controls toogleFullscreen:self];
869             } else {
870                 [o_controls play: self];
871             }
872             break;
873         case kRemoteButtonVolume_Plus:
874             [o_controls volumeUp: self];
875             break;
876         case kRemoteButtonVolume_Minus:
877             [o_controls volumeDown: self];
878             break;
879         case kRemoteButtonRight:
880             [o_controls next: self];
881             break;
882         case kRemoteButtonLeft:
883             [o_controls prev: self];
884             break;
885         case kRemoteButtonRight_Hold:
886         case kRemoteButtonLeft_Hold:
887         case kRemoteButtonVolume_Plus_Hold:
888         case kRemoteButtonVolume_Minus_Hold:
889             /* simulate an event as long as the user holds the button */
890             b_remote_button_hold = pressedDown;
891             if( pressedDown )
892             {
893                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
894                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
895                            withObject:buttonIdentifierNumber];
896             }
897             break;
898         case kRemoteButtonMenu:
899             [o_controls showPosition: self];
900             break;
901         default:
902             /* Add here whatever you want other buttons to do */
903             break;
904     }
905 }
906
907 - (char *)delocalizeString:(NSString *)id
908 {
909     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
910                           allowLossyConversion: NO];
911     char * psz_string;
912
913     if( o_data == nil )
914     {
915         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
916                      allowLossyConversion: YES];
917         psz_string = malloc( [o_data length] + 1 );
918         [o_data getBytes: psz_string];
919         psz_string[ [o_data length] ] = '\0';
920         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
921                  psz_string );
922     }
923     else
924     {
925         psz_string = malloc( [o_data length] + 1 );
926         [o_data getBytes: psz_string];
927         psz_string[ [o_data length] ] = '\0';
928     }
929
930     return psz_string;
931 }
932
933 /* i_width is in pixels */
934 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
935 {
936     NSMutableString *o_wrapped;
937     NSString *o_out_string;
938     NSRange glyphRange, effectiveRange, charRange;
939     NSRect lineFragmentRect;
940     unsigned glyphIndex, breaksInserted = 0;
941
942     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
943         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
944         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
945     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
946     NSTextContainer *o_container = [[NSTextContainer alloc]
947         initWithContainerSize: NSMakeSize(i_width, 2000)];
948
949     [o_layout_manager addTextContainer: o_container];
950     [o_container release];
951     [o_storage addLayoutManager: o_layout_manager];
952     [o_layout_manager release];
953
954     o_wrapped = [o_in_string mutableCopy];
955     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
956
957     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
958             glyphIndex += effectiveRange.length) {
959         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
960                                             effectiveRange: &effectiveRange];
961         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
962                                     actualGlyphRange: &effectiveRange];
963         if([o_wrapped lineRangeForRange:
964                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
965             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
966             breaksInserted++;
967         }
968     }
969     o_out_string = [NSString stringWithString: o_wrapped];
970     [o_wrapped release];
971     [o_storage release];
972
973     return o_out_string;
974 }
975
976
977 /*****************************************************************************
978  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
979  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
980  * otherwise ignore it and return NO (where it will get handled by Cocoa).
981  *****************************************************************************/
982 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
983 {
984     unichar key = 0;
985     vlc_value_t val;
986     unsigned int i_pressed_modifiers = 0;
987     struct hotkey *p_hotkeys;
988     int i;
989
990     val.i_int = 0;
991     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
992
993     i_pressed_modifiers = [o_event modifierFlags];
994
995     if( i_pressed_modifiers & NSShiftKeyMask )
996         val.i_int |= KEY_MODIFIER_SHIFT;
997     if( i_pressed_modifiers & NSControlKeyMask )
998         val.i_int |= KEY_MODIFIER_CTRL;
999     if( i_pressed_modifiers & NSAlternateKeyMask )
1000         val.i_int |= KEY_MODIFIER_ALT;
1001     if( i_pressed_modifiers & NSCommandKeyMask )
1002         val.i_int |= KEY_MODIFIER_COMMAND;
1003
1004     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1005
1006     switch( key )
1007     {
1008         case NSDeleteCharacter:
1009         case NSDeleteFunctionKey:
1010         case NSDeleteCharFunctionKey:
1011         case NSBackspaceCharacter:
1012         case NSUpArrowFunctionKey:
1013         case NSDownArrowFunctionKey:
1014         case NSRightArrowFunctionKey:
1015         case NSLeftArrowFunctionKey:
1016         case NSEnterCharacter:
1017         case NSCarriageReturnCharacter:
1018             return NO;
1019     }
1020
1021     val.i_int |= CocoaKeyToVLC( key );
1022
1023     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1024     {
1025         if( p_hotkeys[i].i_key == val.i_int )
1026         {
1027             var_Set( p_intf->p_libvlc, "key-pressed", val );
1028             return YES;
1029         }
1030     }
1031
1032     return NO;
1033 }
1034
1035 - (id)getControls
1036 {
1037     if( o_controls )
1038         return o_controls;
1039
1040     return nil;
1041 }
1042
1043 - (id)getSimplePreferences
1044 {
1045     if( !o_sprefs )
1046         return nil;
1047
1048     if( !nib_prefs_loaded )
1049         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1050
1051     return o_sprefs;
1052 }
1053
1054 - (id)getPreferences
1055 {
1056     if( !o_prefs )
1057         return nil;
1058
1059     if( !nib_prefs_loaded )
1060         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1061
1062     return o_prefs;
1063 }
1064
1065 - (id)getPlaylist
1066 {
1067     if( o_playlist )
1068         return o_playlist;
1069
1070     return nil;
1071 }
1072
1073 - (id)getInfo
1074 {
1075     if( o_info )
1076         return o_info;
1077
1078     return nil;
1079 }
1080
1081 - (id)getWizard
1082 {
1083     if( o_wizard )
1084         return o_wizard;
1085
1086     return nil;
1087 }
1088
1089 - (id)getBookmarks
1090 {
1091     if( o_bookmarks )
1092         return o_bookmarks;
1093
1094     return nil;
1095 }
1096
1097 - (id)getEmbeddedList
1098 {
1099     if( o_embedded_list )
1100         return o_embedded_list;
1101
1102     return nil;
1103 }
1104
1105 - (id)getInteractionList
1106 {
1107     if( o_interaction_list )
1108         return o_interaction_list;
1109
1110     return nil;
1111 }
1112
1113 - (id)getMainIntfPgbar
1114 {
1115     if( o_main_pgbar )
1116         return o_main_pgbar;
1117
1118     return nil;
1119 }
1120
1121 - (id)getControllerWindow
1122 {
1123     if( o_window )
1124         return o_window;
1125     return nil;
1126 }
1127
1128 - (id)getVoutMenu
1129 {
1130     return o_vout_menu;
1131 }
1132
1133 - (id)getEyeTVController
1134 {
1135     if( o_eyetv )
1136         return o_eyetv;
1137
1138     return nil;
1139 }
1140
1141 - (void)manage
1142 {
1143     playlist_t * p_playlist;
1144
1145     /* new thread requires a new pool */
1146     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
1147
1148     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1149
1150     p_playlist = pl_Yield( p_intf );
1151
1152     var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1153     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1154     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1155     var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
1156     var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1157
1158     pl_Release( p_intf );
1159
1160     vlc_object_lock( p_intf );
1161     while( vlc_object_alive( p_intf ) )
1162     {
1163         vlc_mutex_lock( &p_intf->change_lock );
1164
1165         if( p_intf->p_sys->p_input == NULL )
1166         {
1167             p_intf->p_sys->p_input = p_playlist->p_input;
1168
1169             /* Refresh the interface */
1170             if( p_intf->p_sys->p_input )
1171             {
1172                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1173                 p_intf->p_sys->b_input_update = true;
1174             }
1175         }
1176         else if( !vlc_object_alive (p_intf->p_sys->p_input) || p_intf->p_sys->p_input->b_dead )
1177         {
1178             /* input stopped */
1179             p_intf->p_sys->b_intf_update = true;
1180             p_intf->p_sys->i_play_status = END_S;
1181             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1182             p_intf->p_sys->p_input = NULL;
1183         }
1184
1185         /* Manage volume status */
1186         [self manageVolumeSlider];
1187
1188         vlc_mutex_unlock( &p_intf->change_lock );
1189
1190         vlc_object_timedwait( p_intf, 100000 + mdate());
1191     }
1192     vlc_object_unlock( p_intf );
1193     [o_pool release];
1194
1195     var_DelCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1196     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1197     var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1198     var_DelCallback( p_playlist, "item-append", PlaylistChanged, self );
1199     var_DelCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1200
1201     pthread_testcancel(); /* If we were cancelled stop here */
1202
1203     msg_Dbg( p_intf, "Killing the Mac OS X module" );
1204
1205     /* We are dead, terminate */
1206     [NSApp performSelectorOnMainThread: @selector(terminate:) withObject:nil waitUntilDone:NO];
1207 }
1208
1209 - (void)manageIntf:(NSTimer *)o_timer
1210 {
1211     vlc_value_t val;
1212     playlist_t * p_playlist;
1213     input_thread_t * p_input;
1214
1215     if( p_intf->p_sys->b_input_update )
1216     {
1217         /* Called when new input is opened */
1218         p_intf->p_sys->b_current_title_update = true;
1219         p_intf->p_sys->b_intf_update = true;
1220         p_intf->p_sys->b_input_update = false;
1221     }
1222     if( p_intf->p_sys->b_intf_update )
1223     {
1224         bool b_input = false;
1225         bool b_plmul = false;
1226         bool b_control = false;
1227         bool b_seekable = false;
1228         bool b_chapters = false;
1229
1230         playlist_t * p_playlist = pl_Yield( p_intf );
1231     /* TODO: fix i_size use */
1232         b_plmul = p_playlist->items.i_size > 1;
1233
1234         p_input = vlc_object_find( p_playlist, VLC_OBJECT_INPUT,
1235                                    FIND_CHILD );
1236
1237         if( ( b_input = ( p_input != NULL ) ) )
1238         {
1239             /* seekable streams */
1240             b_seekable = var_GetBool( p_input, "seekable" );
1241
1242             /* check whether slow/fast motion is possible */
1243             b_control = p_input->b_can_pace_control;
1244
1245             /* chapters & titles */
1246             //b_chapters = p_input->stream.i_area_nb > 1;
1247             vlc_object_release( p_input );
1248         }
1249         vlc_object_release( p_playlist );
1250
1251         [o_btn_stop setEnabled: b_input];
1252         [o_btn_ff setEnabled: b_seekable];
1253         [o_btn_rewind setEnabled: b_seekable];
1254         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1255         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1256
1257         [o_timeslider setFloatValue: 0.0];
1258         [o_timeslider setEnabled: b_seekable];
1259         [o_timefield setStringValue: @"00:00"];
1260         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1261         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1262
1263         [o_embedded_window setSeekable: b_seekable];
1264
1265         p_intf->p_sys->b_current_title_update = true;
1266         
1267         p_intf->p_sys->b_intf_update = false;
1268     }
1269
1270     if( p_intf->p_sys->b_playmode_update )
1271     {
1272         [o_playlist playModeUpdated];
1273         p_intf->p_sys->b_playmode_update = false;
1274     }
1275     if( p_intf->p_sys->b_playlist_update )
1276     {
1277         [o_playlist playlistUpdated];
1278         p_intf->p_sys->b_playlist_update = false;
1279     }
1280
1281     if( p_intf->p_sys->b_fullscreen_update )
1282     {
1283         p_intf->p_sys->b_fullscreen_update = false;
1284     }
1285
1286     if( p_intf->p_sys->b_intf_show )
1287     {
1288         [o_window makeKeyAndOrderFront: self];
1289
1290         p_intf->p_sys->b_intf_show = false;
1291     }
1292
1293     p_playlist = pl_Yield( p_intf );
1294     p_input = vlc_object_find( p_playlist, VLC_OBJECT_INPUT,
1295                                FIND_CHILD );
1296
1297     if( p_input && vlc_object_alive (p_input) )
1298     {
1299         vlc_value_t val;
1300
1301         if( p_intf->p_sys->b_current_title_update )
1302         {
1303             NSString *o_temp;
1304
1305             if( p_playlist->status.p_item == NULL )
1306             {
1307                 vlc_object_release( p_input );
1308                 pl_Release( p_intf );
1309                 goto end;
1310             }
1311             if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1312                 o_temp = [NSString stringWithUTF8String: 
1313                     input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1314             else
1315                 o_temp = [NSString stringWithUTF8String:
1316                     p_playlist->status.p_item->p_input->psz_name];
1317             [self setScrollField: o_temp stopAfter:-1];
1318             [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1319
1320             [[o_controls getVoutView] updateTitle];
1321  
1322             [o_playlist updateRowSelection];
1323             p_intf->p_sys->b_current_title_update = FALSE;
1324         }
1325
1326         if( [o_timeslider isEnabled] )
1327         {
1328             /* Update the slider */
1329             vlc_value_t time;
1330             NSString * o_time;
1331             vlc_value_t pos;
1332             char psz_time[MSTRTIME_MAX_SIZE];
1333             float f_updated;
1334
1335             var_Get( p_input, "position", &pos );
1336             f_updated = 10000. * pos.f_float;
1337             [o_timeslider setFloatValue: f_updated];
1338
1339             var_Get( p_input, "time", &time );
1340
1341             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1342
1343             [o_timefield setStringValue: o_time];
1344             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1345             [o_embedded_window setTime: o_time position: f_updated];
1346         }
1347
1348         if( p_intf->p_sys->b_volume_update )
1349         {
1350             NSString *o_text;
1351             int i_volume_step = 0;
1352             o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1353             if( i_lastShownVolume != -1 )
1354             [self setScrollField:o_text stopAfter:1000000];
1355             i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1356             [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1357             [o_volumeslider setEnabled: TRUE];
1358             [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1359             p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1360             p_intf->p_sys->b_volume_update = FALSE;
1361         }
1362
1363         /* Manage Playing status */
1364         var_Get( p_input, "state", &val );
1365         if( p_intf->p_sys->i_play_status != val.i_int )
1366         {
1367             p_intf->p_sys->i_play_status = val.i_int;
1368             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1369             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1370         }
1371         vlc_object_release( p_input );
1372     }
1373     else
1374     {
1375         p_intf->p_sys->i_play_status = END_S;
1376         p_intf->p_sys->b_playlist_update = true;
1377         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1378         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1379         [self setSubmenusEnabled: FALSE];
1380     }
1381     pl_Release( p_intf );
1382
1383 end:
1384     [self updateMessageArray];
1385
1386     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1387         [self resetScrollField];
1388
1389     [interfaceTimer autorelease];
1390
1391     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1392         target: self selector: @selector(manageIntf:)
1393         userInfo: nil repeats: FALSE] retain];
1394 }
1395
1396 - (void)setupMenus
1397 {
1398     playlist_t * p_playlist = pl_Yield( p_intf );
1399     input_thread_t * p_input = p_playlist->p_input;
1400     if( p_input != NULL )
1401     {
1402         vlc_object_yield( p_input );
1403         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1404             var: "program" selector: @selector(toggleVar:)];
1405
1406         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1407             var: "title" selector: @selector(toggleVar:)];
1408
1409         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1410             var: "chapter" selector: @selector(toggleVar:)];
1411
1412         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1413             var: "audio-es" selector: @selector(toggleVar:)];
1414
1415         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1416             var: "video-es" selector: @selector(toggleVar:)];
1417
1418         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1419             var: "spu-es" selector: @selector(toggleVar:)];
1420
1421         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1422                                                     FIND_ANYWHERE );
1423         if( p_aout != NULL )
1424         {
1425             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1426                 var: "audio-channels" selector: @selector(toggleVar:)];
1427
1428             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1429                 var: "audio-device" selector: @selector(toggleVar:)];
1430
1431             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1432                 var: "visual" selector: @selector(toggleVar:)];
1433             vlc_object_release( (vlc_object_t *)p_aout );
1434         }
1435
1436         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1437                                                             FIND_ANYWHERE );
1438
1439         if( p_vout != NULL )
1440         {
1441             vlc_object_t * p_dec_obj;
1442
1443             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1444                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1445
1446             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1447                 var: "crop" selector: @selector(toggleVar:)];
1448
1449             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1450                 var: "video-device" selector: @selector(toggleVar:)];
1451
1452             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1453                 var: "deinterlace" selector: @selector(toggleVar:)];
1454
1455             p_dec_obj = (vlc_object_t *)vlc_object_find(
1456                                                  (vlc_object_t *)p_vout,
1457                                                  VLC_OBJECT_DECODER,
1458                                                  FIND_PARENT );
1459             if( p_dec_obj != NULL )
1460             {
1461                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1462                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1463                     @selector(toggleVar:)];
1464
1465                 vlc_object_release(p_dec_obj);
1466             }
1467             vlc_object_release( (vlc_object_t *)p_vout );
1468         }
1469         vlc_object_release( p_input );
1470     }
1471     vlc_object_release( p_playlist );
1472 }
1473
1474 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1475 {
1476     int x,y = 0;
1477     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1478                                               FIND_ANYWHERE );
1479  
1480     if(! p_vout )
1481         return;
1482  
1483     /* clean the menu before adding new entries */
1484     if( [o_mi_screen hasSubmenu] )
1485     {
1486         y = [[o_mi_screen submenu] numberOfItems] - 1;
1487         msg_Dbg( VLCIntf, "%i items in submenu", y );
1488         while( x != y )
1489         {
1490             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1491             [[o_mi_screen submenu] removeItemAtIndex: x];
1492             x++;
1493         }
1494     }
1495
1496     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1497                              var: "video-device" selector: @selector(toggleVar:)];
1498     vlc_object_release( (vlc_object_t *)p_vout );
1499 }
1500
1501 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1502 {
1503     if( timeout != -1 )
1504         i_end_scroll = mdate() + timeout;
1505     else
1506         i_end_scroll = -1;
1507     [o_scrollfield setStringValue: o_string];
1508 }
1509
1510 - (void)resetScrollField
1511 {
1512     playlist_t * p_playlist = pl_Yield( p_intf );
1513     input_thread_t * p_input = p_playlist->p_input;
1514
1515     i_end_scroll = -1;
1516     if( p_input && vlc_object_alive (p_input) )
1517     {
1518         NSString *o_temp;
1519         vlc_object_yield( p_input );
1520         if( input_item_GetNowPlaying ( p_playlist->status.p_item->p_input ) )
1521             o_temp = [NSString stringWithUTF8String: 
1522                 input_item_GetNowPlaying ( p_playlist->status.p_item->p_input )];
1523         else
1524             o_temp = [NSString stringWithUTF8String:
1525                 p_playlist->status.p_item->p_input->psz_name];
1526         [self setScrollField: o_temp stopAfter:-1];
1527         [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1528         vlc_object_release( p_input );
1529         vlc_object_release( p_playlist );
1530         return;
1531     }
1532     vlc_object_release( p_playlist );
1533     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1534 }
1535
1536 - (void)updateMessageArray
1537 {
1538     int i_start, i_stop;
1539
1540     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1541     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1542     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1543
1544     if( p_intf->p_sys->p_sub->i_start != i_stop )
1545     {
1546         NSColor *o_white = [NSColor whiteColor];
1547         NSColor *o_red = [NSColor redColor];
1548         NSColor *o_yellow = [NSColor yellowColor];
1549         NSColor *o_gray = [NSColor grayColor];
1550
1551         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1552         static const char * ppsz_type[4] = { ": ", " error: ",
1553                                              " warning: ", " debug: " };
1554
1555         for( i_start = p_intf->p_sys->p_sub->i_start;
1556              i_start != i_stop;
1557              i_start = (i_start+1) % VLC_MSG_QSIZE )
1558         {
1559             NSString *o_msg;
1560             NSDictionary *o_attr;
1561             NSAttributedString *o_msg_color;
1562
1563             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1564
1565             [o_msg_lock lock];
1566
1567             if( [o_msg_arr count] + 2 > 400 )
1568             {
1569                 unsigned rid[] = { 0, 1 };
1570                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1571                            numIndices: sizeof(rid)/sizeof(rid[0])];
1572             }
1573
1574             o_attr = [NSDictionary dictionaryWithObject: o_gray
1575                 forKey: NSForegroundColorAttributeName];
1576             o_msg = [NSString stringWithFormat: @"%s%s",
1577                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1578                 ppsz_type[i_type]];
1579             o_msg_color = [[NSAttributedString alloc]
1580                 initWithString: o_msg attributes: o_attr];
1581             [o_msg_arr addObject: [o_msg_color autorelease]];
1582
1583             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1584                 forKey: NSForegroundColorAttributeName];
1585             o_msg = [NSString stringWithFormat: @"%s\n",
1586                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1587             o_msg_color = [[NSAttributedString alloc]
1588                 initWithString: o_msg attributes: o_attr];
1589             [o_msg_arr addObject: [o_msg_color autorelease]];
1590
1591             [o_msg_lock unlock];
1592         }
1593
1594         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1595         p_intf->p_sys->p_sub->i_start = i_start;
1596         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1597     }
1598 }
1599
1600 - (void)playStatusUpdated:(int)i_status
1601 {
1602     if( i_status == PLAYING_S )
1603     {
1604         [[[self getControls] getFSPanel] setPause];
1605         [o_btn_play setImage: o_img_pause];
1606         [o_btn_play setAlternateImage: o_img_pause_pressed];
1607         [o_btn_play setToolTip: _NS("Pause")];
1608         [o_mi_play setTitle: _NS("Pause")];
1609         [o_dmi_play setTitle: _NS("Pause")];
1610         [o_vmi_play setTitle: _NS("Pause")];
1611     }
1612     else
1613     {
1614         [[[self getControls] getFSPanel] setPlay];
1615         [o_btn_play setImage: o_img_play];
1616         [o_btn_play setAlternateImage: o_img_play_pressed];
1617         [o_btn_play setToolTip: _NS("Play")];
1618         [o_mi_play setTitle: _NS("Play")];
1619         [o_dmi_play setTitle: _NS("Play")];
1620         [o_vmi_play setTitle: _NS("Play")];
1621     }
1622 }
1623
1624 - (void)setSubmenusEnabled:(BOOL)b_enabled
1625 {
1626     [o_mi_program setEnabled: b_enabled];
1627     [o_mi_title setEnabled: b_enabled];
1628     [o_mi_chapter setEnabled: b_enabled];
1629     [o_mi_audiotrack setEnabled: b_enabled];
1630     [o_mi_visual setEnabled: b_enabled];
1631     [o_mi_videotrack setEnabled: b_enabled];
1632     [o_mi_subtitle setEnabled: b_enabled];
1633     [o_mi_channels setEnabled: b_enabled];
1634     [o_mi_deinterlace setEnabled: b_enabled];
1635     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1636     [o_mi_device setEnabled: b_enabled];
1637     [o_mi_screen setEnabled: b_enabled];
1638     [o_mi_aspect_ratio setEnabled: b_enabled];
1639     [o_mi_crop setEnabled: b_enabled];
1640 }
1641
1642 - (void)manageVolumeSlider
1643 {
1644     audio_volume_t i_volume;
1645     aout_VolumeGet( p_intf, &i_volume );
1646
1647     if( i_volume != i_lastShownVolume )
1648     {
1649         i_lastShownVolume = i_volume;
1650         p_intf->p_sys->b_volume_update = TRUE;
1651     }
1652 }
1653
1654 - (IBAction)timesliderUpdate:(id)sender
1655 {
1656     float f_updated;
1657     playlist_t * p_playlist;
1658     input_thread_t * p_input;
1659
1660     switch( [[NSApp currentEvent] type] )
1661     {
1662         case NSLeftMouseUp:
1663         case NSLeftMouseDown:
1664         case NSLeftMouseDragged:
1665             f_updated = [sender floatValue];
1666             break;
1667
1668         default:
1669             return;
1670     }
1671     p_playlist = pl_Yield( p_intf );
1672     p_input = p_playlist->p_input;
1673     if( p_input != NULL )
1674     {
1675         vlc_value_t time;
1676         vlc_value_t pos;
1677         NSString * o_time;
1678         char psz_time[MSTRTIME_MAX_SIZE];
1679         vlc_object_yield( p_input );
1680
1681         pos.f_float = f_updated / 10000.;
1682         var_Set( p_input, "position", pos );
1683         [o_timeslider setFloatValue: f_updated];
1684
1685         var_Get( p_input, "time", &time );
1686
1687         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1688         [o_timefield setStringValue: o_time];
1689         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1690         [o_embedded_window setTime: o_time position: f_updated];
1691         vlc_object_release( p_input );
1692     }
1693     vlc_object_release( p_playlist );
1694 }
1695
1696 - (void)applicationWillTerminate:(NSNotification *)notification
1697 {
1698     playlist_t * p_playlist;
1699     vout_thread_t * p_vout;
1700     int returnedValue = 0;
1701  
1702     msg_Dbg( p_intf, "Terminating" );
1703
1704     /* Make sure the manage_thread won't call -terminate: again */
1705     pthread_cancel( manage_thread );
1706
1707     /* Make sure the intf object is getting killed */
1708     vlc_object_kill( p_intf );
1709
1710     /* Make sure our manage_thread ends */
1711     pthread_join( manage_thread, NULL );
1712
1713     /* Make sure the interfaceTimer is destroyed */
1714     [interfaceTimer invalidate];
1715     [interfaceTimer release];
1716     interfaceTimer = nil;
1717
1718     /* make sure that the current volume is saved */
1719     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
1720     returnedValue = config_SaveConfigFile( p_intf->p_libvlc, "main" );
1721     if( returnedValue != 0 )
1722         msg_Err( p_intf,
1723                  "error while saving volume in osx's terminate method (%i)",
1724                  returnedValue );
1725
1726     /* save the prefs if they were changed in the extended panel */
1727     if(o_extended && [o_extended getConfigChanged])
1728     {
1729         [o_extended savePrefs];
1730     }
1731  
1732     p_intf->b_interaction = false;
1733     var_DelCallback( p_intf, "interaction", InteractCallback, self );
1734
1735     /* remove global observer watching for vout device changes correctly */
1736     [[NSNotificationCenter defaultCenter] removeObserver: self];
1737
1738     /* release some other objects here, because it isn't sure whether dealloc
1739      * will be called later on */
1740
1741     if( nib_about_loaded )
1742         [o_about release];
1743
1744     if( nib_prefs_loaded )
1745     {
1746         [o_sprefs release];
1747         [o_prefs release];
1748     }
1749
1750     if( nib_open_loaded )
1751         [o_open release];
1752
1753     if( nib_extended_loaded )
1754     {
1755         [o_extended release];
1756     }
1757
1758     if( nib_bookmarks_loaded )
1759         [o_bookmarks release];
1760
1761     if( nib_info_loaded )
1762         [o_info release];
1763     
1764     if( nib_wizard_loaded )
1765         [o_wizard release];
1766  
1767     [o_embedded_list release];
1768     [o_interaction_list release];
1769     [o_eyetv release];
1770
1771     [o_img_pause_pressed release];
1772     [o_img_play_pressed release];
1773     [o_img_pause release];
1774     [o_img_play release];
1775
1776     [o_msg_arr removeAllObjects];
1777     [o_msg_arr release];
1778
1779     [o_msg_lock release];
1780
1781     /* write cached user defaults to disk */
1782     [[NSUserDefaults standardUserDefaults] synchronize];
1783
1784     vlc_object_kill( p_intf->p_libvlc );
1785
1786     /* Go back to Run() and make libvlc exit properly */
1787     if( jmpbuffer )
1788         longjmp( jmpbuffer, 1 );
1789     /* not reached */
1790 }
1791
1792
1793 - (IBAction)clearRecentItems:(id)sender
1794 {
1795     [[NSDocumentController sharedDocumentController]
1796                           clearRecentDocuments: nil];
1797 }
1798
1799 - (void)openRecentItem:(id)sender
1800 {
1801     [self application: nil openFile: [sender title]];
1802 }
1803
1804 - (IBAction)intfOpenFile:(id)sender
1805 {
1806     if( !nib_open_loaded )
1807     {
1808         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1809         [o_open awakeFromNib];
1810         [o_open openFile];
1811     } else {
1812         [o_open openFile];
1813     }
1814 }
1815
1816 - (IBAction)intfOpenFileGeneric:(id)sender
1817 {
1818     if( !nib_open_loaded )
1819     {
1820         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1821         [o_open awakeFromNib];
1822         [o_open openFileGeneric];
1823     } else {
1824         [o_open openFileGeneric];
1825     }
1826 }
1827
1828 - (IBAction)intfOpenDisc:(id)sender
1829 {
1830     if( !nib_open_loaded )
1831     {
1832         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1833         [o_open awakeFromNib];
1834         [o_open openDisc];
1835     } else {
1836         [o_open openDisc];
1837     }
1838 }
1839
1840 - (IBAction)intfOpenNet:(id)sender
1841 {
1842     if( !nib_open_loaded )
1843     {
1844         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1845         [o_open awakeFromNib];
1846         [o_open openNet];
1847     } else {
1848         [o_open openNet];
1849     }
1850 }
1851
1852 - (IBAction)intfOpenCapture:(id)sender
1853 {
1854     if( !nib_open_loaded )
1855     {
1856         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1857         [o_open awakeFromNib];
1858         [o_open openCapture];
1859     } else {
1860         [o_open openCapture];
1861     }
1862 }
1863
1864 - (IBAction)showWizard:(id)sender
1865 {
1866     if( !nib_wizard_loaded )
1867     {
1868         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1869         [o_wizard initStrings];
1870         [o_wizard resetWizard];
1871         [o_wizard showWizard];
1872     } else {
1873         [o_wizard resetWizard];
1874         [o_wizard showWizard];
1875     }
1876 }
1877
1878 - (IBAction)showExtended:(id)sender
1879 {
1880     if( o_extended == nil )
1881         o_extended = [[VLCExtended alloc] init];
1882
1883     if( !nib_extended_loaded )
1884         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
1885
1886     [o_extended showPanel];
1887 }
1888
1889 - (IBAction)showSFilters:(id)sender
1890 {
1891     if( o_sfilters == nil )
1892     {
1893         o_sfilters = [[VLCsFilters alloc] init];
1894     }
1895     if( !nib_sfilters_loaded )
1896     {
1897         nib_sfilters_loaded = [NSBundle loadNibNamed:@"SFilters" owner:self];
1898         [o_sfilters initStrings];
1899         [o_sfilters showAsPanel];
1900     } else {
1901         [o_sfilters showAsPanel];
1902     }
1903 }
1904
1905 - (IBAction)showBookmarks:(id)sender
1906 {
1907     /* we need the wizard-nib for the bookmarks's extract functionality */
1908     if( !nib_wizard_loaded )
1909     {
1910         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1911         [o_wizard initStrings];
1912     }
1913  
1914     if( !nib_bookmarks_loaded )
1915         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
1916
1917     [o_bookmarks showBookmarks];
1918 }
1919
1920 - (IBAction)viewAbout:(id)sender
1921 {
1922     if( !nib_about_loaded )
1923         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1924
1925     [o_about showAbout];
1926 }
1927
1928 - (IBAction)showLicense:(id)sender
1929 {
1930     if( !nib_about_loaded )
1931         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1932
1933     [o_about showGPL: sender];
1934 }
1935     
1936 - (IBAction)viewPreferences:(id)sender
1937 {
1938     if( !nib_prefs_loaded )
1939     {
1940         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1941         o_sprefs = [[VLCSimplePrefs alloc] init];
1942         o_prefs= [[VLCPrefs alloc] init];
1943     }
1944
1945     if( sender == o_mi_sprefs )
1946     {
1947         [o_sprefs showSimplePrefs];
1948     }
1949     else
1950         [o_prefs showPrefs];
1951 }
1952
1953 - (IBAction)checkForUpdate:(id)sender
1954 {
1955 #ifdef UPDATE_CHECK
1956     if( !nib_update_loaded )
1957         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
1958     [o_update showUpdateWindow];
1959 #else
1960     msg_Err( VLCIntf, "Update checker wasn't enabled in this build" );
1961     intf_UserFatal( VLCIntf, false, _("Update check failed"), _("Checking for updates was not enabled in this build.") );
1962 #endif
1963 }
1964
1965 - (IBAction)viewHelp:(id)sender
1966 {
1967     if( !nib_about_loaded )
1968     {
1969         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1970         [o_about showHelp];
1971     }
1972     else
1973         [o_about showHelp];
1974 }
1975
1976 - (IBAction)openReadMe:(id)sender
1977 {
1978     NSString * o_path = [[NSBundle mainBundle]
1979         pathForResource: @"README.MacOSX" ofType: @"rtf"];
1980
1981     [[NSWorkspace sharedWorkspace] openFile: o_path
1982                                    withApplication: @"TextEdit"];
1983 }
1984
1985 - (IBAction)openDocumentation:(id)sender
1986 {
1987     NSURL * o_url = [NSURL URLWithString:
1988         @"http://www.videolan.org/doc/"];
1989
1990     [[NSWorkspace sharedWorkspace] openURL: o_url];
1991 }
1992
1993 - (IBAction)openWebsite:(id)sender
1994 {
1995     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
1996
1997     [[NSWorkspace sharedWorkspace] openURL: o_url];
1998 }
1999
2000 - (IBAction)openForum:(id)sender
2001 {
2002     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2003
2004     [[NSWorkspace sharedWorkspace] openURL: o_url];
2005 }
2006
2007 - (IBAction)openDonate:(id)sender
2008 {
2009     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2010
2011     [[NSWorkspace sharedWorkspace] openURL: o_url];
2012 }
2013
2014 - (IBAction)openCrashLog:(id)sender
2015 {
2016     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
2017                                     stringByExpandingTildeInPath];
2018
2019
2020     if( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
2021     {
2022         [[NSWorkspace sharedWorkspace] openFile: o_path
2023                                     withApplication: @"Console"];
2024     }
2025     else
2026     {
2027         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.") );
2028
2029     }
2030 }
2031
2032 - (IBAction)viewErrorsAndWarnings:(id)sender
2033 {
2034     [[[self getInteractionList] getErrorPanel] showPanel];
2035 }
2036
2037 - (IBAction)showMessagesPanel:(id)sender
2038 {
2039     [o_msgs_panel makeKeyAndOrderFront: sender];
2040 }
2041
2042 - (IBAction)showInformationPanel:(id)sender
2043 {
2044     if(! nib_info_loaded )
2045         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: self];
2046     
2047     [o_info initPanel];
2048 }
2049
2050 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2051 {
2052     if( [o_notification object] == o_msgs_panel )
2053     {
2054         id o_msg;
2055         NSEnumerator * o_enum;
2056
2057         [o_messages setString: @""];
2058
2059         [o_msg_lock lock];
2060
2061         o_enum = [o_msg_arr objectEnumerator];
2062
2063         while( ( o_msg = [o_enum nextObject] ) != nil )
2064         {
2065             [o_messages insertText: o_msg];
2066         }
2067
2068         [o_msg_lock unlock];
2069     }
2070 }
2071
2072 - (IBAction)togglePlaylist:(id)sender
2073 {
2074     NSRect o_rect = [o_window frame];
2075     /*First, check if the playlist is visible*/
2076     if( o_rect.size.height <= 200 )
2077     {
2078         o_restore_rect = o_rect;
2079         b_restore_size = true;
2080         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2081         /* make large */
2082         if( o_size_with_playlist.height > 200 )
2083         {
2084             o_rect.size.height = o_size_with_playlist.height;
2085         } else {
2086             o_rect.size.height = 500;
2087         }
2088  
2089         if( o_size_with_playlist.width > [o_window minSize].width )
2090         {
2091             o_rect.size.width = o_size_with_playlist.width;
2092         } else {
2093             o_rect.size.width = 500;
2094         }
2095  
2096         o_rect.size.height = (o_size_with_playlist.height > 200) ?
2097             o_size_with_playlist.height : 500;
2098         o_rect.origin.x = [o_window frame].origin.x;
2099         o_rect.origin.y = [o_window frame].origin.y - o_rect.size.height +
2100                                                 [o_window minSize].height;
2101
2102         NSRect screenRect = [[o_window screen] visibleFrame];
2103         if( !NSContainsRect( screenRect, o_rect ) ) {
2104             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2105                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2106             if( NSMinY(o_rect) < NSMinY(screenRect) )
2107                 o_rect.origin.y = ( NSMinY(screenRect) );
2108         }
2109
2110         [o_btn_playlist setState: YES];
2111     }
2112     else
2113     {
2114         NSSize curSize = o_rect.size;
2115         /* make small */
2116         o_rect.size.height = [o_window minSize].height;
2117         o_rect.size.width = [o_window minSize].width;
2118         o_rect.origin.x = [o_window frame].origin.x;
2119         /* Calculate the position of the lower right corner after resize */
2120         o_rect.origin.y = [o_window frame].origin.y +
2121             [o_window frame].size.height - [o_window minSize].height;
2122
2123         if( b_restore_size )
2124             o_rect = o_restore_rect;
2125
2126         [o_playlist_view setAutoresizesSubviews: NO];
2127         [o_playlist_view removeFromSuperview];
2128         [o_btn_playlist setState: NO];
2129         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2130     }
2131
2132     [o_window setFrame: o_rect display:YES animate: YES];
2133 }
2134
2135 - (void)updateTogglePlaylistState
2136 {
2137     if( [o_window frame].size.height <= 200 )
2138     {
2139         [o_btn_playlist setState: NO];
2140     }
2141     else
2142     {
2143         [o_btn_playlist setState: YES];
2144     }
2145 }
2146
2147 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2148 {
2149     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2150
2151    /*Stores the size the controller one resize, to be able to restore it when
2152      toggling the playlist*/
2153     o_size_with_playlist = proposedFrameSize;
2154
2155     if( proposedFrameSize.height <= 200 )
2156     {
2157         if( b_small_window == NO )
2158         {
2159             /* if large and going to small then hide */
2160             b_small_window = YES;
2161             [o_playlist_view setAutoresizesSubviews: NO];
2162             [o_playlist_view removeFromSuperview];
2163         }
2164         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2165     }
2166     return proposedFrameSize;
2167 }
2168
2169 - (void)windowDidMove:(NSNotification *)notif
2170 {
2171     b_restore_size = false;
2172 }
2173
2174 - (void)windowDidResize:(NSNotification *)notif
2175 {
2176     if( [o_window frame].size.height > 200 && b_small_window )
2177     {
2178         /* If large and coming from small then show */
2179         [o_playlist_view setAutoresizesSubviews: YES];
2180         [o_playlist_view setFrame: NSMakeRect( 0, 0, [o_window frame].size.width, [o_window frame].size.height - [o_window minSize].height )];
2181         [o_playlist_view setNeedsDisplay:YES];
2182         [[o_window contentView] addSubview: o_playlist_view];
2183         b_small_window = NO;
2184     }
2185     [self updateTogglePlaylistState];
2186 }
2187
2188 @end
2189
2190 @implementation VLCMain (NSMenuValidation)
2191
2192 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2193 {
2194     NSString *o_title = [o_mi title];
2195     BOOL bEnabled = TRUE;
2196
2197     /* Recent Items Menu */
2198     if( [o_title isEqualToString: _NS("Clear Menu")] )
2199     {
2200         NSMenu * o_menu = [o_mi_open_recent submenu];
2201         int i_nb_items = [o_menu numberOfItems];
2202         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2203                                                        recentDocumentURLs];
2204         UInt32 i_nb_docs = [o_docs count];
2205
2206         if( i_nb_items > 1 )
2207         {
2208             while( --i_nb_items )
2209             {
2210                 [o_menu removeItemAtIndex: 0];
2211             }
2212         }
2213
2214         if( i_nb_docs > 0 )
2215         {
2216             NSURL * o_url;
2217             NSString * o_doc;
2218
2219             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2220
2221             while( TRUE )
2222             {
2223                 i_nb_docs--;
2224
2225                 o_url = [o_docs objectAtIndex: i_nb_docs];
2226
2227                 if( [o_url isFileURL] )
2228                 {
2229                     o_doc = [o_url path];
2230                 }
2231                 else
2232                 {
2233                     o_doc = [o_url absoluteString];
2234                 }
2235
2236                 [o_menu insertItemWithTitle: o_doc
2237                     action: @selector(openRecentItem:)
2238                     keyEquivalent: @"" atIndex: 0];
2239
2240                 if( i_nb_docs == 0 )
2241                 {
2242                     break;
2243                 }
2244             }
2245         }
2246         else
2247         {
2248             bEnabled = FALSE;
2249         }
2250     }
2251     return( bEnabled );
2252 }
2253
2254 @end
2255
2256 @implementation VLCMain (Internal)
2257
2258 - (void)handlePortMessage:(NSPortMessage *)o_msg
2259 {
2260     id ** val;
2261     NSData * o_data;
2262     NSValue * o_value;
2263     NSInvocation * o_inv;
2264     NSConditionLock * o_lock;
2265
2266     o_data = [[o_msg components] lastObject];
2267     o_inv = *((NSInvocation **)[o_data bytes]);
2268     [o_inv getArgument: &o_value atIndex: 2];
2269     val = (id **)[o_value pointerValue];
2270     [o_inv setArgument: val[1] atIndex: 2];
2271     o_lock = *(val[0]);
2272
2273     [o_lock lock];
2274     [o_inv invoke];
2275     [o_lock unlockWithCondition: 1];
2276 }
2277
2278 @end