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