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