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