misc/events.c: Fix event sending, by properly supporting event_manager edition (event...
[vlc.git] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2007 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  *          Felix Paul K├╝hne <fkuehne at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <stdlib.h>                                      /* malloc(), free() */
31 #include <sys/param.h>                                    /* for MAXPATHLEN */
32 #include <string.h>
33 #include <vlc_keys.h>
34
35 #import "intf.h"
36 #import "fspanel.h"
37 #import "vout.h"
38 #import "prefs.h"
39 #import "playlist.h"
40 #import "controls.h"
41 #import "about.h"
42 #import "open.h"
43 #import "wizard.h"
44 #import "extended.h"
45 #import "bookmarks.h"
46 #import "sfilters.h"
47 #import "interaction.h"
48 #import "embeddedwindow.h"
49 #import "update.h"
50 #import "AppleRemote.h"
51 #import "eyetv.h"
52
53 #import <vlc_input.h>
54
55 /*****************************************************************************
56  * Local prototypes.
57  *****************************************************************************/
58 static void Run ( intf_thread_t *p_intf );
59
60 /* Quick hack */
61 /*****************************************************************************
62  * VLCApplication implementation (this hack is really disgusting now,
63  *                                feel free to fix.)
64  *****************************************************************************/
65 @interface VLCApplication : NSApplication
66 {
67    libvlc_int_t *o_libvlc;
68 }
69 - (void)setVLC: (libvlc_int_t *)p_libvlc;
70 @end
71
72
73 @implementation VLCApplication
74 - (void)setVLC: (libvlc_int_t *) p_libvlc
75 {
76     o_libvlc = p_libvlc;
77 }
78 - (void)terminate: (id)sender
79 {
80     vlc_object_kill( o_libvlc );
81     [super terminate: sender];
82 }
83 @end
84
85 /*****************************************************************************
86  * OpenIntf: initialize interface
87  *****************************************************************************/
88 int E_(OpenIntf) ( vlc_object_t *p_this )
89 {
90     intf_thread_t *p_intf = (intf_thread_t*) p_this;
91
92     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
93     if( p_intf->p_sys == NULL )
94     {
95         return( 1 );
96     }
97
98     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
99
100     p_intf->p_sys->o_pool = [[NSAutoreleasePool alloc] init];
101
102     p_intf->p_sys->o_sendport = [[NSPort port] retain];
103     p_intf->p_sys->p_sub = msg_Subscribe( p_intf, MSG_QUEUE_NORMAL );
104     p_intf->b_play = VLC_TRUE;
105     p_intf->pf_run = Run;
106     p_intf->b_should_run_on_first_thread = VLC_TRUE;
107
108     return( 0 );
109 }
110
111 /*****************************************************************************
112  * CloseIntf: destroy interface
113  *****************************************************************************/
114 void E_(CloseIntf) ( vlc_object_t *p_this )
115 {
116     intf_thread_t *p_intf = (intf_thread_t*) p_this;
117
118     msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
119
120     [p_intf->p_sys->o_sendport release];
121     [p_intf->p_sys->o_pool release];
122
123     free( p_intf->p_sys );
124 }
125
126 /*****************************************************************************
127  * Run: main loop
128  *****************************************************************************/
129 jmp_buf jmpbuffer;
130
131 static void Run( intf_thread_t *p_intf )
132 {
133     sigset_t set;
134
135     /* Do it again - for some unknown reason, vlc_thread_create() often
136      * fails to go to real-time priority with the first launched thread
137      * (???) --Meuuh */
138     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
139
140     /* Make sure the "force quit" menu item does quit instantly.
141      * VLC overrides SIGTERM which is sent by the "force quit"
142      * menu item to make sure deamon mode quits gracefully, so
143      * we un-override SIGTERM here. */
144     sigemptyset( &set );
145     sigaddset( &set, SIGTERM );
146     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
147
148     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
149
150     /* Install a jmpbuffer to where we can go back before the NSApp exit
151      * see applicationWillTerminate: */
152     /* We need that code to run on main thread */
153     [VLCApplication sharedApplication];
154     [NSApp setVLC: p_intf->p_libvlc];
155
156     [[VLCMain sharedInstance] setIntf: p_intf];
157     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
158
159     /* Install a jmpbuffer to where we can go back before the NSApp exit
160      * see applicationWillTerminate: */
161     if(setjmp(jmpbuffer) == 0)
162         [NSApp run];
163
164     [o_pool release];
165 }
166
167 int ExecuteOnMainThread( id target, SEL sel, void * p_arg )
168 {
169     int i_ret = 0;
170
171     //NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
172
173     if( [target respondsToSelector: @selector(performSelectorOnMainThread:
174                                              withObject:waitUntilDone:)] )
175     {
176         [target performSelectorOnMainThread: sel
177                 withObject: [NSValue valueWithPointer: p_arg]
178                 waitUntilDone: NO];
179     }
180     else if( NSApp != nil && [[VLCMain sharedInstance] respondsToSelector: @selector(getIntf)] )
181     {
182         NSValue * o_v1;
183         NSValue * o_v2;
184         NSArray * o_array;
185         NSPort * o_recv_port;
186         NSInvocation * o_inv;
187         NSPortMessage * o_msg;
188         intf_thread_t * p_intf;
189         NSConditionLock * o_lock;
190         NSMethodSignature * o_sig;
191
192         id * val[] = { &o_lock, &o_v2 };
193
194         p_intf = (intf_thread_t *)VLCIntf;
195
196         o_recv_port = [[NSPort port] retain];
197         o_v1 = [NSValue valueWithPointer: val];
198         o_v2 = [NSValue valueWithPointer: p_arg];
199
200         o_sig = [target methodSignatureForSelector: sel];
201         o_inv = [NSInvocation invocationWithMethodSignature: o_sig];
202         [o_inv setArgument: &o_v1 atIndex: 2];
203         [o_inv setTarget: target];
204         [o_inv setSelector: sel];
205
206         o_array = [NSArray arrayWithObject:
207             [NSData dataWithBytes: &o_inv length: sizeof(o_inv)]];
208         o_msg = [[NSPortMessage alloc]
209             initWithSendPort: p_intf->p_sys->o_sendport
210             receivePort: o_recv_port components: o_array];
211
212         o_lock = [[NSConditionLock alloc] initWithCondition: 0];
213         [o_msg sendBeforeDate: [NSDate distantPast]];
214         [o_lock lockWhenCondition: 1];
215         [o_lock unlock];
216         [o_lock release];
217
218         [o_msg release];
219         [o_recv_port release];
220     }
221     else
222     {
223         i_ret = 1;
224     }
225
226     //[o_pool release];
227
228     return( i_ret );
229 }
230
231 /*****************************************************************************
232  * playlistChanged: Callback triggered by the intf-change playlist
233  * variable, to let the intf update the playlist.
234  *****************************************************************************/
235 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
236                      vlc_value_t old_val, vlc_value_t new_val, void *param )
237 {
238     intf_thread_t * p_intf = VLCIntf;
239     p_intf->p_sys->b_playlist_update = VLC_TRUE;
240     p_intf->p_sys->b_intf_update = VLC_TRUE;
241     p_intf->p_sys->b_playmode_update = VLC_TRUE;
242     p_intf->p_sys->b_current_title_update = VLC_TRUE;
243     return VLC_SUCCESS;
244 }
245
246 /*****************************************************************************
247  * ShowController: Callback triggered by the show-intf playlist variable
248  * through the ShowIntf-control-intf, to let us show the controller-win;
249  * usually when in fullscreen-mode
250  *****************************************************************************/
251 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
252                      vlc_value_t old_val, vlc_value_t new_val, void *param )
253 {
254     intf_thread_t * p_intf = VLCIntf;
255     p_intf->p_sys->b_intf_show = VLC_TRUE;
256     return VLC_SUCCESS;
257 }
258
259 /*****************************************************************************
260  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
261  * variable, to let the intf update the controller.
262  *****************************************************************************/
263 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
264                      vlc_value_t old_val, vlc_value_t new_val, void *param )
265 {
266     intf_thread_t * p_intf = VLCIntf;
267     p_intf->p_sys->b_fullscreen_update = VLC_TRUE;
268     return VLC_SUCCESS;
269 }
270
271 /*****************************************************************************
272  * InteractCallback: Callback triggered by the interaction
273  * variable, to let the intf display error and interaction dialogs
274  *****************************************************************************/
275 static int InteractCallback( vlc_object_t *p_this, const char *psz_variable,
276                      vlc_value_t old_val, vlc_value_t new_val, void *param )
277 {
278     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
279     VLCMain *interface = (VLCMain *)param;
280     interaction_dialog_t *p_dialog = (interaction_dialog_t *)(new_val.p_address);
281     NSValue *o_value = [NSValue valueWithPointer:p_dialog];
282  
283     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewInteractionEventNotification" object:[interface getInteractionList]
284      userInfo:[NSDictionary dictionaryWithObject:o_value forKey:@"VLCDialogPointer"]];
285  
286     [o_pool release];
287     return VLC_SUCCESS;
288 }
289
290 static struct
291 {
292     unichar i_nskey;
293     unsigned int i_vlckey;
294 } nskeys_to_vlckeys[] =
295 {
296     { NSUpArrowFunctionKey, KEY_UP },
297     { NSDownArrowFunctionKey, KEY_DOWN },
298     { NSLeftArrowFunctionKey, KEY_LEFT },
299     { NSRightArrowFunctionKey, KEY_RIGHT },
300     { NSF1FunctionKey, KEY_F1 },
301     { NSF2FunctionKey, KEY_F2 },
302     { NSF3FunctionKey, KEY_F3 },
303     { NSF4FunctionKey, KEY_F4 },
304     { NSF5FunctionKey, KEY_F5 },
305     { NSF6FunctionKey, KEY_F6 },
306     { NSF7FunctionKey, KEY_F7 },
307     { NSF8FunctionKey, KEY_F8 },
308     { NSF9FunctionKey, KEY_F9 },
309     { NSF10FunctionKey, KEY_F10 },
310     { NSF11FunctionKey, KEY_F11 },
311     { NSF12FunctionKey, KEY_F12 },
312     { NSHomeFunctionKey, KEY_HOME },
313     { NSEndFunctionKey, KEY_END },
314     { NSPageUpFunctionKey, KEY_PAGEUP },
315     { NSPageDownFunctionKey, KEY_PAGEDOWN },
316     { NSTabCharacter, KEY_TAB },
317     { NSCarriageReturnCharacter, KEY_ENTER },
318     { NSEnterCharacter, KEY_ENTER },
319     { NSBackspaceCharacter, KEY_BACKSPACE },
320     { (unichar) ' ', KEY_SPACE },
321     { (unichar) 0x1b, KEY_ESC },
322     {0,0}
323 };
324
325 unichar VLCKeyToCocoa( unsigned int i_key )
326 {
327     unsigned int i;
328
329     for( i = 0; nskeys_to_vlckeys[i].i_vlckey != 0; i++ )
330     {
331         if( nskeys_to_vlckeys[i].i_vlckey == (i_key & ~KEY_MODIFIER) )
332         {
333             return nskeys_to_vlckeys[i].i_nskey;
334         }
335     }
336     return (unichar)(i_key & ~KEY_MODIFIER);
337 }
338
339 unsigned int CocoaKeyToVLC( unichar i_key )
340 {
341     unsigned int i;
342
343     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
344     {
345         if( nskeys_to_vlckeys[i].i_nskey == i_key )
346         {
347             return nskeys_to_vlckeys[i].i_vlckey;
348         }
349     }
350     return (unsigned int)i_key;
351 }
352
353 unsigned int VLCModifiersToCocoa( unsigned int i_key )
354 {
355     unsigned int new = 0;
356     if( i_key & KEY_MODIFIER_COMMAND )
357         new |= NSCommandKeyMask;
358     if( i_key & KEY_MODIFIER_ALT )
359         new |= NSAlternateKeyMask;
360     if( i_key & KEY_MODIFIER_SHIFT )
361         new |= NSShiftKeyMask;
362     if( i_key & KEY_MODIFIER_CTRL )
363         new |= NSControlKeyMask;
364     return new;
365 }
366
367 /*****************************************************************************
368  * VLCMain implementation
369  *****************************************************************************/
370 @implementation VLCMain
371
372 static VLCMain *_o_sharedMainInstance = nil;
373
374 + (VLCMain *)sharedInstance
375 {
376     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
377 }
378
379 - (id)init
380 {
381     if( _o_sharedMainInstance) {
382         [self dealloc];
383     } else {
384         _o_sharedMainInstance = [super init];
385     }
386
387     o_about = [[VLAboutBox alloc] init];
388     o_prefs = [[VLCPrefs alloc] init];
389     o_open = [[VLCOpen alloc] init];
390     o_wizard = [[VLCWizard alloc] init];
391     o_extended = nil;
392     o_bookmarks = [[VLCBookmarks alloc] init];
393     o_embedded_list = [[VLCEmbeddedList alloc] init];
394     o_interaction_list = [[VLCInteractionList alloc] init];
395     o_sfilters = nil;
396 #ifdef UPDATE_CHECK
397     //FIXME o_update = [[VLCUpdate alloc] init];
398 #endif
399
400     i_lastShownVolume = -1;
401
402     o_remote = [[AppleRemote alloc] init];
403     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
404     [o_remote setDelegate: _o_sharedMainInstance];
405
406     o_eyetv = [[VLCEyeTVController alloc] init];
407
408     /* announce our launch to a potential eyetv plugin */
409     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
410                                                                    object: @"VLCEyeTVSupport"
411                                                                  userInfo: NULL
412                                                        deliverImmediately: YES];
413
414     return _o_sharedMainInstance;
415 }
416
417 - (void)setIntf: (intf_thread_t *)p_mainintf {
418     p_intf = p_mainintf;
419 }
420
421 - (intf_thread_t *)getIntf {
422     return p_intf;
423 }
424
425 - (void)awakeFromNib
426 {
427     unsigned int i_key = 0;
428     playlist_t *p_playlist;
429     vlc_value_t val;
430
431     /* Check if we already did this once. Opening the other nibs calls it too, because VLCMain is the owner */
432     if( nib_main_loaded ) return;
433
434     [self initStrings];
435     [o_window setExcludedFromWindowsMenu: TRUE];
436     [o_msgs_panel setExcludedFromWindowsMenu: TRUE];
437     [o_msgs_panel setDelegate: self];
438
439     i_key = config_GetInt( p_intf, "key-quit" );
440     [o_mi_quit setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
441     [o_mi_quit setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
442     i_key = config_GetInt( p_intf, "key-play-pause" );
443     [o_mi_play setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
444     [o_mi_play setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
445     i_key = config_GetInt( p_intf, "key-stop" );
446     [o_mi_stop setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
447     [o_mi_stop setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
448     i_key = config_GetInt( p_intf, "key-faster" );
449     [o_mi_faster setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
450     [o_mi_faster setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
451     i_key = config_GetInt( p_intf, "key-slower" );
452     [o_mi_slower setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
453     [o_mi_slower setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
454     i_key = config_GetInt( p_intf, "key-prev" );
455     [o_mi_previous setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
456     [o_mi_previous setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
457     i_key = config_GetInt( p_intf, "key-next" );
458     [o_mi_next setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
459     [o_mi_next setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
460     i_key = config_GetInt( p_intf, "key-jump+short" );
461     [o_mi_fwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
462     [o_mi_fwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
463     i_key = config_GetInt( p_intf, "key-jump-short" );
464     [o_mi_bwd setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
465     [o_mi_bwd setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
466     i_key = config_GetInt( p_intf, "key-jump+medium" );
467     [o_mi_fwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
468     [o_mi_fwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
469     i_key = config_GetInt( p_intf, "key-jump-medium" );
470     [o_mi_bwd1m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
471     [o_mi_bwd1m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
472     i_key = config_GetInt( p_intf, "key-jump+long" );
473     [o_mi_fwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
474     [o_mi_fwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
475     i_key = config_GetInt( p_intf, "key-jump-long" );
476     [o_mi_bwd5m setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
477     [o_mi_bwd5m setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
478     i_key = config_GetInt( p_intf, "key-vol-up" );
479     [o_mi_vol_up setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
480     [o_mi_vol_up setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
481     i_key = config_GetInt( p_intf, "key-vol-down" );
482     [o_mi_vol_down setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
483     [o_mi_vol_down setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
484     i_key = config_GetInt( p_intf, "key-vol-mute" );
485     [o_mi_mute setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
486     [o_mi_mute setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
487     i_key = config_GetInt( p_intf, "key-fullscreen" );
488     [o_mi_fullscreen setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
489     [o_mi_fullscreen setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
490     i_key = config_GetInt( p_intf, "key-snapshot" );
491     [o_mi_snapshot setKeyEquivalent: [NSString stringWithFormat:@"%C", VLCKeyToCocoa( i_key )]];
492     [o_mi_snapshot setKeyEquivalentModifierMask: VLCModifiersToCocoa(i_key)];
493
494     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
495
496     [self setSubmenusEnabled: FALSE];
497     [self manageVolumeSlider];
498     [o_window setDelegate: self];
499  
500     b_restore_size = false;
501     if( [o_window frame].size.height <= 200 )
502     {
503         b_small_window = YES;
504         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
505             [o_window frame].origin.y, [o_window frame].size.width,
506             [o_window minSize].height ) display: YES animate:YES];
507         [o_playlist_view setAutoresizesSubviews: NO];
508     }
509     else
510     {
511         b_small_window = NO;
512         [o_playlist_view setFrame: NSMakeRect( 10, 10, [o_window frame].size.width - 20, [o_window frame].size.height - 105 )];
513         [o_playlist_view setNeedsDisplay:YES];
514         [o_playlist_view setAutoresizesSubviews: YES];
515         [[o_window contentView] addSubview: o_playlist_view];
516     }
517     [self updateTogglePlaylistState];
518
519     o_size_with_playlist = [o_window frame].size;
520
521     p_playlist = pl_Yield( p_intf );
522
523     /* Check if we need to start playing */
524     if( p_intf->b_play )
525     {
526         playlist_Control( p_playlist, PLAYLIST_AUTOPLAY, VLC_FALSE );
527     }
528     var_Create( p_playlist, "fullscreen", VLC_VAR_BOOL | VLC_VAR_DOINHERIT);
529     val.b_bool = VLC_FALSE;
530
531     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
532     var_AddCallback( p_playlist, "intf-show", ShowController, self);
533
534     vlc_object_release( p_playlist );
535  
536     var_Create( p_intf, "interaction", VLC_VAR_ADDRESS );
537     var_AddCallback( p_intf, "interaction", InteractCallback, self );
538     p_intf->b_interaction = VLC_TRUE;
539
540     /* update the playmode stuff */
541     p_intf->p_sys->b_playmode_update = VLC_TRUE;
542
543     [[NSNotificationCenter defaultCenter] addObserver: self
544                                              selector: @selector(refreshVoutDeviceMenu:)
545                                                  name: NSApplicationDidChangeScreenParametersNotification
546                                                object: nil];
547
548     o_img_play = [NSImage imageNamed: @"play"];
549     o_img_pause = [NSImage imageNamed: @"pause"];    
550     
551     [self controlTintChanged];
552
553     [[NSNotificationCenter defaultCenter] addObserver: self
554                                              selector: @selector( controlTintChanged )
555                                                  name: NSControlTintDidChangeNotification
556                                                object: nil];
557     
558     nib_main_loaded = TRUE;
559 }
560
561 - (void)controlTintChanged
562 {
563     BOOL b_playing = NO;
564     
565     if( [o_btn_play alternateImage] == o_img_play_pressed )
566         b_playing = YES;
567     
568     if( [NSColor currentControlTint] == NSGraphiteControlTint )
569     {
570         o_img_play_pressed = [NSImage imageNamed: @"play_graphite"];
571         o_img_pause_pressed = [NSImage imageNamed: @"pause_graphite"];
572         
573         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_graphite"]];
574         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_graphite"]];
575         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_graphite"]];
576         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_graphite"]];
577         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_graphite"]];
578         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_graphite"]];
579         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_graphite"]];
580         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_graphite"]];
581     }
582     else
583     {
584         o_img_play_pressed = [NSImage imageNamed: @"play_blue"];
585         o_img_pause_pressed = [NSImage imageNamed: @"pause_blue"];
586         
587         [o_btn_prev setAlternateImage: [NSImage imageNamed: @"previous_blue"]];
588         [o_btn_rewind setAlternateImage: [NSImage imageNamed: @"skip_previous_blue"]];
589         [o_btn_stop setAlternateImage: [NSImage imageNamed: @"stop_blue"]];
590         [o_btn_ff setAlternateImage: [NSImage imageNamed: @"skip_forward_blue"]];
591         [o_btn_next setAlternateImage: [NSImage imageNamed: @"next_blue"]];
592         [o_btn_fullscreen setAlternateImage: [NSImage imageNamed: @"fullscreen_blue"]];
593         [o_btn_playlist setAlternateImage: [NSImage imageNamed: @"playlistdrawer_blue"]];
594         [o_btn_equalizer setAlternateImage: [NSImage imageNamed: @"equalizerdrawer_blue"]];
595     }
596     
597     if( b_playing )
598         [o_btn_play setAlternateImage: o_img_play_pressed];
599     else
600         [o_btn_play setAlternateImage: o_img_pause_pressed];
601 }
602
603 - (void)initStrings
604 {
605     [o_window setTitle: _NS("VLC - Controller")];
606     [self setScrollField:_NS("VLC media player") stopAfter:-1];
607
608     /* button controls */
609     [o_btn_prev setToolTip: _NS("Previous")];
610     [o_btn_rewind setToolTip: _NS("Rewind")];
611     [o_btn_play setToolTip: _NS("Play")];
612     [o_btn_stop setToolTip: _NS("Stop")];
613     [o_btn_ff setToolTip: _NS("Fast Forward")];
614     [o_btn_next setToolTip: _NS("Next")];
615     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
616     [o_volumeslider setToolTip: _NS("Volume")];
617     [o_timeslider setToolTip: _NS("Position")];
618     [o_btn_playlist setToolTip: _NS("Playlist")];
619
620     /* messages panel */
621     [o_msgs_panel setTitle: _NS("Messages")];
622     [o_msgs_btn_crashlog setTitle: _NS("Open CrashLog...")];
623
624     /* main menu */
625     [o_mi_about setTitle: [_NS("About VLC media player") \
626         stringByAppendingString: @"..."]];
627     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
628     [o_mi_prefs setTitle: _NS("Preferences...")];
629     [o_mi_add_intf setTitle: _NS("Add Interface")];
630     [o_mu_add_intf setTitle: _NS("Add Interface")];
631     [o_mi_services setTitle: _NS("Services")];
632     [o_mi_hide setTitle: _NS("Hide VLC")];
633     [o_mi_hide_others setTitle: _NS("Hide Others")];
634     [o_mi_show_all setTitle: _NS("Show All")];
635     [o_mi_quit setTitle: _NS("Quit VLC")];
636
637     [o_mu_file setTitle: _ANS("1:File")];
638     [o_mi_open_generic setTitle: _NS("Open File...")];
639     [o_mi_open_file setTitle: _NS("Quick Open File...")];
640     [o_mi_open_disc setTitle: _NS("Open Disc...")];
641     [o_mi_open_net setTitle: _NS("Open Network...")];
642     [o_mi_open_recent setTitle: _NS("Open Recent")];
643     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
644     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
645
646     [o_mu_edit setTitle: _NS("Edit")];
647     [o_mi_cut setTitle: _NS("Cut")];
648     [o_mi_copy setTitle: _NS("Copy")];
649     [o_mi_paste setTitle: _NS("Paste")];
650     [o_mi_clear setTitle: _NS("Clear")];
651     [o_mi_select_all setTitle: _NS("Select All")];
652
653     [o_mu_controls setTitle: _NS("Playback")];
654     [o_mi_play setTitle: _NS("Play")];
655     [o_mi_stop setTitle: _NS("Stop")];
656     [o_mi_faster setTitle: _NS("Faster")];
657     [o_mi_slower setTitle: _NS("Slower")];
658     [o_mi_previous setTitle: _NS("Previous")];
659     [o_mi_next setTitle: _NS("Next")];
660     [o_mi_random setTitle: _NS("Random")];
661     [o_mi_repeat setTitle: _NS("Repeat One")];
662     [o_mi_loop setTitle: _NS("Repeat All")];
663     [o_mi_fwd setTitle: _NS("Step Forward")];
664     [o_mi_bwd setTitle: _NS("Step Backward")];
665
666     [o_mi_program setTitle: _NS("Program")];
667     [o_mu_program setTitle: _NS("Program")];
668     [o_mi_title setTitle: _NS("Title")];
669     [o_mu_title setTitle: _NS("Title")];
670     [o_mi_chapter setTitle: _NS("Chapter")];
671     [o_mu_chapter setTitle: _NS("Chapter")];
672
673     [o_mu_audio setTitle: _NS("Audio")];
674     [o_mi_vol_up setTitle: _NS("Volume Up")];
675     [o_mi_vol_down setTitle: _NS("Volume Down")];
676     [o_mi_mute setTitle: _NS("Mute")];
677     [o_mi_audiotrack setTitle: _NS("Audio Track")];
678     [o_mu_audiotrack setTitle: _NS("Audio Track")];
679     [o_mi_channels setTitle: _NS("Audio Channels")];
680     [o_mu_channels setTitle: _NS("Audio Channels")];
681     [o_mi_device setTitle: _NS("Audio Device")];
682     [o_mu_device setTitle: _NS("Audio Device")];
683     [o_mi_visual setTitle: _NS("Visualizations")];
684     [o_mu_visual setTitle: _NS("Visualizations")];
685
686     [o_mu_video setTitle: _NS("Video")];
687     [o_mi_half_window setTitle: _NS("Half Size")];
688     [o_mi_normal_window setTitle: _NS("Normal Size")];
689     [o_mi_double_window setTitle: _NS("Double Size")];
690     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
691     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
692     [o_mi_floatontop setTitle: _NS("Float on Top")];
693     [o_mi_snapshot setTitle: _NS("Snapshot")];
694     [o_mi_videotrack setTitle: _NS("Video Track")];
695     [o_mu_videotrack setTitle: _NS("Video Track")];
696     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
697     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
698     [o_mi_crop setTitle: _NS("Crop")];
699     [o_mu_crop setTitle: _NS("Crop")];
700     [o_mi_screen setTitle: _NS("Video Device")];
701     [o_mu_screen setTitle: _NS("Video Device")];
702     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
703     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
704     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
705     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
706     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
707     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
708
709     [o_mu_window setTitle: _NS("Window")];
710     [o_mi_minimize setTitle: _NS("Minimize Window")];
711     [o_mi_close_window setTitle: _NS("Close Window")];
712     [o_mi_controller setTitle: _NS("Controller...")];
713     [o_mi_equalizer setTitle: _NS("Equalizer...")];
714     [o_mi_extended setTitle: _NS("Extended Controls...")];
715     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
716     [o_mi_playlist setTitle: _NS("Playlist...")];
717     [o_mi_info setTitle: _NS("Media Information...")];
718     [o_mi_messages setTitle: _NS("Messages...")];
719     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
720
721     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
722
723     [o_mu_help setTitle: _NS("Help")];
724     [o_mi_help setTitle: _NS("VLC media player Help...")];
725     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
726     [o_mi_license setTitle: _NS("License")];
727     [o_mi_documentation setTitle: _NS("Online Documentation...")];
728     [o_mi_website setTitle: _NS("VideoLAN Website...")];
729     [o_mi_donation setTitle: _NS("Make a donation...")];
730     [o_mi_forum setTitle: _NS("Online Forum...")];
731
732     /* dock menu */
733     [o_dmi_play setTitle: _NS("Play")];
734     [o_dmi_stop setTitle: _NS("Stop")];
735     [o_dmi_next setTitle: _NS("Next")];
736     [o_dmi_previous setTitle: _NS("Previous")];
737     [o_dmi_mute setTitle: _NS("Mute")];
738  
739     /* vout menu */
740     [o_vmi_play setTitle: _NS("Play")];
741     [o_vmi_stop setTitle: _NS("Stop")];
742     [o_vmi_prev setTitle: _NS("Previous")];
743     [o_vmi_next setTitle: _NS("Next")];
744     [o_vmi_volup setTitle: _NS("Volume Up")];
745     [o_vmi_voldown setTitle: _NS("Volume Down")];
746     [o_vmi_mute setTitle: _NS("Mute")];
747     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
748     [o_vmi_snapshot setTitle: _NS("Snapshot")];
749
750     [o_info_window setTitle: _NS("Media Information")];
751 }
752
753 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
754 {
755     o_msg_lock = [[NSLock alloc] init];
756     o_msg_arr = [[NSMutableArray arrayWithCapacity: 200] retain];
757
758     [p_intf->p_sys->o_sendport setDelegate: self];
759     [[NSRunLoop currentRunLoop]
760         addPort: p_intf->p_sys->o_sendport
761         forMode: NSDefaultRunLoopMode];
762
763     [NSTimer scheduledTimerWithTimeInterval: 0.5
764         target: self selector: @selector(manageIntf:)
765         userInfo: nil repeats: FALSE];
766
767     [NSThread detachNewThreadSelector: @selector(manage)
768         toTarget: self withObject: nil];
769
770     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
771         var: "intf-add" selector: @selector(toggleVar:)];
772
773     /* check whether the user runs a valid version of OSX; alert is auto-released */
774     if( MACOS_VERSION < 10.4f )
775     {
776         NSAlert *ourAlert;
777         int i_returnValue;
778         ourAlert = [NSAlert alertWithMessageText: _NS("Your version of Mac OS X is not supported")
779                         defaultButton: _NS("Quit")
780                       alternateButton: NULL
781                           otherButton: NULL
782             informativeTextWithFormat: _NS("VLC media player requires Mac OS X 10.4 or higher.")];
783         [ourAlert setAlertStyle: NSCriticalAlertStyle];
784         i_returnValue = [ourAlert runModal];
785         [NSApp terminate: self];
786     }
787
788     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
789 }
790
791 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
792 {
793     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
794     NSDictionary *o_dic = [NSDictionary dictionaryWithObjectsAndKeys: o_filename, @"ITEM_URL", nil];
795     if( b_autoplay )
796         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
797     else
798         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
799
800     return( TRUE );
801 }
802
803 - (NSString *)localizedString:(const char *)psz
804 {
805     NSString * o_str = nil;
806
807     if( psz != NULL )
808     {
809         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
810
811         if ( o_str == NULL )
812         {
813             msg_Err( VLCIntf, "could not translate: %s", psz );
814             return( @"" );
815         }
816     }
817     else
818     {
819         msg_Warn( VLCIntf, "can't translate empty strings" );
820         return( @"" );
821     }
822
823     return( o_str );
824 }
825
826 /* When user click in the Dock icon our double click in the finder */
827 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
828 {    
829     if (!hasVisibleWindows)
830         [o_window makeKeyAndOrderFront:self];
831
832     return YES;
833 }
834
835 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
836 {
837 #ifdef UPDATE_CHECK
838     /* Check for update silently on startup */
839     if ( !nib_update_loaded )
840         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
841
842     // FIXME
843     //if([o_update shouldCheckForUpdate])
844     //    [NSThread detachNewThreadSelector:@selector(checkForUpdate) toTarget:o_update withObject:NULL];
845 #endif
846
847     /* Handle sleep notification */
848     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
849            name:NSWorkspaceWillSleepNotification object:nil];
850 }
851
852 /* Listen to the remote in exclusive mode, only when VLC is the active
853    application */
854 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
855 {
856     [o_remote startListening: self];
857 }
858 - (void)applicationDidResignActive:(NSNotification *)aNotification
859 {
860     [o_remote stopListening: self];
861 }
862
863 /* Triggered when the computer goes to sleep */
864 - (void)computerWillSleep: (NSNotification *)notification
865 {
866     /* Pause */
867     if ( p_intf->p_sys->i_play_status == PLAYING_S )
868     {
869         vlc_value_t val;
870         val.i_int = config_GetInt( p_intf, "key-play-pause" );
871         var_Set( p_intf->p_libvlc, "key-pressed", val );
872     }
873 }
874
875 /* Helper method for the remote control interface in order to trigger forward/backward and volume
876    increase/decrease as long as the user holds the left/right, plus/minus button */
877 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
878 {
879     if (b_remote_button_hold)
880     {
881         switch([buttonIdentifierNumber intValue])
882         {
883             case kRemoteButtonRight_Hold:
884                   [o_controls forward: self];
885             break;
886             case kRemoteButtonLeft_Hold:
887                   [o_controls backward: self];
888             break;
889             case kRemoteButtonVolume_Plus_Hold:
890                 [o_controls volumeUp: self];
891             break;
892             case kRemoteButtonVolume_Minus_Hold:
893                 [o_controls volumeDown: self];
894             break;
895         }
896         if (b_remote_button_hold)
897         {
898             /* trigger event */
899             [self performSelector:@selector(executeHoldActionForRemoteButton:)
900                          withObject:buttonIdentifierNumber
901                          afterDelay:0.25];
902         }
903     }
904 }
905
906 /* Apple Remote callback */
907 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
908                pressedDown: (BOOL) pressedDown
909                 clickCount: (unsigned int) count
910 {
911     switch( buttonIdentifier )
912     {
913         case kRemoteButtonPlay:
914             if (count >= 2) {
915                 [o_controls toogleFullscreen:self];
916             } else {
917                 [o_controls play: self];
918             }
919             break;
920         case kRemoteButtonVolume_Plus:
921             [o_controls volumeUp: self];
922             break;
923         case kRemoteButtonVolume_Minus:
924             [o_controls volumeDown: self];
925             break;
926         case kRemoteButtonRight:
927             [o_controls next: self];
928             break;
929         case kRemoteButtonLeft:
930             [o_controls prev: self];
931             break;
932         case kRemoteButtonRight_Hold:
933         case kRemoteButtonLeft_Hold:
934         case kRemoteButtonVolume_Plus_Hold:
935         case kRemoteButtonVolume_Minus_Hold:
936             /* simulate an event as long as the user holds the button */
937             b_remote_button_hold = pressedDown;
938             if( pressedDown )
939             {
940                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
941                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
942                            withObject:buttonIdentifierNumber];
943             }
944             break;
945         case kRemoteButtonMenu:
946             [o_controls showPosition: self];
947             break;
948         default:
949             /* Add here whatever you want other buttons to do */
950             break;
951     }
952 }
953
954 - (char *)delocalizeString:(NSString *)id
955 {
956     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
957                           allowLossyConversion: NO];
958     char * psz_string;
959
960     if ( o_data == nil )
961     {
962         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
963                      allowLossyConversion: YES];
964         psz_string = malloc( [o_data length] + 1 );
965         [o_data getBytes: psz_string];
966         psz_string[ [o_data length] ] = '\0';
967         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
968                  psz_string );
969     }
970     else
971     {
972         psz_string = malloc( [o_data length] + 1 );
973         [o_data getBytes: psz_string];
974         psz_string[ [o_data length] ] = '\0';
975     }
976
977     return psz_string;
978 }
979
980 /* i_width is in pixels */
981 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
982 {
983     NSMutableString *o_wrapped;
984     NSString *o_out_string;
985     NSRange glyphRange, effectiveRange, charRange;
986     NSRect lineFragmentRect;
987     unsigned glyphIndex, breaksInserted = 0;
988
989     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
990         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
991         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
992     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
993     NSTextContainer *o_container = [[NSTextContainer alloc]
994         initWithContainerSize: NSMakeSize(i_width, 2000)];
995
996     [o_layout_manager addTextContainer: o_container];
997     [o_container release];
998     [o_storage addLayoutManager: o_layout_manager];
999     [o_layout_manager release];
1000
1001     o_wrapped = [o_in_string mutableCopy];
1002     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1003
1004     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1005             glyphIndex += effectiveRange.length) {
1006         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1007                                             effectiveRange: &effectiveRange];
1008         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1009                                     actualGlyphRange: &effectiveRange];
1010         if ([o_wrapped lineRangeForRange:
1011                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1012             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1013             breaksInserted++;
1014         }
1015     }
1016     o_out_string = [NSString stringWithString: o_wrapped];
1017     [o_wrapped release];
1018     [o_storage release];
1019
1020     return o_out_string;
1021 }
1022
1023
1024 /*****************************************************************************
1025  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1026  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1027  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1028  *****************************************************************************/
1029 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1030 {
1031     unichar key = 0;
1032     vlc_value_t val;
1033     unsigned int i_pressed_modifiers = 0;
1034     struct hotkey *p_hotkeys;
1035     int i;
1036
1037     val.i_int = 0;
1038     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1039
1040     i_pressed_modifiers = [o_event modifierFlags];
1041
1042     if( i_pressed_modifiers & NSShiftKeyMask )
1043         val.i_int |= KEY_MODIFIER_SHIFT;
1044     if( i_pressed_modifiers & NSControlKeyMask )
1045         val.i_int |= KEY_MODIFIER_CTRL;
1046     if( i_pressed_modifiers & NSAlternateKeyMask )
1047         val.i_int |= KEY_MODIFIER_ALT;
1048     if( i_pressed_modifiers & NSCommandKeyMask )
1049         val.i_int |= KEY_MODIFIER_COMMAND;
1050
1051     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1052
1053     switch( key )
1054     {
1055         case NSDeleteCharacter:
1056         case NSDeleteFunctionKey:
1057         case NSDeleteCharFunctionKey:
1058         case NSBackspaceCharacter:
1059         case NSUpArrowFunctionKey:
1060         case NSDownArrowFunctionKey:
1061         case NSRightArrowFunctionKey:
1062         case NSLeftArrowFunctionKey:
1063         case NSEnterCharacter:
1064         case NSCarriageReturnCharacter:
1065             return NO;
1066     }
1067
1068     val.i_int |= CocoaKeyToVLC( key );
1069
1070     for( i = 0; p_hotkeys[i].psz_action != NULL; i++ )
1071     {
1072         if( p_hotkeys[i].i_key == val.i_int )
1073         {
1074             var_Set( p_intf->p_libvlc, "key-pressed", val );
1075             return YES;
1076         }
1077     }
1078
1079     return NO;
1080 }
1081
1082 - (id)getControls
1083 {
1084     if ( o_controls )
1085     {
1086         return o_controls;
1087     }
1088     return nil;
1089 }
1090
1091 - (id)getPlaylist
1092 {
1093     if( o_playlist )
1094         return o_playlist;
1095     return nil;
1096 }
1097
1098 - (id)getInfo
1099 {
1100     if ( o_info )
1101     {
1102         return o_info;
1103     }
1104     return nil;
1105 }
1106
1107 - (id)getWizard
1108 {
1109     if ( o_wizard )
1110     {
1111         return o_wizard;
1112     }
1113     return nil;
1114 }
1115
1116 - (id)getBookmarks
1117 {
1118     if ( o_bookmarks )
1119     {
1120         return o_bookmarks;
1121     }
1122     return nil;
1123 }
1124
1125 - (id)getEmbeddedList
1126 {
1127     if( o_embedded_list )
1128     {
1129         return o_embedded_list;
1130     }
1131     return nil;
1132 }
1133
1134 - (id)getInteractionList
1135 {
1136     if( o_interaction_list )
1137     {
1138         return o_interaction_list;
1139     }
1140     return nil;
1141 }
1142
1143 - (id)getMainIntfPgbar
1144 {
1145     if( o_main_pgbar )
1146         return o_main_pgbar;
1147
1148     msg_Err( p_intf, "main interface progress bar item wasn't found" );
1149     return nil;
1150 }
1151
1152 - (id)getControllerWindow
1153 {
1154     if( o_window )
1155         return o_window;
1156     return nil;
1157 }
1158
1159 - (id)getVoutMenu
1160 {
1161     return o_vout_menu;
1162 }
1163
1164 - (id)getEyeTVController
1165 {
1166     if( o_eyetv )
1167         return o_eyetv;
1168     return nil;
1169 }
1170
1171 - (void)manage
1172 {
1173     playlist_t * p_playlist;
1174
1175     /* new thread requires a new pool */
1176     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
1177
1178     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1179
1180     p_playlist = pl_Yield( p_intf );
1181
1182     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1183     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1184     var_AddCallback( p_playlist, "item-append", PlaylistChanged, self );
1185     var_AddCallback( p_playlist, "item-deleted", PlaylistChanged, self );
1186     var_AddCallback( p_playlist, "playlist-current", PlaylistChanged, self );
1187
1188     vlc_object_release( p_playlist );
1189
1190     while( !intf_ShouldDie( p_intf ) )
1191     {
1192         vlc_mutex_lock( &p_intf->change_lock );
1193
1194
1195         if( p_intf->p_sys->p_input == NULL )
1196         {
1197             p_intf->p_sys->p_input = p_playlist->p_input;
1198
1199                 /* Refresh the interface */
1200             if( p_intf->p_sys->p_input )
1201             {
1202                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1203                 p_intf->p_sys->b_input_update = VLC_TRUE;
1204             }
1205         }
1206         else if( p_intf->p_sys->p_input->b_die || p_intf->p_sys->p_input->b_dead )
1207         {
1208             /* input stopped */
1209             p_intf->p_sys->b_intf_update = VLC_TRUE;
1210             p_intf->p_sys->i_play_status = END_S;
1211             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1212             p_intf->p_sys->p_input = NULL;
1213         }
1214
1215         /* Manage volume status */
1216         [self manageVolumeSlider];
1217
1218         vlc_mutex_unlock( &p_intf->change_lock );
1219         msleep( 100000 );
1220     }
1221     [o_pool release];
1222 }
1223
1224 - (void)manageIntf:(NSTimer *)o_timer
1225 {
1226     vlc_value_t val;
1227     playlist_t * p_playlist;
1228     input_thread_t * p_input;
1229
1230     if( p_intf->p_libvlc->b_die == VLC_TRUE )
1231     {
1232         [o_timer invalidate];
1233         return;
1234     }
1235
1236     if( p_intf->p_sys->b_input_update )
1237     {
1238         /* Called when new input is opened */
1239         p_intf->p_sys->b_current_title_update = VLC_TRUE;
1240         p_intf->p_sys->b_intf_update = VLC_TRUE;
1241         p_intf->p_sys->b_input_update = VLC_FALSE;
1242     }
1243     if( p_intf->p_sys->b_intf_update )
1244     {
1245         vlc_bool_t b_input = VLC_FALSE;
1246         vlc_bool_t b_plmul = VLC_FALSE;
1247         vlc_bool_t b_control = VLC_FALSE;
1248         vlc_bool_t b_seekable = VLC_FALSE;
1249         vlc_bool_t b_chapters = VLC_FALSE;
1250
1251         playlist_t * p_playlist = pl_Yield( p_intf );
1252     /* TODO: fix i_size use */
1253         b_plmul = p_playlist->items.i_size > 1;
1254         p_input = p_playlist->p_input;
1255
1256         if( ( b_input = ( p_input != NULL ) ) )
1257         {
1258             /* seekable streams */
1259             vlc_object_yield( p_input );
1260             b_seekable = var_GetBool( p_input, "seekable" );
1261
1262             /* check whether slow/fast motion is possible */
1263             b_control = p_input->b_can_pace_control;
1264
1265             /* chapters & titles */
1266             //b_chapters = p_input->stream.i_area_nb > 1;
1267             vlc_object_release( p_input );
1268         }
1269         vlc_object_release( p_playlist );
1270
1271         [o_btn_stop setEnabled: b_input];
1272         [o_btn_ff setEnabled: b_seekable];
1273         [o_btn_rewind setEnabled: b_seekable];
1274         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1275         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1276
1277         [o_timeslider setFloatValue: 0.0];
1278         [o_timeslider setEnabled: b_seekable];
1279         [o_timefield setStringValue: @"00:00"];
1280         [[[self getControls] getFSPanel] setStreamPos: 0 andTime: @"00:00"];
1281         [[[self getControls] getFSPanel] setSeekable: b_seekable];
1282
1283         [o_embedded_window setSeekable: b_seekable];
1284
1285         p_intf->p_sys->b_current_title_update = VLC_TRUE;
1286         
1287         p_intf->p_sys->b_intf_update = VLC_FALSE;
1288     }
1289
1290     if( p_intf->p_sys->b_playmode_update )
1291     {
1292         [o_playlist playModeUpdated];
1293         p_intf->p_sys->b_playmode_update = VLC_FALSE;
1294     }
1295     if( p_intf->p_sys->b_playlist_update )
1296     {
1297         [o_playlist playlistUpdated];
1298         p_intf->p_sys->b_playlist_update = VLC_FALSE;
1299     }
1300
1301     if( p_intf->p_sys->b_fullscreen_update )
1302     {
1303         p_intf->p_sys->b_fullscreen_update = VLC_FALSE;
1304     }
1305
1306     if( p_intf->p_sys->b_intf_show )
1307     {
1308         [o_window makeKeyAndOrderFront: self];
1309
1310         p_intf->p_sys->b_intf_show = VLC_FALSE;
1311     }
1312
1313     p_playlist = pl_Yield( p_intf );
1314     p_input = p_playlist->p_input;
1315
1316     if( p_input && !p_input->b_die )
1317     {
1318         vlc_value_t val;
1319         vlc_object_yield( p_input );
1320
1321         if( p_intf->p_sys->b_current_title_update )
1322         {
1323             NSString *o_temp;
1324
1325             if( p_playlist->status.p_item == NULL )
1326             {
1327                 vlc_object_release( p_input );
1328                 vlc_object_release( p_playlist );
1329                 return;
1330             }
1331             o_temp = [NSString stringWithUTF8String:
1332                 p_playlist->status.p_item->p_input->psz_name];
1333             [self setScrollField: o_temp stopAfter:-1];
1334             [[[self getControls] getFSPanel] setStreamTitle: o_temp];
1335
1336             [[o_controls getVoutView] updateTitle];
1337  
1338             [o_playlist updateRowSelection];
1339             p_intf->p_sys->b_current_title_update = FALSE;
1340         }
1341
1342         if( [o_timeslider isEnabled] )
1343         {
1344             /* Update the slider */
1345             vlc_value_t time;
1346             NSString * o_time;
1347             vlc_value_t pos;
1348             char psz_time[MSTRTIME_MAX_SIZE];
1349             float f_updated;
1350
1351             var_Get( p_input, "position", &pos );
1352             f_updated = 10000. * pos.f_float;
1353             [o_timeslider setFloatValue: f_updated];
1354
1355             var_Get( p_input, "time", &time );
1356
1357             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1358
1359             [o_timefield setStringValue: o_time];
1360             [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1361             [o_embedded_window setTime: o_time position: f_updated];
1362         }
1363
1364         if( p_intf->p_sys->b_volume_update )
1365         {
1366             NSString *o_text;
1367             int i_volume_step = 0;
1368             o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1369             if( i_lastShownVolume != -1 )
1370             [self setScrollField:o_text stopAfter:1000000];
1371             i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1372             [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1373             [o_volumeslider setEnabled: TRUE];
1374             [[[self getControls] getFSPanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1375             p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1376             p_intf->p_sys->b_volume_update = FALSE;
1377         }
1378
1379         /* Manage Playing status */
1380         var_Get( p_input, "state", &val );
1381         if( p_intf->p_sys->i_play_status != val.i_int )
1382         {
1383             p_intf->p_sys->i_play_status = val.i_int;
1384             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1385             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1386         }
1387         vlc_object_release( p_input );
1388     }
1389     else
1390     {
1391         p_intf->p_sys->i_play_status = END_S;
1392         p_intf->p_sys->b_intf_update = VLC_TRUE;
1393         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1394         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1395         [self setSubmenusEnabled: FALSE];
1396     }
1397     vlc_object_release( p_playlist );
1398
1399     [self updateMessageArray];
1400
1401     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1402         [self resetScrollField];
1403
1404     [NSTimer scheduledTimerWithTimeInterval: 0.3
1405         target: self selector: @selector(manageIntf:)
1406         userInfo: nil repeats: FALSE];
1407 }
1408
1409 - (void)setupMenus
1410 {
1411     playlist_t * p_playlist = pl_Yield( p_intf );
1412     input_thread_t * p_input = p_playlist->p_input;
1413     if( p_input != NULL )
1414     {
1415         vlc_object_yield( p_input );
1416         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1417             var: "program" selector: @selector(toggleVar:)];
1418
1419         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1420             var: "title" selector: @selector(toggleVar:)];
1421
1422         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1423             var: "chapter" selector: @selector(toggleVar:)];
1424
1425         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1426             var: "audio-es" selector: @selector(toggleVar:)];
1427
1428         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1429             var: "video-es" selector: @selector(toggleVar:)];
1430
1431         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1432             var: "spu-es" selector: @selector(toggleVar:)];
1433
1434         aout_instance_t * p_aout = vlc_object_find( p_intf, VLC_OBJECT_AOUT,
1435                                                     FIND_ANYWHERE );
1436         if ( p_aout != NULL )
1437         {
1438             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1439                 var: "audio-channels" selector: @selector(toggleVar:)];
1440
1441             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1442                 var: "audio-device" selector: @selector(toggleVar:)];
1443
1444             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1445                 var: "visual" selector: @selector(toggleVar:)];
1446             vlc_object_release( (vlc_object_t *)p_aout );
1447         }
1448
1449         vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1450                                                             FIND_ANYWHERE );
1451
1452         if ( p_vout != NULL )
1453         {
1454             vlc_object_t * p_dec_obj;
1455
1456             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1457                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1458
1459             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1460                 var: "crop" selector: @selector(toggleVar:)];
1461
1462             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1463                 var: "video-device" selector: @selector(toggleVar:)];
1464
1465             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1466                 var: "deinterlace" selector: @selector(toggleVar:)];
1467
1468             p_dec_obj = (vlc_object_t *)vlc_object_find(
1469                                                  (vlc_object_t *)p_vout,
1470                                                  VLC_OBJECT_DECODER,
1471                                                  FIND_PARENT );
1472             if ( p_dec_obj != NULL )
1473             {
1474                [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1475                     (vlc_object_t *)p_dec_obj var:"ffmpeg-pp-q" selector:
1476                     @selector(toggleVar:)];
1477
1478                 vlc_object_release(p_dec_obj);
1479             }
1480             vlc_object_release( (vlc_object_t *)p_vout );
1481         }
1482         vlc_object_release( p_input );
1483     }
1484     vlc_object_release( p_playlist );
1485 }
1486
1487 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1488 {
1489     int x,y = 0;
1490     vout_thread_t * p_vout = vlc_object_find( p_intf, VLC_OBJECT_VOUT,
1491                                               FIND_ANYWHERE );
1492  
1493     if(! p_vout )
1494         return;
1495  
1496     /* clean the menu before adding new entries */
1497     if( [o_mi_screen hasSubmenu] )
1498     {
1499         y = [[o_mi_screen submenu] numberOfItems] - 1;
1500         msg_Dbg( VLCIntf, "%i items in submenu", y );
1501         while( x != y )
1502         {
1503             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
1504             [[o_mi_screen submenu] removeItemAtIndex: x];
1505             x++;
1506         }
1507     }
1508
1509     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1510                              var: "video-device" selector: @selector(toggleVar:)];
1511     vlc_object_release( (vlc_object_t *)p_vout );
1512 }
1513
1514 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
1515 {
1516     if( timeout != -1 )
1517         i_end_scroll = mdate() + timeout;
1518     else
1519         i_end_scroll = -1;
1520     [o_scrollfield setStringValue: o_string];
1521 }
1522
1523 - (void)resetScrollField
1524 {
1525     playlist_t * p_playlist = pl_Yield( p_intf );
1526     input_thread_t * p_input = p_playlist->p_input;
1527
1528     i_end_scroll = -1;
1529     if( p_input && !p_input->b_die )
1530     {
1531         NSString *o_temp;
1532         vlc_object_yield( p_input );
1533         o_temp = [NSString stringWithUTF8String:
1534                   p_playlist->status.p_item->p_input->psz_name];
1535         [self setScrollField: o_temp stopAfter:-1];
1536         vlc_object_release( p_input );
1537         vlc_object_release( p_playlist );
1538         return;
1539     }
1540     vlc_object_release( p_playlist );
1541     [self setScrollField: _NS("VLC media player") stopAfter:-1];
1542 }
1543
1544 - (void)updateMessageArray
1545 {
1546     int i_start, i_stop;
1547
1548     vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1549     i_stop = *p_intf->p_sys->p_sub->pi_stop;
1550     vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1551
1552     if( p_intf->p_sys->p_sub->i_start != i_stop )
1553     {
1554         NSColor *o_white = [NSColor whiteColor];
1555         NSColor *o_red = [NSColor redColor];
1556         NSColor *o_yellow = [NSColor yellowColor];
1557         NSColor *o_gray = [NSColor grayColor];
1558
1559         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1560         static const char * ppsz_type[4] = { ": ", " error: ",
1561                                              " warning: ", " debug: " };
1562
1563         for( i_start = p_intf->p_sys->p_sub->i_start;
1564              i_start != i_stop;
1565              i_start = (i_start+1) % VLC_MSG_QSIZE )
1566         {
1567             NSString *o_msg;
1568             NSDictionary *o_attr;
1569             NSAttributedString *o_msg_color;
1570
1571             int i_type = p_intf->p_sys->p_sub->p_msg[i_start].i_type;
1572
1573             [o_msg_lock lock];
1574
1575             if( [o_msg_arr count] + 2 > 400 )
1576             {
1577                 unsigned rid[] = { 0, 1 };
1578                 [o_msg_arr removeObjectsFromIndices: (unsigned *)&rid
1579                            numIndices: sizeof(rid)/sizeof(rid[0])];
1580             }
1581
1582             o_attr = [NSDictionary dictionaryWithObject: o_gray
1583                 forKey: NSForegroundColorAttributeName];
1584             o_msg = [NSString stringWithFormat: @"%s%s",
1585                 p_intf->p_sys->p_sub->p_msg[i_start].psz_module,
1586                 ppsz_type[i_type]];
1587             o_msg_color = [[NSAttributedString alloc]
1588                 initWithString: o_msg attributes: o_attr];
1589             [o_msg_arr addObject: [o_msg_color autorelease]];
1590
1591             o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
1592                 forKey: NSForegroundColorAttributeName];
1593             o_msg = [NSString stringWithFormat: @"%s\n",
1594                 p_intf->p_sys->p_sub->p_msg[i_start].psz_msg];
1595             o_msg_color = [[NSAttributedString alloc]
1596                 initWithString: o_msg attributes: o_attr];
1597             [o_msg_arr addObject: [o_msg_color autorelease]];
1598
1599             [o_msg_lock unlock];
1600         }
1601
1602         vlc_mutex_lock( p_intf->p_sys->p_sub->p_lock );
1603         p_intf->p_sys->p_sub->i_start = i_start;
1604         vlc_mutex_unlock( p_intf->p_sys->p_sub->p_lock );
1605     }
1606 }
1607
1608 - (void)playStatusUpdated:(int)i_status
1609 {
1610     if( i_status == PLAYING_S )
1611     {
1612         [[[self getControls] getFSPanel] setPause];
1613         [o_btn_play setImage: o_img_pause];
1614         [o_btn_play setAlternateImage: o_img_pause_pressed];
1615         [o_btn_play setToolTip: _NS("Pause")];
1616         [o_mi_play setTitle: _NS("Pause")];
1617         [o_dmi_play setTitle: _NS("Pause")];
1618         [o_vmi_play setTitle: _NS("Pause")];
1619     }
1620     else
1621     {
1622         [[[self getControls] getFSPanel] setPlay];
1623         [o_btn_play setImage: o_img_play];
1624         [o_btn_play setAlternateImage: o_img_play_pressed];
1625         [o_btn_play setToolTip: _NS("Play")];
1626         [o_mi_play setTitle: _NS("Play")];
1627         [o_dmi_play setTitle: _NS("Play")];
1628         [o_vmi_play setTitle: _NS("Play")];
1629     }
1630 }
1631
1632 - (void)setSubmenusEnabled:(BOOL)b_enabled
1633 {
1634     [o_mi_program setEnabled: b_enabled];
1635     [o_mi_title setEnabled: b_enabled];
1636     [o_mi_chapter setEnabled: b_enabled];
1637     [o_mi_audiotrack setEnabled: b_enabled];
1638     [o_mi_visual setEnabled: b_enabled];
1639     [o_mi_videotrack setEnabled: b_enabled];
1640     [o_mi_subtitle setEnabled: b_enabled];
1641     [o_mi_channels setEnabled: b_enabled];
1642     [o_mi_deinterlace setEnabled: b_enabled];
1643     [o_mi_ffmpeg_pp setEnabled: b_enabled];
1644     [o_mi_device setEnabled: b_enabled];
1645     [o_mi_screen setEnabled: b_enabled];
1646     [o_mi_aspect_ratio setEnabled: b_enabled];
1647     [o_mi_crop setEnabled: b_enabled];
1648 }
1649
1650 - (void)manageVolumeSlider
1651 {
1652     audio_volume_t i_volume;
1653     aout_VolumeGet( p_intf, &i_volume );
1654
1655     if( i_volume != i_lastShownVolume )
1656     {
1657         i_lastShownVolume = i_volume;
1658         p_intf->p_sys->b_volume_update = TRUE;
1659     }
1660 }
1661
1662 - (IBAction)timesliderUpdate:(id)sender
1663 {
1664     float f_updated;
1665     playlist_t * p_playlist;
1666     input_thread_t * p_input;
1667
1668     switch( [[NSApp currentEvent] type] )
1669     {
1670         case NSLeftMouseUp:
1671         case NSLeftMouseDown:
1672         case NSLeftMouseDragged:
1673             f_updated = [sender floatValue];
1674             break;
1675
1676         default:
1677             return;
1678     }
1679     p_playlist = pl_Yield( p_intf );
1680     p_input = p_playlist->p_input;
1681     if( p_input != NULL )
1682     {
1683         vlc_value_t time;
1684         vlc_value_t pos;
1685         NSString * o_time;
1686         char psz_time[MSTRTIME_MAX_SIZE];
1687         vlc_object_yield( p_input );
1688
1689         pos.f_float = f_updated / 10000.;
1690         var_Set( p_input, "position", pos );
1691         [o_timeslider setFloatValue: f_updated];
1692
1693         var_Get( p_input, "time", &time );
1694
1695         o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1696         [o_timefield setStringValue: o_time];
1697         [[[self getControls] getFSPanel] setStreamPos: f_updated andTime: o_time];
1698         [o_embedded_window setTime: o_time position: f_updated];
1699         vlc_object_release( p_input );
1700     }
1701     vlc_object_release( p_playlist );
1702 }
1703
1704 - (void)applicationWillTerminate:(NSNotification *)notification
1705 {
1706     playlist_t * p_playlist;
1707     vout_thread_t * p_vout;
1708     int returnedValue = 0;
1709  
1710     /* Stop playback */
1711     p_playlist = pl_Yield( p_intf );
1712     playlist_Stop( p_playlist );
1713     vlc_object_release( p_playlist );
1714
1715     /* make sure that the current volume is saved */
1716     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
1717     returnedValue = config_SaveConfigFile( p_intf->p_libvlc, "main" );
1718     if( returnedValue != 0 )
1719         msg_Err( p_intf,
1720                  "error while saving volume in osx's terminate method (%i)",
1721                  returnedValue );
1722
1723     /* save the prefs if they were changed in the extended panel */
1724     if (o_extended && [o_extended getConfigChanged])
1725     {
1726         [o_extended savePrefs];
1727     }
1728  
1729     p_intf->b_interaction = VLC_FALSE;
1730     var_DelCallback( p_intf, "interaction", InteractCallback, self );
1731
1732     /* remove global observer watching for vout device changes correctly */
1733     [[NSNotificationCenter defaultCenter] removeObserver: self];
1734
1735     /* release some other objects here, because it isn't sure whether dealloc
1736      * will be called later on */
1737     
1738     if( nib_about_loaded && o_about )
1739         [o_about release];
1740     
1741     if( nib_prefs_loaded && o_prefs )
1742         [o_prefs release];
1743     
1744     if( nib_open_loaded && o_open )
1745         [o_open release];
1746  
1747     if( nib_extended_loaded && o_extended )
1748     {
1749         [o_extended collapsAll];
1750         [o_extended release];
1751     }
1752  
1753     if( nib_bookmarks_loaded && o_bookmarks )
1754         [o_bookmarks release];
1755
1756     if( nib_wizard_loaded && o_wizard )
1757         [o_wizard release];
1758  
1759     if( o_embedded_list != nil )
1760         [o_embedded_list release];
1761
1762     if( o_interaction_list != nil )
1763         [o_interaction_list release];
1764
1765     if( o_eyetv != nil )
1766         [o_eyetv release];
1767
1768     if( o_img_pause_pressed != nil )
1769     {
1770         [o_img_pause_pressed release];
1771         o_img_pause_pressed = nil;
1772     }
1773
1774     if( o_img_play_pressed != nil )
1775     {
1776         [o_img_pause_pressed release];
1777         o_img_pause_pressed = nil;
1778     }
1779
1780     if( o_img_pause != nil )
1781     {
1782         [o_img_pause release];
1783         o_img_pause = nil;
1784     }
1785
1786     if( o_img_play != nil )
1787     {
1788         [o_img_play release];
1789         o_img_play = nil;
1790     }
1791
1792     if( o_msg_arr != nil )
1793     {
1794         [o_msg_arr removeAllObjects];
1795         [o_msg_arr release];
1796         o_msg_arr = nil;
1797     }
1798
1799     if( o_msg_lock != nil )
1800     {
1801         [o_msg_lock release];
1802         o_msg_lock = nil;
1803     }
1804
1805     /* write cached user defaults to disk */
1806     [[NSUserDefaults standardUserDefaults] synchronize];
1807
1808     vlc_object_kill( p_intf );
1809
1810     /* Go back to Run() and make libvlc exit properly */
1811     longjmp( jmpbuffer, 1 );
1812     /* not reached */
1813 }
1814
1815
1816 - (IBAction)clearRecentItems:(id)sender
1817 {
1818     [[NSDocumentController sharedDocumentController]
1819                           clearRecentDocuments: nil];
1820 }
1821
1822 - (void)openRecentItem:(id)sender
1823 {
1824     [self application: nil openFile: [sender title]];
1825 }
1826
1827 - (IBAction)intfOpenFile:(id)sender
1828 {
1829     if ( !nib_open_loaded )
1830     {
1831         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1832         [o_open awakeFromNib];
1833         [o_open openFile];
1834     } else {
1835         [o_open openFile];
1836     }
1837 }
1838
1839 - (IBAction)intfOpenFileGeneric:(id)sender
1840 {
1841     if ( !nib_open_loaded )
1842     {
1843         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1844         [o_open awakeFromNib];
1845         [o_open openFileGeneric];
1846     } else {
1847         [o_open openFileGeneric];
1848     }
1849 }
1850
1851 - (IBAction)intfOpenDisc:(id)sender
1852 {
1853     if ( !nib_open_loaded )
1854     {
1855         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1856         [o_open awakeFromNib];
1857         [o_open openDisc];
1858     } else {
1859         [o_open openDisc];
1860     }
1861 }
1862
1863 - (IBAction)intfOpenNet:(id)sender
1864 {
1865     if ( !nib_open_loaded )
1866     {
1867         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner:self];
1868         [o_open awakeFromNib];
1869         [o_open openNet];
1870     } else {
1871         [o_open openNet];
1872     }
1873 }
1874
1875 - (IBAction)showWizard:(id)sender
1876 {
1877     if ( !nib_wizard_loaded )
1878     {
1879         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1880         [o_wizard initStrings];
1881         [o_wizard resetWizard];
1882         [o_wizard showWizard];
1883     } else {
1884         [o_wizard resetWizard];
1885         [o_wizard showWizard];
1886     }
1887 }
1888
1889 - (IBAction)showExtended:(id)sender
1890 {
1891     if ( o_extended == nil )
1892     {
1893         o_extended = [[VLCExtended alloc] init];
1894     }
1895     if ( !nib_extended_loaded )
1896     {
1897         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner:self];
1898         [o_extended initStrings];
1899         [o_extended showPanel];
1900     } else {
1901         [o_extended showPanel];
1902     }
1903 }
1904
1905 - (IBAction)showSFilters:(id)sender
1906 {
1907     if ( o_sfilters == nil )
1908     {
1909         o_sfilters = [[VLCsFilters alloc] init];
1910     }
1911     if ( !nib_sfilters_loaded )
1912     {
1913         nib_sfilters_loaded = [NSBundle loadNibNamed:@"SFilters" owner:self];
1914         [o_sfilters initStrings];
1915         [o_sfilters showAsPanel];
1916     } else {
1917         [o_sfilters showAsPanel];
1918     }
1919 }
1920
1921 - (IBAction)showBookmarks:(id)sender
1922 {
1923     /* we need the wizard-nib for the bookmarks's extract functionality */
1924     if ( !nib_wizard_loaded )
1925     {
1926         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner:self];
1927         [o_wizard initStrings];
1928     }
1929  
1930     if ( !nib_bookmarks_loaded )
1931         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner:self];
1932
1933     [o_bookmarks showBookmarks];
1934 }
1935
1936 - (IBAction)viewAbout:(id)sender
1937 {
1938     if( !nib_about_loaded )
1939         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1940
1941     [o_about showAbout];
1942 }
1943
1944 - (IBAction)showLicense:(id)sender
1945 {
1946     if( !nib_about_loaded )
1947         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1948
1949     [o_about showGPL: sender];
1950 }
1951     
1952 - (IBAction)viewPreferences:(id)sender
1953 {
1954     if( !nib_prefs_loaded )
1955         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: self];
1956
1957     [o_prefs showPrefs];
1958 }
1959
1960 #ifdef UPDATE_CHECK
1961 - (IBAction)checkForUpdate:(id)sender
1962 {/* FIXME
1963     if( !nib_update_loaded )
1964         nib_update_loaded = [NSBundle loadNibNamed:@"Update" owner:self];
1965
1966     [o_update showUpdateWindow];
1967 */}
1968 #endif
1969
1970 - (IBAction)viewHelp:(id)sender
1971 {
1972     if( !nib_about_loaded )
1973     {
1974         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner:self];
1975         [o_about showHelp];
1976     }
1977     else
1978         [o_about showHelp];
1979 }
1980
1981 - (IBAction)openReadMe:(id)sender
1982 {
1983     NSString * o_path = [[NSBundle mainBundle]
1984         pathForResource: @"README.MacOSX" ofType: @"rtf"];
1985
1986     [[NSWorkspace sharedWorkspace] openFile: o_path
1987                                    withApplication: @"TextEdit"];
1988 }
1989
1990 - (IBAction)openDocumentation:(id)sender
1991 {
1992     NSURL * o_url = [NSURL URLWithString:
1993         @"http://www.videolan.org/doc/"];
1994
1995     [[NSWorkspace sharedWorkspace] openURL: o_url];
1996 }
1997
1998 - (IBAction)openWebsite:(id)sender
1999 {
2000     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2001
2002     [[NSWorkspace sharedWorkspace] openURL: o_url];
2003 }
2004
2005 - (IBAction)openForum:(id)sender
2006 {
2007     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2008
2009     [[NSWorkspace sharedWorkspace] openURL: o_url];
2010 }
2011
2012 - (IBAction)openDonate:(id)sender
2013 {
2014     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2015
2016     [[NSWorkspace sharedWorkspace] openURL: o_url];
2017 }
2018
2019 - (IBAction)openCrashLog:(id)sender
2020 {
2021     NSString * o_path = [@"~/Library/Logs/CrashReporter/VLC.crash.log"
2022                                     stringByExpandingTildeInPath];
2023
2024
2025     if ( [[NSFileManager defaultManager] fileExistsAtPath: o_path ] )
2026     {
2027         [[NSWorkspace sharedWorkspace] openFile: o_path
2028                                     withApplication: @"Console"];
2029     }
2030     else
2031     {
2032         NSBeginInformationalAlertSheet(_NS("No CrashLog found"), @"Continue", nil, nil, o_msgs_panel, self, NULL, NULL, nil, _NS("Couldn't find any trace of a previous crash.") );
2033
2034     }
2035 }
2036
2037 - (IBAction)viewErrorsAndWarnings:(id)sender
2038 {
2039     [[[self getInteractionList] getErrorPanel] showPanel];
2040 }
2041
2042 - (IBAction)showMessagesPanel:(id)sender
2043 {
2044     [o_msgs_panel makeKeyAndOrderFront: sender];
2045 }
2046
2047 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2048 {
2049     if( [o_notification object] == o_msgs_panel )
2050     {
2051         id o_msg;
2052         NSEnumerator * o_enum;
2053
2054         [o_messages setString: @""];
2055
2056         [o_msg_lock lock];
2057
2058         o_enum = [o_msg_arr objectEnumerator];
2059
2060         while( ( o_msg = [o_enum nextObject] ) != nil )
2061         {
2062             [o_messages insertText: o_msg];
2063         }
2064
2065         [o_msg_lock unlock];
2066     }
2067 }
2068
2069 - (IBAction)togglePlaylist:(id)sender
2070 {
2071     NSRect o_rect = [o_window frame];
2072     /*First, check if the playlist is visible*/
2073     if( o_rect.size.height <= 200 )
2074     {
2075         o_restore_rect = o_rect;
2076         b_restore_size = true;
2077         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2078         /* make large */
2079         if ( o_size_with_playlist.height > 200 )
2080         {
2081             o_rect.size.height = o_size_with_playlist.height;
2082         } else {
2083             o_rect.size.height = 500;
2084         }
2085  
2086         if ( o_size_with_playlist.width > [o_window minSize].width )
2087         {
2088             o_rect.size.width = o_size_with_playlist.width;
2089         } else {
2090             o_rect.size.width = 500;
2091         }
2092  
2093         o_rect.size.height = (o_size_with_playlist.height > 200) ?
2094             o_size_with_playlist.height : 500;
2095         o_rect.origin.x = [o_window frame].origin.x;
2096         o_rect.origin.y = [o_window frame].origin.y - o_rect.size.height +
2097                                                 [o_window minSize].height;
2098
2099         NSRect screenRect = [[o_window screen] visibleFrame];
2100         if ( !NSContainsRect( screenRect, o_rect ) ) {
2101             if ( NSMaxX(o_rect) > NSMaxX(screenRect) )
2102                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2103             if ( NSMinY(o_rect) < NSMinY(screenRect) )
2104                 o_rect.origin.y = ( NSMinY(screenRect) );
2105         }
2106
2107         [o_btn_playlist setState: YES];
2108     }
2109     else
2110     {
2111         NSSize curSize = o_rect.size;
2112         /* make small */
2113         o_rect.size.height = [o_window minSize].height;
2114         o_rect.size.width = [o_window minSize].width;
2115         o_rect.origin.x = [o_window frame].origin.x;
2116         /* Calculate the position of the lower right corner after resize */
2117         o_rect.origin.y = [o_window frame].origin.y +
2118             [o_window frame].size.height - [o_window minSize].height;
2119
2120         if ( b_restore_size )
2121             o_rect = o_restore_rect;
2122
2123         [o_playlist_view setAutoresizesSubviews: NO];
2124         [o_playlist_view removeFromSuperview];
2125         [o_btn_playlist setState: NO];
2126         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2127     }
2128
2129     [o_window setFrame: o_rect display:YES animate: YES];
2130 }
2131
2132 - (void)updateTogglePlaylistState
2133 {
2134     if( [o_window frame].size.height <= 200 )
2135     {
2136         [o_btn_playlist setState: NO];
2137     }
2138     else
2139     {
2140         [o_btn_playlist setState: YES];
2141     }
2142 }
2143
2144 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2145 {
2146     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2147
2148    /*Stores the size the controller one resize, to be able to restore it when
2149      toggling the playlist*/
2150     o_size_with_playlist = proposedFrameSize;
2151
2152     if( proposedFrameSize.height <= 200 )
2153     {
2154         if( b_small_window == NO )
2155         {
2156             /* if large and going to small then hide */
2157             b_small_window = YES;
2158             [o_playlist_view setAutoresizesSubviews: NO];
2159             [o_playlist_view removeFromSuperview];
2160         }
2161         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2162     }
2163     return proposedFrameSize;
2164 }
2165
2166 - (void)windowDidMove:(NSNotification *)notif
2167 {
2168     b_restore_size = false;
2169 }
2170
2171 - (void)windowDidResize:(NSNotification *)notif
2172 {
2173     if( [o_window frame].size.height > 200 && b_small_window )
2174     {
2175         /* If large and coming from small then show */
2176         [o_playlist_view setAutoresizesSubviews: YES];
2177         [o_playlist_view setFrame: NSMakeRect( 10, 10, [o_window frame].size.width - 20, [o_window frame].size.height - [o_window minSize].height - 10 )];
2178         [o_playlist_view setNeedsDisplay:YES];
2179         [[o_window contentView] addSubview: o_playlist_view];
2180         b_small_window = NO;
2181     }
2182     [self updateTogglePlaylistState];
2183 }
2184
2185 @end
2186
2187 @implementation VLCMain (NSMenuValidation)
2188
2189 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2190 {
2191     NSString *o_title = [o_mi title];
2192     BOOL bEnabled = TRUE;
2193
2194     /* Recent Items Menu */
2195     if( [o_title isEqualToString: _NS("Clear Menu")] )
2196     {
2197         NSMenu * o_menu = [o_mi_open_recent submenu];
2198         int i_nb_items = [o_menu numberOfItems];
2199         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2200                                                        recentDocumentURLs];
2201         UInt32 i_nb_docs = [o_docs count];
2202
2203         if( i_nb_items > 1 )
2204         {
2205             while( --i_nb_items )
2206             {
2207                 [o_menu removeItemAtIndex: 0];
2208             }
2209         }
2210
2211         if( i_nb_docs > 0 )
2212         {
2213             NSURL * o_url;
2214             NSString * o_doc;
2215
2216             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2217
2218             while( TRUE )
2219             {
2220                 i_nb_docs--;
2221
2222                 o_url = [o_docs objectAtIndex: i_nb_docs];
2223
2224                 if( [o_url isFileURL] )
2225                 {
2226                     o_doc = [o_url path];
2227                 }
2228                 else
2229                 {
2230                     o_doc = [o_url absoluteString];
2231                 }
2232
2233                 [o_menu insertItemWithTitle: o_doc
2234                     action: @selector(openRecentItem:)
2235                     keyEquivalent: @"" atIndex: 0];
2236
2237                 if( i_nb_docs == 0 )
2238                 {
2239                     break;
2240                 }
2241             }
2242         }
2243         else
2244         {
2245             bEnabled = FALSE;
2246         }
2247     }
2248     return( bEnabled );
2249 }
2250
2251 @end
2252
2253 @implementation VLCMain (Internal)
2254
2255 - (void)handlePortMessage:(NSPortMessage *)o_msg
2256 {
2257     id ** val;
2258     NSData * o_data;
2259     NSValue * o_value;
2260     NSInvocation * o_inv;
2261     NSConditionLock * o_lock;
2262
2263     o_data = [[o_msg components] lastObject];
2264     o_inv = *((NSInvocation **)[o_data bytes]);
2265     [o_inv getArgument: &o_value atIndex: 2];
2266     val = (id **)[o_value pointerValue];
2267     [o_inv setArgument: val[1] atIndex: 2];
2268     o_lock = *(val[0]);
2269
2270     [o_lock lock];
2271     [o_inv invoke];
2272     [o_lock unlockWithCondition: 1];
2273 }
2274
2275 @end