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