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