]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: adapted to latest config API changes
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2011 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_common.h>
34 #include <vlc_keys.h>
35 #include <vlc_dialog.h>
36 #include <vlc_url.h>
37 #include <vlc_modules.h>
38 #include <unistd.h> /* execl() */
39
40 #import "intf.h"
41 #import "fspanel.h"
42 #import "vout.h"
43 #import "prefs.h"
44 #import "playlist.h"
45 #import "playlistinfo.h"
46 #import "controls.h"
47 #import "about.h"
48 #import "open.h"
49 #import "wizard.h"
50 #import "extended.h"
51 #import "bookmarks.h"
52 #import "coredialogs.h"
53 #import "embeddedwindow.h"
54 #import "AppleRemote.h"
55 #import "eyetv.h"
56 #import "simple_prefs.h"
57 #import "AudioEffects.h"
58
59 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
60 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
61
62 /*****************************************************************************
63  * Local prototypes.
64  *****************************************************************************/
65 static void Run ( intf_thread_t *p_intf );
66
67 static void * ManageThread( void *user_data );
68
69 static void updateProgressPanel (void *, const char *, float);
70 static bool checkProgressPanel (void *);
71 static void destroyProgressPanel (void *);
72
73 static void MsgCallback( msg_cb_data_t *, msg_item_t *, unsigned );
74
75 #pragma mark -
76 #pragma mark VLC Interface Object Callbacks
77
78 /*****************************************************************************
79  * OpenIntf: initialize interface
80  *****************************************************************************/
81 int OpenIntf ( vlc_object_t *p_this )
82 {
83     intf_thread_t *p_intf = (intf_thread_t*) p_this;
84
85     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
86     if( p_intf->p_sys == NULL )
87         return VLC_ENOMEM;
88
89     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
90
91     /* subscribe to LibVLCCore's messages */
92     p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
93     p_intf->pf_run = Run;
94     p_intf->b_should_run_on_first_thread = true;
95
96     return VLC_SUCCESS;
97 }
98
99 /*****************************************************************************
100  * CloseIntf: destroy interface
101  *****************************************************************************/
102 void CloseIntf ( vlc_object_t *p_this )
103 {
104     intf_thread_t *p_intf = (intf_thread_t*) p_this;
105
106     free( p_intf->p_sys );
107 }
108
109 /*****************************************************************************
110  * Run: main loop
111  *****************************************************************************/
112 static NSLock * o_appLock = nil;    // controls access to f_appExit
113 static int f_appExit = 0;           // set to 1 when application termination signaled
114
115 static void Run( intf_thread_t *p_intf )
116 {
117     sigset_t set;
118
119     /* Do it again - for some unknown reason, vlc_thread_create() often
120      * fails to go to real-time priority with the first launched thread
121      * (???) --Meuuh */
122     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
123
124     /* Make sure the "force quit" menu item does quit instantly.
125      * VLC overrides SIGTERM which is sent by the "force quit"
126      * menu item to make sure deamon mode quits gracefully, so
127      * we un-override SIGTERM here. */
128     sigemptyset( &set );
129     sigaddset( &set, SIGTERM );
130     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
131
132     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
133
134     o_appLock = [[NSLock alloc] init];
135
136     [VLCApplication sharedApplication];
137
138     [[VLCMain sharedInstance] setIntf: p_intf];
139     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
140
141     [NSApp run];
142     [[VLCMain sharedInstance] applicationWillTerminate:nil];
143
144     [o_pool release];
145 }
146
147 #pragma mark -
148 #pragma mark Variables Callback
149
150 /*****************************************************************************
151  * MsgCallback: Callback triggered by the core once a new debug message is
152  * ready to be displayed. We store everything in a NSArray in our Cocoa part
153  * of this file, so we are forwarding everything through notifications.
154  *****************************************************************************/
155 static void MsgCallback( msg_cb_data_t *data, msg_item_t *item, unsigned int i )
156 {
157     int canc = vlc_savecancel();
158     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
159
160     /* this may happen from time to time, let's bail out as info would be useless anyway */
161     if( !item->psz_module || !item->psz_msg )
162         return;
163
164     NSDictionary *o_dict = [NSDictionary dictionaryWithObjectsAndKeys:
165                                 [NSString stringWithUTF8String: item->psz_module], @"Module",
166                                 [NSString stringWithUTF8String: item->psz_msg], @"Message",
167                                 [NSNumber numberWithInt: item->i_type], @"Type", nil];
168
169     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCCoreMessageReceived"
170                                                         object: nil
171                                                       userInfo: o_dict];
172
173     [o_pool release];
174     vlc_restorecancel( canc );
175 }
176
177 /*****************************************************************************
178  * playlistChanged: Callback triggered by the intf-change playlist
179  * variable, to let the intf update the playlist.
180  *****************************************************************************/
181 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
182                      vlc_value_t old_val, vlc_value_t new_val, void *param )
183 {
184     intf_thread_t * p_intf = VLCIntf;
185     if( p_intf && p_intf->p_sys )
186     {
187         p_intf->p_sys->b_intf_update = true;
188         p_intf->p_sys->b_playlist_update = true;
189         p_intf->p_sys->b_playmode_update = true;
190         p_intf->p_sys->b_current_title_update = true;
191     }
192     return VLC_SUCCESS;
193 }
194
195 /*****************************************************************************
196  * ShowController: Callback triggered by the show-intf playlist variable
197  * through the ShowIntf-control-intf, to let us show the controller-win;
198  * usually when in fullscreen-mode
199  *****************************************************************************/
200 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
201                      vlc_value_t old_val, vlc_value_t new_val, void *param )
202 {
203     intf_thread_t * p_intf = VLCIntf;
204     if( p_intf && p_intf->p_sys )
205         p_intf->p_sys->b_intf_show = true;
206     return VLC_SUCCESS;
207 }
208
209 /*****************************************************************************
210  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
211  * variable, to let the intf update the controller.
212  *****************************************************************************/
213 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
214                      vlc_value_t old_val, vlc_value_t new_val, void *param )
215 {
216     intf_thread_t * p_intf = VLCIntf;
217     if( p_intf && p_intf->p_sys )
218         p_intf->p_sys->b_fullscreen_update = true;
219     return VLC_SUCCESS;
220 }
221
222 /*****************************************************************************
223  * DialogCallback: Callback triggered by the "dialog-*" variables
224  * to let the intf display error and interaction dialogs
225  *****************************************************************************/
226 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
227 {
228     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
229     VLCMain *interface = (VLCMain *)data;
230
231     if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
232     {
233         /* the progress panel needs to update itself and therefore wants special treatment within this context */
234         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
235
236         p_dialog->pf_update = updateProgressPanel;
237         p_dialog->pf_check = checkProgressPanel;
238         p_dialog->pf_destroy = destroyProgressPanel;
239         p_dialog->p_sys = VLCIntf->p_libvlc;
240     }
241
242     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
243     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCNewCoreDialogEventNotification" object:[interface coreDialogProvider] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: o_value, @"VLCDialogPointer", [NSString stringWithUTF8String: type], @"VLCDialogType", nil]];
244
245     [o_pool release];
246     return VLC_SUCCESS;
247 }
248
249 void updateProgressPanel (void *priv, const char *text, float value)
250 {
251     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
252
253     NSString *o_txt;
254     if( text != NULL )
255         o_txt = [NSString stringWithUTF8String: text];
256     else
257         o_txt = @"";
258
259     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
260
261     [o_pool release];
262 }
263
264 void destroyProgressPanel (void *priv)
265 {
266     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
267     [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
268     [o_pool release];
269 }
270
271 bool checkProgressPanel (void *priv)
272 {
273     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
274     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
275     [o_pool release];
276 }
277
278 #pragma mark -
279 #pragma mark Helpers
280
281 input_thread_t *getInput(void)
282 {
283     intf_thread_t *p_intf = VLCIntf;
284     if (!p_intf)
285         return NULL;
286     return pl_CurrentInput(p_intf);
287 }
288
289 vout_thread_t *getVout(void)
290 {
291     input_thread_t *p_input = getInput();
292     if (!p_input)
293         return NULL;
294     vout_thread_t *p_vout = input_GetVout(p_input);
295     vlc_object_release(p_input);
296     return p_vout;
297 }
298
299 aout_instance_t *getAout(void)
300 {
301     input_thread_t *p_input = getInput();
302     if (!p_input)
303         return NULL;
304     aout_instance_t *p_aout = input_GetAout(p_input);
305     vlc_object_release(p_input);
306     return p_aout;
307 }
308
309 #pragma mark -
310 #pragma mark Private
311
312 @interface VLCMain ()
313 - (void)_removeOldPreferences;
314 @end
315
316 /*****************************************************************************
317  * VLCMain implementation
318  *****************************************************************************/
319 @implementation VLCMain
320
321 #pragma mark -
322 #pragma mark Initialization
323
324 static VLCMain *_o_sharedMainInstance = nil;
325
326 + (VLCMain *)sharedInstance
327 {
328     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
329 }
330
331 - (id)init
332 {
333     if( _o_sharedMainInstance)
334     {
335         [self dealloc];
336         return _o_sharedMainInstance;
337     }
338     else
339         _o_sharedMainInstance = [super init];
340
341     p_intf = NULL;
342
343     o_msg_lock = [[NSLock alloc] init];
344     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
345     /* subscribe to LibVLC's debug messages as early as possible (for us) */
346     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
347
348     o_about = [[VLAboutBox alloc] init];
349     o_prefs = nil;
350     o_open = [[VLCOpen alloc] init];
351     o_wizard = [[VLCWizard alloc] init];
352     o_extended = nil;
353     o_bookmarks = [[VLCBookmarks alloc] init];
354     //o_embedded_list = [[VLCEmbeddedList alloc] init];
355     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
356     o_info = [[VLCInfo alloc] init];
357
358     i_lastShownVolume = -1;
359
360     o_eyetv = [[VLCEyeTVController alloc] init];
361
362     /* announce our launch to a potential eyetv plugin */
363     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
364                                                                    object: @"VLCEyeTVSupport"
365                                                                  userInfo: NULL
366                                                        deliverImmediately: YES];
367     return _o_sharedMainInstance;
368 }
369
370 - (void)setIntf: (intf_thread_t *)p_mainintf {
371     p_intf = p_mainintf;
372 }
373
374 - (intf_thread_t *)intf {
375     return p_intf;
376 }
377
378 - (void)awakeFromNib
379 {
380     NSString* o_key;
381     playlist_t *p_playlist;
382     vlc_value_t val;
383
384     if( !p_intf ) return;
385
386     /* Check if we already did this once. Opening the other nibs calls it too,
387        because VLCMain is the owner */
388     if( nib_main_loaded ) return;
389
390     [self initStrings];
391
392     [o_window setExcludedFromWindowsMenu: YES];
393     [o_msgs_panel setExcludedFromWindowsMenu: YES];
394     [o_msgs_panel setDelegate: self];
395
396     /* In code and not in Nib for 10.4 compat */
397     NSToolbar * toolbar = [[[NSToolbar alloc] initWithIdentifier:@"mainControllerToolbar"] autorelease];
398     [toolbar setDelegate:self];
399     [toolbar setShowsBaselineSeparator:NO];
400     [toolbar setAllowsUserCustomization:NO];
401     [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
402     [toolbar setAutosavesConfiguration:YES];
403     [o_window setToolbar:toolbar];
404
405     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-quit" )];
406     [o_mi_quit setKeyEquivalent: [self VLCKeyToString: o_key]];
407     [o_mi_quit setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
408     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-play-pause" )];
409     [o_mi_play setKeyEquivalent: [self VLCKeyToString: o_key]];
410     [o_mi_play setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
411     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-stop" )];
412     [o_mi_stop setKeyEquivalent: [self VLCKeyToString: o_key]];
413     [o_mi_stop setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
414     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-faster" )];
415     [o_mi_faster setKeyEquivalent: [self VLCKeyToString: o_key]];
416     [o_mi_faster setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
417     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-slower" )];
418     [o_mi_slower setKeyEquivalent: [self VLCKeyToString: o_key]];
419     [o_mi_slower setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
420     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-rate-normal" )];
421     [o_mi_normalSpeed setKeyEquivalent: [self VLCKeyToString: o_key]];
422     [o_mi_normalSpeed setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
423     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-prev" )];
424     [o_mi_previous setKeyEquivalent: [self VLCKeyToString: o_key]];
425     [o_mi_previous setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
426     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-next" )];
427     [o_mi_next setKeyEquivalent: [self VLCKeyToString: o_key]];
428     [o_mi_next setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
429     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump+short" )];
430     [o_mi_fwd setKeyEquivalent: [self VLCKeyToString: o_key]];
431     [o_mi_fwd setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
432     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump-short" )];
433     [o_mi_bwd setKeyEquivalent: [self VLCKeyToString: o_key]];
434     [o_mi_bwd setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
435     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump+medium" )];
436     [o_mi_fwd1m setKeyEquivalent: [self VLCKeyToString: o_key]];
437     [o_mi_fwd1m setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
438     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump-medium" )];
439     [o_mi_bwd1m setKeyEquivalent: [self VLCKeyToString: o_key]];
440     [o_mi_bwd1m setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
441     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump+long" )];
442     [o_mi_fwd5m setKeyEquivalent: [self VLCKeyToString: o_key]];
443     [o_mi_fwd5m setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
444     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-jump-long" )];
445     [o_mi_bwd5m setKeyEquivalent: [self VLCKeyToString: o_key]];
446     [o_mi_bwd5m setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
447     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-vol-up" )];
448     [o_mi_vol_up setKeyEquivalent: [self VLCKeyToString: o_key]];
449     [o_mi_vol_up setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
450     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-vol-down" )];
451     [o_mi_vol_down setKeyEquivalent: [self VLCKeyToString: o_key]];
452     [o_mi_vol_down setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
453     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-vol-mute" )];
454     [o_mi_mute setKeyEquivalent: [self VLCKeyToString: o_key]];
455     [o_mi_mute setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
456     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-toggle-fullscreen" )];
457     [o_mi_fullscreen setKeyEquivalent: [self VLCKeyToString: o_key]];
458     [o_mi_fullscreen setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
459     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-snapshot" )];
460     [o_mi_snapshot setKeyEquivalent: [self VLCKeyToString: o_key]];
461     [o_mi_snapshot setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
462     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-random" )];
463     [o_mi_random setKeyEquivalent: [self VLCKeyToString: o_key]];
464     [o_mi_random setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
465     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-zoom-half" )];
466     [o_mi_half_window setKeyEquivalent: [self VLCKeyToString: o_key]];
467     [o_mi_half_window setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
468     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-zoom-original" )];
469     [o_mi_normal_window setKeyEquivalent: [self VLCKeyToString: o_key]];
470     [o_mi_normal_window setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
471     o_key = [NSString stringWithFormat:@"%s", config_GetPsz( p_intf, "key-zoom-double" )];
472     [o_mi_double_window setKeyEquivalent: [self VLCKeyToString: o_key]];
473     [o_mi_double_window setKeyEquivalentModifierMask: [self VLCModifiersToCocoa:o_key]];
474     
475     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
476
477     [self setSubmenusEnabled: FALSE];
478     [o_volumeslider setEnabled: YES];
479     [self manageVolumeSlider];
480     [o_window setDelegate: self];
481
482     b_restore_size = false;
483
484     // Set that here as IB seems to be buggy
485     [o_window setContentMinSize:NSMakeSize(338., 30.)];
486
487     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
488     {
489         b_small_window = YES;
490         [o_window setFrame: NSMakeRect( [o_window frame].origin.x,
491             [o_window frame].origin.y, [o_window frame].size.width,
492             [o_window minSize].height ) display: YES animate:YES];
493         [o_playlist_view setAutoresizesSubviews: NO];
494     }
495     else
496     {
497         b_small_window = NO;
498         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
499         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
500         [o_playlist_view setNeedsDisplay:YES];
501         [o_playlist_view setAutoresizesSubviews: YES];
502         [[o_window contentView] addSubview: o_playlist_view];
503     }
504
505     [self updateTogglePlaylistState];
506
507     o_size_with_playlist = [o_window contentRectForFrameRect:[o_window frame]].size;
508
509     p_playlist = pl_Get( p_intf );
510
511     val.b_bool = false;
512
513     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
514     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
515
516     /* load our Core Dialogs nib */
517     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
518
519     /* subscribe to various interactive dialogues */
520     var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
521     var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
522     var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
523     var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
524     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
525     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
526     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
527     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
528     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
529     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
530     dialog_Register( p_intf );
531
532     /* update the playmode stuff */
533     p_intf->p_sys->b_playmode_update = true;
534
535     [[NSNotificationCenter defaultCenter] addObserver: self
536                                              selector: @selector(refreshVoutDeviceMenu:)
537                                                  name: NSApplicationDidChangeScreenParametersNotification
538                                                object: nil];
539
540     /* take care of tint changes during runtime */
541     o_img_play = [NSImage imageNamed: @"play"];
542     o_img_pause = [NSImage imageNamed: @"pause"];
543
544     /* init Apple Remote support */
545     o_remote = [[AppleRemote alloc] init];
546     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
547     [o_remote setDelegate: _o_sharedMainInstance];
548
549     /* init media key support */
550     o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
551     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
552     [o_mediaKeyController startWatchingMediaKeys];
553     [o_mediaKeyController setShouldInterceptMediaKeyEvents:b_mediaKeySupport];
554     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
555     [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
556                                                              [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
557                                                              nil]];
558
559     /* yeah, we are done */
560     nib_main_loaded = TRUE;
561 }
562
563 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
564 {
565     if( !p_intf ) return;
566
567     /* FIXME: don't poll */
568     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
569                                      target: self selector: @selector(manageIntf:)
570                                    userInfo: nil repeats: FALSE] retain];
571
572     /* Note: we use the pthread API to support pre-10.5 */
573     pthread_create( &manage_thread, NULL, ManageThread, self );
574
575     [o_controls setupVarMenuItem: o_mi_add_intf target: (vlc_object_t *)p_intf
576         var: "intf-add" selector: @selector(toggleVar:)];
577
578     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
579 }
580
581 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
582 {
583     if( !p_intf ) return;
584
585     [self _removeOldPreferences];
586
587     /* Handle sleep notification */
588     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
589            name:NSWorkspaceWillSleepNotification object:nil];
590
591     [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
592 }
593
594 - (void)initStrings
595 {
596     if( !p_intf ) return;
597
598     [o_window setTitle: _NS("VLC media player")];
599     [self setScrollField:_NS("VLC media player") stopAfter:-1];
600
601     /* button controls */
602     [o_btn_prev setToolTip: _NS("Previous")];
603     [o_btn_rewind setToolTip: _NS("Rewind")];
604     [o_btn_play setToolTip: _NS("Play")];
605     [o_btn_stop setToolTip: _NS("Stop")];
606     [o_btn_ff setToolTip: _NS("Fast Forward")];
607     [o_btn_next setToolTip: _NS("Next")];
608     [o_btn_fullscreen setToolTip: _NS("Fullscreen")];
609     [o_volumeslider setToolTip: _NS("Volume")];
610     [o_timeslider setToolTip: _NS("Position")];
611     [o_btn_playlist setToolTip: _NS("Playlist")];
612
613     /* messages panel */
614     [o_msgs_panel setTitle: _NS("Messages")];
615     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
616     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
617
618     /* main menu */
619     [o_mi_about setTitle: [_NS("About VLC media player") \
620         stringByAppendingString: @"..."]];
621     [o_mi_checkForUpdate setTitle: _NS("Check for Update...")];
622     [o_mi_prefs setTitle: _NS("Preferences...")];
623     [o_mi_add_intf setTitle: _NS("Add Interface")];
624     [o_mu_add_intf setTitle: _NS("Add Interface")];
625     [o_mi_services setTitle: _NS("Services")];
626     [o_mi_hide setTitle: _NS("Hide VLC")];
627     [o_mi_hide_others setTitle: _NS("Hide Others")];
628     [o_mi_show_all setTitle: _NS("Show All")];
629     [o_mi_quit setTitle: _NS("Quit VLC")];
630
631     [o_mu_file setTitle: _ANS("1:File")];
632     [o_mi_open_generic setTitle: _NS("Advanced Open File...")];
633     [o_mi_open_file setTitle: _NS("Open File...")];
634     [o_mi_open_disc setTitle: _NS("Open Disc...")];
635     [o_mi_open_net setTitle: _NS("Open Network...")];
636     [o_mi_open_capture setTitle: _NS("Open Capture Device...")];
637     [o_mi_open_recent setTitle: _NS("Open Recent")];
638     [o_mi_open_recent_cm setTitle: _NS("Clear Menu")];
639     [o_mi_open_wizard setTitle: _NS("Streaming/Exporting Wizard...")];
640
641     [o_mu_edit setTitle: _NS("Edit")];
642     [o_mi_cut setTitle: _NS("Cut")];
643     [o_mi_copy setTitle: _NS("Copy")];
644     [o_mi_paste setTitle: _NS("Paste")];
645     [o_mi_clear setTitle: _NS("Clear")];
646     [o_mi_select_all setTitle: _NS("Select All")];
647
648     [o_mu_controls setTitle: _NS("Playback")];
649     [o_mi_play setTitle: _NS("Play")];
650     [o_mi_stop setTitle: _NS("Stop")];
651     [o_mi_faster setTitle: _NS("Faster")];
652     [o_mi_slower setTitle: _NS("Slower")];
653     [o_mi_normalSpeed setTitle: _NS("Normal rate")];
654     [o_mi_previous setTitle: _NS("Previous")];
655     [o_mi_next setTitle: _NS("Next")];
656     [o_mi_random setTitle: _NS("Random")];
657     [o_mi_repeat setTitle: _NS("Repeat One")];
658     [o_mi_loop setTitle: _NS("Repeat All")];
659     [o_mi_quitAfterPB setTitle: _NS("Quit after Playback")];
660     [o_mi_fwd setTitle: _NS("Step Forward")];
661     [o_mi_bwd setTitle: _NS("Step Backward")];
662
663     [o_mi_program setTitle: _NS("Program")];
664     [o_mu_program setTitle: _NS("Program")];
665     [o_mi_title setTitle: _NS("Title")];
666     [o_mu_title setTitle: _NS("Title")];
667     [o_mi_chapter setTitle: _NS("Chapter")];
668     [o_mu_chapter setTitle: _NS("Chapter")];
669
670     [o_mu_audio setTitle: _NS("Audio")];
671     [o_mi_vol_up setTitle: _NS("Increase Volume")];
672     [o_mi_vol_down setTitle: _NS("Decrease Volume")];
673     [o_mi_mute setTitle: _NS("Mute")];
674     [o_mi_audiotrack setTitle: _NS("Audio Track")];
675     [o_mu_audiotrack setTitle: _NS("Audio Track")];
676     [o_mi_channels setTitle: _NS("Audio Channels")];
677     [o_mu_channels setTitle: _NS("Audio Channels")];
678     [o_mi_device setTitle: _NS("Audio Device")];
679     [o_mu_device setTitle: _NS("Audio Device")];
680     [o_mi_visual setTitle: _NS("Visualizations")];
681     [o_mu_visual setTitle: _NS("Visualizations")];
682
683     [o_mu_video setTitle: _NS("Video")];
684     [o_mi_half_window setTitle: _NS("Half Size")];
685     [o_mi_normal_window setTitle: _NS("Normal Size")];
686     [o_mi_double_window setTitle: _NS("Double Size")];
687     [o_mi_fittoscreen setTitle: _NS("Fit to Screen")];
688     [o_mi_fullscreen setTitle: _NS("Fullscreen")];
689     [o_mi_floatontop setTitle: _NS("Float on Top")];
690     [o_mi_snapshot setTitle: _NS("Snapshot")];
691     [o_mi_videotrack setTitle: _NS("Video Track")];
692     [o_mu_videotrack setTitle: _NS("Video Track")];
693     [o_mi_aspect_ratio setTitle: _NS("Aspect-ratio")];
694     [o_mu_aspect_ratio setTitle: _NS("Aspect-ratio")];
695     [o_mi_crop setTitle: _NS("Crop")];
696     [o_mu_crop setTitle: _NS("Crop")];
697     [o_mi_screen setTitle: _NS("Fullscreen Video Device")];
698     [o_mu_screen setTitle: _NS("Fullscreen Video Device")];
699     [o_mi_subtitle setTitle: _NS("Subtitles Track")];
700     [o_mu_subtitle setTitle: _NS("Subtitles Track")];
701     [o_mi_addSub setTitle: _NS("Open File...")];
702     [o_mi_deinterlace setTitle: _NS("Deinterlace")];
703     [o_mu_deinterlace setTitle: _NS("Deinterlace")];
704     [o_mi_deinterlace_mode setTitle: _NS("Deinterlace mode")];
705     [o_mu_deinterlace_mode setTitle: _NS("Deinterlace mode")];
706     [o_mi_ffmpeg_pp setTitle: _NS("Post processing")];
707     [o_mu_ffmpeg_pp setTitle: _NS("Post processing")];
708     [o_mi_teletext setTitle: _NS("Teletext")];
709     [o_mi_teletext_transparent setTitle: _NS("Transparent")];
710     [o_mi_teletext_index setTitle: _NS("Index")];
711     [o_mi_teletext_red setTitle: _NS("Red")];
712     [o_mi_teletext_green setTitle: _NS("Green")];
713     [o_mi_teletext_yellow setTitle: _NS("Yellow")];
714     [o_mi_teletext_blue setTitle: _NS("Blue")];
715
716     [o_mu_window setTitle: _NS("Window")];
717     [o_mi_minimize setTitle: _NS("Minimize Window")];
718     [o_mi_close_window setTitle: _NS("Close Window")];
719     [o_mi_player setTitle: _NS("Player...")];
720     [o_mi_controller setTitle: _NS("Controller...")];
721     [o_mi_audioeffects setTitle: _NS("Audio Effects...")];
722     [o_mi_extended setTitle: _NS("Extended Controls...")];
723     [o_mi_bookmarks setTitle: _NS("Bookmarks...")];
724     [o_mi_playlist setTitle: _NS("Playlist...")];
725     [o_mi_info setTitle: _NS("Media Information...")];
726     [o_mi_messages setTitle: _NS("Messages...")];
727     [o_mi_errorsAndWarnings setTitle: _NS("Errors and Warnings...")];
728
729     [o_mi_bring_atf setTitle: _NS("Bring All to Front")];
730
731     [o_mu_help setTitle: _NS("Help")];
732     [o_mi_help setTitle: _NS("VLC media player Help...")];
733     [o_mi_readme setTitle: _NS("ReadMe / FAQ...")];
734     [o_mi_license setTitle: _NS("License")];
735     [o_mi_documentation setTitle: _NS("Online Documentation...")];
736     [o_mi_website setTitle: _NS("VideoLAN Website...")];
737     [o_mi_donation setTitle: _NS("Make a donation...")];
738     [o_mi_forum setTitle: _NS("Online Forum...")];
739
740     /* dock menu */
741     [o_dmi_play setTitle: _NS("Play")];
742     [o_dmi_stop setTitle: _NS("Stop")];
743     [o_dmi_next setTitle: _NS("Next")];
744     [o_dmi_previous setTitle: _NS("Previous")];
745     [o_dmi_mute setTitle: _NS("Mute")];
746
747     /* vout menu */
748     [o_vmi_play setTitle: _NS("Play")];
749     [o_vmi_stop setTitle: _NS("Stop")];
750     [o_vmi_prev setTitle: _NS("Previous")];
751     [o_vmi_next setTitle: _NS("Next")];
752     [o_vmi_volup setTitle: _NS("Volume Up")];
753     [o_vmi_voldown setTitle: _NS("Volume Down")];
754     [o_vmi_mute setTitle: _NS("Mute")];
755     [o_vmi_fullscreen setTitle: _NS("Fullscreen")];
756     [o_vmi_snapshot setTitle: _NS("Snapshot")];
757
758     /* crash reporter panel */
759     [o_crashrep_send_btn setTitle: _NS("Send")];
760     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
761     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
762     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
763     [o_crashrep_desc_txt setStringValue: _NS("Do you want to send details on the crash to VLC's development team?\n\nIf you want, you can enter a few lines on what you did before VLC crashed along with other helpful information: a link to download a sample file, a URL of a network stream, ...")];
764     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
765     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
766 }
767
768 #pragma mark -
769 #pragma mark Termination
770
771 - (void)releaseRepresentedObjects:(NSMenu *)the_menu
772 {
773     if( !p_intf ) return;
774
775     NSArray *menuitems_array = [the_menu itemArray];
776     for( int i=0; i<[menuitems_array count]; i++ )
777     {
778         NSMenuItem *one_item = [menuitems_array objectAtIndex: i];
779         if( [one_item hasSubmenu] )
780             [self releaseRepresentedObjects: [one_item submenu]];
781
782         [one_item setRepresentedObject:NULL];
783     }
784 }
785
786 - (void)applicationWillTerminate:(NSNotification *)notification
787 {
788     playlist_t * p_playlist;
789     vout_thread_t * p_vout;
790     int returnedValue = 0;
791
792     if( !p_intf )
793         return;
794
795     // don't allow a double termination call. If the user has
796     // already invoked the quit then simply return this time.
797     int isTerminating = false;
798
799     [o_appLock lock];
800     isTerminating = (f_appExit++ > 0 ? 1 : 0);
801     [o_appLock unlock];
802
803     if (isTerminating)
804         return;
805
806     msg_Dbg( p_intf, "Terminating" );
807
808     pthread_join( manage_thread, NULL );
809
810     /* Make sure the intf object is getting killed */
811     vlc_object_kill( p_intf );
812
813     /* Make sure the interfaceTimer is destroyed */
814     [interfaceTimer invalidate];
815     [interfaceTimer release];
816     interfaceTimer = nil;
817
818     /* make sure that the current volume is saved */
819     config_PutInt( p_intf->p_libvlc, "volume", i_lastShownVolume );
820
821     /* unsubscribe from the interactive dialogues */
822     dialog_Unregister( p_intf );
823     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
824     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
825     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
826     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
827     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
828
829     /* remove global observer watching for vout device changes correctly */
830     [[NSNotificationCenter defaultCenter] removeObserver: self];
831
832     /* release some other objects here, because it isn't sure whether dealloc
833      * will be called later on */
834     if( nib_about_loaded )
835         [o_about release];
836
837     if( nib_prefs_loaded )
838     {
839         [o_sprefs release];
840         [o_prefs release];
841     }
842
843     if( nib_open_loaded )
844         [o_open release];
845
846     if( nib_extended_loaded )
847         [o_extended release];
848
849     if (nib_audioeffects_loaded)
850         [o_audioeffects release];
851
852     if( nib_bookmarks_loaded )
853         [o_bookmarks release];
854
855     if( o_info )
856     {
857         [o_info stopTimers];
858         [o_info release];
859     }
860
861     if( nib_wizard_loaded )
862         [o_wizard release];
863
864     [crashLogURLConnection cancel];
865     [crashLogURLConnection release];
866
867     [o_embedded_list release];
868     [o_coredialogs release];
869     [o_eyetv release];
870
871     [o_img_pause_pressed release];
872     [o_img_play_pressed release];
873     [o_img_pause release];
874     [o_img_play release];
875
876     /* unsubscribe from libvlc's debug messages */
877     msg_Unsubscribe( p_intf->p_sys->p_sub );
878
879     [o_msg_arr removeAllObjects];
880     [o_msg_arr release];
881
882     [o_msg_lock release];
883
884     /* write cached user defaults to disk */
885     [[NSUserDefaults standardUserDefaults] synchronize];
886
887     /* Make sure the Menu doesn't have any references to vlc objects anymore */
888     [self releaseRepresentedObjects:[NSApp mainMenu]];
889
890     /* Kill the playlist, so that it doesn't accept new request
891      * such as the play request from vlc.c (we are a blocking interface). */
892     p_playlist = pl_Get( p_intf );
893     vlc_object_kill( p_playlist );
894     libvlc_Quit( p_intf->p_libvlc );
895
896     [self setIntf:nil];
897 }
898
899 #pragma mark -
900 #pragma mark Sparkle delegate
901 /* received directly before the update gets installed, so let's shut down a bit */
902 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
903 {
904     [o_remote stopListening: self];
905     var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
906
907     /* Close the window directly, because we do know that there
908      * won't be anymore video. It's currently waiting a bit. */
909     [[[o_controls voutView] window] orderOut:self];
910 }
911
912 #pragma mark -
913 #pragma mark Toolbar delegate
914
915 /* Our item identifiers */
916 static NSString * VLCToolbarMediaControl     = @"VLCToolbarMediaControl";
917
918 - (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
919 {
920     return [NSArray arrayWithObjects:
921 //                        NSToolbarCustomizeToolbarItemIdentifier,
922 //                        NSToolbarFlexibleSpaceItemIdentifier,
923 //                        NSToolbarSpaceItemIdentifier,
924 //                        NSToolbarSeparatorItemIdentifier,
925                         VLCToolbarMediaControl,
926                         nil ];
927 }
928
929 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
930 {
931     return [NSArray arrayWithObjects:
932                         VLCToolbarMediaControl,
933                         nil ];
934 }
935
936 - (NSToolbarItem *) toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
937 {
938     NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdentifier] autorelease];
939
940     if( [itemIdentifier isEqual: VLCToolbarMediaControl] )
941     {
942         [toolbarItem setLabel:@"Media Controls"];
943         [toolbarItem setPaletteLabel:@"Media Controls"];
944
945         NSSize size = toolbarMediaControl.frame.size;
946         [toolbarItem setView:toolbarMediaControl];
947         [toolbarItem setMinSize:size];
948         size.width += 1000.;
949         [toolbarItem setMaxSize:size];
950
951         // Hack: For some reason we need to make sure
952         // that the those element are on top
953         // Add them again will put them frontmost
954         [toolbarMediaControl addSubview:o_scrollfield];
955         [toolbarMediaControl addSubview:o_timeslider];
956         [toolbarMediaControl addSubview:o_timefield];
957         [toolbarMediaControl addSubview:o_main_pgbar];
958
959         /* TODO: setup a menu */
960     }
961     else
962     {
963         /* itemIdentifier referred to a toolbar item that is not
964          * provided or supported by us or Cocoa
965          * Returning nil will inform the toolbar
966          * that this kind of item is not supported */
967         toolbarItem = nil;
968     }
969     return toolbarItem;
970 }
971
972 #pragma mark -
973 #pragma mark Media Key support
974
975 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
976 {
977     if( b_mediaKeySupport )
978        {
979         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
980
981         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
982         int keyFlags = ([event data1] & 0x0000FFFF);
983         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
984         int keyRepeat = (keyFlags & 0x1);
985
986         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
987             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
988
989         if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
990         {
991             if( keyState == 0 && keyRepeat == 0 )
992                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
993             else if( keyRepeat == 1 )
994             {
995                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
996                 b_mediakeyJustJumped = YES;
997                 [self performSelector:@selector(resetMediaKeyJump)
998                            withObject: NULL
999                            afterDelay:0.25];
1000             }
1001         }
1002
1003         if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
1004         {
1005             if( keyState == 0 && keyRepeat == 0 )
1006                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
1007             else if( keyRepeat == 1 )
1008             {
1009                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
1010                 b_mediakeyJustJumped = YES;
1011                 [self performSelector:@selector(resetMediaKeyJump)
1012                            withObject: NULL
1013                            afterDelay:0.25];
1014             }
1015         }
1016     }
1017 }
1018
1019 #pragma mark -
1020 #pragma mark Other notification
1021
1022 /* Listen to the remote in exclusive mode, only when VLC is the active
1023    application */
1024 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1025 {
1026     if( !p_intf ) return;
1027         if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
1028                 [o_remote startListening: self];
1029 }
1030 - (void)applicationDidResignActive:(NSNotification *)aNotification
1031 {
1032     if( !p_intf ) return;
1033     [o_remote stopListening: self];
1034 }
1035
1036 /* Triggered when the computer goes to sleep */
1037 - (void)computerWillSleep: (NSNotification *)notification
1038 {
1039     /* Pause */
1040     if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
1041     {
1042         var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
1043     }
1044 }
1045
1046 #pragma mark -
1047 #pragma mark File opening
1048
1049 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
1050 {
1051     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
1052     char *psz_uri = make_URI([o_filename UTF8String], "file" );
1053     if( !psz_uri )
1054         return( FALSE );
1055
1056     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1057
1058     free( psz_uri );
1059
1060     if( b_autoplay )
1061         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
1062     else
1063         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
1064
1065     return( TRUE );
1066 }
1067
1068 /* When user click in the Dock icon our double click in the finder */
1069 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1070 {
1071     if(!hasVisibleWindows)
1072         [o_window makeKeyAndOrderFront:self];
1073
1074     return YES;
1075 }
1076
1077 #pragma mark -
1078 #pragma mark Apple Remote Control
1079
1080 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1081    increase/decrease as long as the user holds the left/right, plus/minus button */
1082 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1083 {
1084     if(b_remote_button_hold)
1085     {
1086         switch([buttonIdentifierNumber intValue])
1087         {
1088             case kRemoteButtonRight_Hold:
1089                   [o_controls forward: self];
1090             break;
1091             case kRemoteButtonLeft_Hold:
1092                   [o_controls backward: self];
1093             break;
1094             case kRemoteButtonVolume_Plus_Hold:
1095                 [o_controls volumeUp: self];
1096             break;
1097             case kRemoteButtonVolume_Minus_Hold:
1098                 [o_controls volumeDown: self];
1099             break;
1100         }
1101         if(b_remote_button_hold)
1102         {
1103             /* trigger event */
1104             [self performSelector:@selector(executeHoldActionForRemoteButton:)
1105                          withObject:buttonIdentifierNumber
1106                          afterDelay:0.25];
1107         }
1108     }
1109 }
1110
1111 /* Apple Remote callback */
1112 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1113                pressedDown: (BOOL) pressedDown
1114                 clickCount: (unsigned int) count
1115 {
1116     switch( buttonIdentifier )
1117     {
1118         case k2009RemoteButtonFullscreen:
1119             [o_controls toogleFullscreen:self];
1120             break;
1121         case k2009RemoteButtonPlay:
1122             [o_controls play:self];
1123             break;
1124         case kRemoteButtonPlay:
1125             if(count >= 2) {
1126                 [o_controls toogleFullscreen:self];
1127             } else {
1128                 [o_controls play: self];
1129             }
1130             break;
1131         case kRemoteButtonVolume_Plus:
1132             [o_controls volumeUp: self];
1133             break;
1134         case kRemoteButtonVolume_Minus:
1135             [o_controls volumeDown: self];
1136             break;
1137         case kRemoteButtonRight:
1138             [o_controls next: self];
1139             break;
1140         case kRemoteButtonLeft:
1141             [o_controls prev: self];
1142             break;
1143         case kRemoteButtonRight_Hold:
1144         case kRemoteButtonLeft_Hold:
1145         case kRemoteButtonVolume_Plus_Hold:
1146         case kRemoteButtonVolume_Minus_Hold:
1147             /* simulate an event as long as the user holds the button */
1148             b_remote_button_hold = pressedDown;
1149             if( pressedDown )
1150             {
1151                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
1152                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1153                            withObject:buttonIdentifierNumber];
1154             }
1155             break;
1156         case kRemoteButtonMenu:
1157             [o_controls showPosition: self];
1158             break;
1159         default:
1160             /* Add here whatever you want other buttons to do */
1161             break;
1162     }
1163 }
1164
1165 #pragma mark -
1166 #pragma mark String utility
1167 // FIXME: this has nothing to do here
1168
1169 - (NSString *)localizedString:(const char *)psz
1170 {
1171     NSString * o_str = nil;
1172
1173     if( psz != NULL )
1174     {
1175         o_str = [[[NSString alloc] initWithUTF8String: psz] autorelease];
1176
1177         if( o_str == NULL )
1178         {
1179             msg_Err( VLCIntf, "could not translate: %s", psz );
1180             return( @"" );
1181         }
1182     }
1183     else
1184     {
1185         msg_Warn( VLCIntf, "can't translate empty strings" );
1186         return( @"" );
1187     }
1188
1189     return( o_str );
1190 }
1191
1192
1193
1194 - (char *)delocalizeString:(NSString *)id
1195 {
1196     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1197                           allowLossyConversion: NO];
1198     char * psz_string;
1199
1200     if( o_data == nil )
1201     {
1202         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
1203                      allowLossyConversion: YES];
1204         psz_string = malloc( [o_data length] + 1 );
1205         [o_data getBytes: psz_string];
1206         psz_string[ [o_data length] ] = '\0';
1207         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
1208                  psz_string );
1209     }
1210     else
1211     {
1212         psz_string = malloc( [o_data length] + 1 );
1213         [o_data getBytes: psz_string];
1214         psz_string[ [o_data length] ] = '\0';
1215     }
1216
1217     return psz_string;
1218 }
1219
1220 /* i_width is in pixels */
1221 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
1222 {
1223     NSMutableString *o_wrapped;
1224     NSString *o_out_string;
1225     NSRange glyphRange, effectiveRange, charRange;
1226     NSRect lineFragmentRect;
1227     unsigned glyphIndex, breaksInserted = 0;
1228
1229     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
1230         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
1231         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
1232     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
1233     NSTextContainer *o_container = [[NSTextContainer alloc]
1234         initWithContainerSize: NSMakeSize(i_width, 2000)];
1235
1236     [o_layout_manager addTextContainer: o_container];
1237     [o_container release];
1238     [o_storage addLayoutManager: o_layout_manager];
1239     [o_layout_manager release];
1240
1241     o_wrapped = [o_in_string mutableCopy];
1242     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
1243
1244     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
1245             glyphIndex += effectiveRange.length) {
1246         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
1247                                             effectiveRange: &effectiveRange];
1248         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
1249                                     actualGlyphRange: &effectiveRange];
1250         if([o_wrapped lineRangeForRange:
1251                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
1252             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
1253             breaksInserted++;
1254         }
1255     }
1256     o_out_string = [NSString stringWithString: o_wrapped];
1257     [o_wrapped release];
1258     [o_storage release];
1259
1260     return o_out_string;
1261 }
1262
1263
1264 #pragma mark -
1265 #pragma mark Key Shortcuts
1266
1267 static struct
1268 {
1269     unichar i_nskey;
1270     unsigned int i_vlckey;
1271 } nskeys_to_vlckeys[] =
1272 {
1273     { NSUpArrowFunctionKey, KEY_UP },
1274     { NSDownArrowFunctionKey, KEY_DOWN },
1275     { NSLeftArrowFunctionKey, KEY_LEFT },
1276     { NSRightArrowFunctionKey, KEY_RIGHT },
1277     { NSF1FunctionKey, KEY_F1 },
1278     { NSF2FunctionKey, KEY_F2 },
1279     { NSF3FunctionKey, KEY_F3 },
1280     { NSF4FunctionKey, KEY_F4 },
1281     { NSF5FunctionKey, KEY_F5 },
1282     { NSF6FunctionKey, KEY_F6 },
1283     { NSF7FunctionKey, KEY_F7 },
1284     { NSF8FunctionKey, KEY_F8 },
1285     { NSF9FunctionKey, KEY_F9 },
1286     { NSF10FunctionKey, KEY_F10 },
1287     { NSF11FunctionKey, KEY_F11 },
1288     { NSF12FunctionKey, KEY_F12 },
1289     { NSInsertFunctionKey, KEY_INSERT },
1290     { NSHomeFunctionKey, KEY_HOME },
1291     { NSEndFunctionKey, KEY_END },
1292     { NSPageUpFunctionKey, KEY_PAGEUP },
1293     { NSPageDownFunctionKey, KEY_PAGEDOWN },
1294     { NSMenuFunctionKey, KEY_MENU },
1295     { NSTabCharacter, KEY_TAB },
1296     { NSCarriageReturnCharacter, KEY_ENTER },
1297     { NSEnterCharacter, KEY_ENTER },
1298     { NSBackspaceCharacter, KEY_BACKSPACE },
1299     {0,0}
1300 };
1301
1302 unsigned int CocoaKeyToVLC( unichar i_key )
1303 {
1304     unsigned int i;
1305
1306     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
1307     {
1308         if( nskeys_to_vlckeys[i].i_nskey == i_key )
1309         {
1310             return nskeys_to_vlckeys[i].i_vlckey;
1311         }
1312     }
1313     return (unsigned int)i_key;
1314 }
1315
1316 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
1317 {
1318     unsigned int new = 0;
1319
1320     if([theString rangeOfString:@"Command"].location != NSNotFound)
1321         new |= NSCommandKeyMask;
1322     if([theString rangeOfString:@"Alt"].location != NSNotFound)
1323         new |= NSAlternateKeyMask;
1324     if([theString rangeOfString:@"Shift"].location != NSNotFound)
1325         new |= NSShiftKeyMask;
1326     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
1327         new |= NSControlKeyMask;
1328     return new;
1329 }
1330
1331 - (NSString *)VLCKeyToString:(NSString *)theString
1332 {
1333     if (![theString isEqualToString:@""]) {
1334         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1335         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1336         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1337         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1338         theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1339         theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1340     }
1341     return theString;
1342 }
1343
1344
1345 /*****************************************************************************
1346  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1347  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1348  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1349  *****************************************************************************/
1350 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1351 {
1352     unichar key = 0;
1353     vlc_value_t val;
1354     unsigned int i_pressed_modifiers = 0;
1355     const struct hotkey *p_hotkeys;
1356     int i;
1357     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1358     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1359     
1360     val.i_int = 0;
1361     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1362
1363     i_pressed_modifiers = [o_event modifierFlags];
1364
1365     if( i_pressed_modifiers & NSShiftKeyMask ) {
1366         val.i_int |= KEY_MODIFIER_SHIFT;
1367         [tempString appendString:@"Shift-"];
1368         [tempStringPlus appendString:@"Shift+"];
1369     }
1370     if( i_pressed_modifiers & NSControlKeyMask ) {
1371         val.i_int |= KEY_MODIFIER_CTRL;
1372         [tempString appendString:@"Ctrl-"];
1373         [tempStringPlus appendString:@"Ctrl+"];
1374     }
1375     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1376         val.i_int |= KEY_MODIFIER_ALT;
1377         [tempString appendString:@"Alt-"];
1378         [tempStringPlus appendString:@"Alt+"];
1379     }
1380     if( i_pressed_modifiers & NSCommandKeyMask ) {
1381         val.i_int |= KEY_MODIFIER_COMMAND;
1382         [tempString appendString:@"Command-"];
1383         [tempStringPlus appendString:@"Command+"];
1384     }
1385     
1386     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1387     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1388     
1389     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1390
1391     switch( key )
1392     {
1393         case NSDeleteCharacter:
1394         case NSDeleteFunctionKey:
1395         case NSDeleteCharFunctionKey:
1396         case NSBackspaceCharacter:
1397         case NSUpArrowFunctionKey:
1398         case NSDownArrowFunctionKey:
1399         case NSRightArrowFunctionKey:
1400         case NSLeftArrowFunctionKey:
1401         case NSEnterCharacter:
1402         case NSCarriageReturnCharacter:
1403             return NO;
1404     }
1405
1406     val.i_int |= CocoaKeyToVLC( key );
1407
1408     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1409     {
1410         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1411         return YES;
1412     }
1413
1414     return NO;
1415 }
1416
1417 - (void)updateCurrentlyUsedHotkeys
1418 {
1419     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1420     /* Get the main Module */
1421     module_t *p_main = module_get_main();
1422     assert( p_main );
1423     unsigned confsize;
1424     module_config_t *p_config;
1425     
1426     p_config = module_config_get (p_main, &confsize);
1427     
1428     for (size_t i = 0; i < confsize; i++)
1429     {
1430         module_config_t *p_item = p_config + i;
1431         
1432         if( (p_item->i_type & CONFIG_ITEM) && p_item->psz_name != NULL
1433            && !strncmp( p_item->psz_name , "key-", 4 )
1434            && !EMPTY_STR( p_item->psz_text ) )
1435         {
1436             if (p_item->value.psz)
1437                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1438         }
1439     }
1440     module_config_free (p_config);
1441     module_release (p_main);
1442     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];    
1443 }
1444
1445
1446 #pragma mark -
1447 #pragma mark Other objects getters
1448
1449 - (id)controls
1450 {
1451     if( o_controls )
1452         return o_controls;
1453
1454     return nil;
1455 }
1456
1457 - (id)simplePreferences
1458 {
1459     if( !o_sprefs )
1460         return nil;
1461
1462     if( !nib_prefs_loaded )
1463         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1464
1465     return o_sprefs;
1466 }
1467
1468 - (id)preferences
1469 {
1470     if( !o_prefs )
1471         return nil;
1472
1473     if( !nib_prefs_loaded )
1474         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1475
1476     return o_prefs;
1477 }
1478
1479 - (id)playlist
1480 {
1481     if( o_playlist )
1482         return o_playlist;
1483
1484     return nil;
1485 }
1486
1487 - (BOOL)isPlaylistCollapsed
1488 {
1489     return ![o_btn_playlist state];
1490 }
1491
1492 - (id)info
1493 {
1494     if( o_info )
1495         return o_info;
1496
1497     return nil;
1498 }
1499
1500 - (id)wizard
1501 {
1502     if( o_wizard )
1503         return o_wizard;
1504
1505     return nil;
1506 }
1507
1508 - (id)bookmarks
1509 {
1510     if( o_bookmarks )
1511         return o_bookmarks;
1512
1513     return nil;
1514 }
1515
1516 - (id)embeddedList
1517 {
1518     if( o_embedded_list )
1519         return o_embedded_list;
1520
1521     return nil;
1522 }
1523
1524 - (id)coreDialogProvider
1525 {
1526     if( o_coredialogs )
1527         return o_coredialogs;
1528
1529     return nil;
1530 }
1531
1532 - (id)mainIntfPgbar
1533 {
1534     if( o_main_pgbar )
1535         return o_main_pgbar;
1536
1537     return nil;
1538 }
1539
1540 - (id)controllerWindow
1541 {
1542     if( o_window )
1543         return o_window;
1544     return nil;
1545 }
1546
1547 - (id)voutMenu
1548 {
1549     return o_vout_menu;
1550 }
1551
1552 - (id)eyeTVController
1553 {
1554     if( o_eyetv )
1555         return o_eyetv;
1556
1557     return nil;
1558 }
1559
1560 - (id)appleRemoteController
1561 {
1562         return o_remote;
1563 }
1564
1565 #pragma mark -
1566 #pragma mark Polling
1567
1568 /*****************************************************************************
1569  * ManageThread: An ugly thread that polls
1570  *****************************************************************************/
1571 static void * ManageThread( void *user_data )
1572 {
1573     id self = user_data;
1574
1575     [self manage];
1576
1577     return NULL;
1578 }
1579
1580 struct manage_cleanup_stack {
1581     intf_thread_t * p_intf;
1582     input_thread_t ** p_input;
1583     playlist_t * p_playlist;
1584     id self;
1585 };
1586
1587 static void manage_cleanup( void * args )
1588 {
1589     struct manage_cleanup_stack * manage_cleanup_stack = args;
1590     intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1591     input_thread_t * p_input = *manage_cleanup_stack->p_input;
1592     id self = manage_cleanup_stack->self;
1593     playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1594
1595     var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1596     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1597     var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1598     var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1599     var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1600
1601     if( p_input ) vlc_object_release( p_input );
1602 }
1603
1604 - (void)manage
1605 {
1606     playlist_t * p_playlist;
1607     input_thread_t * p_input = NULL;
1608
1609     /* new thread requires a new pool */
1610
1611     vlc_thread_set_priority( p_intf, VLC_THREAD_PRIORITY_LOW );
1612
1613     p_playlist = pl_Get( p_intf );
1614
1615     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1616     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1617     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1618     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1619     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1620
1621     struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1622     pthread_cleanup_push(manage_cleanup, &stack);
1623
1624     bool exitLoop = false;
1625     while( !exitLoop )
1626     {
1627         NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1628
1629         if( !p_input )
1630         {
1631             p_input = playlist_CurrentInput( p_playlist );
1632
1633             /* Refresh the interface */
1634             if( p_input )
1635             {
1636                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1637                 p_intf->p_sys->b_input_update = true;
1638             }
1639         }
1640         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1641         {
1642             /* input stopped */
1643             p_intf->p_sys->b_intf_update = true;
1644             p_intf->p_sys->i_play_status = END_S;
1645             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1646             vlc_object_release( p_input );
1647             p_input = NULL;
1648         }
1649         else if( cachedInputState != input_GetState( p_input ) )
1650         {
1651             p_intf->p_sys->b_intf_update = true;
1652         }
1653
1654         /* Manage volume status */
1655         [self manageVolumeSlider];
1656
1657         msleep( INTF_IDLE_SLEEP );
1658
1659         [pool release];
1660
1661         [o_appLock lock];
1662         exitLoop = (f_appExit != 0 ? true : false);
1663         [o_appLock unlock];
1664     }
1665
1666     pthread_cleanup_pop(1);
1667 }
1668
1669 - (void)manageVolumeSlider
1670 {
1671     audio_volume_t i_volume;
1672     playlist_t * p_playlist = pl_Get( p_intf );
1673
1674     i_volume = aout_VolumeGet( p_playlist );
1675
1676     if( i_volume != i_lastShownVolume )
1677     {
1678         i_lastShownVolume = i_volume;
1679         p_intf->p_sys->b_volume_update = TRUE;
1680     }
1681 }
1682
1683 - (void)manageIntf:(NSTimer *)o_timer
1684 {
1685     vlc_value_t val;
1686     playlist_t * p_playlist;
1687     input_thread_t * p_input;
1688
1689     if( p_intf->p_sys->b_input_update )
1690     {
1691         /* Called when new input is opened */
1692         p_intf->p_sys->b_current_title_update = true;
1693         p_intf->p_sys->b_intf_update = true;
1694         p_intf->p_sys->b_input_update = false;
1695         [self setupMenus]; /* Make sure input menu is up to date */
1696
1697         /* update our info-panel to reflect the new item, if we don't show
1698          * the playlist or the selection is empty */
1699         if( [self isPlaylistCollapsed] == YES )
1700         {
1701             playlist_t * p_playlist = pl_Get( p_intf );
1702             PL_LOCK;
1703             playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
1704             PL_UNLOCK;
1705             if( p_item )
1706                 [[self info] updatePanelWithItem: p_item->p_input];
1707         }
1708     }
1709     if( p_intf->p_sys->b_intf_update )
1710     {
1711         bool b_input = false;
1712         bool b_plmul = false;
1713         bool b_control = false;
1714         bool b_seekable = false;
1715         bool b_chapters = false;
1716
1717         playlist_t * p_playlist = pl_Get( p_intf );
1718
1719         PL_LOCK;
1720         b_plmul = playlist_CurrentSize( p_playlist ) > 1;
1721         PL_UNLOCK;
1722
1723         p_input = playlist_CurrentInput( p_playlist );
1724
1725         bool b_buffering = NO;
1726
1727         if( ( b_input = ( p_input != NULL ) ) )
1728         {
1729             /* seekable streams */
1730             cachedInputState = input_GetState( p_input );
1731             if ( cachedInputState == INIT_S ||
1732                  cachedInputState == OPENING_S )
1733             {
1734                 b_buffering = YES;
1735             }
1736
1737             /* seekable streams */
1738             b_seekable = var_GetBool( p_input, "can-seek" );
1739
1740             /* check whether slow/fast motion is possible */
1741             b_control = var_GetBool( p_input, "can-rate" );
1742
1743             /* chapters & titles */
1744             //b_chapters = p_input->stream.i_area_nb > 1;
1745             vlc_object_release( p_input );
1746         }
1747
1748         if( b_buffering )
1749         {
1750             [o_main_pgbar startAnimation:self];
1751             [o_main_pgbar setIndeterminate:YES];
1752             [o_main_pgbar setHidden:NO];
1753         }
1754         else
1755         {
1756             [o_main_pgbar stopAnimation:self];
1757             [o_main_pgbar setHidden:YES];
1758         }
1759
1760         [o_btn_stop setEnabled: b_input];
1761         [o_embedded_window setStop: b_input];
1762         [o_btn_ff setEnabled: b_seekable];
1763         [o_btn_rewind setEnabled: b_seekable];
1764         [o_btn_prev setEnabled: (b_plmul || b_chapters)];
1765         [o_embedded_window setPrev: (b_plmul || b_chapters)];
1766         [o_btn_next setEnabled: (b_plmul || b_chapters)];
1767         [o_embedded_window setNext: (b_plmul || b_chapters)];
1768
1769         [o_timeslider setFloatValue: 0.0];
1770         [o_timeslider setEnabled: b_seekable];
1771         [o_timefield setStringValue: @"00:00"];
1772         [[[self controls] fspanel] setStreamPos: 0 andTime: @"00:00"];
1773         [[[self controls] fspanel] setSeekable: b_seekable];
1774
1775         [o_embedded_window setSeekable: b_seekable];
1776         [o_embedded_window setTime:@"00:00" position:0.0];
1777
1778         p_intf->p_sys->b_current_title_update = true;
1779
1780         p_intf->p_sys->b_intf_update = false;
1781     }
1782
1783     if( p_intf->p_sys->b_playmode_update )
1784     {
1785         [o_playlist playModeUpdated];
1786         p_intf->p_sys->b_playmode_update = false;
1787     }
1788     if( p_intf->p_sys->b_playlist_update )
1789     {
1790         [o_playlist playlistUpdated];
1791         p_intf->p_sys->b_playlist_update = false;
1792     }
1793
1794     if( p_intf->p_sys->b_fullscreen_update )
1795     {
1796         p_intf->p_sys->b_fullscreen_update = false;
1797     }
1798
1799     if( p_intf->p_sys->b_intf_show )
1800     {
1801         if( [[o_controls voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
1802             [[o_controls fspanel] fadeIn];
1803         else
1804             [o_window makeKeyAndOrderFront: self];
1805
1806         p_intf->p_sys->b_intf_show = false;
1807     }
1808
1809     p_input = pl_CurrentInput( p_intf );
1810     if( p_input && vlc_object_alive (p_input) )
1811     {
1812         vlc_value_t val;
1813
1814         if( p_intf->p_sys->b_current_title_update )
1815         {
1816             NSString *aString;
1817             input_item_t * p_item = input_GetItem( p_input );
1818             char * name = input_item_GetNowPlaying( p_item );
1819
1820             if( !name )
1821                 name = input_item_GetName( p_item );
1822
1823             aString = [NSString stringWithUTF8String:name];
1824
1825             free(name);
1826
1827             [self setScrollField: aString stopAfter:-1];
1828             [[[self controls] fspanel] setStreamTitle: aString];
1829
1830             [[o_controls voutView] updateTitle];
1831
1832             [o_playlist updateRowSelection];
1833
1834             p_intf->p_sys->b_current_title_update = FALSE;
1835         }
1836
1837         if( [o_timeslider isEnabled] )
1838         {
1839             /* Update the slider */
1840             vlc_value_t time;
1841             NSString * o_time;
1842             vlc_value_t pos;
1843             char psz_time[MSTRTIME_MAX_SIZE];
1844             float f_updated;
1845
1846             var_Get( p_input, "position", &pos );
1847             f_updated = 10000. * pos.f_float;
1848             [o_timeslider setFloatValue: f_updated];
1849
1850             var_Get( p_input, "time", &time );
1851
1852             mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
1853             if( b_time_remaining && dur != -1 )
1854             {
1855                 o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000))];
1856             }
1857             else
1858                 o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
1859
1860             [o_timefield setStringValue: o_time];
1861             [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
1862             [o_embedded_window setTime: o_time position: f_updated];
1863         }
1864
1865         /* Manage Playing status */
1866         var_Get( p_input, "state", &val );
1867         if( p_intf->p_sys->i_play_status != val.i_int )
1868         {
1869             p_intf->p_sys->i_play_status = val.i_int;
1870             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1871             [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1872         }
1873         vlc_object_release( p_input );
1874     }
1875     else if( p_input )
1876     {
1877         vlc_object_release( p_input );
1878     }
1879     else
1880     {
1881         p_intf->p_sys->i_play_status = END_S;
1882         [self playStatusUpdated: p_intf->p_sys->i_play_status];
1883         [o_embedded_window playStatusUpdated: p_intf->p_sys->i_play_status];
1884         [self setSubmenusEnabled: FALSE];
1885     }
1886
1887     if( p_intf->p_sys->b_volume_update )
1888     {
1889         NSString *o_text;
1890         int i_volume_step = 0;
1891         o_text = [NSString stringWithFormat: _NS("Volume: %d%%"), i_lastShownVolume * 400 / AOUT_VOLUME_MAX];
1892         if( i_lastShownVolume != -1 )
1893         [self setScrollField:o_text stopAfter:1000000];
1894         i_volume_step = config_GetInt( p_intf->p_libvlc, "volume-step" );
1895         [o_volumeslider setFloatValue: (float)i_lastShownVolume / i_volume_step];
1896         [o_volumeslider setEnabled: TRUE];
1897         [o_embedded_window setVolumeSlider: (float)i_lastShownVolume / i_volume_step];
1898         [o_embedded_window setVolumeEnabled: TRUE];
1899         [[[self controls] fspanel] setVolumeLevel: (float)i_lastShownVolume / i_volume_step];
1900         p_intf->p_sys->b_mute = ( i_lastShownVolume == 0 );
1901         p_intf->p_sys->b_volume_update = FALSE;
1902     }
1903
1904 end:
1905     [self updateMessageDisplay];
1906
1907     if( ((i_end_scroll != -1) && (mdate() > i_end_scroll)) || !p_input )
1908         [self resetScrollField];
1909
1910     [interfaceTimer autorelease];
1911
1912     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1913         target: self selector: @selector(manageIntf:)
1914         userInfo: nil repeats: FALSE] retain];
1915 }
1916
1917 #pragma mark -
1918 #pragma mark Interface update
1919
1920 - (void)setupMenus
1921 {
1922     playlist_t * p_playlist = pl_Get( p_intf );
1923     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
1924     if( p_input != NULL )
1925     {
1926         [o_controls setupVarMenuItem: o_mi_program target: (vlc_object_t *)p_input
1927             var: "program" selector: @selector(toggleVar:)];
1928
1929         [o_controls setupVarMenuItem: o_mi_title target: (vlc_object_t *)p_input
1930             var: "title" selector: @selector(toggleVar:)];
1931
1932         [o_controls setupVarMenuItem: o_mi_chapter target: (vlc_object_t *)p_input
1933             var: "chapter" selector: @selector(toggleVar:)];
1934
1935         [o_controls setupVarMenuItem: o_mi_audiotrack target: (vlc_object_t *)p_input
1936             var: "audio-es" selector: @selector(toggleVar:)];
1937
1938         [o_controls setupVarMenuItem: o_mi_videotrack target: (vlc_object_t *)p_input
1939             var: "video-es" selector: @selector(toggleVar:)];
1940
1941         [o_controls setupVarMenuItem: o_mi_subtitle target: (vlc_object_t *)p_input
1942             var: "spu-es" selector: @selector(toggleVar:)];
1943
1944         /* special case for "Open File" inside the subtitles menu item */
1945         if( [o_mi_videotrack isEnabled] == YES )
1946             [o_mi_subtitle setEnabled: YES];
1947
1948         aout_instance_t * p_aout = input_GetAout( p_input );
1949         if( p_aout != NULL )
1950         {
1951             [o_controls setupVarMenuItem: o_mi_channels target: (vlc_object_t *)p_aout
1952                 var: "audio-channels" selector: @selector(toggleVar:)];
1953
1954             [o_controls setupVarMenuItem: o_mi_device target: (vlc_object_t *)p_aout
1955                 var: "audio-device" selector: @selector(toggleVar:)];
1956
1957             [o_controls setupVarMenuItem: o_mi_visual target: (vlc_object_t *)p_aout
1958                 var: "visual" selector: @selector(toggleVar:)];
1959             vlc_object_release( (vlc_object_t *)p_aout );
1960         }
1961
1962         vout_thread_t * p_vout = input_GetVout( p_input );
1963
1964         if( p_vout != NULL )
1965         {
1966             vlc_object_t * p_dec_obj;
1967
1968             [o_controls setupVarMenuItem: o_mi_aspect_ratio target: (vlc_object_t *)p_vout
1969                 var: "aspect-ratio" selector: @selector(toggleVar:)];
1970
1971             [o_controls setupVarMenuItem: o_mi_crop target: (vlc_object_t *) p_vout
1972                 var: "crop" selector: @selector(toggleVar:)];
1973
1974             [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
1975                 var: "video-device" selector: @selector(toggleVar:)];
1976
1977             [o_controls setupVarMenuItem: o_mi_deinterlace target: (vlc_object_t *)p_vout
1978                 var: "deinterlace" selector: @selector(toggleVar:)];
1979
1980             [o_controls setupVarMenuItem: o_mi_deinterlace_mode target: (vlc_object_t *)p_vout
1981                 var: "deinterlace-mode" selector: @selector(toggleVar:)];
1982
1983 #if 1
1984            [o_controls setupVarMenuItem: o_mi_ffmpeg_pp target:
1985                     (vlc_object_t *)p_vout var:"postprocess" selector:
1986                     @selector(toggleVar:)];
1987
1988 #endif
1989             vlc_object_release( (vlc_object_t *)p_vout );
1990         }
1991         vlc_object_release( p_input );
1992     }
1993 }
1994
1995 - (void)refreshVoutDeviceMenu:(NSNotification *)o_notification
1996 {
1997     int x, y = 0;
1998     vout_thread_t * p_vout = getVout();
1999     if( !p_vout )
2000         return;
2001
2002     /* clean the menu before adding new entries */
2003     if( [o_mi_screen hasSubmenu] )
2004     {
2005         y = [[o_mi_screen submenu] numberOfItems] - 1;
2006         msg_Dbg( VLCIntf, "%i items in submenu", y );
2007         while( x != y )
2008         {
2009             msg_Dbg( VLCIntf, "removing item %i of %i", x, y );
2010             [[o_mi_screen submenu] removeItemAtIndex: x];
2011             x++;
2012         }
2013     }
2014
2015     [o_controls setupVarMenuItem: o_mi_screen target: (vlc_object_t *)p_vout
2016                              var: "video-device" selector: @selector(toggleVar:)];
2017     vlc_object_release( (vlc_object_t *)p_vout );
2018 }
2019
2020 - (void)setScrollField:(NSString *)o_string stopAfter:(int)timeout
2021 {
2022     if( timeout != -1 )
2023         i_end_scroll = mdate() + timeout;
2024     else
2025         i_end_scroll = -1;
2026     [o_scrollfield setStringValue: o_string];
2027     [o_embedded_window setScrollString: o_string];
2028 }
2029
2030 - (void)resetScrollField
2031 {
2032     playlist_t * p_playlist = pl_Get( p_intf );
2033     input_thread_t * p_input = playlist_CurrentInput( p_playlist );
2034
2035     i_end_scroll = -1;
2036     if( p_input && vlc_object_alive (p_input) )
2037     {
2038         NSString *o_temp;
2039         PL_LOCK;
2040         playlist_item_t * p_item = playlist_CurrentPlayingItem( p_playlist );
2041         if( input_item_GetNowPlaying( p_item->p_input ) )
2042             o_temp = [NSString stringWithUTF8String:input_item_GetNowPlaying( p_item->p_input )];
2043         else
2044             o_temp = [NSString stringWithUTF8String:p_item->p_input->psz_name];
2045         PL_UNLOCK;
2046         [self setScrollField: o_temp stopAfter:-1];
2047         [[[self controls] fspanel] setStreamTitle: o_temp];
2048         vlc_object_release( p_input );
2049         return;
2050     }
2051     [self setScrollField: _NS("VLC media player") stopAfter:-1];
2052 }
2053
2054 - (void)playStatusUpdated:(int)i_status
2055 {
2056     if( i_status == PLAYING_S )
2057     {
2058         [[[self controls] fspanel] setPause];
2059         [o_btn_play setImage: o_img_pause];
2060         [o_btn_play setAlternateImage: o_img_pause_pressed];
2061         [o_btn_play setToolTip: _NS("Pause")];
2062         [o_mi_play setTitle: _NS("Pause")];
2063         [o_dmi_play setTitle: _NS("Pause")];
2064         [o_vmi_play setTitle: _NS("Pause")];
2065     }
2066     else
2067     {
2068         [[[self controls] fspanel] setPlay];
2069         [o_btn_play setImage: o_img_play];
2070         [o_btn_play setAlternateImage: o_img_play_pressed];
2071         [o_btn_play setToolTip: _NS("Play")];
2072         [o_mi_play setTitle: _NS("Play")];
2073         [o_dmi_play setTitle: _NS("Play")];
2074         [o_vmi_play setTitle: _NS("Play")];
2075     }
2076 }
2077
2078 - (void)setSubmenusEnabled:(BOOL)b_enabled
2079 {
2080     [o_mi_program setEnabled: b_enabled];
2081     [o_mi_title setEnabled: b_enabled];
2082     [o_mi_chapter setEnabled: b_enabled];
2083     [o_mi_audiotrack setEnabled: b_enabled];
2084     [o_mi_visual setEnabled: b_enabled];
2085     [o_mi_videotrack setEnabled: b_enabled];
2086     [o_mi_subtitle setEnabled: b_enabled];
2087     [o_mi_channels setEnabled: b_enabled];
2088     [o_mi_deinterlace setEnabled: b_enabled];
2089     [o_mi_deinterlace_mode setEnabled: b_enabled];
2090     [o_mi_ffmpeg_pp setEnabled: b_enabled];
2091     [o_mi_device setEnabled: b_enabled];
2092     [o_mi_screen setEnabled: b_enabled];
2093     [o_mi_aspect_ratio setEnabled: b_enabled];
2094     [o_mi_crop setEnabled: b_enabled];
2095     [o_mi_teletext setEnabled: b_enabled];
2096 }
2097
2098 - (IBAction)timesliderUpdate:(id)sender
2099 {
2100     float f_updated;
2101     playlist_t * p_playlist;
2102     input_thread_t * p_input;
2103
2104     switch( [[NSApp currentEvent] type] )
2105     {
2106         case NSLeftMouseUp:
2107         case NSLeftMouseDown:
2108         case NSLeftMouseDragged:
2109             f_updated = [sender floatValue];
2110             break;
2111
2112         default:
2113             return;
2114     }
2115     p_playlist = pl_Get( p_intf );
2116     p_input = playlist_CurrentInput( p_playlist );
2117     if( p_input != NULL )
2118     {
2119         vlc_value_t time;
2120         vlc_value_t pos;
2121         NSString * o_time;
2122         char psz_time[MSTRTIME_MAX_SIZE];
2123
2124         pos.f_float = f_updated / 10000.;
2125         var_Set( p_input, "position", pos );
2126         [o_timeslider setFloatValue: f_updated];
2127
2128         var_Get( p_input, "time", &time );
2129
2130         mtime_t dur = input_item_GetDuration( input_GetItem( p_input ) );
2131         if( b_time_remaining && dur != -1 )
2132         {
2133             o_time = [NSString stringWithFormat: @"-%s", secstotimestr( psz_time, ((dur - time.i_time) / 1000000) )];
2134         }
2135         else
2136             o_time = [NSString stringWithUTF8String: secstotimestr( psz_time, (time.i_time / 1000000) )];
2137
2138         [o_timefield setStringValue: o_time];
2139         [[[self controls] fspanel] setStreamPos: f_updated andTime: o_time];
2140         [o_embedded_window setTime: o_time position: f_updated];
2141         vlc_object_release( p_input );
2142     }
2143 }
2144
2145 - (IBAction)timeFieldWasClicked:(id)sender
2146 {
2147     b_time_remaining = !b_time_remaining;
2148 }
2149
2150
2151 #pragma mark -
2152 #pragma mark Recent Items
2153
2154 - (IBAction)clearRecentItems:(id)sender
2155 {
2156     [[NSDocumentController sharedDocumentController]
2157                           clearRecentDocuments: nil];
2158 }
2159
2160 - (void)openRecentItem:(id)sender
2161 {
2162     [self application: nil openFile: [sender title]];
2163 }
2164
2165 #pragma mark -
2166 #pragma mark Panels
2167
2168 - (IBAction)intfOpenFile:(id)sender
2169 {
2170     if( !nib_open_loaded )
2171     {
2172         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2173         [o_open awakeFromNib];
2174         [o_open openFile];
2175     } else {
2176         [o_open openFile];
2177     }
2178 }
2179
2180 - (IBAction)intfOpenFileGeneric:(id)sender
2181 {
2182     if( !nib_open_loaded )
2183     {
2184         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2185         [o_open awakeFromNib];
2186         [o_open openFileGeneric];
2187     } else {
2188         [o_open openFileGeneric];
2189     }
2190 }
2191
2192 - (IBAction)intfOpenDisc:(id)sender
2193 {
2194     if( !nib_open_loaded )
2195     {
2196         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2197         [o_open awakeFromNib];
2198         [o_open openDisc];
2199     } else {
2200         [o_open openDisc];
2201     }
2202 }
2203
2204 - (IBAction)intfOpenNet:(id)sender
2205 {
2206     if( !nib_open_loaded )
2207     {
2208         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2209         [o_open awakeFromNib];
2210         [o_open openNet];
2211     } else {
2212         [o_open openNet];
2213     }
2214 }
2215
2216 - (IBAction)intfOpenCapture:(id)sender
2217 {
2218     if( !nib_open_loaded )
2219     {
2220         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
2221         [o_open awakeFromNib];
2222         [o_open openCapture];
2223     } else {
2224         [o_open openCapture];
2225     }
2226 }
2227
2228 - (IBAction)showWizard:(id)sender
2229 {
2230     if( !nib_wizard_loaded )
2231     {
2232         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2233         [o_wizard initStrings];
2234         [o_wizard resetWizard];
2235         [o_wizard showWizard];
2236     } else {
2237         [o_wizard resetWizard];
2238         [o_wizard showWizard];
2239     }
2240 }
2241
2242 - (IBAction)showExtended:(id)sender
2243 {
2244     if( o_extended == nil )
2245         o_extended = [[VLCExtended alloc] init];
2246
2247     if( !nib_extended_loaded )
2248         nib_extended_loaded = [NSBundle loadNibNamed:@"Extended" owner: NSApp];
2249
2250     [o_extended showPanel];
2251 }
2252
2253 - (IBAction)showAudioEffects:(id)sender
2254 {
2255     if (!o_audioeffects)
2256         o_audioeffects = [[VLCAudioEffects alloc] init];
2257
2258     if (!nib_audioeffects_loaded)
2259         nib_audioeffects_loaded = [NSBundle loadNibNamed:@"AudioEffects" owner:NSApp];
2260
2261     [o_audioeffects toggleWindow:sender];
2262 }
2263
2264 - (IBAction)showBookmarks:(id)sender
2265 {
2266     /* we need the wizard-nib for the bookmarks's extract functionality */
2267     if( !nib_wizard_loaded )
2268     {
2269         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
2270         [o_wizard initStrings];
2271     }
2272
2273     if( !nib_bookmarks_loaded )
2274         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
2275
2276     [o_bookmarks showBookmarks];
2277 }
2278
2279 - (IBAction)viewPreferences:(id)sender
2280 {
2281     if( !nib_prefs_loaded )
2282     {
2283         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
2284         o_sprefs = [[VLCSimplePrefs alloc] init];
2285         o_prefs= [[VLCPrefs alloc] init];
2286     }
2287
2288     [o_sprefs showSimplePrefs];
2289 }
2290
2291 #pragma mark -
2292 #pragma mark Help and Docs
2293
2294 - (IBAction)viewAbout:(id)sender
2295 {
2296     if( !nib_about_loaded )
2297         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2298
2299     [o_about showAbout];
2300 }
2301
2302 - (IBAction)showLicense:(id)sender
2303 {
2304     if( !nib_about_loaded )
2305         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2306
2307     [o_about showGPL: sender];
2308 }
2309
2310 - (IBAction)viewHelp:(id)sender
2311 {
2312     if( !nib_about_loaded )
2313     {
2314         nib_about_loaded = [NSBundle loadNibNamed:@"About" owner: NSApp];
2315         [o_about showHelp];
2316     }
2317     else
2318         [o_about showHelp];
2319 }
2320
2321 - (IBAction)openReadMe:(id)sender
2322 {
2323     NSString * o_path = [[NSBundle mainBundle]
2324         pathForResource: @"README.MacOSX" ofType: @"rtf"];
2325
2326     [[NSWorkspace sharedWorkspace] openFile: o_path
2327                                    withApplication: @"TextEdit"];
2328 }
2329
2330 - (IBAction)openDocumentation:(id)sender
2331 {
2332     NSURL * o_url = [NSURL URLWithString:
2333         @"http://www.videolan.org/doc/"];
2334
2335     [[NSWorkspace sharedWorkspace] openURL: o_url];
2336 }
2337
2338 - (IBAction)openWebsite:(id)sender
2339 {
2340     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/"];
2341
2342     [[NSWorkspace sharedWorkspace] openURL: o_url];
2343 }
2344
2345 - (IBAction)openForum:(id)sender
2346 {
2347     NSURL * o_url = [NSURL URLWithString: @"http://forum.videolan.org/"];
2348
2349     [[NSWorkspace sharedWorkspace] openURL: o_url];
2350 }
2351
2352 - (IBAction)openDonate:(id)sender
2353 {
2354     NSURL * o_url = [NSURL URLWithString: @"http://www.videolan.org/contribute.html#paypal"];
2355
2356     [[NSWorkspace sharedWorkspace] openURL: o_url];
2357 }
2358
2359 #pragma mark -
2360 #pragma mark Crash Log
2361 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
2362 {
2363     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
2364     NSURL *url = [NSURL URLWithString:urlStr];
2365
2366     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
2367     [req setHTTPMethod:@"POST"];
2368
2369     NSString * email;
2370     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
2371     {
2372         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
2373         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
2374         email = [emails valueAtIndex:[emails indexForIdentifier:
2375                     [emails primaryIdentifier]]];
2376     }
2377     else
2378         email = [NSString string];
2379
2380     NSString *postBody;
2381     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
2382             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2383             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
2384             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2385
2386     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
2387
2388     /* Released from delegate */
2389     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
2390 }
2391
2392 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
2393 {
2394     [crashLogURLConnection release];
2395     crashLogURLConnection = nil;
2396 }
2397
2398 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
2399 {
2400     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
2401     [crashLogURLConnection release];
2402     crashLogURLConnection = nil;
2403 }
2404
2405 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
2406 {
2407     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
2408     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
2409     NSString *fname;
2410     NSString * latestLog = nil;
2411     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
2412     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
2413     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
2414     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
2415
2416     while (fname = [direnum nextObject])
2417     {
2418         [direnum skipDescendents];
2419         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
2420         {
2421             NSArray * compo = [fname componentsSeparatedByString:@"_"];
2422             if( [compo count] < 3 ) continue;
2423             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
2424             if( [compo count] < 4 ) continue;
2425
2426             // Dooh. ugly.
2427             if( year < [[compo objectAtIndex:0] intValue] ||
2428                 (year ==[[compo objectAtIndex:0] intValue] &&
2429                  (month < [[compo objectAtIndex:1] intValue] ||
2430                   (month ==[[compo objectAtIndex:1] intValue] &&
2431                    (day   < [[compo objectAtIndex:2] intValue] ||
2432                     (day   ==[[compo objectAtIndex:2] intValue] &&
2433                       hours < [[compo objectAtIndex:3] intValue] ))))))
2434             {
2435                 year  = [[compo objectAtIndex:0] intValue];
2436                 month = [[compo objectAtIndex:1] intValue];
2437                 day   = [[compo objectAtIndex:2] intValue];
2438                 hours = [[compo objectAtIndex:3] intValue];
2439                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
2440             }
2441         }
2442     }
2443
2444     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
2445         return nil;
2446
2447     if( !previouslySeen )
2448     {
2449         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
2450         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
2451         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
2452         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
2453     }
2454     return latestLog;
2455 }
2456
2457 - (NSString *)latestCrashLogPath
2458 {
2459     return [self latestCrashLogPathPreviouslySeen:YES];
2460 }
2461
2462 - (void)lookForCrashLog
2463 {
2464     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
2465     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
2466     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
2467     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
2468     if( latestLog && !areCrashLogsTooOld )
2469         [NSApp runModalForWindow: o_crashrep_win];
2470     [o_pool release];
2471 }
2472
2473 - (IBAction)crashReporterAction:(id)sender
2474 {
2475     if( sender == o_crashrep_send_btn )
2476         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
2477
2478     [NSApp stopModal];
2479     [o_crashrep_win orderOut: sender];
2480 }
2481
2482 - (IBAction)openCrashLog:(id)sender
2483 {
2484     NSString * latestLog = [self latestCrashLogPath];
2485     if( latestLog )
2486     {
2487         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
2488     }
2489     else
2490     {
2491         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.") );
2492     }
2493 }
2494
2495 #pragma mark -
2496 #pragma mark Remove old prefs
2497
2498 - (void)_removeOldPreferences
2499 {
2500     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
2501     static const int kCurrentPreferencesVersion = 1;
2502     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
2503     if( version >= kCurrentPreferencesVersion ) return;
2504
2505     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
2506         NSUserDomainMask, YES);
2507     if( !libraries || [libraries count] == 0) return;
2508     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
2509
2510     /* File not found, don't attempt anything */
2511     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
2512        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
2513     {
2514         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2515         return;
2516     }
2517
2518     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
2519                 _NS("We just found an older version of VLC's preferences files."),
2520                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
2521     if( res != NSOKButton )
2522     {
2523         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2524         return;
2525     }
2526
2527     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
2528
2529     /* Move the file to trash so that user can find them later */
2530     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
2531
2532     /* really reset the defaults from now on */
2533     [NSUserDefaults resetStandardUserDefaults];
2534
2535     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
2536     [[NSUserDefaults standardUserDefaults] synchronize];
2537
2538     /* Relaunch now */
2539     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
2540
2541     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
2542     if(fork() != 0)
2543     {
2544         exit(0);
2545         return;
2546     }
2547     execl(path, path, NULL);
2548 }
2549
2550 #pragma mark -
2551 #pragma mark Errors, warnings and messages
2552
2553 - (IBAction)viewErrorsAndWarnings:(id)sender
2554 {
2555     [[[self coreDialogProvider] errorPanel] showPanel];
2556 }
2557
2558 - (IBAction)showMessagesPanel:(id)sender
2559 {
2560     [o_msgs_panel makeKeyAndOrderFront: sender];
2561 }
2562
2563 - (IBAction)showInformationPanel:(id)sender
2564 {
2565     if(! nib_info_loaded )
2566         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
2567
2568     [o_info initPanel];
2569 }
2570
2571 - (void)windowDidBecomeKey:(NSNotification *)o_notification
2572 {
2573     if( [o_notification object] == o_msgs_panel )
2574         [self updateMessageDisplay];
2575 }
2576
2577 - (void)updateMessageDisplay
2578 {
2579     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
2580     {
2581         id o_msg;
2582         NSEnumerator * o_enum;
2583
2584         [o_messages setString: @""];
2585
2586         [o_msg_lock lock];
2587
2588         o_enum = [o_msg_arr objectEnumerator];
2589
2590         while( ( o_msg = [o_enum nextObject] ) != nil )
2591         {
2592             [o_messages insertText: o_msg];
2593         }
2594
2595         b_msg_arr_changed = NO;
2596         [o_msg_lock unlock];
2597     }
2598 }
2599
2600 - (void)libvlcMessageReceived: (NSNotification *)o_notification
2601 {
2602     NSColor *o_white = [NSColor whiteColor];
2603     NSColor *o_red = [NSColor redColor];
2604     NSColor *o_yellow = [NSColor yellowColor];
2605     NSColor *o_gray = [NSColor grayColor];
2606
2607     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2608     static const char * ppsz_type[4] = { ": ", " error: ",
2609     " warning: ", " debug: " };
2610
2611     NSString *o_msg;
2612     NSDictionary *o_attr;
2613     NSAttributedString *o_msg_color;
2614
2615     int i_type = [[[o_notification userInfo] objectForKey: @"Type"] intValue];
2616
2617     [o_msg_lock lock];
2618
2619     if( [o_msg_arr count] + 2 > 600 )
2620     {
2621         [o_msg_arr removeObjectAtIndex: 0];
2622         [o_msg_arr removeObjectAtIndex: 1];
2623     }
2624
2625     o_attr = [NSDictionary dictionaryWithObject: o_gray
2626                                          forKey: NSForegroundColorAttributeName];
2627     o_msg = [NSString stringWithFormat: @"%@%s",
2628              [[o_notification userInfo] objectForKey: @"Module"],
2629              ppsz_type[i_type]];
2630     o_msg_color = [[NSAttributedString alloc]
2631                    initWithString: o_msg attributes: o_attr];
2632     [o_msg_arr addObject: [o_msg_color autorelease]];
2633
2634     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]
2635                                          forKey: NSForegroundColorAttributeName];
2636     o_msg = [[[o_notification userInfo] objectForKey: @"Message"] stringByAppendingString: @"\n"];
2637     o_msg_color = [[NSAttributedString alloc]
2638                    initWithString: o_msg attributes: o_attr];
2639     [o_msg_arr addObject: [o_msg_color autorelease]];
2640
2641     b_msg_arr_changed = YES;
2642     [o_msg_lock unlock];
2643 }
2644
2645 - (IBAction)saveDebugLog:(id)sender
2646 {
2647     NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
2648
2649     [saveFolderPanel setCanChooseDirectories: NO];
2650     [saveFolderPanel setCanChooseFiles: YES];
2651     [saveFolderPanel setCanSelectHiddenExtension: NO];
2652     [saveFolderPanel setCanCreateDirectories: YES];
2653     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
2654     [saveFolderPanel beginSheetForDirectory:nil file: [NSString stringWithFormat: _NS("VLC Debug Log (%s).rtfd"), VERSION_MESSAGE] modalForWindow: o_msgs_panel modalDelegate:self didEndSelector:@selector(saveDebugLogAsRTF:returnCode:contextInfo:) contextInfo:nil];
2655 }
2656
2657 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2658 {
2659     BOOL b_returned;
2660     if( returnCode == NSOKButton )
2661     {
2662         b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
2663         if(! b_returned )
2664             msg_Warn( p_intf, "Error while saving the debug log" );
2665     }
2666 }
2667
2668 #pragma mark -
2669 #pragma mark Playlist toggling
2670
2671 - (IBAction)togglePlaylist:(id)sender
2672 {
2673     NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2674     NSRect o_rect = [o_window contentRectForFrameRect:[o_window frame]];
2675     /*First, check if the playlist is visible*/
2676     if( contentRect.size.height <= 169. )
2677     {
2678         o_restore_rect = contentRect;
2679         b_restore_size = true;
2680         b_small_window = YES; /* we know we are small, make sure this is actually set (see case below) */
2681
2682         /* make large */
2683         if( o_size_with_playlist.height > 169. )
2684             o_rect.size.height = o_size_with_playlist.height;
2685         else
2686             o_rect.size.height = 500.;
2687
2688         if( o_size_with_playlist.width >= [o_window contentMinSize].width )
2689             o_rect.size.width = o_size_with_playlist.width;
2690         else
2691             o_rect.size.width = [o_window contentMinSize].width;
2692
2693         o_rect.origin.x = contentRect.origin.x;
2694         o_rect.origin.y = contentRect.origin.y - o_rect.size.height +
2695             [o_window contentMinSize].height;
2696
2697         o_rect = [o_window frameRectForContentRect:o_rect];
2698
2699         NSRect screenRect = [[o_window screen] visibleFrame];
2700         if( !NSContainsRect( screenRect, o_rect ) ) {
2701             if( NSMaxX(o_rect) > NSMaxX(screenRect) )
2702                 o_rect.origin.x = ( NSMaxX(screenRect) - o_rect.size.width );
2703             if( NSMinY(o_rect) < NSMinY(screenRect) )
2704                 o_rect.origin.y = ( NSMinY(screenRect) );
2705         }
2706
2707         [o_btn_playlist setState: YES];
2708     }
2709     else
2710     {
2711         NSSize curSize = o_rect.size;
2712         if( b_restore_size )
2713         {
2714             o_rect = o_restore_rect;
2715             if( o_rect.size.height < [o_window contentMinSize].height )
2716                 o_rect.size.height = [o_window contentMinSize].height;
2717             if( o_rect.size.width < [o_window contentMinSize].width )
2718                 o_rect.size.width = [o_window contentMinSize].width;
2719         }
2720         else
2721         {
2722             NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2723             /* make small */
2724             o_rect.size.height = [o_window contentMinSize].height;
2725             o_rect.size.width = [o_window contentMinSize].width;
2726             o_rect.origin.x = contentRect.origin.x;
2727             /* Calculate the position of the lower right corner after resize */
2728             o_rect.origin.y = contentRect.origin.y +
2729                 contentRect.size.height - [o_window contentMinSize].height;
2730         }
2731
2732         [o_playlist_view setAutoresizesSubviews: NO];
2733         [o_playlist_view removeFromSuperview];
2734         [o_btn_playlist setState: NO];
2735         b_small_window = NO; /* we aren't small here just yet. we are doing an animated resize after this */
2736         o_rect = [o_window frameRectForContentRect:o_rect];
2737     }
2738
2739     [o_window setFrame: o_rect display:YES animate: YES];
2740 }
2741
2742 - (void)updateTogglePlaylistState
2743 {
2744     if( [o_window contentRectForFrameRect:[o_window frame]].size.height <= 169. )
2745         [o_btn_playlist setState: NO];
2746     else
2747         [o_btn_playlist setState: YES];
2748
2749     [[self playlist] outlineViewSelectionDidChange: NULL];
2750 }
2751
2752 - (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize
2753 {
2754
2755     /* Not triggered on a window resize or maxification of the window. only by window mouse dragging resize */
2756
2757    /*Stores the size the controller one resize, to be able to restore it when
2758      toggling the playlist*/
2759     o_size_with_playlist = proposedFrameSize;
2760
2761     NSRect rect;
2762     rect.size = proposedFrameSize;
2763     if( [o_window contentRectForFrameRect:rect].size.height <= 169. )
2764     {
2765         if( b_small_window == NO )
2766         {
2767             /* if large and going to small then hide */
2768             b_small_window = YES;
2769             [o_playlist_view setAutoresizesSubviews: NO];
2770             [o_playlist_view removeFromSuperview];
2771         }
2772         return NSMakeSize( proposedFrameSize.width, [o_window minSize].height);
2773     }
2774     return proposedFrameSize;
2775 }
2776
2777 - (void)windowDidMove:(NSNotification *)notif
2778 {
2779     b_restore_size = false;
2780 }
2781
2782 - (void)windowDidResize:(NSNotification *)notif
2783 {
2784     if( [o_window contentRectForFrameRect:[o_window frame]].size.height > 169. && b_small_window )
2785     {
2786         /* If large and coming from small then show */
2787         [o_playlist_view setAutoresizesSubviews: YES];
2788         NSRect contentRect = [o_window contentRectForFrameRect:[o_window frame]];
2789         [o_playlist_view setFrame: NSMakeRect( 0, 0, contentRect.size.width, contentRect.size.height - [o_window contentMinSize].height )];
2790         [o_playlist_view setNeedsDisplay:YES];
2791         [[o_window contentView] addSubview: o_playlist_view];
2792         b_small_window = NO;
2793     }
2794     [self updateTogglePlaylistState];
2795 }
2796
2797 #pragma mark -
2798
2799 @end
2800
2801 @implementation VLCMain (NSMenuValidation)
2802
2803 - (BOOL)validateMenuItem:(NSMenuItem *)o_mi
2804 {
2805     NSString *o_title = [o_mi title];
2806     BOOL bEnabled = TRUE;
2807
2808     /* Recent Items Menu */
2809     if( [o_title isEqualToString: _NS("Clear Menu")] )
2810     {
2811         NSMenu * o_menu = [o_mi_open_recent submenu];
2812         int i_nb_items = [o_menu numberOfItems];
2813         NSArray * o_docs = [[NSDocumentController sharedDocumentController]
2814                                                        recentDocumentURLs];
2815         UInt32 i_nb_docs = [o_docs count];
2816
2817         if( i_nb_items > 1 )
2818         {
2819             while( --i_nb_items )
2820             {
2821                 [o_menu removeItemAtIndex: 0];
2822             }
2823         }
2824
2825         if( i_nb_docs > 0 )
2826         {
2827             NSURL * o_url;
2828             NSString * o_doc;
2829
2830             [o_menu insertItem: [NSMenuItem separatorItem] atIndex: 0];
2831
2832             while( TRUE )
2833             {
2834                 i_nb_docs--;
2835
2836                 o_url = [o_docs objectAtIndex: i_nb_docs];
2837
2838                 if( [o_url isFileURL] )
2839                 {
2840                     o_doc = [o_url path];
2841                 }
2842                 else
2843                 {
2844                     o_doc = [o_url absoluteString];
2845                 }
2846
2847                 [o_menu insertItemWithTitle: o_doc
2848                     action: @selector(openRecentItem:)
2849                     keyEquivalent: @"" atIndex: 0];
2850
2851                 if( i_nb_docs == 0 )
2852                 {
2853                     break;
2854                 }
2855             }
2856         }
2857         else
2858         {
2859             bEnabled = FALSE;
2860         }
2861     }
2862     return( bEnabled );
2863 }
2864
2865 @end
2866
2867 @implementation VLCMain (Internal)
2868
2869 - (void)handlePortMessage:(NSPortMessage *)o_msg
2870 {
2871     id ** val;
2872     NSData * o_data;
2873     NSValue * o_value;
2874     NSInvocation * o_inv;
2875     NSConditionLock * o_lock;
2876
2877     o_data = [[o_msg components] lastObject];
2878     o_inv = *((NSInvocation **)[o_data bytes]);
2879     [o_inv getArgument: &o_value atIndex: 2];
2880     val = (id **)[o_value pointerValue];
2881     [o_inv setArgument: val[1] atIndex: 2];
2882     o_lock = *(val[0]);
2883
2884     [o_lock lock];
2885     [o_inv invoke];
2886     [o_lock unlockWithCondition: 1];
2887 }
2888 - (void)resetMediaKeyJump
2889 {
2890     b_mediakeyJustJumped = NO;
2891 }
2892 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2893 {
2894     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
2895     [o_mediaKeyController setShouldInterceptMediaKeyEvents:b_mediaKeySupport];
2896 }
2897
2898 @end
2899
2900 /*****************************************************************************
2901  * VLCApplication interface
2902  *****************************************************************************/
2903
2904 @implementation VLCApplication
2905 // when user selects the quit menu from dock it sends a terminate:
2906 // but we need to send a stop: to properly exits libvlc.
2907 // However, we are not able to change the action-method sent by this standard menu item.
2908 // thus we override terminat: to send a stop:
2909 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp() 
2910 - (void)terminate:(id)sender
2911 {
2912     [self activateIgnoringOtherApps:YES];
2913     [self stop:sender];
2914 }
2915
2916 @end