6941b578942b57ce9508df93ea43031408d9e434
[vlc.git] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2004 VideoLAN
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  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdlib.h>                                      /* malloc(), free() */
30 #include <sys/param.h>                                    /* for MAXPATHLEN */
31 #include <string.h>
32 #include <vlc_keys.h>
33
34 #include "intf.h"
35 #include "vout.h"
36 #include "prefs.h"
37 #include "playlist.h"
38 #include "info.h"
39 #include "controls.h"
40
41 /*****************************************************************************
42  * Local prototypes.
43  *****************************************************************************/
44 static void Run ( intf_thread_t *p_intf );
45
46 /*****************************************************************************
47  * OpenIntf: initialize interface
48  *****************************************************************************/
49 int E_(OpenIntf) ( vlc_object_t *p_this )
50 {   
51     intf_thread_t *p_intf = (intf_thread_t*) p_this;
52
53     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
54     if( p_intf->p_sys == NULL )
55     {
56         return( 1 );
57     }
58
59     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
60     
61     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
62     
63     /* Put Cocoa into multithread mode as soon as possible.
64      * http://developer.apple.com/techpubs/macosx/Cocoa/
65      * TasksAndConcepts/ProgrammingTopics/Multithreading/index.html
66      * This thread does absolutely nothing at all. */
67     [NSThread detachNewThreadSelector:@selector(self) toTarget:[NSString string] withObject:nil];
68     
69     p_intf->p_sys->o_sendport = [[NSPort port] retain];
70     p_intf->p_sys->p_sub = msg_Subscribe( p_intf );
71     p_intf->pf_run = Run;
72     
73     [[VLCApplication sharedApplication] autorelease];
74     [NSApp setIntf: p_intf];
75
76
77     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
78
79     return( 0 );
80 }
81
82 /*****************************************************************************
83  * CloseIntf: destroy interface
84  *****************************************************************************/
85 void E_(CloseIntf) ( vlc_object_t *p_this )
86 {
87     intf_thread_t *p_intf = (intf_thread_t*) p_this;
88
89     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
90
91     [p_intf->p_sys->o_sendport release];
92     [p_intf->p_sys->o_pool release];
93
94     free( p_intf->p_sys );
95 }
96
97 /*****************************************************************************
98  * Run: main loop
99  *****************************************************************************/
100 static void Run( intf_thread_t *p_intf )
101 {
102     /* Do it again - for some unknown reason, vlc_thread_create() often
103      * fails to go to real-time priority with the first launched thread
104      * (???) --Meuuh */
105     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
106
107     [NSApp run];
108 }
109
110 /*****************************************************************************
111  * VLCApplication implementation 
112  *****************************************************************************/
113 @implementation VLCApplication
114
115 - (NSString *)localizedString:(char *)psz
116 {
117     NSString * o_str = nil;
118
119     if( psz != NULL )
120     {
121         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
122     }
123     if ( o_str == NULL )
124     {
125         msg_Err( p_intf, "could not translate: %s", psz );
126     }
127
128     return( o_str );
129 }
130
131 - (char *)delocalizeString:(NSString *)id
132 {
133     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
134                           allowLossyConversion: NO];
135     char * psz_string;
136
137     if ( o_data == nil )
138     {
139         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
140                      allowLossyConversion: YES];
141         psz_string = malloc( [o_data length] + 1 ); 
142         [o_data getBytes: psz_string];
143         psz_string[ [o_data length] ] = '\0';
144         msg_Err( p_intf, "cannot convert to wanted encoding: %s",
145                  psz_string );
146     }
147     else
148     {
149         psz_string = malloc( [o_data length] + 1 ); 
150         [o_data getBytes: psz_string];
151         psz_string[ [o_data length] ] = '\0';
152     }
153
154     return psz_string;
155 }
156
157 /* i_width is in pixels */
158 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
159 {
160     NSMutableString *o_wrapped;
161     NSString *o_out_string;
162     NSRange glyphRange, effectiveRange, charRange;
163     NSRect lineFragmentRect;
164     unsigned glyphIndex, breaksInserted = 0;
165
166     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
167         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
168         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
169     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
170     NSTextContainer *o_container = [[NSTextContainer alloc]
171         initWithContainerSize: NSMakeSize(i_width, 2000)];
172     
173     [o_layout_manager addTextContainer: o_container];
174     [o_container release];
175     [o_storage addLayoutManager: o_layout_manager];
176     [o_layout_manager release];
177         
178     o_wrapped = [o_in_string mutableCopy];
179     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
180     
181     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
182             glyphIndex += effectiveRange.length) {
183         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
184                                             effectiveRange: &effectiveRange];
185         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
186                                     actualGlyphRange: &effectiveRange];
187         if ([o_wrapped lineRangeForRange:
188                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
189             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
190             breaksInserted++;
191         }
192     }
193     o_out_string = [NSString stringWithString: o_wrapped];
194     [o_wrapped release];
195     [o_storage release];
196     
197     return o_out_string;
198 }
199
200 - (void)setIntf:(intf_thread_t *)_p_intf
201 {
202     p_intf = _p_intf;
203 }
204
205 - (intf_thread_t *)getIntf
206 {
207     return( p_intf );
208 }
209
210 - (void)terminate:(id)sender
211 {
212     p_intf->p_vlc->b_die = VLC_TRUE;
213 }
214
215
216 /*****************************************************************************
217  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
218  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
219  * otherwise ignore it and return NO (where it will get handled by Cocoa).
220  *****************************************************************************/
221 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
222 {
223     unichar key = 0;
224     vlc_value_t val;
225     unsigned int i_pressed_modifiers = 0;
226     struct hotkey *p_hotkeys;
227     int i;
228
229     val.i_int = 0;
230     p_hotkeys = p_intf->p_vlc->p_hotkeys;
231
232     i_pressed_modifiers = [o_event modifierFlags];
233
234     if( i_pressed_modifiers & NSShiftKeyMask )
235         val.i_int |= KEY_MODIFIER_SHIFT;
236     if( i_pressed_modifiers & NSControlKeyMask )
237         val.i_int |= KEY_MODIFIER_CTRL;
238     if( i_pressed_modifiers & NSAlternateKeyMask )
239         val.i_int |= KEY_MODIFIER_ALT;
240     if( i_pressed_modifiers & NSCommandKeyMask )
241         val.i_int |= KEY_MODIFIER_COMMAND;
242
243     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
244
245     val.i_int |= CocoaKeyToVLC( key );
246
247     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
248     {
249         if( p_hotkeys[i].i_key == val.i_int )
250         {
251             var_Set( p_intf->p_vlc, "key-pressed", val );
252             return YES;
253         }
254     }
255
256     return NO;
257 }
258
259 @end
260
261 int ExecuteOnMainThread( id target, SEL sel, void * p_arg )
262 {
263     int i_ret = 0;
264
265     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
266
267     if( [target respondsToSelector: @selector(performSelectorOnMainThread:
268                                              withObject:waitUntilDone:)] )
269     {
270         [target performSelectorOnMainThread: sel
271                 withObject: [NSValue valueWithPointer: p_arg]
272                 waitUntilDone: YES];
273     }
274     else if( NSApp != nil && [NSApp respondsToSelector: @selector(getIntf)] ) 
275     {
276         NSValue * o_v1;
277         NSValue * o_v2;
278         NSArray * o_array;
279         NSPort * o_recv_port;
280         NSInvocation * o_inv;
281         NSPortMessage * o_msg;
282         intf_thread_t * p_intf;
283         NSConditionLock * o_lock;
284         NSMethodSignature * o_sig;
285
286         id * val[] = { &o_lock, &o_v2 };
287
288         p_intf = (intf_thread_t *)[NSApp getIntf];
289
290         o_recv_port = [[NSPort port] retain];
291         o_v1 = [NSValue valueWithPointer: val]; 
292         o_v2 = [NSValue valueWithPointer: p_arg];
293
294         o_sig = [target methodSignatureForSelector: sel];
295         o_inv = [NSInvocation invocationWithMethodSignature: o_sig];
296         [o_inv setArgument: &o_v1 atIndex: 2];
297         [o_inv setTarget: target];
298         [o_inv setSelector: sel];
299
300         o_array = [NSArray arrayWithObject:
301             [NSData dataWithBytes: &o_inv length: sizeof(o_inv)]];
302         o_msg = [[NSPortMessage alloc]
303             initWithSendPort: p_intf->p_sys->o_sendport
304             receivePort: o_recv_port components: o_array];
305
306         o_lock = [[NSConditionLock alloc] initWithCondition: 0];
307         [o_msg sendBeforeDate: [NSDate distantPast]];
308         [o_lock lockWhenCondition: 1];
309         [o_lock unlock];
310         [o_lock release];
311
312         [o_msg release];
313         [o_recv_port release];
314     } 
315     else
316     {
317         i_ret = 1;
318     }
319
320     [o_pool release];
321
322     return( i_ret );
323 }
324
325 /*****************************************************************************
326  * playlistChanged: Callback triggered by the intf-change playlist
327  * variable, to let the intf update the playlist.
328  *****************************************************************************/
329 int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
330                      vlc_value_t old_val, vlc_value_t new_val, void *param )
331 {
332     intf_thread_t * p_intf = [NSApp getIntf];
333     p_intf->p_sys->b_playlist_update = TRUE;
334     p_intf->p_sys->b_intf_update = TRUE;
335     return VLC_SUCCESS;
336 }
337
338 static struct
339 {
340     unichar i_nskey;
341     unsigned int i_vlckey;
342 } nskeys_to_vlckeys[] = 
343 {
344     { NSUpArrowFunctionKey, KEY_UP },
345     { NSDownArrowFunctionKey, KEY_DOWN },
346     { NSLeftArrowFunctionKey, KEY_LEFT },
347     { NSRightArrowFunctionKey, KEY_RIGHT },
348     { NSF1FunctionKey, KEY_F1 },
349     { NSF2FunctionKey, KEY_F2 },
350     { NSF3FunctionKey, KEY_F3 },
351     { NSF4FunctionKey, KEY_F4 },
352     { NSF5FunctionKey, KEY_F5 },
353     { NSF6FunctionKey, KEY_F6 },
354     { NSF7FunctionKey, KEY_F7 },
355     { NSF8FunctionKey, KEY_F8 },
356     { NSF9FunctionKey, KEY_F9 },
357     { NSF10FunctionKey, KEY_F10 },
358     { NSF11FunctionKey, KEY_F11 },
359     { NSF12FunctionKey, KEY_F12 },
360     { NSHomeFunctionKey, KEY_HOME },
361     { NSEndFunctionKey, KEY_END },
362     { NSPageUpFunctionKey, KEY_PAGEUP },
363     { NSPageDownFunctionKey, KEY_PAGEDOWN },
364     { NSTabCharacter, KEY_TAB },
365     { NSCarriageReturnCharacter, KEY_ENTER },
366     { NSEnterCharacter, KEY_ENTER },
367     { NSBackspaceCharacter, KEY_BACKSPACE },
368     { (unichar) ' ', KEY_SPACE },
369     { (unichar) 0x1b, KEY_ESC },
370     {0,0}
371 };
372
373 unichar VLCKeyToCocoa( unsigned int i_key )
374 {
375     unsigned int i;
376     
377     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
378     {
379         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
380         {
381             return nskeys_to_vlckeys[i].i_nskey;
382         }
383     }
384     return (unichar)(i_key & ~KEY_MODIFIER);
385 }
386
387 unsigned int CocoaKeyToVLC( unichar i_key )
388 {
389     unsigned int i;
390     
391     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
392     {
393         if( nskeys_to_vlckeys[i].i_nskey == i_key )
394         {
395             return nskeys_to_vlckeys[i].i_vlckey;
396         }
397     }
398     return (unsigned int)i_key;
399 }
400
401 unsigned int VLCModifiersToCocoa( unsigned int i_key )
402 {
403     unsigned int new = 0;
404     if( i_key & KEY_MODIFIER_COMMAND )
405         new |= NSCommandKeyMask;
406     if( i_key & KEY_MODIFIER_ALT )
407         new |= NSAlternateKeyMask;
408     if( i_key & KEY_MODIFIER_SHIFT )
409         new |= NSShiftKeyMask;
410     if( i_key & KEY_MODIFIER_CTRL )
411         new |= NSControlKeyMask;
412     return new;
413 }
414
415 /*****************************************************************************
416  * VLCMain implementation 
417  *****************************************************************************/
418 @implementation VLCMain
419
420 - (void)awakeFromNib
421 {
422     unsigned int i_key = 0;
423     intf_thread_t * p_intf = [NSApp getIntf];
424     vlc_value_t val;
425
426     [self initStrings];
427     [o_window setExcludedFromWindowsMenu: TRUE];
428     [o_msgs_panel setExcludedFromWindowsMenu: TRUE];
429     [o_msgs_panel setDelegate: self];
430     
431     i_key = config_GetInt( p_intf, "key-quit" );
432     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
433     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
434     i_key = config_GetInt( p_intf, "key-play-pause" );
435     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
436     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
437     i_key = config_GetInt( p_intf, "key-stop" );
438     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
439     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
440     i_key = config_GetInt( p_intf, "key-faster" );
441     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
442     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
443     i_key = config_GetInt( p_intf, "key-slower" );
444     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
445     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
446     i_key = config_GetInt( p_intf, "key-prev" );
447     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
448     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
449     i_key = config_GetInt( p_intf, "key-next" );
450     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
451     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
452     i_key = config_GetInt( p_intf, "key-jump+10sec" );
453     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
454     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
455     i_key = config_GetInt( p_intf, "key-jump-10sec" );
456     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
457     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
458     i_key = config_GetInt( p_intf, "key-jump+1min" );
459     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
460     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
461     i_key = config_GetInt( p_intf, "key-jump-1min" );
462     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
463     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
464     i_key = config_GetInt( p_intf, "key-jump+5min" );
465     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
466     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
467     i_key = config_GetInt( p_intf, "key-jump-5min" );
468     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
469     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
470     i_key = config_GetInt( p_intf, "key-vol-up" );
471     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
472     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
473     i_key = config_GetInt( p_intf, "key-vol-down" );
474     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
475     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
476     i_key = config_GetInt( p_intf, "key-vol-mute" );
477     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
478     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
479     i_key = config_GetInt( p_intf, "key-fullscreen" );
480     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
481     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
482
483     var_Create (p_intf, "fullscreen", VLC_VAR_BOOL );
484     var_Change (p_intf, "fullscreen", VLC_VAR_INHERITVALUE, &val, NULL );
485     [o_btn_fullscreen setState: val.b_bool];
486
487     var_Create(p_intf,"intf-change",VLC_VAR_BOOL );
488
489     [self setSubmenusEnabled: FALSE];
490     [self manageVolumeSlider];
491
492 }
493
494 - (void)initStrings
495 {
496     [o_window setTitle: _NS("VLC - Controller")];
497     [o_scrollfield setStringValue: _NS("VLC media player")];
498
499     /* button controls */
500     [o_btn_prev setToolTip: _NS("Previous")];
501     [o_btn_rewind setToolTip: _NS("Rewind")];
502     [o_btn_play setToolTip: _NS("Play")];
503     [o_btn_stop setToolTip: _NS("Stop")];
504     [o_btn_ff setToolTip: _NS("Fast Forward")];
505     [o_btn_next setToolTip: _NS("Next")];
506     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
507     [o_volumeslider setToolTip: _NS("Volume")];
508     [o_timeslider setToolTip: _NS("Position")];
509
510     /* messages panel */ 
511     [o_msgs_panel setTitle: _NS("Messages")];
512     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog")];
513
514     /* main menu */
515     [o_mi_about setTitle: _NS("About VLC media player")];
516     [o_mi_prefs setTitle: _NS("Preferences...")];
517     [o_mi_add_intf setTitle: _NS("Add Interface")];
518     [o_mu_add_intf setTitle: _NS("Add Interface")];
519     [o_mi_hide setTitle: _NS("Hide VLC")];
520     [o_mi_hide_others setTitle: _NS("Hide Others")];
521     [o_mi_show_all setTitle: _NS("Show All")];
522     [o_mi_quit setTitle: _NS("Quit VLC")];
523
524     [o_mu_file setTitle: _ANS("1:File")];
525     [o_mi_open_generic setTitle: _NS("Open File...")];
526     [o_mi_open_file setTitle: _NS("Quick Open File...")];
527     [o_mi_open_disc setTitle: _NS("Open Disc...")];
528     [o_mi_open_net setTitle: _NS("Open Network...")];
529     [o_mi_open_recent setTitle: _NS("Open Recent")];
530     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
531
532     [o_mu_edit setTitle: _NS("Edit")];
533     [o_mi_cut setTitle: _NS("Cut")];
534     [o_mi_copy setTitle: _NS("Copy")];
535     [o_mi_paste setTitle: _NS("Paste")];
536     [o_mi_clear setTitle: _NS("Clear")];
537     [o_mi_select_all setTitle: _NS("Select All")];
538
539     [o_mu_controls setTitle: _NS("Controls")];
540     [o_mi_play setTitle: _NS("Play")];
541     [o_mi_stop setTitle: _NS("Stop")];
542     [o_mi_faster setTitle: _NS("Faster")];
543     [o_mi_slower setTitle: _NS("Slower")];
544     [o_mi_previous setTitle: _NS("Previous")];
545     [o_mi_next setTitle: _NS("Next")];
546     [o_mi_random setTitle: _NS("Random")];
547     [o_mi_repeat setTitle: _NS("Repeat One")];
548     [o_mi_loop setTitle: _NS("Repeat All")];
549     [o_mi_fwd setTitle: _NS("Step Forward")];
550     [o_mi_bwd setTitle: _NS("Step Backward")];
551
552     [o_mi_program setTitle: _NS("Program")];
553     [o_mu_program setTitle: _NS("Program")];
554     [o_mi_title setTitle: _NS("Title")];
555     [o_mu_title setTitle: _NS("Title")];
556     [o_mi_chapter setTitle: _NS("Chapter")];
557     [o_mu_chapter setTitle: _NS("Chapter")];
558     
559     [o_mu_audio setTitle: _NS("Audio")];
560     [o_mi_vol_up setTitle: _NS("Volume Up")];
561     [o_mi_vol_down setTitle: _NS("Volume Down")];
562     [o_mi_mute setTitle: _NS("Mute")];
563     [o_mi_audiotrack setTitle: _NS("Audio Track")];
564     [o_mu_audiotrack setTitle: _NS("Audio Track")];
565     [o_mi_channels setTitle: _NS("Audio Channels")];
566     [o_mu_channels setTitle: _NS("Audio Channels")];
567     [o_mi_device setTitle: _NS("Audio Device")];
568     [o_mu_device setTitle: _NS("Audio Device")];
569     [o_mi_visual setTitle: _NS("Visualizations")];
570     [o_mu_visual setTitle: _NS("Visualizations")];
571     
572     [o_mu_video setTitle: _NS("Video")];
573     [o_mi_half_window setTitle: _NS("Half Size")];
574     [o_mi_normal_window setTitle: _NS("Normal Size")];
575     [o_mi_double_window setTitle: _NS("Double Size")];
576     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
577     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
578     [o_mi_floatontop setTitle: _NS("Float on Top")];
579     [o_mi_videotrack setTitle: _NS("Video Track")];
580     [o_mu_videotrack setTitle: _NS("Video Track")];
581     [o_mi_screen setTitle: _NS("Video Device")];
582     [o_mu_screen setTitle: _NS("Video Device")];
583     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
584     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
585     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
586     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
587
588     [o_mu_window setTitle: _NS("Window")];
589     [o_mi_minimize setTitle: _NS("Minimize Window")];
590     [o_mi_close_window setTitle: _NS("Close Window")];
591     [o_mi_controller setTitle: _NS("Controller")];
592     [o_mi_playlist setTitle: _NS("Playlist")];
593     [o_mi_info setTitle: _NS("Info")];
594     [o_mi_messages setTitle: _NS("Messages")];
595
596     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
597
598     [o_mu_help setTitle: _NS("Help")];
599     [o_mi_readme setTitle: _NS("ReadMe...")];
600     [o_mi_documentation setTitle: _NS("Online Documentation")];
601     [o_mi_reportabug setTitle: _NS("Report a Bug")];
602     [o_mi_website setTitle: _NS("VideoLAN Website")];
603     [o_mi_license setTitle: _NS("License")];
604
605     /* dock menu */
606     [o_dmi_play setTitle: _NS("Play")];
607     [o_dmi_stop setTitle: _NS("Stop")];
608     [o_dmi_next setTitle: _NS("Next")];
609     [o_dmi_previous setTitle: _NS("Previous")];
610     [o_dmi_mute setTitle: _NS("Mute")];
611
612     /* error panel */
613     [o_error setTitle: _NS("Error")];
614     [o_err_lbl setStringValue: _NS("An error has occurred which probably prevented the execution of your request:")];
615     [o_err_bug_lbl setStringValue: _NS("If you believe that it is a bug, please follow the instructions at:")]; 
616     [o_err_btn_msgs setTitle: _NS("Open Messages Window")];
617     [o_err_btn_dismiss setTitle: _NS("Dismiss")];
618     [o_err_ckbk_surpress setTitle: _NS("Surpress further errors")];
619
620     [o_info_window setTitle: _NS("Info")];
621 }
622
623 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
624 {
625     intf_thread_t * p_intf = [NSApp getIntf];
626
627     o_msg_lock = [[NSLock alloc] init];
628     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
629
630     o_img_play = [[NSImage imageNamed: @"play"] retain];
631     o_img_play_pressed = [[NSImage imageNamed: @"play_blue"] retain];
632     o_img_pause = [[NSImage imageNamed: @"pause"] retain];
633     o_img_pause_pressed = [[NSImage imageNamed: @"pause_blue"] retain];
634
635     [p_intf->p_sys->o_sendport setDelegate: self];
636     [[NSRunLoop currentRunLoop] 
637         addPort: p_intf->p_sys->o_sendport
638         forMode: NSDefaultRunLoopMode];
639
640     [NSTimer scheduledTimerWithTimeInterval: 0.5
641         target: self selector: @selector(manageIntf:)
642         userInfo: nil repeats: FALSE];
643
644     [NSThread detachNewThreadSelector: @selector(manage)
645         toTarget: self withObject: nil];
646         
647     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
648         var: "intf-add" selector: @selector(toggleVar:)];
649
650     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
651 }
652
653 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
654 {
655     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
656     [o_playlist appendArray:
657         [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
658             
659     return( TRUE );
660 }
661
662 - (id)getControls
663 {
664     if ( o_controls )
665     {
666         return o_controls;
667     }
668     return nil;
669 }
670
671 - (id)getPlaylist
672 {
673     if ( o_playlist )
674     {
675         return o_playlist;
676     }
677     return nil;
678 }
679
680 - (void)manage
681 {
682     NSDate * o_sleep_date;
683     intf_thread_t * p_intf = [NSApp getIntf];
684     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
685
686     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
687
688     while( !p_intf->b_die )
689     {
690         playlist_t * p_playlist;
691         vlc_value_t val;
692         vlc_mutex_lock( &p_intf->change_lock );
693
694         p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
695                                               FIND_ANYWHERE );
696
697         if( p_playlist != NULL )
698         {
699             var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
700             var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
701             var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
702
703 #define p_input p_playlist->p_input
704         
705             if( p_input )
706             {
707                 if( !p_input->b_die )
708                 {
709                     vlc_value_t val;
710
711                     /* New input or stream map change */
712                     if( p_input->stream.b_changed )
713                     {
714                         msg_Dbg( p_intf, "stream has changed, refreshing interface" );
715                         p_intf->p_sys->b_playing = TRUE;
716                         p_intf->p_sys->b_current_title_update = 1;
717                         p_input->stream.b_changed = 0;
718                         p_intf->p_sys->b_intf_update = TRUE;
719                     }
720
721                     if( var_Get( (vlc_object_t *)p_input, "intf-change", &val )
722                         >= 0 && val.b_bool )
723                     {
724                         p_intf->p_sys->b_input_update = TRUE;
725                     }
726                 }
727             }
728             else if( p_intf->p_sys->b_playing && !p_intf->b_die )
729             {
730                 p_intf->p_sys->b_playing = FALSE;
731             }
732             
733 #undef p_input
734             vlc_object_release( p_playlist );
735
736             if( var_Get( p_intf, "intf-change", &val )
737                         >= 0 && val.b_bool )
738             {
739                 p_intf->p_sys->b_fullscreen_update = TRUE;
740             }
741             val.b_bool = VLC_FALSE;
742             var_Set( p_intf,"intf-change",val);
743         }
744
745         vlc_mutex_unlock( &p_intf->change_lock );
746
747         o_sleep_date = [NSDate dateWithTimeIntervalSinceNow: .5];
748         [NSThread sleepUntilDate: o_sleep_date];
749     }
750
751     [self terminate];
752     [o_pool release];
753 }
754
755 - (void)manageIntf:(NSTimer *)o_timer
756 {
757     intf_thread_t * p_intf = [NSApp getIntf];
758
759     if( p_intf->p_vlc->b_die == VLC_TRUE )
760     {
761         [o_timer invalidate];
762         return;
763     }
764
765     playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
766                                                        FIND_ANYWHERE );
767
768     if( p_playlist == NULL )
769     {
770         return;
771     }
772
773     if ( p_intf->p_sys->b_playlist_update )
774     {
775         [o_playlist playlistUpdated];
776         p_intf->p_sys->b_playlist_update = VLC_FALSE;
777     }
778
779     if( p_intf->p_sys->b_current_title_update )
780     {
781         vout_thread_t *p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
782                                                 FIND_ANYWHERE );
783
784         vlc_mutex_lock( &p_playlist->object_lock );
785         [o_scrollfield setStringValue: [NSString stringWithUTF8String: 
786             p_playlist->pp_items[p_playlist->i_index]->input.psz_name]]; 
787         vlc_mutex_unlock( &p_playlist->object_lock );
788
789         if( p_vout != NULL )
790         {
791             id o_vout_wnd;
792             NSEnumerator * o_enum = [[NSApp orderedWindows] objectEnumerator];
793             
794             while( ( o_vout_wnd = [o_enum nextObject] ) )
795             {
796                 if( [[o_vout_wnd className] isEqualToString: @"VLCWindow"] )
797                 {
798                     [o_vout_wnd updateTitle];
799                 }
800             }
801             vlc_object_release( (vlc_object_t *)p_vout );
802         }
803         [o_playlist updateRowSelection];
804         [o_info updateInfo];
805
806         p_intf->p_sys->b_current_title_update = FALSE;
807     }
808
809     vlc_mutex_lock( &p_playlist->object_lock );
810
811 #define p_input p_playlist->p_input
812
813     if( p_intf->p_sys->b_intf_update )
814     {
815         vlc_bool_t b_input = VLC_FALSE;
816         vlc_bool_t b_plmul = VLC_FALSE;
817         vlc_bool_t b_control = VLC_FALSE;
818         vlc_bool_t b_seekable = VLC_FALSE;
819         vlc_bool_t b_chapters = VLC_FALSE;
820
821         b_plmul = p_playlist->i_size > 1;
822
823         if( ( b_input = ( p_input != NULL ) ) )
824         {
825             vlc_mutex_lock( &p_input->stream.stream_lock );
826
827             /* seekable streams */
828             b_seekable = p_input->stream.b_seekable;
829
830             /* check wether slow/fast motion is possible*/
831             b_control = p_input->stream.b_pace_control; 
832
833             /* chapters & titles */
834             b_chapters = p_input->stream.i_area_nb > 1; 
835  
836             vlc_mutex_unlock( &p_input->stream.stream_lock );
837         }
838
839         [o_btn_stop setEnabled: b_input];
840         [o_btn_ff setEnabled: b_seekable];
841         [o_btn_rewind setEnabled: b_seekable];
842         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
843         [o_btn_next setEnabled: (b_plmul || b_chapters)];
844
845         [o_timeslider setFloatValue: 0.0];
846         [o_timeslider setEnabled: b_seekable];
847         [o_timefield setStringValue: @"0:00:00"];
848
849         [self manageVolumeSlider];
850         p_intf->p_sys->b_intf_update = VLC_FALSE;
851     }
852
853     if (p_intf->p_sys->b_fullscreen_update )
854     {
855         vout_thread_t * p_vout;
856         vlc_value_t val;
857         if (var_Change (p_intf, "fullscreen", VLC_VAR_INHERITVALUE, &val, NULL)>=0 &&  val.b_bool )
858         {
859             [o_btn_fullscreen setState:VLC_TRUE];
860         }
861         else
862         {
863             [o_btn_fullscreen setState:VLC_FALSE];
864         }
865         p_vout = vlc_object_find(p_intf,VLC_OBJECT_VOUT,FIND_ANYWHERE);
866         if (p_vout != NULL)
867         {
868             [o_btn_fullscreen setEnabled: VLC_TRUE];
869             vlc_object_release(p_vout);
870         }
871         else
872         {
873             [o_btn_fullscreen setEnabled: VLC_FALSE];
874         }
875         p_intf->p_sys->b_fullscreen_update = VLC_FALSE;
876     }
877
878     if( p_intf->p_sys->b_playing && p_input != NULL )
879     {
880         vlc_value_t time;
881         NSString * o_time;
882         mtime_t i_seconds;
883
884         if( p_input->stream.b_seekable )
885         {
886             vlc_value_t pos;
887             float f_updated;
888             
889             var_Get( p_input, "position", &pos );
890             f_updated = 10000. * pos.f_float;
891
892             if( f_slider != f_updated )
893             {
894                 [o_timeslider setFloatValue: f_updated];
895             }
896         }
897             
898         var_Get( p_input, "time", &time );
899         i_seconds = time.i_time / 1000000;
900         
901         o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
902                         (int) (i_seconds / (60 * 60)),
903                         (int) (i_seconds / 60 % 60),
904                         (int) (i_seconds % 60)];
905         [o_timefield setStringValue: o_time];
906     }
907     if( p_input )
908     {
909         vlc_value_t val;
910         var_Get( p_input, "state", &val );
911
912         if( val.i_int != PAUSE_S )
913         {
914             p_intf->p_sys->b_play_status = TRUE;
915         }
916         else
917         {
918             p_intf->p_sys->b_play_status = FALSE;
919         }
920         [self playStatusUpdated: p_intf->p_sys->b_play_status];
921     }
922     else
923     {
924         p_intf->p_sys->b_play_status = FALSE;
925         [self playStatusUpdated: p_intf->p_sys->b_play_status];
926         [self setSubmenusEnabled: FALSE];
927     }
928
929 #undef p_input
930
931     vlc_mutex_unlock( &p_playlist->object_lock );
932     vlc_object_release( p_playlist );
933
934     [self updateMessageArray];
935
936     [NSTimer scheduledTimerWithTimeInterval: 0.5
937         target: self selector: @selector(manageIntf:)
938         userInfo: nil repeats: FALSE];
939 }
940
941 - (void)setupMenus
942 {
943     intf_thread_t * p_intf = [NSApp getIntf];
944     playlist_t *p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST, 
945                                                 FIND_ANYWHERE );
946     
947     if( p_playlist != NULL )
948     {
949 #define p_input p_playlist->p_input
950         if( p_input != NULL )
951         {
952             [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
953                 var: "program" selector: @selector(toggleVar:)];
954             
955             [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
956                 var: "title" selector: @selector(toggleVar:)];
957             
958             [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
959                 var: "chapter" selector: @selector(toggleVar:)];
960             
961             [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
962                 var: "audio-es" selector: @selector(toggleVar:)];
963             
964             [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
965                 var: "video-es" selector: @selector(toggleVar:)];
966             
967             [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
968                 var: "spu-es" selector: @selector(toggleVar:)];
969         
970             aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
971                                                         FIND_ANYWHERE );
972             if ( p_aout != NULL )
973             {
974                 [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
975                     var: "audio-channels" selector: @selector(toggleVar:)];
976             
977                 [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
978                     var: "audio-device" selector: @selector(toggleVar:)];
979                     
980                 [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
981                     var: "visual" selector: @selector(toggleVar:)];
982                 vlc_object_release( (vlc_object_t *)p_aout );
983             }
984             
985             vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
986                                                                 FIND_ANYWHERE );
987             
988             if ( p_vout != NULL )
989             {
990                 [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
991                     var: "video-device" selector: @selector(toggleVar:)];
992                 
993                 [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
994                     var: "deinterlace" selector: @selector(toggleVar:)];
995                 vlc_object_release( (vlc_object_t *)p_vout );
996             }
997         }
998 #undef p_input
999     }
1000     vlc_object_release( (vlc_object_t *)p_playlist );
1001 }
1002
1003 - (void)updateMessageArray
1004 {
1005     int i_start, i_stop;
1006     intf_thread_t * p_intf = [NSApp getIntf];
1007     vlc_value_t quiet;
1008
1009     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1010     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1011     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1012
1013     if( p_intf->p_sys->p_sub->i_start != i_stop )
1014     {
1015         NSColor *o_white = [NSColor whiteColor];
1016         NSColor *o_red = [NSColor redColor];
1017         NSColor *o_yellow = [NSColor yellowColor];
1018         NSColor *o_gray = [NSColor grayColor];
1019
1020         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1021         static const char * ppsz_type[4] = { ": ", " error: ",
1022                                              " warning: ", " debug: " };
1023
1024         for( i_start = p_intf->p_sys->p_sub->i_start;
1025              i_start != i_stop;
1026              i_start = (i_start+1) % VLC_MSG_QSIZE )
1027         {
1028             NSString *o_msg;
1029             NSDictionary *o_attr;
1030             NSAttributedString *o_msg_color;
1031
1032             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1033
1034             [o_msg_lock lock];
1035
1036             if( [o_msg_arr count] + 2 > 400 )
1037             {
1038                 unsigned rid[] = { 0, 1 };
1039                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1040                            numIndices: sizeof(rid)/sizeof(rid[0])];
1041             }
1042
1043             o_attr = [NSDictionary dictionaryWithObject: o_gray
1044                 forKey: NSForegroundColorAttributeName];
1045             o_msg = [NSString stringWithFormat: @"%s%s",
1046                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1047                 ppsz_type[i_type]];
1048             o_msg_color = [[NSAttributedString alloc]
1049                 initWithString: o_msg attributes: o_attr];
1050             [o_msg_arr addObject: [o_msg_color autorelease]];
1051
1052             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1053                 forKey: NSForegroundColorAttributeName];
1054             o_msg = [NSString stringWithFormat: @"%s\n",
1055                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1056             o_msg_color = [[NSAttributedString alloc]
1057                 initWithString: o_msg attributes: o_attr];
1058             [o_msg_arr addObject: [o_msg_color autorelease]];
1059
1060             [o_msg_lock unlock];
1061
1062             var_Get( p_intf->p_vlc, "verbose", &quiet );
1063
1064             if( i_type == 1 && quiet.i_int > -1 )
1065             {
1066                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
1067                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1068                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1069
1070                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
1071                 [o_err_msg setEditable: YES];
1072                 [o_err_msg setSelectedRange: s_r];
1073                 [o_err_msg insertText: o_my_msg];
1074
1075                 [o_error makeKeyAndOrderFront: self];
1076                 [o_err_msg setEditable: NO];
1077             }
1078         }
1079
1080         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1081         p_intf->p_sys->p_sub->i_start = i_start;
1082         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1083     }
1084 }
1085
1086 - (void)playStatusUpdated:(BOOL)b_pause
1087 {
1088     if( b_pause )
1089     {
1090         [o_btn_play setImage: o_img_pause];
1091         [o_btn_play setAlternateImage: o_img_pause_pressed];
1092         [o_btn_play setToolTip: _NS("Pause")];
1093         [o_mi_play setTitle: _NS("Pause")];
1094         [o_dmi_play setTitle: _NS("Pause")];
1095     }
1096     else
1097     {
1098         [o_btn_play setImage: o_img_play];
1099         [o_btn_play setAlternateImage: o_img_play_pressed];
1100         [o_btn_play setToolTip: _NS("Play")];
1101         [o_mi_play setTitle: _NS("Play")];
1102         [o_dmi_play setTitle: _NS("Play")];
1103     }
1104 }
1105
1106 - (void)setSubmenusEnabled:(BOOL)b_enabled
1107 {
1108     [o_mi_program setEnabled: b_enabled];
1109     [o_mi_title setEnabled: b_enabled];
1110     [o_mi_chapter setEnabled: b_enabled];
1111     [o_mi_audiotrack setEnabled: b_enabled];
1112     [o_mi_visual setEnabled: b_enabled];
1113     [o_mi_videotrack setEnabled: b_enabled];
1114     [o_mi_subtitle setEnabled: b_enabled];
1115     [o_mi_channels setEnabled: b_enabled];
1116     [o_mi_deinterlace setEnabled: b_enabled];
1117     [o_mi_device setEnabled: b_enabled];
1118     [o_mi_screen setEnabled: b_enabled];
1119 }
1120
1121 - (void)manageVolumeSlider
1122 {
1123     audio_volume_t i_volume;
1124     intf_thread_t * p_intf = [NSApp getIntf];
1125
1126     aout_VolumeGet( p_intf, &i_volume );
1127
1128     [o_volumeslider setFloatValue: (float)i_volume / AOUT_VOLUME_STEP]; 
1129     [o_volumeslider setEnabled: TRUE];
1130
1131     p_intf->p_sys->b_mute = ( i_volume == 0 );
1132 }
1133
1134 - (IBAction)timesliderUpdate:(id)sender
1135 {
1136     intf_thread_t * p_intf;
1137     input_thread_t * p_input;
1138     float f_updated;
1139
1140     switch( [[NSApp currentEvent] type] )
1141     {
1142         case NSLeftMouseUp:
1143         case NSLeftMouseDown:
1144         case NSLeftMouseDragged:
1145             f_updated = [sender floatValue];
1146             break;
1147
1148         default:
1149             return;
1150     }
1151
1152     p_intf = [NSApp getIntf];
1153     p_input = vlc_object_find( p_intf, VLC_OBJECT_INPUT,
1154                                             FIND_ANYWHERE );
1155
1156     if( p_input != NULL )
1157     {
1158         vlc_value_t time;
1159         mtime_t i_seconds;
1160         NSString * o_time;
1161
1162         if( p_input->stream.b_seekable )
1163         {
1164                 vlc_value_t pos;
1165                 pos.f_float = f_updated / 10000.;
1166                 if( f_slider != f_updated )
1167                 {
1168                     var_Set( p_input, "position", pos );
1169                     [o_timeslider setFloatValue: f_updated];
1170                 }
1171         }
1172             
1173         var_Get( p_input, "time", &time );
1174         i_seconds = time.i_time / 1000000;
1175         
1176         o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
1177                         (int) (i_seconds / (60 * 60)),
1178                         (int) (i_seconds / 60 % 60),
1179                         (int) (i_seconds % 60)];
1180         [o_timefield setStringValue: o_time];
1181         vlc_object_release( p_input );
1182     }
1183 }
1184
1185 - (void)terminate
1186 {
1187     NSEvent * o_event;
1188     playlist_t * p_playlist;
1189     vout_thread_t * p_vout;
1190     intf_thread_t * p_intf = [NSApp getIntf];
1191
1192     /* Stop playback */
1193     if( ( p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
1194                                         FIND_ANYWHERE ) ) )
1195     {
1196         playlist_Stop( p_playlist );
1197         vlc_object_release( p_playlist );
1198     }
1199
1200     /* FIXME - Wait here until all vouts are terminated because
1201        libvlc's VLC_Stop destroys interfaces before vouts, which isn't
1202        good on OS X. We definitly need a cleaner way to handle this,
1203        but this may hopefully be good enough for now.
1204          -- titer 2003/11/22 */
1205     while( ( p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1206                                        FIND_ANYWHERE ) ) )
1207     {
1208         vlc_object_release( p_vout );
1209         msleep( 100000 );
1210     }
1211     msleep( 500000 );
1212
1213     if( o_img_pause_pressed != nil )
1214     {
1215         [o_img_pause_pressed release];
1216         o_img_pause_pressed = nil;
1217     }
1218     
1219     if( o_img_pause_pressed != nil )
1220     {
1221         [o_img_pause_pressed release];
1222         o_img_pause_pressed = nil;
1223     }
1224     
1225     if( o_img_pause != nil )
1226     {
1227         [o_img_pause release];
1228         o_img_pause = nil;
1229     }
1230
1231     if( o_img_play != nil )
1232     {
1233         [o_img_play release];
1234         o_img_play = nil;
1235     }
1236
1237     if( o_msg_arr != nil )
1238     {
1239         [o_msg_arr removeAllObjects];
1240         [o_msg_arr release];
1241         o_msg_arr = nil;
1242     }
1243
1244     if( o_msg_lock != nil )
1245     {
1246         [o_msg_lock release];
1247         o_msg_lock = nil;
1248     }
1249
1250     [NSApp stop: nil];
1251
1252     /* write cached user defaults to disk */
1253     [[NSUserDefaults standardUserDefaults] synchronize];
1254
1255     /* send a dummy event to break out of the event loop */
1256     o_event = [NSEvent mouseEventWithType: NSLeftMouseDown
1257                 location: NSMakePoint( 1, 1 ) modifierFlags: 0
1258                 timestamp: 1 windowNumber: [[NSApp mainWindow] windowNumber]
1259                 context: [NSGraphicsContext currentContext] eventNumber: 1
1260                 clickCount: 1 pressure: 0.0];
1261     [NSApp postEvent: o_event atStart: YES];
1262 }
1263
1264 - (IBAction)clearRecentItems:(id)sender
1265 {
1266     [[NSDocumentController sharedDocumentController]
1267                           clearRecentDocuments: nil];
1268 }
1269
1270 - (void)openRecentItem:(id)sender
1271 {
1272     [self application: nil openFile: [sender title]]; 
1273 }
1274
1275 - (IBAction)viewPreferences:(id)sender
1276 {
1277     [o_prefs showPrefs];
1278 }
1279
1280 - (IBAction)closeError:(id)sender
1281 {
1282     vlc_value_t val;
1283     intf_thread_t * p_intf = [NSApp getIntf];
1284     
1285     if( [o_err_ckbk_surpress state] == NSOnState )
1286     {
1287         val.i_int = -1;
1288         var_Set( p_intf->p_vlc, "verbose", val );
1289     }
1290     [o_err_msg setString: @""];
1291     [o_error performClose: self];
1292 }
1293
1294 - (IBAction)openReadMe:(id)sender
1295 {
1296     NSString * o_path = [[NSBundle mainBundle] 
1297         pathForResource: @"README.MacOSX" ofType: @"rtf"]; 
1298
1299     [[NSWorkspace sharedWorkspace] openFile: o_path 
1300                                    withApplication: @"TextEdit"];
1301 }
1302
1303 - (IBAction)openDocumentation:(id)sender
1304 {
1305     NSURL * o_url = [NSURL URLWithString: 
1306         @"http://www.videolan.org/doc/"];
1307
1308     [[NSWorkspace sharedWorkspace] openURL: o_url];
1309 }
1310
1311 - (IBAction)reportABug:(id)sender
1312 {
1313     NSURL * o_url = [NSURL URLWithString: 
1314         @"http://www.videolan.org/support/bug-reporting.html"];
1315
1316     [[NSWorkspace sharedWorkspace] openURL: o_url];
1317 }
1318
1319 - (IBAction)openWebsite:(id)sender
1320 {
1321     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
1322
1323     [[NSWorkspace sharedWorkspace] openURL: o_url];
1324 }
1325
1326 - (IBAction)openLicense:(id)sender
1327 {
1328     NSString * o_path = [[NSBundle mainBundle] 
1329         pathForResource: @"COPYING" ofType: nil];
1330
1331     [[NSWorkspace sharedWorkspace] openFile: o_path 
1332                                    withApplication: @"TextEdit"];
1333 }
1334
1335 - (IBAction)openCrashLog:(id)sender
1336 {
1337     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1338                                     stringByExpandingTildeInPath]; 
1339
1340     
1341     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1342     {
1343         [[NSWorkspace sharedWorkspace] openFile: o_path 
1344                                     withApplication: @"Console"];
1345     }
1346     else
1347     {
1348         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), @"Continue", nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Either you are running Mac OS X pre 10.2 or you haven't experienced any heavy crashes yet.") );
1349
1350     }
1351 }
1352
1353 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1354 {
1355     if( [o_notification object] == o_msgs_panel )
1356     {
1357         id o_msg;
1358         NSEnumerator * o_enum;
1359
1360         [o_messages setString: @""]; 
1361
1362         [o_msg_lock lock];
1363
1364         o_enum = [o_msg_arr objectEnumerator];
1365
1366         while( ( o_msg = [o_enum nextObject] ) != nil )
1367         {
1368             [o_messages insertText: o_msg];
1369         }
1370
1371         [o_msg_lock unlock];
1372     }
1373 }
1374
1375 @end
1376
1377 @implementation VLCMain (NSMenuValidation)
1378
1379 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1380 {
1381     NSString *o_title = [o_mi title];
1382     BOOL bEnabled = TRUE;
1383
1384     if( [o_title isEqualToString: _NS("License")] )
1385     {
1386         /* we need to do this only once */
1387         [self setupMenus];
1388     }
1389
1390     /* Recent Items Menu */
1391     if( [o_title isEqualToString: _NS("Clear Menu")] )
1392     {
1393         NSMenu * o_menu = [o_mi_open_recent submenu];
1394         int i_nb_items = [o_menu numberOfItems];
1395         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1396                                                        recentDocumentURLs];
1397         UInt32 i_nb_docs = [o_docs count];
1398
1399         if( i_nb_items > 1 )
1400         {
1401             while( --i_nb_items )
1402             {
1403                 [o_menu removeItemAtIndex: 0];
1404             }
1405         }
1406
1407         if( i_nb_docs > 0 )
1408         {
1409             NSURL * o_url;
1410             NSString * o_doc;
1411
1412             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1413
1414             while( TRUE )
1415             {
1416                 i_nb_docs--;
1417
1418                 o_url = [o_docs objectAtIndex: i_nb_docs];
1419
1420                 if( [o_url isFileURL] )
1421                 {
1422                     o_doc = [o_url path];
1423                 }
1424                 else
1425                 {
1426                     o_doc = [o_url absoluteString];
1427                 }
1428
1429                 [o_menu insertItemWithTitle: o_doc
1430                     action: @selector(openRecentItem:)
1431                     keyEquivalent: @"" atIndex: 0]; 
1432
1433                 if( i_nb_docs == 0 )
1434                 {
1435                     break;
1436                 }
1437             } 
1438         }
1439         else
1440         {
1441             bEnabled = FALSE;
1442         }
1443     }
1444     return( bEnabled );
1445 }
1446
1447 @end
1448
1449 @implementation VLCMain (Internal)
1450
1451 - (void)handlePortMessage:(NSPortMessage *)o_msg
1452 {
1453     id ** val;
1454     NSData * o_data;
1455     NSValue * o_value;
1456     NSInvocation * o_inv;
1457     NSConditionLock * o_lock;
1458  
1459     o_data = [[o_msg components] lastObject];
1460     o_inv = *((NSInvocation **)[o_data bytes]); 
1461     [o_inv getArgument: &o_value atIndex: 2];
1462     val = (id **)[o_value pointerValue];
1463     [o_inv setArgument: val[1] atIndex: 2];
1464     o_lock = *(val[0]);
1465
1466     [o_lock lock];
1467     [o_inv invoke];
1468     [o_lock unlockWithCondition: 1];
1469 }
1470
1471 @end