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