]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
* AUTHORS: add a location to bigben's entry to prevent the OSX-About-Window-Parser...
[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 - (id)getWizard
771 {
772     if ( o_wizard )
773     {
774         return o_wizard;
775     }
776     return nil;
777 }
778
779 - (void)manage
780 {
781     NSDate * o_sleep_date;
782     playlist_t * p_playlist;
783
784     /* new thread requires a new pool */
785     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
786
787     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
788
789     p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
790                                               FIND_ANYWHERE );
791
792     if( p_playlist != NULL )
793     {
794         var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
795         var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
796         var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
797         var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
798         var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
799
800         vlc_object_release( p_playlist );
801     }
802
803     while( !p_intf->b_die )
804     {
805         vlc_mutex_lock( &p_intf->change_lock );
806
807 #define p_input p_intf->p_sys->p_input
808
809         if( p_input == NULL )
810         {
811             p_input = (input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
812                                            FIND_ANYWHERE );
813
814             /* Refresh the interface */
815             if( p_input )
816             {
817                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
818                 p_intf->p_sys->b_input_update = VLC_TRUE;
819             }
820         }
821         else if( p_input->b_die || p_input->b_dead )
822         {
823             /* input stopped */
824             p_intf->p_sys->b_intf_update = VLC_TRUE;
825             p_intf->p_sys->i_play_status = END_S;
826             [self setScrollField: _NS("VLC media player") stopAfter:-1];
827             vlc_object_release( p_input );
828             p_input = NULL;
829         }
830 #undef p_input
831
832         /* Manage volume status */
833         [self manageVolumeSlider];
834
835         vlc_mutex_unlock( &p_intf->change_lock );
836
837         o_sleep_date = [NSDate dateWithTimeIntervalSinceNow: .1];
838         [NSThread sleepUntilDate: o_sleep_date];
839     }
840
841     [self terminate];
842     [o_pool release];
843 }
844
845 - (void)manageIntf:(NSTimer *)o_timer
846 {
847     vlc_value_t val;
848
849     if( p_intf->p_vlc->b_die == VLC_TRUE )
850     {
851         [o_timer invalidate];
852         return;
853     }
854
855 #define p_input p_intf->p_sys->p_input
856     if( p_intf->p_sys->b_input_update )
857     {
858         /* Called when new input is opened */
859         p_intf->p_sys->b_current_title_update = VLC_TRUE;
860         p_intf->p_sys->b_intf_update = VLC_TRUE;
861         p_intf->p_sys->b_input_update = VLC_FALSE;
862     }
863     if( p_intf->p_sys->b_intf_update )
864     {
865         vlc_bool_t b_input = VLC_FALSE;
866         vlc_bool_t b_plmul = VLC_FALSE;
867         vlc_bool_t b_control = VLC_FALSE;
868         vlc_bool_t b_seekable = VLC_FALSE;
869         vlc_bool_t b_chapters = VLC_FALSE;
870
871         playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
872                                                    FIND_ANYWHERE );
873         b_plmul = p_playlist->i_size > 1;
874
875         vlc_object_release( p_playlist );
876
877         if( ( b_input = ( p_input != NULL ) ) )
878         {
879             /* seekable streams */
880             var_Get( p_input, "seekable", &val);
881             b_seekable = val.b_bool;
882
883             /* check wether slow/fast motion is possible*/
884             b_control = p_input->input.b_can_pace_control;
885
886             /* chapters & titles */
887             //b_chapters = p_input->stream.i_area_nb > 1;
888         }
889
890         [o_btn_stop setEnabled: b_input];
891         [o_btn_ff setEnabled: b_seekable];
892         [o_btn_rewind setEnabled: b_seekable];
893         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
894         [o_btn_next setEnabled: (b_plmul || b_chapters)];
895
896         [o_timeslider setFloatValue: 0.0];
897         [o_timeslider setEnabled: b_seekable];
898         [o_timefield setStringValue: @"0:00:00"];
899
900         p_intf->p_sys->b_intf_update = VLC_FALSE;
901     }
902
903     if( p_intf->p_sys->b_playmode_update )
904     {
905         [o_playlist playModeUpdated];
906         p_intf->p_sys->b_playmode_update = VLC_FALSE;
907     }
908     if( p_intf->p_sys->b_playlist_update )
909     {
910         [o_playlist playlistUpdated];
911         p_intf->p_sys->b_playlist_update = VLC_FALSE;
912     }
913
914     if( p_intf->p_sys->b_fullscreen_update )
915     {
916         playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
917                                                    FIND_ANYWHERE );
918         var_Get( p_playlist, "fullscreen", &val );
919         [o_btn_fullscreen setState: val.b_bool];
920         vlc_object_release( p_playlist );
921
922         p_intf->p_sys->b_fullscreen_update = VLC_FALSE;
923     }
924
925     if( p_input && !p_input->b_die )
926     {
927         vlc_value_t val;
928
929         if( p_intf->p_sys->b_current_title_update )
930         {
931             NSString *o_temp;
932             vout_thread_t *p_vout;
933             playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
934                                                        FIND_ANYWHERE );
935
936             if( p_playlist == NULL || p_playlist->status.p_item == NULL )
937             {
938                 return;
939             }
940             o_temp = [NSString stringWithUTF8String:
941                 p_playlist->status.p_item->input.psz_name];
942             if( o_temp == NULL )
943                 o_temp = [NSString stringWithCString:
944                     p_playlist->status.p_item->input.psz_name];
945             [self setScrollField: o_temp stopAfter:-1];
946
947             p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
948                                                     FIND_ANYWHERE );
949             if( p_vout != NULL )
950             {
951                 id o_vout_wnd;
952                 NSEnumerator * o_enum = [[NSApp orderedWindows] objectEnumerator];
953
954                 while( ( o_vout_wnd = [o_enum nextObject] ) )
955                 {
956                     if( [[o_vout_wnd className] isEqualToString: @"VLCWindow"] )
957                     {
958                         [o_vout_wnd updateTitle];
959                     }
960                 }
961                 vlc_object_release( (vlc_object_t *)p_vout );
962             }
963             [o_playlist updateRowSelection];
964             vlc_object_release( p_playlist );
965             p_intf->p_sys->b_current_title_update = FALSE;
966         }
967
968         if( p_input && [o_timeslider isEnabled] )
969         {
970             /* Update the slider */
971             vlc_value_t time;
972             NSString * o_time;
973             mtime_t i_seconds;
974             vlc_value_t pos;
975             float f_updated;
976
977             var_Get( p_input, "position", &pos );
978             f_updated = 10000. * pos.f_float;
979             [o_timeslider setFloatValue: f_updated];
980
981             var_Get( p_input, "time", &time );
982             i_seconds = time.i_time / 1000000;
983
984             o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
985                             (int) (i_seconds / (60 * 60)),
986                             (int) (i_seconds / 60 % 60),
987                             (int) (i_seconds % 60)];
988             [o_timefield setStringValue: o_time];
989         }
990         
991         if( p_intf->p_sys->b_volume_update )
992         {
993             NSString *o_text;
994             o_text = [NSString stringWithFormat: _NS("Volume: %d"), i_lastShownVolume * 200 / AOUT_VOLUME_MAX];
995             if( i_lastShownVolume != -1 )
996             [self setScrollField:o_text stopAfter:1000000];
997
998             [o_volumeslider setFloatValue: (float)i_lastShownVolume / AOUT_VOLUME_STEP];
999             [o_volumeslider setEnabled: TRUE];
1000             p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1001             p_intf->p_sys->b_volume_update = FALSE;
1002         }
1003
1004         /* Manage Playing status */
1005         var_Get( p_input, "state", &val );
1006         if( p_intf->p_sys->i_play_status != val.i_int )
1007         {
1008             p_intf->p_sys->i_play_status = val.i_int;
1009             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1010         }
1011     }
1012     else
1013     {
1014         p_intf->p_sys->i_play_status = END_S;
1015         p_intf->p_sys->b_intf_update = VLC_TRUE;
1016         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1017         [self setSubmenusEnabled: FALSE];
1018     }
1019
1020 #undef p_input
1021
1022     [self updateMessageArray];
1023
1024     if( (i_end_scroll != -1) && (mdate() > i_end_scroll) )
1025         [self resetScrollField];
1026
1027
1028     [NSTimer scheduledTimerWithTimeInterval: 0.3
1029         target: self selector: @selector(manageIntf:)
1030         userInfo: nil repeats: FALSE];
1031 }
1032
1033 - (void)setupMenus
1034 {
1035 #define p_input p_intf->p_sys->p_input
1036     if( p_input != NULL )
1037     {
1038         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1039             var: "program" selector: @selector(toggleVar:)];
1040
1041         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1042             var: "title" selector: @selector(toggleVar:)];
1043
1044         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1045             var: "chapter" selector: @selector(toggleVar:)];
1046
1047         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1048             var: "audio-es" selector: @selector(toggleVar:)];
1049
1050         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1051             var: "video-es" selector: @selector(toggleVar:)];
1052
1053         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1054             var: "spu-es" selector: @selector(toggleVar:)];
1055
1056         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1057                                                     FIND_ANYWHERE );
1058         if ( p_aout != NULL )
1059         {
1060             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1061                 var: "audio-channels" selector: @selector(toggleVar:)];
1062
1063             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1064                 var: "audio-device" selector: @selector(toggleVar:)];
1065
1066             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1067                 var: "visual" selector: @selector(toggleVar:)];
1068             vlc_object_release( (vlc_object_t *)p_aout );
1069         }
1070
1071         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1072                                                             FIND_ANYWHERE );
1073
1074         if ( p_vout != NULL )
1075         {
1076             vlc_object_t * p_dec_obj;
1077
1078             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1079                 var: "video-device" selector: @selector(toggleVar:)];
1080
1081             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1082                 var: "deinterlace" selector: @selector(toggleVar:)];
1083
1084             p_dec_obj = (vlc_object_t *)vlc_object_find(
1085                                                  (vlc_object_t *)p_vout,
1086                                                  VLC_OBJECT_DECODER,
1087                                                  FIND_PARENT );
1088             if ( p_dec_obj != NULL )
1089             {
1090                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1091                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1092                     @selector(toggleVar:)];
1093
1094                 vlc_object_release(p_dec_obj);
1095             }
1096             vlc_object_release( (vlc_object_t *)p_vout );
1097         }
1098     }
1099 #undef p_input
1100 }
1101
1102 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1103 {
1104     if( timeout != -1 )
1105         i_end_scroll = mdate() + timeout;
1106     else
1107         i_end_scroll = -1;
1108     [o_scrollfield setStringValue: o_string];
1109 }
1110
1111 - (void)resetScrollField
1112 {
1113     i_end_scroll = -1;
1114 #define p_input p_intf->p_sys->p_input
1115     if( p_input && !p_input->b_die )
1116     {
1117         NSString *o_temp;
1118         playlist_t * p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
1119                                                    FIND_ANYWHERE );
1120         if( p_playlist == NULL )
1121         {
1122             return;
1123         }
1124         o_temp = [NSString stringWithUTF8String:
1125                   p_playlist->status.p_item->input.psz_name];
1126         if( o_temp == NULL )
1127             o_temp = [NSString stringWithCString:
1128                     p_playlist->status.p_item->input.psz_name];
1129         [self setScrollField: o_temp stopAfter:-1];
1130         vlc_object_release( p_playlist );
1131         return;
1132     }
1133 #undef p_input
1134     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1135 }
1136
1137 - (void)updateMessageArray
1138 {
1139     int i_start, i_stop;
1140     vlc_value_t quiet;
1141
1142     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1143     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1144     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1145
1146     if( p_intf->p_sys->p_sub->i_start != i_stop )
1147     {
1148         NSColor *o_white = [NSColor whiteColor];
1149         NSColor *o_red = [NSColor redColor];
1150         NSColor *o_yellow = [NSColor yellowColor];
1151         NSColor *o_gray = [NSColor grayColor];
1152
1153         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1154         static const char * ppsz_type[4] = { ": ", " error: ",
1155                                              " warning: ", " debug: " };
1156
1157         for( i_start = p_intf->p_sys->p_sub->i_start;
1158              i_start != i_stop;
1159              i_start = (i_start+1) % VLC_MSG_QSIZE )
1160         {
1161             NSString *o_msg;
1162             NSDictionary *o_attr;
1163             NSAttributedString *o_msg_color;
1164
1165             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1166
1167             [o_msg_lock lock];
1168
1169             if( [o_msg_arr count] + 2 > 400 )
1170             {
1171                 unsigned rid[] = { 0, 1 };
1172                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1173                            numIndices: sizeof(rid)/sizeof(rid[0])];
1174             }
1175
1176             o_attr = [NSDictionary dictionaryWithObject: o_gray
1177                 forKey: NSForegroundColorAttributeName];
1178             o_msg = [NSString stringWithFormat: @"%s%s",
1179                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1180                 ppsz_type[i_type]];
1181             o_msg_color = [[NSAttributedString alloc]
1182                 initWithString: o_msg attributes: o_attr];
1183             [o_msg_arr addObject: [o_msg_color autorelease]];
1184
1185             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1186                 forKey: NSForegroundColorAttributeName];
1187             o_msg = [NSString stringWithFormat: @"%s\n",
1188                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1189             o_msg_color = [[NSAttributedString alloc]
1190                 initWithString: o_msg attributes: o_attr];
1191             [o_msg_arr addObject: [o_msg_color autorelease]];
1192
1193             [o_msg_lock unlock];
1194
1195             var_Get( p_intf->p_vlc, "verbose", &quiet );
1196
1197             if( i_type == 1 && quiet.i_int > -1 )
1198             {
1199                 NSString *o_my_msg = [NSString stringWithFormat: @"%s: %s\n",
1200                     p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1201                     p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1202
1203                 NSRange s_r = NSMakeRange( [[o_err_msg string] length], 0 );
1204                 [o_err_msg setEditable: YES];
1205                 [o_err_msg setSelectedRange: s_r];
1206                 [o_err_msg insertText: o_my_msg];
1207
1208                 [o_error makeKeyAndOrderFront: self];
1209                 [o_err_msg setEditable: NO];
1210             }
1211         }
1212
1213         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1214         p_intf->p_sys->p_sub->i_start = i_start;
1215         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1216     }
1217 }
1218
1219 - (void)playStatusUpdated:(int)i_status
1220 {
1221     if( i_status == PLAYING_S )
1222     {
1223         [o_btn_play setImage: o_img_pause];
1224         [o_btn_play setAlternateImage: o_img_pause_pressed];
1225         [o_btn_play setToolTip: _NS("Pause")];
1226         [o_mi_play setTitle: _NS("Pause")];
1227         [o_dmi_play setTitle: _NS("Pause")];
1228     }
1229     else
1230     {
1231         [o_btn_play setImage: o_img_play];
1232         [o_btn_play setAlternateImage: o_img_play_pressed];
1233         [o_btn_play setToolTip: _NS("Play")];
1234         [o_mi_play setTitle: _NS("Play")];
1235         [o_dmi_play setTitle: _NS("Play")];
1236     }
1237 }
1238
1239 - (void)setSubmenusEnabled:(BOOL)b_enabled
1240 {
1241     [o_mi_program setEnabled: b_enabled];
1242     [o_mi_title setEnabled: b_enabled];
1243     [o_mi_chapter setEnabled: b_enabled];
1244     [o_mi_audiotrack setEnabled: b_enabled];
1245     [o_mi_visual setEnabled: b_enabled];
1246     [o_mi_videotrack setEnabled: b_enabled];
1247     [o_mi_subtitle setEnabled: b_enabled];
1248     [o_mi_channels setEnabled: b_enabled];
1249     [o_mi_deinterlace setEnabled: b_enabled];
1250     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1251     [o_mi_device setEnabled: b_enabled];
1252     [o_mi_screen setEnabled: b_enabled];
1253 }
1254
1255 - (void)manageVolumeSlider
1256 {
1257     audio_volume_t i_volume;
1258     aout_VolumeGet( p_intf, &i_volume );
1259
1260     if( i_volume != i_lastShownVolume )
1261     {
1262         i_lastShownVolume = i_volume;
1263         p_intf->p_sys->b_volume_update = TRUE;
1264     }
1265 }
1266
1267 - (IBAction)timesliderUpdate:(id)sender
1268 {
1269 #define p_input p_intf->p_sys->p_input
1270     float f_updated;
1271
1272     switch( [[NSApp currentEvent] type] )
1273     {
1274         case NSLeftMouseUp:
1275         case NSLeftMouseDown:
1276         case NSLeftMouseDragged:
1277             f_updated = [sender floatValue];
1278             break;
1279
1280         default:
1281             return;
1282     }
1283
1284     if( p_input != NULL )
1285     {
1286         vlc_value_t time;
1287         vlc_value_t pos;
1288         mtime_t i_seconds;
1289         NSString * o_time;
1290
1291         pos.f_float = f_updated / 10000.;
1292         var_Set( p_input, "position", pos );
1293         [o_timeslider setFloatValue: f_updated];
1294
1295         var_Get( p_input, "time", &time );
1296         i_seconds = time.i_time / 1000000;
1297
1298         o_time = [NSString stringWithFormat: @"%d:%02d:%02d",
1299                         (int) (i_seconds / (60 * 60)),
1300                         (int) (i_seconds / 60 % 60),
1301                         (int) (i_seconds % 60)];
1302         [o_timefield setStringValue: o_time];
1303     }
1304 #undef p_input
1305 }
1306
1307 - (void)terminate
1308 {
1309     playlist_t * p_playlist;
1310     vout_thread_t * p_vout;
1311
1312     /* Stop playback */
1313     if( ( p_playlist = vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
1314                                         FIND_ANYWHERE ) ) )
1315     {
1316         playlist_Stop( p_playlist );
1317         vlc_object_release( p_playlist );
1318     }
1319
1320     /* FIXME - Wait here until all vouts are terminated because
1321        libvlc's VLC_CleanUp destroys interfaces before vouts, which isn't
1322        good on OS X. We definitly need a cleaner way to handle this,
1323        but this may hopefully be good enough for now.
1324          -- titer 2003/11/22 */
1325     while( ( p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1326                                        FIND_ANYWHERE ) ) )
1327     {
1328         vlc_object_release( p_vout );
1329         msleep( 100000 );
1330     }
1331     msleep( 500000 );
1332
1333     if( o_img_pause_pressed != nil )
1334     {
1335         [o_img_pause_pressed release];
1336         o_img_pause_pressed = nil;
1337     }
1338
1339     if( o_img_pause_pressed != nil )
1340     {
1341         [o_img_pause_pressed release];
1342         o_img_pause_pressed = nil;
1343     }
1344
1345     if( o_img_pause != nil )
1346     {
1347         [o_img_pause release];
1348         o_img_pause = nil;
1349     }
1350
1351     if( o_img_play != nil )
1352     {
1353         [o_img_play release];
1354         o_img_play = nil;
1355     }
1356
1357     if( o_msg_arr != nil )
1358     {
1359         [o_msg_arr removeAllObjects];
1360         [o_msg_arr release];
1361         o_msg_arr = nil;
1362     }
1363
1364     if( o_msg_lock != nil )
1365     {
1366         [o_msg_lock release];
1367         o_msg_lock = nil;
1368     }
1369
1370     /* write cached user defaults to disk */
1371     [[NSUserDefaults standardUserDefaults] synchronize];
1372
1373     p_intf->b_die = VLC_TRUE;
1374     [NSApp stop:NULL];
1375 }
1376
1377 - (IBAction)clearRecentItems:(id)sender
1378 {
1379     [[NSDocumentController sharedDocumentController]
1380                           clearRecentDocuments: nil];
1381 }
1382
1383 - (void)openRecentItem:(id)sender
1384 {
1385     [self application: nil openFile: [sender title]];
1386 }
1387
1388 - (IBAction)intfOpenFile:(id)sender
1389 {
1390     if (!nib_open_loaded)
1391     {
1392         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1393         [o_open awakeFromNib];
1394         [o_open openFile];
1395     } else {
1396         [o_open openFile];
1397     }
1398 }
1399
1400 - (IBAction)intfOpenFileGeneric:(id)sender
1401 {
1402     if (!nib_open_loaded)
1403     {
1404         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1405         [o_open awakeFromNib];
1406         [o_open openFileGeneric];
1407     } else {
1408         [o_open openFileGeneric];
1409     }
1410 }
1411
1412 - (IBAction)intfOpenDisc:(id)sender
1413 {
1414     if (!nib_open_loaded)
1415     {
1416         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1417         [o_open awakeFromNib];
1418         [o_open openDisc];
1419     } else {
1420         [o_open openDisc];
1421     }
1422 }
1423
1424 - (IBAction)intfOpenNet:(id)sender
1425 {
1426     if (!nib_open_loaded)
1427     {
1428         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1429         [o_open awakeFromNib];
1430         [o_open openNet];
1431     } else {
1432         [o_open openNet];
1433     }
1434 }
1435
1436 - (IBAction)showWizard:(id)sender
1437 {
1438     if (!nib_wizard_loaded)
1439     {
1440         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1441         [o_wizard initStrings];
1442         [o_wizard showWizard];
1443     } else {
1444         [o_wizard showWizard];
1445     }
1446 }
1447
1448 - (IBAction)viewAbout:(id)sender
1449 {
1450     if (!nib_about_loaded)
1451     {
1452         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1453         [o_about showPanel];
1454     } else {
1455         [o_about showPanel];
1456     }
1457 }
1458
1459 - (IBAction)viewPreferences:(id)sender
1460 {
1461 /* GRUIIIIIIIK */
1462     if( o_prefs == nil )
1463         o_prefs = [[VLCPrefs alloc] init];
1464     [o_prefs showPrefs];
1465 }
1466
1467 - (IBAction)closeError:(id)sender
1468 {
1469     vlc_value_t val;
1470
1471     if( [o_err_ckbk_surpress state] == NSOnState )
1472     {
1473         val.i_int = -1;
1474         var_Set( p_intf->p_vlc, "verbose", val );
1475     }
1476     [o_err_msg setString: @""];
1477     [o_error performClose: self];
1478 }
1479
1480 - (IBAction)openReadMe:(id)sender
1481 {
1482     NSString * o_path = [[NSBundle mainBundle]
1483         pathForResource: @"README.MacOSX" ofType: @"rtf"];
1484
1485     [[NSWorkspace sharedWorkspace] openFile: o_path
1486                                    withApplication: @"TextEdit"];
1487 }
1488
1489 - (IBAction)openDocumentation:(id)sender
1490 {
1491     NSURL * o_url = [NSURL URLWithString:
1492         @"http://www.videolan.org/doc/"];
1493
1494     [[NSWorkspace sharedWorkspace] openURL: o_url];
1495 }
1496
1497 - (IBAction)reportABug:(id)sender
1498 {
1499     NSURL * o_url = [NSURL URLWithString:
1500         @"http://www.videolan.org/support/bug-reporting.html"];
1501
1502     [[NSWorkspace sharedWorkspace] openURL: o_url];
1503 }
1504
1505 - (IBAction)openWebsite:(id)sender
1506 {
1507     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
1508
1509     [[NSWorkspace sharedWorkspace] openURL: o_url];
1510 }
1511
1512 - (IBAction)openLicense:(id)sender
1513 {
1514     NSString * o_path = [[NSBundle mainBundle]
1515         pathForResource: @"COPYING" ofType: nil];
1516
1517     [[NSWorkspace sharedWorkspace] openFile: o_path
1518                                    withApplication: @"TextEdit"];
1519 }
1520
1521 - (IBAction)openForum:(id)sender
1522 {
1523     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
1524
1525     [[NSWorkspace sharedWorkspace] openURL: o_url];
1526 }
1527
1528 - (IBAction)openDonate:(id)sender
1529 {
1530     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
1531
1532     [[NSWorkspace sharedWorkspace] openURL: o_url];
1533 }
1534
1535 - (IBAction)openCrashLog:(id)sender
1536 {
1537     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
1538                                     stringByExpandingTildeInPath];
1539
1540
1541     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
1542     {
1543         [[NSWorkspace sharedWorkspace] openFile: o_path
1544                                     withApplication: @"Console"];
1545     }
1546     else
1547     {
1548         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), @"Continue", nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("You haven't experienced any heavy crashes yet.") );
1549
1550     }
1551 }
1552
1553 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1554 {
1555     if( [o_notification object] == o_msgs_panel )
1556     {
1557         id o_msg;
1558         NSEnumerator * o_enum;
1559
1560         [o_messages setString: @""];
1561
1562         [o_msg_lock lock];
1563
1564         o_enum = [o_msg_arr objectEnumerator];
1565
1566         while( ( o_msg = [o_enum nextObject] ) != nil )
1567         {
1568             [o_messages insertText: o_msg];
1569         }
1570
1571         [o_msg_lock unlock];
1572     }
1573 }
1574
1575 - (IBAction)togglePlaylist:(id)sender
1576 {
1577     NSRect o_rect = [o_window frame];
1578     /*First, check if the playlist is visible*/
1579     if( o_rect.size.height <= 200 )
1580     {
1581         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
1582         /* make large */
1583         if ( o_size_with_playlist.height > 200 )
1584         {
1585             o_rect.size.height = o_size_with_playlist.height;
1586         } else {
1587             o_rect.size.height = 500;
1588         }
1589         
1590         if ( o_size_with_playlist.width > [o_window minSize].width )
1591         {
1592             o_rect.size.width = o_size_with_playlist.width;
1593         } else {
1594             o_rect.size.width = 500;
1595         }
1596         
1597         o_rect.size.height = (o_size_with_playlist.height > 200) ?
1598             o_size_with_playlist.height : 500;
1599         o_rect.origin.x = [o_window frame].origin.x;
1600         o_rect.origin.y = [o_window frame].origin.y - o_rect.size.height +
1601                                                 [o_window minSize].height;
1602         [o_btn_playlist setState: YES];
1603     }
1604     else
1605     {
1606         /* make small */
1607         o_rect.size.height = [o_window minSize].height;
1608         o_rect.size.width = [o_window minSize].width;
1609         o_rect.origin.x = [o_window frame].origin.x;
1610         /* Calculate the position of the lower right corner after resize */
1611         o_rect.origin.y = [o_window frame].origin.y +
1612             [o_window frame].size.height - [o_window minSize].height;
1613
1614         [o_playlist_view setAutoresizesSubviews: NO];
1615         [o_playlist_view removeFromSuperview];
1616         [o_btn_playlist setState: NO];
1617         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
1618     }
1619
1620     [o_window setFrame: o_rect display:YES animate: YES];
1621 }
1622
1623 - (void)updateTogglePlaylistState
1624 {
1625     if( [o_window frame].size.height <= 200 )
1626     {
1627         [o_btn_playlist setState: NO];
1628     }
1629     else
1630     {
1631         [o_btn_playlist setState: YES];
1632     }
1633 }
1634
1635 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
1636 {
1637     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
1638
1639    /*Stores the size the controller one resize, to be able to restore it when
1640      toggling the playlist*/
1641     o_size_with_playlist = proposedFrameSize;
1642
1643     if( proposedFrameSize.height <= 200 )
1644     {
1645         if( b_small_window == NO )
1646         {
1647             /* if large and going to small then hide */
1648             b_small_window = YES;
1649             [o_playlist_view setAutoresizesSubviews: NO];
1650             [o_playlist_view removeFromSuperview];
1651         }
1652         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
1653     }
1654     return proposedFrameSize;
1655 }
1656
1657 - (void)windowDidResize:(NSNotification *)notif
1658 {
1659     if( [o_window frame].size.height > 200 && b_small_window )
1660     {
1661         /* If large and coming from small then show */
1662         [o_playlist_view setAutoresizesSubviews: YES];
1663         [o_playlist_view setFrame: NSMakeRect( 10, 10, [o_window frame].size.width - 20, [o_window frame].size.height - [o_window minSize].height - 10 )];
1664         [o_playlist_view setNeedsDisplay:YES];
1665         [[o_window contentView] addSubview: o_playlist_view];
1666         b_small_window = NO;
1667     }
1668     [self updateTogglePlaylistState];
1669 }
1670
1671 @end
1672
1673 @implementation VLCMain (NSMenuValidation)
1674
1675 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
1676 {
1677     NSString *o_title = [o_mi title];
1678     BOOL bEnabled = TRUE;
1679
1680     /* Recent Items Menu */
1681     if( [o_title isEqualToString: _NS("Clear Menu")] )
1682     {
1683         NSMenu * o_menu = [o_mi_open_recent submenu];
1684         int i_nb_items = [o_menu numberOfItems];
1685         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
1686                                                        recentDocumentURLs];
1687         UInt32 i_nb_docs = [o_docs count];
1688
1689         if( i_nb_items > 1 )
1690         {
1691             while( --i_nb_items )
1692             {
1693                 [o_menu removeItemAtIndex: 0];
1694             }
1695         }
1696
1697         if( i_nb_docs > 0 )
1698         {
1699             NSURL * o_url;
1700             NSString * o_doc;
1701
1702             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
1703
1704             while( TRUE )
1705             {
1706                 i_nb_docs--;
1707
1708                 o_url = [o_docs objectAtIndex: i_nb_docs];
1709
1710                 if( [o_url isFileURL] )
1711                 {
1712                     o_doc = [o_url path];
1713                 }
1714                 else
1715                 {
1716                     o_doc = [o_url absoluteString];
1717                 }
1718
1719                 [o_menu insertItemWithTitle: o_doc
1720                     action: @selector(openRecentItem:)
1721                     keyEquivalent: @"" atIndex: 0];
1722
1723                 if( i_nb_docs == 0 )
1724                 {
1725                     break;
1726                 }
1727             }
1728         }
1729         else
1730         {
1731             bEnabled = FALSE;
1732         }
1733     }
1734     return( bEnabled );
1735 }
1736
1737 @end
1738
1739 @implementation VLCMain (Internal)
1740
1741 - (void)handlePortMessage:(NSPortMessage *)o_msg
1742 {
1743     id ** val;
1744     NSData * o_data;
1745     NSValue * o_value;
1746     NSInvocation * o_inv;
1747     NSConditionLock * o_lock;
1748
1749     o_data = [[o_msg components] lastObject];
1750     o_inv = *((NSInvocation **)[o_data bytes]);
1751     [o_inv getArgument: &o_value atIndex: 2];
1752     val = (id **)[o_value pointerValue];
1753     [o_inv setArgument: val[1] atIndex: 2];
1754     o_lock = *(val[0]);
1755
1756     [o_lock lock];
1757     [o_inv invoke];
1758     [o_lock unlockWithCondition: 1];
1759 }
1760
1761 @end