]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: don't use Carbon to retrieve icons from the OS
[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 <vlc_aout_intf.h>
39 #include <vlc_vout_window.h>
40 #include <unistd.h> /* execl() */
41
42 #import "intf.h"
43 #import "MainMenu.h"
44 #import "MainWindow.h"
45 #import "fspanel.h"
46 #import "vout.h"
47 #import "prefs.h"
48 #import "playlist.h"
49 #import "playlistinfo.h"
50 #import "controls.h"
51 #import "open.h"
52 #import "wizard.h"
53 #import "bookmarks.h"
54 #import "coredialogs.h"
55 #import "embeddedwindow.h"
56 #import "AppleRemote.h"
57 #import "eyetv.h"
58 #import "simple_prefs.h"
59 #import "CoreInteraction.h"
60
61 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
62 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
63
64 /*****************************************************************************
65  * Local prototypes.
66  *****************************************************************************/
67 static void Run ( intf_thread_t *p_intf );
68
69 static void * ManageThread( void *user_data );
70
71 static void updateProgressPanel (void *, const char *, float);
72 static bool checkProgressPanel (void *);
73 static void destroyProgressPanel (void *);
74
75 static void MsgCallback( msg_cb_data_t *, const msg_item_t * );
76
77 #pragma mark -
78 #pragma mark VLC Interface Object Callbacks
79
80 /*****************************************************************************
81  * OpenIntf: initialize interface
82  *****************************************************************************/
83 int OpenIntf ( vlc_object_t *p_this )
84 {
85     intf_thread_t *p_intf = (intf_thread_t*) p_this;
86
87     p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
88     if( p_intf->p_sys == NULL )
89         return VLC_ENOMEM;
90
91     memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
92
93     /* subscribe to LibVLCCore's messages */
94     p_intf->p_sys->p_sub = msg_Subscribe( p_intf->p_libvlc, MsgCallback, NULL );
95     p_intf->pf_run = Run;
96     p_intf->b_should_run_on_first_thread = true;
97
98     return VLC_SUCCESS;
99 }
100
101 /*****************************************************************************
102  * CloseIntf: destroy interface
103  *****************************************************************************/
104 void CloseIntf ( vlc_object_t *p_this )
105 {
106     intf_thread_t *p_intf = (intf_thread_t*) p_this;
107
108     free( p_intf->p_sys );
109 }
110
111 static int WindowControl( vout_window_t *, int i_query, va_list );
112
113 int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
114 {
115     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
116     intf_thread_t *p_intf = VLCIntf;
117     if (!p_intf) {
118         msg_Err( p_wnd, "Mac OS X interface not found" );
119         return VLC_EGENERIC;
120     }
121
122     msg_Dbg( p_wnd, "looking for video view" );
123     int i_x = cfg->x;
124     int i_y = cfg->y;
125     unsigned i_width = cfg->width;
126     unsigned i_height = cfg->height;
127     p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];
128
129     if ( !p_wnd->handle.nsobject ) {
130         msg_Err( p_wnd, "got no video view from the interface" );
131         [o_pool release];
132         return VLC_EGENERIC;
133     }
134
135     [[VLCMainWindow sharedInstance] setVideoplayEnabled:YES];
136     [[VLCMainWindow sharedInstance] togglePlaylist:nil];
137     p_wnd->control = WindowControl;
138     p_wnd->sys = (vout_window_sys_t *)VLCIntf;
139     [o_pool release];
140     return VLC_SUCCESS;
141 }
142
143 static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
144 {
145     /* TODO */
146     if( i_query == VOUT_WINDOW_SET_STATE )
147         NSLog( @"WindowControl:VOUT_WINDOW_SET_STATE" );
148     else if( i_query == VOUT_WINDOW_SET_SIZE )
149         NSLog( @"WindowControl:VOUT_WINDOW_SET_SIZE" );
150     else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
151         NSLog( @"WindowControl:VOUT_WINDOW_SET_FULLSCREEN" );
152     else
153         NSLog( @"WindowControl: unknown query" );
154     return VLC_SUCCESS;
155 }
156
157 void WindowClose( vout_window_t *p_wnd )
158 {
159     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
160     [[VLCMainWindow sharedInstance] setVideoplayEnabled:NO];
161     NSLog( @"Window Close" );
162     // tell the interface to get rid of the video, TODO
163     [o_pool release];
164 }
165
166 /*****************************************************************************
167  * Run: main loop
168  *****************************************************************************/
169 static NSLock * o_appLock = nil;    // controls access to f_appExit
170 static int f_appExit = 0;           // set to 1 when application termination signaled
171
172 static void Run( intf_thread_t *p_intf )
173 {
174     sigset_t set;
175
176     /* Make sure the "force quit" menu item does quit instantly.
177      * VLC overrides SIGTERM which is sent by the "force quit"
178      * menu item to make sure deamon mode quits gracefully, so
179      * we un-override SIGTERM here. */
180     sigemptyset( &set );
181     sigaddset( &set, SIGTERM );
182     pthread_sigmask( SIG_UNBLOCK, &set, NULL );
183
184     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
185
186     o_appLock = [[NSLock alloc] init];
187
188     [VLCApplication sharedApplication];
189
190     [[VLCMain sharedInstance] setIntf: p_intf];
191     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
192
193     [NSApp run];
194     [[VLCMain sharedInstance] applicationWillTerminate:nil];
195     [o_appLock release];
196     [o_pool release];
197 }
198
199 #pragma mark -
200 #pragma mark Variables Callback
201
202 /*****************************************************************************
203  * MsgCallback: Callback triggered by the core once a new debug message is
204  * ready to be displayed. We store everything in a NSArray in our Cocoa part
205  * of this file.
206  *****************************************************************************/
207 static void MsgCallback( msg_cb_data_t *data, const msg_item_t *item )
208 {
209     int canc = vlc_savecancel();
210
211     /* this may happen from time to time, let's bail out as info would be useless anyway */
212     if( !item->psz_module || !item->psz_msg )
213         return;
214
215     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
216     [[VLCMain sharedInstance] processReceivedlibvlcMessage: item];
217     [o_pool release];
218
219     vlc_restorecancel( canc );
220 }
221
222 /*****************************************************************************
223  * playlistChanged: Callback triggered by the intf-change playlist
224  * variable, to let the intf update the playlist.
225  *****************************************************************************/
226 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
227                      vlc_value_t old_val, vlc_value_t new_val, void *param )
228 {
229     intf_thread_t * p_intf = VLCIntf;
230     if( p_intf && p_intf->p_sys )
231     {
232         NSLog( @"event from %s", psz_variable );
233         p_intf->p_sys->b_intf_update = true;
234         p_intf->p_sys->b_playlist_update = true;
235         p_intf->p_sys->b_playmode_update = true;
236         p_intf->p_sys->b_current_title_update = true;
237     }
238     return VLC_SUCCESS;
239 }
240
241 /*****************************************************************************
242  * ShowController: Callback triggered by the show-intf playlist variable
243  * through the ShowIntf-control-intf, to let us show the controller-win;
244  * usually when in fullscreen-mode
245  *****************************************************************************/
246 static int ShowController( vlc_object_t *p_this, const char *psz_variable,
247                      vlc_value_t old_val, vlc_value_t new_val, void *param )
248 {
249     intf_thread_t * p_intf = VLCIntf;
250     if( p_intf && p_intf->p_sys )
251     {
252         NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
253         if( [[[VLCCoreInteraction sharedInstance] voutView] isFullscreen] && config_GetInt( VLCIntf, "macosx-fspanel" ) )
254             [[[[VLCMain sharedInstance] controls] fspanel] fadeIn];
255         else
256             [[VLCMainWindow sharedInstance] makeKeyAndOrderFront: nil];
257         [o_pool release];
258     }
259     return VLC_SUCCESS;
260 }
261
262 /*****************************************************************************
263  * FullscreenChanged: Callback triggered by the fullscreen-change playlist
264  * variable, to let the intf update the controller.
265  *****************************************************************************/
266 static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
267                      vlc_value_t old_val, vlc_value_t new_val, void *param )
268 {
269     intf_thread_t * p_intf = VLCIntf;
270     if( p_intf && p_intf->p_sys )
271         NSLog( @"we should update fullscreen state" ); //FIXME
272     return VLC_SUCCESS;
273 }
274
275 /*****************************************************************************
276  * DialogCallback: Callback triggered by the "dialog-*" variables
277  * to let the intf display error and interaction dialogs
278  *****************************************************************************/
279 static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
280 {
281     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
282     VLCMain *interface = (VLCMain *)data;
283
284     if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
285     {
286         /* the progress panel needs to update itself and therefore wants special treatment within this context */
287         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
288
289         p_dialog->pf_update = updateProgressPanel;
290         p_dialog->pf_check = checkProgressPanel;
291         p_dialog->pf_destroy = destroyProgressPanel;
292         p_dialog->p_sys = VLCIntf->p_libvlc;
293     }
294
295     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
296     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
297
298     [o_pool release];
299     return VLC_SUCCESS;
300 }
301
302 void updateProgressPanel (void *priv, const char *text, float value)
303 {
304     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
305
306     NSString *o_txt;
307     if( text != NULL )
308         o_txt = [NSString stringWithUTF8String: text];
309     else
310         o_txt = @"";
311
312     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
313
314     [o_pool release];
315 }
316
317 void destroyProgressPanel (void *priv)
318 {
319     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
320     [[[VLCMain sharedInstance] coreDialogProvider] destroyProgressPanel];
321     [o_pool release];
322 }
323
324 bool checkProgressPanel (void *priv)
325 {
326     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
327     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
328     [o_pool release];
329 }
330
331 #pragma mark -
332 #pragma mark Helpers
333
334 input_thread_t *getInput(void)
335 {
336     intf_thread_t *p_intf = VLCIntf;
337     if (!p_intf)
338         return NULL;
339     return pl_CurrentInput(p_intf);
340 }
341
342 vout_thread_t *getVout(void)
343 {
344     input_thread_t *p_input = getInput();
345     if (!p_input)
346         return NULL;
347     vout_thread_t *p_vout = input_GetVout(p_input);
348     vlc_object_release(p_input);
349     return p_vout;
350 }
351
352 aout_instance_t *getAout(void)
353 {
354     input_thread_t *p_input = getInput();
355     if (!p_input)
356         return NULL;
357     aout_instance_t *p_aout = input_GetAout(p_input);
358     vlc_object_release(p_input);
359     return p_aout;
360 }
361
362 #pragma mark -
363 #pragma mark Private
364
365 @interface VLCMain ()
366 - (void)_removeOldPreferences;
367 @end
368
369 /*****************************************************************************
370  * VLCMain implementation
371  *****************************************************************************/
372 @implementation VLCMain
373
374 #pragma mark -
375 #pragma mark Initialization
376
377 static VLCMain *_o_sharedMainInstance = nil;
378
379 + (VLCMain *)sharedInstance
380 {
381     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
382 }
383
384 - (id)init
385 {
386     if( _o_sharedMainInstance)
387     {
388         [self dealloc];
389         return _o_sharedMainInstance;
390     }
391     else
392         _o_sharedMainInstance = [super init];
393
394     p_intf = NULL;
395
396     o_msg_lock = [[NSLock alloc] init];
397     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
398     /* subscribe to LibVLC's debug messages as early as possible (for us) */
399     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(libvlcMessageReceived:) name: @"VLCCoreMessageReceived" object: nil];
400
401     o_open = [[VLCOpen alloc] init];
402     //o_embedded_list = [[VLCEmbeddedList alloc] init];
403     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
404     o_info = [[VLCInfo alloc] init];
405     o_mainmenu = [[VLCMainMenu alloc] init];
406     o_coreinteraction = [[VLCCoreInteraction alloc] init];
407     o_eyetv = [[VLCEyeTVController alloc] init];
408
409     /* announce our launch to a potential eyetv plugin */
410     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
411                                                                    object: @"VLCEyeTVSupport"
412                                                                  userInfo: NULL
413                                                        deliverImmediately: YES];
414     return _o_sharedMainInstance;
415 }
416
417 - (void)setIntf: (intf_thread_t *)p_mainintf {
418     p_intf = p_mainintf;
419 }
420
421 - (intf_thread_t *)intf {
422     return p_intf;
423 }
424
425 - (void)awakeFromNib
426 {
427     playlist_t *p_playlist;
428     vlc_value_t val;
429     var_Create( p_intf, "intf-change", VLC_VAR_BOOL );
430
431     [o_msgs_panel setExcludedFromWindowsMenu: YES];
432     [o_msgs_panel setDelegate: self];
433
434     p_playlist = pl_Get( p_intf );
435
436     val.b_bool = false;
437
438     var_AddCallback( p_playlist, "fullscreen", FullscreenChanged, self);
439     var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
440
441     /* load our Core Dialogs nib */
442     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
443
444     /* subscribe to various interactive dialogues */
445     var_Create( p_intf, "dialog-error", VLC_VAR_ADDRESS );
446     var_AddCallback( p_intf, "dialog-error", DialogCallback, self );
447     var_Create( p_intf, "dialog-critical", VLC_VAR_ADDRESS );
448     var_AddCallback( p_intf, "dialog-critical", DialogCallback, self );
449     var_Create( p_intf, "dialog-login", VLC_VAR_ADDRESS );
450     var_AddCallback( p_intf, "dialog-login", DialogCallback, self );
451     var_Create( p_intf, "dialog-question", VLC_VAR_ADDRESS );
452     var_AddCallback( p_intf, "dialog-question", DialogCallback, self );
453     var_Create( p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS );
454     var_AddCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
455     dialog_Register( p_intf );
456
457     /* update the playmode stuff */
458     p_intf->p_sys->b_playmode_update = true;
459
460     /* init Apple Remote support */
461     o_remote = [[AppleRemote alloc] init];
462     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
463     [o_remote setDelegate: _o_sharedMainInstance];
464
465     /* yeah, we are done */
466     nib_main_loaded = TRUE;
467 }
468
469 - (void)applicationWillFinishLaunching:(NSNotification *)o_notification
470 {
471     if( !p_intf ) return;
472
473     /* FIXME: don't poll */
474     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.5
475                                      target: self selector: @selector(manageIntf:)
476                                    userInfo: nil repeats: FALSE] retain];
477
478     /* Note: we use the pthread API to support pre-10.5 */
479     pthread_create( &manage_thread, NULL, ManageThread, self );
480 }
481
482 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
483 {
484     if( !p_intf ) return;
485
486     /* init media key support */
487     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
488     if( b_mediaKeySupport )
489     {
490         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
491         [o_mediaKeyController startWatchingMediaKeys];
492         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
493                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
494                                                                  nil]];
495     }
496     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
497
498     [self _removeOldPreferences];
499
500     [o_mainwindow makeKeyAndOrderFront: self];
501
502     /* Handle sleep notification */
503     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
504            name:NSWorkspaceWillSleepNotification object:nil];
505
506     [NSThread detachNewThreadSelector:@selector(lookForCrashLog) toTarget:self withObject:nil];
507 }
508
509 - (void)initStrings
510 {
511     if( !p_intf ) return;
512
513     /* messages panel */
514     [o_msgs_panel setTitle: _NS("Messages")];
515     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
516     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
517
518     /* crash reporter panel */
519     [o_crashrep_send_btn setTitle: _NS("Send")];
520     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
521     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
522     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
523     [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, ...")];
524     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
525     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
526 }
527
528 #pragma mark -
529 #pragma mark Termination
530
531 - (void)applicationWillTerminate:(NSNotification *)notification
532 {
533     playlist_t * p_playlist;
534     vout_thread_t * p_vout;
535     int returnedValue = 0;
536
537     if( !p_intf )
538         return;
539
540     // don't allow a double termination call. If the user has
541     // already invoked the quit then simply return this time.
542     int isTerminating = false;
543
544     [o_appLock lock];
545     isTerminating = (f_appExit++ > 0 ? 1 : 0);
546     [o_appLock unlock];
547
548     if (isTerminating)
549         return;
550
551     msg_Dbg( p_intf, "Terminating" );
552
553     pthread_join( manage_thread, NULL );
554
555     /* Make sure the intf object is getting killed */
556     vlc_object_kill( p_intf );
557
558     /* Make sure the interfaceTimer is destroyed */
559     [interfaceTimer invalidate];
560     [interfaceTimer release];
561     interfaceTimer = nil;
562
563     /* unsubscribe from the interactive dialogues */
564     dialog_Unregister( p_intf );
565     var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
566     var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
567     var_DelCallback( p_intf, "dialog-login", DialogCallback, self );
568     var_DelCallback( p_intf, "dialog-question", DialogCallback, self );
569     var_DelCallback( p_intf, "dialog-progress-bar", DialogCallback, self );
570
571     /* remove global observer watching for vout device changes correctly */
572     [[NSNotificationCenter defaultCenter] removeObserver: self];
573
574     /* release some other objects here, because it isn't sure whether dealloc
575      * will be called later on */
576     if( o_sprefs )
577         [o_sprefs release];
578
579     if( o_prefs )
580         [o_prefs release];
581
582     [o_open release];
583
584     if( o_info )
585     {
586         [o_info stopTimers];
587         [o_info release];
588     }
589
590     if( o_wizard )
591         [o_wizard release];
592
593     [crashLogURLConnection cancel];
594     [crashLogURLConnection release];
595
596     [o_embedded_list release];
597     [o_coredialogs release];
598     [o_eyetv release];
599
600     /* unsubscribe from libvlc's debug messages */
601     msg_Unsubscribe( p_intf->p_sys->p_sub );
602
603     [o_msg_arr removeAllObjects];
604     [o_msg_arr release];
605
606     [o_msg_lock release];
607
608     /* write cached user defaults to disk */
609     [[NSUserDefaults standardUserDefaults] synchronize];
610
611     /* Make sure the Menu doesn't have any references to vlc objects anymore */
612     //FIXME: this should be moved to VLCMainMenu
613     [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
614     [o_mainmenu release];
615
616     /* Kill the playlist, so that it doesn't accept new request
617      * such as the play request from vlc.c (we are a blocking interface). */
618     p_playlist = pl_Get( p_intf );
619     vlc_object_kill( p_playlist );
620     libvlc_Quit( p_intf->p_libvlc );
621
622     [self setIntf:nil];
623 }
624
625 #pragma mark -
626 #pragma mark Sparkle delegate
627 /* received directly before the update gets installed, so let's shut down a bit */
628 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
629 {
630     [o_remote stopListening: self];
631     var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_STOP );
632
633     /* Close the window directly, because we do know that there
634      * won't be anymore video. It's currently waiting a bit. */
635     [[[o_coreinteraction voutView] window] orderOut:self];
636 }
637
638 #pragma mark -
639 #pragma mark Media Key support
640
641 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
642 {
643     if( b_mediaKeySupport )
644        {
645         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
646
647         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
648         int keyFlags = ([event data1] & 0x0000FFFF);
649         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
650         int keyRepeat = (keyFlags & 0x1);
651
652         if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
653             var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
654
655         if( keyCode == NX_KEYTYPE_FAST && !b_mediakeyJustJumped )
656         {
657             if( keyState == 0 && keyRepeat == 0 )
658                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_NEXT );
659             else if( keyRepeat == 1 )
660             {
661                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_FORWARD_SHORT );
662                 b_mediakeyJustJumped = YES;
663                 [self performSelector:@selector(resetMediaKeyJump)
664                            withObject: NULL
665                            afterDelay:0.25];
666             }
667         }
668
669         if( keyCode == NX_KEYTYPE_REWIND && !b_mediakeyJustJumped )
670         {
671             if( keyState == 0 && keyRepeat == 0 )
672                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PREV );
673             else if( keyRepeat == 1 )
674             {
675                 var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_JUMP_BACKWARD_SHORT );
676                 b_mediakeyJustJumped = YES;
677                 [self performSelector:@selector(resetMediaKeyJump)
678                            withObject: NULL
679                            afterDelay:0.25];
680             }
681         }
682     }
683 }
684
685 #pragma mark -
686 #pragma mark Other notification
687
688 /* Listen to the remote in exclusive mode, only when VLC is the active
689    application */
690 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
691 {
692     if( !p_intf ) return;
693         if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
694                 [o_remote startListening: self];
695 }
696 - (void)applicationDidResignActive:(NSNotification *)aNotification
697 {
698     if( !p_intf ) return;
699     [o_remote stopListening: self];
700 }
701
702 /* Triggered when the computer goes to sleep */
703 - (void)computerWillSleep: (NSNotification *)notification
704 {
705     /* Pause */
706     if( p_intf && p_intf->p_sys->i_play_status == PLAYING_S )
707     {
708         var_SetInteger( p_intf->p_libvlc, "key-action", ACTIONID_PLAY_PAUSE );
709     }
710 }
711
712 #pragma mark -
713 #pragma mark File opening
714
715 - (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
716 {
717     BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
718     char *psz_uri = make_URI([o_filename UTF8String], "file" );
719     if( !psz_uri )
720         return( FALSE );
721
722     NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
723
724     free( psz_uri );
725
726     if( b_autoplay )
727         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
728     else
729         [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];
730
731     return( TRUE );
732 }
733
734 /* When user click in the Dock icon our double click in the finder */
735 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
736 {
737     if(!hasVisibleWindows)
738         [o_mainwindow makeKeyAndOrderFront:self];
739
740     return YES;
741 }
742
743 #pragma mark -
744 #pragma mark Apple Remote Control
745
746 /* Helper method for the remote control interface in order to trigger forward/backward and volume
747    increase/decrease as long as the user holds the left/right, plus/minus button */
748 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
749 {
750     if(b_remote_button_hold)
751     {
752         switch([buttonIdentifierNumber intValue])
753         {
754             case kRemoteButtonRight_Hold:
755                   [o_controls forward: self];
756             break;
757             case kRemoteButtonLeft_Hold:
758                   [o_controls backward: self];
759             break;
760             case kRemoteButtonVolume_Plus_Hold:
761                 [o_controls volumeUp: self];
762             break;
763             case kRemoteButtonVolume_Minus_Hold:
764                 [o_controls volumeDown: self];
765             break;
766         }
767         if(b_remote_button_hold)
768         {
769             /* trigger event */
770             [self performSelector:@selector(executeHoldActionForRemoteButton:)
771                          withObject:buttonIdentifierNumber
772                          afterDelay:0.25];
773         }
774     }
775 }
776
777 /* Apple Remote callback */
778 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
779                pressedDown: (BOOL) pressedDown
780                 clickCount: (unsigned int) count
781 {
782     switch( buttonIdentifier )
783     {
784         case k2009RemoteButtonFullscreen:
785             [o_controls toogleFullscreen:self];
786             break;
787         case k2009RemoteButtonPlay:
788             [o_controls play:self];
789             break;
790         case kRemoteButtonPlay:
791             if(count >= 2) {
792                 [o_controls toogleFullscreen:self];
793             } else {
794                 [o_controls play: self];
795             }
796             break;
797         case kRemoteButtonVolume_Plus:
798             [o_controls volumeUp: self];
799             break;
800         case kRemoteButtonVolume_Minus:
801             [o_controls volumeDown: self];
802             break;
803         case kRemoteButtonRight:
804             [o_controls next: self];
805             break;
806         case kRemoteButtonLeft:
807             [o_controls prev: self];
808             break;
809         case kRemoteButtonRight_Hold:
810         case kRemoteButtonLeft_Hold:
811         case kRemoteButtonVolume_Plus_Hold:
812         case kRemoteButtonVolume_Minus_Hold:
813             /* simulate an event as long as the user holds the button */
814             b_remote_button_hold = pressedDown;
815             if( pressedDown )
816             {
817                 NSNumber* buttonIdentifierNumber = [NSNumber numberWithInt: buttonIdentifier];
818                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
819                            withObject:buttonIdentifierNumber];
820             }
821             break;
822         case kRemoteButtonMenu:
823             [o_controls showPosition: self];
824             break;
825         default:
826             /* Add here whatever you want other buttons to do */
827             break;
828     }
829 }
830
831 #pragma mark -
832 #pragma mark String utility
833 // FIXME: this has nothing to do here
834
835 - (NSString *)localizedString:(const char *)psz
836 {
837     NSString * o_str = nil;
838
839     if( psz != NULL )
840     {
841         o_str = [NSString stringWithCString: psz encoding:NSUTF8StringEncoding];
842
843         if( o_str == NULL )
844         {
845             msg_Err( VLCIntf, "could not translate: %s", psz );
846             return( @"" );
847         }
848     }
849     else
850     {
851         msg_Warn( VLCIntf, "can't translate empty strings" );
852         return( @"" );
853     }
854
855     return( o_str );
856 }
857
858
859
860 - (char *)delocalizeString:(NSString *)id
861 {
862     NSData * o_data = [id dataUsingEncoding: NSUTF8StringEncoding
863                           allowLossyConversion: NO];
864     char * psz_string;
865
866     if( o_data == nil )
867     {
868         o_data = [id dataUsingEncoding: NSUTF8StringEncoding
869                      allowLossyConversion: YES];
870         psz_string = malloc( [o_data length] + 1 );
871         [o_data getBytes: psz_string];
872         psz_string[ [o_data length] ] = '\0';
873         msg_Err( VLCIntf, "cannot convert to the requested encoding: %s",
874                  psz_string );
875     }
876     else
877     {
878         psz_string = malloc( [o_data length] + 1 );
879         [o_data getBytes: psz_string];
880         psz_string[ [o_data length] ] = '\0';
881     }
882
883     return psz_string;
884 }
885
886 /* i_width is in pixels */
887 - (NSString *)wrapString: (NSString *)o_in_string toWidth: (int) i_width
888 {
889     NSMutableString *o_wrapped;
890     NSString *o_out_string;
891     NSRange glyphRange, effectiveRange, charRange;
892     NSRect lineFragmentRect;
893     unsigned glyphIndex, breaksInserted = 0;
894
895     NSTextStorage *o_storage = [[NSTextStorage alloc] initWithString: o_in_string
896         attributes: [NSDictionary dictionaryWithObjectsAndKeys:
897         [NSFont labelFontOfSize: 0.0], NSFontAttributeName, nil]];
898     NSLayoutManager *o_layout_manager = [[NSLayoutManager alloc] init];
899     NSTextContainer *o_container = [[NSTextContainer alloc]
900         initWithContainerSize: NSMakeSize(i_width, 2000)];
901
902     [o_layout_manager addTextContainer: o_container];
903     [o_container release];
904     [o_storage addLayoutManager: o_layout_manager];
905     [o_layout_manager release];
906
907     o_wrapped = [o_in_string mutableCopy];
908     glyphRange = [o_layout_manager glyphRangeForTextContainer: o_container];
909
910     for( glyphIndex = glyphRange.location ; glyphIndex < NSMaxRange(glyphRange) ;
911             glyphIndex += effectiveRange.length) {
912         lineFragmentRect = [o_layout_manager lineFragmentRectForGlyphAtIndex: glyphIndex
913                                             effectiveRange: &effectiveRange];
914         charRange = [o_layout_manager characterRangeForGlyphRange: effectiveRange
915                                     actualGlyphRange: &effectiveRange];
916         if([o_wrapped lineRangeForRange:
917                 NSMakeRange(charRange.location + breaksInserted, charRange.length)].length > charRange.length) {
918             [o_wrapped insertString: @"\n" atIndex: NSMaxRange(charRange) + breaksInserted];
919             breaksInserted++;
920         }
921     }
922     o_out_string = [NSString stringWithString: o_wrapped];
923     [o_wrapped release];
924     [o_storage release];
925
926     return o_out_string;
927 }
928
929
930 #pragma mark -
931 #pragma mark Key Shortcuts
932
933 static struct
934 {
935     unichar i_nskey;
936     unsigned int i_vlckey;
937 } nskeys_to_vlckeys[] =
938 {
939     { NSUpArrowFunctionKey, KEY_UP },
940     { NSDownArrowFunctionKey, KEY_DOWN },
941     { NSLeftArrowFunctionKey, KEY_LEFT },
942     { NSRightArrowFunctionKey, KEY_RIGHT },
943     { NSF1FunctionKey, KEY_F1 },
944     { NSF2FunctionKey, KEY_F2 },
945     { NSF3FunctionKey, KEY_F3 },
946     { NSF4FunctionKey, KEY_F4 },
947     { NSF5FunctionKey, KEY_F5 },
948     { NSF6FunctionKey, KEY_F6 },
949     { NSF7FunctionKey, KEY_F7 },
950     { NSF8FunctionKey, KEY_F8 },
951     { NSF9FunctionKey, KEY_F9 },
952     { NSF10FunctionKey, KEY_F10 },
953     { NSF11FunctionKey, KEY_F11 },
954     { NSF12FunctionKey, KEY_F12 },
955     { NSInsertFunctionKey, KEY_INSERT },
956     { NSHomeFunctionKey, KEY_HOME },
957     { NSEndFunctionKey, KEY_END },
958     { NSPageUpFunctionKey, KEY_PAGEUP },
959     { NSPageDownFunctionKey, KEY_PAGEDOWN },
960     { NSMenuFunctionKey, KEY_MENU },
961     { NSTabCharacter, KEY_TAB },
962     { NSCarriageReturnCharacter, KEY_ENTER },
963     { NSEnterCharacter, KEY_ENTER },
964     { NSBackspaceCharacter, KEY_BACKSPACE },
965     {0,0}
966 };
967
968 unsigned int CocoaKeyToVLC( unichar i_key )
969 {
970     unsigned int i;
971
972     for( i = 0; nskeys_to_vlckeys[i].i_nskey != 0; i++ )
973     {
974         if( nskeys_to_vlckeys[i].i_nskey == i_key )
975         {
976             return nskeys_to_vlckeys[i].i_vlckey;
977         }
978     }
979     return (unsigned int)i_key;
980 }
981
982 - (unsigned int)VLCModifiersToCocoa:(NSString *)theString
983 {
984     unsigned int new = 0;
985
986     if([theString rangeOfString:@"Command"].location != NSNotFound)
987         new |= NSCommandKeyMask;
988     if([theString rangeOfString:@"Alt"].location != NSNotFound)
989         new |= NSAlternateKeyMask;
990     if([theString rangeOfString:@"Shift"].location != NSNotFound)
991         new |= NSShiftKeyMask;
992     if([theString rangeOfString:@"Ctrl"].location != NSNotFound)
993         new |= NSControlKeyMask;
994     return new;
995 }
996
997 - (NSString *)VLCKeyToString:(NSString *)theString
998 {
999     if (![theString isEqualToString:@""]) {
1000         theString = [theString stringByReplacingOccurrencesOfString:@"Command" withString:@""];
1001         theString = [theString stringByReplacingOccurrencesOfString:@"Alt" withString:@""];
1002         theString = [theString stringByReplacingOccurrencesOfString:@"Shift" withString:@""];
1003         theString = [theString stringByReplacingOccurrencesOfString:@"Ctrl" withString:@""];
1004         theString = [theString stringByReplacingOccurrencesOfString:@"+" withString:@""];
1005         theString = [theString stringByReplacingOccurrencesOfString:@"-" withString:@""];
1006     }
1007     return theString;
1008 }
1009
1010
1011 /*****************************************************************************
1012  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1013  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1014  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1015  *****************************************************************************/
1016 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event
1017 {
1018     unichar key = 0;
1019     vlc_value_t val;
1020     unsigned int i_pressed_modifiers = 0;
1021     const struct hotkey *p_hotkeys;
1022     int i;
1023     NSMutableString *tempString = [[[NSMutableString alloc] init] autorelease];
1024     NSMutableString *tempStringPlus = [[[NSMutableString alloc] init] autorelease];
1025
1026     val.i_int = 0;
1027     p_hotkeys = p_intf->p_libvlc->p_hotkeys;
1028
1029     i_pressed_modifiers = [o_event modifierFlags];
1030
1031     if( i_pressed_modifiers & NSShiftKeyMask ) {
1032         val.i_int |= KEY_MODIFIER_SHIFT;
1033         [tempString appendString:@"Shift-"];
1034         [tempStringPlus appendString:@"Shift+"];
1035     }
1036     if( i_pressed_modifiers & NSControlKeyMask ) {
1037         val.i_int |= KEY_MODIFIER_CTRL;
1038         [tempString appendString:@"Ctrl-"];
1039         [tempStringPlus appendString:@"Ctrl+"];
1040     }
1041     if( i_pressed_modifiers & NSAlternateKeyMask ) {
1042         val.i_int |= KEY_MODIFIER_ALT;
1043         [tempString appendString:@"Alt-"];
1044         [tempStringPlus appendString:@"Alt+"];
1045     }
1046     if( i_pressed_modifiers & NSCommandKeyMask ) {
1047         val.i_int |= KEY_MODIFIER_COMMAND;
1048         [tempString appendString:@"Command-"];
1049         [tempStringPlus appendString:@"Command+"];
1050     }
1051
1052     [tempString appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1053     [tempStringPlus appendString:[[o_event charactersIgnoringModifiers] lowercaseString]];
1054
1055     key = [[o_event charactersIgnoringModifiers] characterAtIndex: 0];
1056
1057     switch( key )
1058     {
1059         case NSDeleteCharacter:
1060         case NSDeleteFunctionKey:
1061         case NSDeleteCharFunctionKey:
1062         case NSBackspaceCharacter:
1063         case NSUpArrowFunctionKey:
1064         case NSDownArrowFunctionKey:
1065         case NSRightArrowFunctionKey:
1066         case NSLeftArrowFunctionKey:
1067         case NSEnterCharacter:
1068         case NSCarriageReturnCharacter:
1069             return NO;
1070     }
1071
1072     val.i_int |= CocoaKeyToVLC( key );
1073
1074     if( [o_usedHotkeys indexOfObject: tempString] != NSNotFound || [o_usedHotkeys indexOfObject: tempStringPlus] != NSNotFound )
1075     {
1076         var_SetInteger( p_intf->p_libvlc, "key-pressed", val.i_int );
1077         return YES;
1078     }
1079
1080     return NO;
1081 }
1082
1083 - (void)updateCurrentlyUsedHotkeys
1084 {
1085     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1086     /* Get the main Module */
1087     module_t *p_main = module_get_main();
1088     assert( p_main );
1089     unsigned confsize;
1090     module_config_t *p_config;
1091
1092     p_config = module_config_get (p_main, &confsize);
1093
1094     for (size_t i = 0; i < confsize; i++)
1095     {
1096         module_config_t *p_item = p_config + i;
1097
1098         if( CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1099            && !strncmp( p_item->psz_name , "key-", 4 )
1100            && !EMPTY_STR( p_item->psz_text ) )
1101         {
1102             if (p_item->value.psz)
1103                 [o_tempArray addObject: [NSString stringWithUTF8String:p_item->value.psz]];
1104         }
1105     }
1106     module_config_free (p_config);
1107     module_release (p_main);
1108     o_usedHotkeys = [[NSArray alloc] initWithArray: o_usedHotkeys copyItems: YES];
1109 }
1110
1111
1112 #pragma mark -
1113 #pragma mark Other objects getters
1114
1115 - (id)mainMenu
1116 {
1117     return o_mainmenu;
1118 }
1119
1120 - (id)controls
1121 {
1122     if( o_controls )
1123         return o_controls;
1124
1125     return nil;
1126 }
1127
1128 - (id)bookmarks
1129 {
1130     if (!o_bookmarks )
1131         o_bookmarks = [[VLCBookmarks alloc] init];
1132
1133     if( !nib_bookmarks_loaded )
1134         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1135
1136     return o_bookmarks;
1137 }
1138
1139 - (id)open
1140 {
1141     if (!o_open)
1142         return nil;
1143
1144     if (!nib_open_loaded)
1145         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1146
1147     return o_open;
1148 }
1149
1150 - (id)simplePreferences
1151 {
1152     if (!o_sprefs)
1153         o_sprefs = [[VLCSimplePrefs alloc] init];
1154
1155     if (!nib_prefs_loaded)
1156         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1157
1158     return o_sprefs;
1159 }
1160
1161 - (id)preferences
1162 {
1163     if( !o_prefs )
1164         o_prefs = [[VLCPrefs alloc] init];
1165
1166     if( !nib_prefs_loaded )
1167         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1168
1169     return o_prefs;
1170 }
1171
1172 - (id)playlist
1173 {
1174     if( o_playlist )
1175         return o_playlist;
1176
1177     return nil;
1178 }
1179
1180 - (id)info
1181 {
1182     if(! nib_info_loaded )
1183         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1184
1185     if( o_info )
1186         return o_info;
1187
1188     return nil;
1189 }
1190
1191 - (id)wizard
1192 {
1193     if( !o_wizard )
1194         o_wizard = [[VLCWizard alloc] init];
1195
1196     if( !nib_wizard_loaded )
1197     {
1198         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1199         [o_wizard initStrings];
1200     }
1201     return o_wizard;
1202 }
1203
1204 - (id)getVideoViewAtPositionX: (int *)pi_x Y: (int *)pi_y withWidth: (unsigned int*)pi_width andHeight: (unsigned int*)pi_height
1205 {
1206     id videoView = [o_mainwindow videoView];
1207     NSRect videoRect = [videoView frame];
1208     int i_x = (int)videoRect.origin.x;
1209     int i_y = (int)videoRect.origin.y;
1210     unsigned int i_width = (int)videoRect.size.width;
1211     unsigned int i_height = (int)videoRect.size.height;
1212     pi_x = (int *)i_x;
1213     pi_y = (int *)i_y;
1214     pi_width = (unsigned int*)i_width;
1215     pi_height = (unsigned int*)i_height;
1216     msg_Dbg( VLCIntf, "returning videoview with x=%i, y=%i, width=%i, height=%i", i_x, i_y, i_width, i_height );
1217     return videoView;
1218 }
1219
1220 - (id)embeddedList
1221 {
1222     if( o_embedded_list )
1223         return o_embedded_list;
1224
1225     return nil;
1226 }
1227
1228 - (id)coreDialogProvider
1229 {
1230     if( o_coredialogs )
1231         return o_coredialogs;
1232
1233     return nil;
1234 }
1235
1236 - (id)eyeTVController
1237 {
1238     if( o_eyetv )
1239         return o_eyetv;
1240
1241     return nil;
1242 }
1243
1244 - (id)appleRemoteController
1245 {
1246         return o_remote;
1247 }
1248
1249 #pragma mark -
1250 #pragma mark Polling
1251
1252 /*****************************************************************************
1253  * ManageThread: An ugly thread that polls
1254  *****************************************************************************/
1255 static void * ManageThread( void *user_data )
1256 {
1257     id self = user_data;
1258
1259     [self manage];
1260
1261     return NULL;
1262 }
1263
1264 struct manage_cleanup_stack {
1265     intf_thread_t * p_intf;
1266     input_thread_t ** p_input;
1267     playlist_t * p_playlist;
1268     id self;
1269 };
1270
1271 static void manage_cleanup( void * args )
1272 {
1273     struct manage_cleanup_stack * manage_cleanup_stack = args;
1274     intf_thread_t * p_intf = manage_cleanup_stack->p_intf;
1275     input_thread_t * p_input = *manage_cleanup_stack->p_input;
1276     id self = manage_cleanup_stack->self;
1277     playlist_t * p_playlist = manage_cleanup_stack->p_playlist;
1278
1279     var_DelCallback( p_playlist, "item-current", PlaylistChanged, self );
1280     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, self );
1281     var_DelCallback( p_playlist, "item-change", PlaylistChanged, self );
1282     var_DelCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1283     var_DelCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1284
1285     if( p_input ) vlc_object_release( p_input );
1286 }
1287
1288 - (void)manage
1289 {
1290     playlist_t * p_playlist;
1291     input_thread_t * p_input = NULL;
1292
1293     /* new thread requires a new pool */
1294
1295     p_playlist = pl_Get( p_intf );
1296
1297     var_AddCallback( p_playlist, "item-current", PlaylistChanged, self );
1298     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, self );
1299     var_AddCallback( p_playlist, "item-change", PlaylistChanged, self );
1300     var_AddCallback( p_playlist, "playlist-item-append", PlaylistChanged, self );
1301     var_AddCallback( p_playlist, "playlist-item-deleted", PlaylistChanged, self );
1302
1303     struct manage_cleanup_stack stack = { p_intf, &p_input, p_playlist, self };
1304     pthread_cleanup_push(manage_cleanup, &stack);
1305
1306     bool exitLoop = false;
1307     while( !exitLoop )
1308     {
1309         NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1310
1311         if( !p_input )
1312         {
1313             p_input = playlist_CurrentInput( p_playlist );
1314
1315             /* Refresh the interface */
1316             if( p_input )
1317             {
1318                 msg_Dbg( p_intf, "input has changed, refreshing interface" );
1319                 p_intf->p_sys->b_input_update = true;
1320             }
1321         }
1322         else if( !vlc_object_alive (p_input) || p_input->b_dead )
1323         {
1324             /* input stopped */
1325             p_intf->p_sys->b_intf_update = true;
1326             p_intf->p_sys->i_play_status = END_S;
1327             msg_Dbg( p_intf, "input has stopped, refreshing interface" );
1328             vlc_object_release( p_input );
1329             p_input = NULL;
1330         }
1331         else if( cachedInputState != input_GetState( p_input ) )
1332         {
1333             cachedInputState = input_GetState( p_input );
1334             p_intf->p_sys->b_intf_update = true;
1335         }
1336
1337         /* Manage volume status */
1338         [o_mainwindow updateVolumeSlider];
1339
1340         msleep( INTF_IDLE_SLEEP );
1341
1342         [pool release];
1343
1344         [o_appLock lock];
1345         exitLoop = (f_appExit != 0 ? true : false);
1346         [o_appLock unlock];
1347     }
1348
1349     pthread_cleanup_pop(1);
1350 }
1351
1352 - (void)manageIntf:(NSTimer *)o_timer
1353 {
1354     vlc_value_t val;
1355     playlist_t * p_playlist;
1356     input_thread_t * p_input;
1357
1358     if( p_intf->p_sys->b_input_update )
1359     {
1360         /* Called when new input is opened */
1361         p_intf->p_sys->b_current_title_update = true;
1362         p_intf->p_sys->b_intf_update = true;
1363         p_intf->p_sys->b_input_update = false;
1364         [o_mainmenu setupMenus]; /* Make sure input menu is up to date */
1365     }
1366     if( p_intf->p_sys->b_intf_update )
1367     {
1368         [o_mainwindow updateWindow];
1369         p_intf->p_sys->b_current_title_update = true;
1370         p_intf->p_sys->b_intf_update = false;
1371     }
1372
1373     if( p_intf->p_sys->b_playmode_update )
1374     {
1375         [o_playlist playModeUpdated];
1376         p_intf->p_sys->b_playmode_update = false;
1377     }
1378     if( p_intf->p_sys->b_playlist_update )
1379     {
1380         [o_playlist playlistUpdated];
1381         p_intf->p_sys->b_playlist_update = false;
1382     }
1383
1384     p_input = pl_CurrentInput( p_intf );
1385     if( p_input && vlc_object_alive (p_input) )
1386     {
1387         vlc_value_t val;
1388
1389         if( p_intf->p_sys->b_current_title_update )
1390         {
1391             NSString *aString;
1392             input_item_t * p_item = input_GetItem( p_input );
1393             char * name = input_item_GetNowPlaying( p_item );
1394
1395             if( !name )
1396                 name = input_item_GetName( p_item );
1397
1398             aString = [NSString stringWithUTF8String:name];
1399
1400             free(name);
1401
1402             [o_mainwindow setTitle: aString];
1403             [[[self controls] fspanel] setStreamTitle: aString];
1404
1405             [[o_coreinteraction voutView] updateTitle];
1406
1407             [o_playlist updateRowSelection];
1408
1409             p_intf->p_sys->b_current_title_update = FALSE;
1410         }
1411
1412         [o_mainwindow updateTimeSlider];
1413
1414         /* Manage Playing status */
1415         var_Get( p_input, "state", &val );
1416         if( p_intf->p_sys->i_play_status != val.i_int )
1417         {
1418             p_intf->p_sys->i_play_status = val.i_int;
1419             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1420         }
1421         vlc_object_release( p_input );
1422     }
1423     else if( p_input )
1424     {
1425         vlc_object_release( p_input );
1426     }
1427     else
1428     {
1429         p_intf->p_sys->i_play_status = END_S;
1430         if (p_intf->p_sys->i_old_play_status != p_intf->p_sys->i_play_status)
1431         {
1432             [self playStatusUpdated: p_intf->p_sys->i_play_status];
1433             [o_mainmenu setSubmenusEnabled: FALSE];
1434             p_intf->p_sys->i_old_play_status = p_intf->p_sys->i_play_status;
1435         }
1436     }
1437 end:
1438     [self updateMessageDisplay];
1439
1440     [interfaceTimer autorelease];
1441
1442     interfaceTimer = [[NSTimer scheduledTimerWithTimeInterval: 0.3
1443         target: self selector: @selector(manageIntf:)
1444         userInfo: nil repeats: FALSE] retain];
1445 }
1446
1447 #pragma mark -
1448 #pragma mark Interface update
1449
1450 - (void)playStatusUpdated:(int)i_status
1451 {
1452     if( i_status == PLAYING_S )
1453     {
1454         [[[self controls] fspanel] setPause];
1455         [[self mainMenu] setPause];
1456         [o_mainwindow setPause];
1457     }
1458     else
1459     {
1460         [[[self controls] fspanel] setPlay];
1461         [[self mainMenu] setPlay];
1462         [o_mainwindow setPlay];
1463     }
1464 }
1465
1466 - (IBAction)showController:(id)sender
1467 {
1468     //FIXME: why is this function here?!
1469     [o_mainwindow makeKeyAndOrderFront:sender];
1470 }
1471
1472 #pragma mark -
1473 #pragma mark Crash Log
1474 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1475 {
1476     NSString *urlStr = @"http://jones.videolan.org/crashlog/sendcrashreport.php";
1477     NSURL *url = [NSURL URLWithString:urlStr];
1478
1479     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1480     [req setHTTPMethod:@"POST"];
1481
1482     NSString * email;
1483     if( [o_crashrep_includeEmail_ckb state] == NSOnState )
1484     {
1485         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1486         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1487         email = [emails valueAtIndex:[emails indexForIdentifier:
1488                     [emails primaryIdentifier]]];
1489     }
1490     else
1491         email = [NSString string];
1492
1493     NSString *postBody;
1494     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1495             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1496             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1497             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1498
1499     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1500
1501     /* Released from delegate */
1502     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1503 }
1504
1505 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1506 {
1507     [crashLogURLConnection release];
1508     crashLogURLConnection = nil;
1509 }
1510
1511 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1512 {
1513     NSRunCriticalAlertPanel(_NS("Error when sending the Crash Report"), [error localizedDescription], @"OK", nil, nil);
1514     [crashLogURLConnection release];
1515     crashLogURLConnection = nil;
1516 }
1517
1518 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1519 {
1520     NSString * crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1521     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1522     NSString *fname;
1523     NSString * latestLog = nil;
1524     int year  = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"] : 0;
1525     int month = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportMonth"]: 0;
1526     int day   = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportDay"]  : 0;
1527     int hours = !previouslySeen ? [[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportHours"]: 0;
1528
1529     while (fname = [direnum nextObject])
1530     {
1531         [direnum skipDescendents];
1532         if([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"])
1533         {
1534             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1535             if( [compo count] < 3 ) continue;
1536             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1537             if( [compo count] < 4 ) continue;
1538
1539             // Dooh. ugly.
1540             if( year < [[compo objectAtIndex:0] intValue] ||
1541                 (year ==[[compo objectAtIndex:0] intValue] &&
1542                  (month < [[compo objectAtIndex:1] intValue] ||
1543                   (month ==[[compo objectAtIndex:1] intValue] &&
1544                    (day   < [[compo objectAtIndex:2] intValue] ||
1545                     (day   ==[[compo objectAtIndex:2] intValue] &&
1546                       hours < [[compo objectAtIndex:3] intValue] ))))))
1547             {
1548                 year  = [[compo objectAtIndex:0] intValue];
1549                 month = [[compo objectAtIndex:1] intValue];
1550                 day   = [[compo objectAtIndex:2] intValue];
1551                 hours = [[compo objectAtIndex:3] intValue];
1552                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1553             }
1554         }
1555     }
1556
1557     if(!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1558         return nil;
1559
1560     if( !previouslySeen )
1561     {
1562         [[NSUserDefaults standardUserDefaults] setInteger:year  forKey:@"LatestCrashReportYear"];
1563         [[NSUserDefaults standardUserDefaults] setInteger:month forKey:@"LatestCrashReportMonth"];
1564         [[NSUserDefaults standardUserDefaults] setInteger:day   forKey:@"LatestCrashReportDay"];
1565         [[NSUserDefaults standardUserDefaults] setInteger:hours forKey:@"LatestCrashReportHours"];
1566     }
1567     return latestLog;
1568 }
1569
1570 - (NSString *)latestCrashLogPath
1571 {
1572     return [self latestCrashLogPathPreviouslySeen:YES];
1573 }
1574
1575 - (void)lookForCrashLog
1576 {
1577     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1578     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1579     BOOL areCrashLogsTooOld = ![[NSUserDefaults standardUserDefaults] integerForKey:@"LatestCrashReportYear"];
1580     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1581     if( latestLog && !areCrashLogsTooOld )
1582         [NSApp runModalForWindow: o_crashrep_win];
1583     [o_pool release];
1584 }
1585
1586 - (IBAction)crashReporterAction:(id)sender
1587 {
1588     if( sender == o_crashrep_send_btn )
1589         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1590
1591     [NSApp stopModal];
1592     [o_crashrep_win orderOut: sender];
1593 }
1594
1595 - (IBAction)openCrashLog:(id)sender
1596 {
1597     NSString * latestLog = [self latestCrashLogPath];
1598     if( latestLog )
1599     {
1600         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1601     }
1602     else
1603     {
1604         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.") );
1605     }
1606 }
1607
1608 #pragma mark -
1609 #pragma mark Remove old prefs
1610
1611 - (void)_removeOldPreferences
1612 {
1613     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1614     static const int kCurrentPreferencesVersion = 1;
1615     int version = [[NSUserDefaults standardUserDefaults] integerForKey:kVLCPreferencesVersion];
1616     if( version >= kCurrentPreferencesVersion ) return;
1617
1618     NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1619         NSUserDomainMask, YES);
1620     if( !libraries || [libraries count] == 0) return;
1621     NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1622
1623     /* File not found, don't attempt anything */
1624     if(![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"VLC"]] &&
1625        ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]] )
1626     {
1627         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1628         return;
1629     }
1630
1631     int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1632                 _NS("We just found an older version of VLC's preferences files."),
1633                 _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1634     if( res != NSOKButton )
1635     {
1636         [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1637         return;
1638     }
1639
1640     NSArray * ourPreferences = [NSArray arrayWithObjects:@"org.videolan.vlc.plist", @"VLC", nil];
1641
1642     /* Move the file to trash so that user can find them later */
1643     [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1644
1645     /* really reset the defaults from now on */
1646     [NSUserDefaults resetStandardUserDefaults];
1647
1648     [[NSUserDefaults standardUserDefaults] setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1649     [[NSUserDefaults standardUserDefaults] synchronize];
1650
1651     /* Relaunch now */
1652     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1653
1654     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1655     if(fork() != 0)
1656     {
1657         exit(0);
1658         return;
1659     }
1660     execl(path, path, NULL);
1661 }
1662
1663 #pragma mark -
1664 #pragma mark Errors, warnings and messages
1665 - (IBAction)showMessagesPanel:(id)sender
1666 {
1667     [o_msgs_panel makeKeyAndOrderFront: sender];
1668 }
1669
1670 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1671 {
1672     if( [o_notification object] == o_msgs_panel )
1673         [self updateMessageDisplay];
1674 }
1675
1676 - (void)updateMessageDisplay
1677 {
1678     if( [o_msgs_panel isVisible] && b_msg_arr_changed )
1679     {
1680         id o_msg;
1681         NSEnumerator * o_enum;
1682
1683         [o_messages setString: @""];
1684
1685         [o_msg_lock lock];
1686
1687         o_enum = [o_msg_arr objectEnumerator];
1688
1689         while( ( o_msg = [o_enum nextObject] ) != nil )
1690         {
1691             [o_messages insertText: o_msg];
1692         }
1693
1694         b_msg_arr_changed = NO;
1695         [o_msg_lock unlock];
1696     }
1697 }
1698
1699 - (void)processReceivedlibvlcMessage:(const msg_item_t *)item
1700 {
1701     NSColor *o_white = [NSColor whiteColor];
1702     NSColor *o_red = [NSColor redColor];
1703     NSColor *o_yellow = [NSColor yellowColor];
1704     NSColor *o_gray = [NSColor grayColor];
1705
1706     NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
1707     static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
1708
1709     NSDictionary *o_attr;
1710     NSAttributedString *o_msg_color;
1711
1712     int i_type = item->i_type;
1713
1714     [o_msg_lock lock];
1715
1716     if( [o_msg_arr count] + 2 > 600 )
1717     {
1718         [o_msg_arr removeObjectAtIndex: 0];
1719         [o_msg_arr removeObjectAtIndex: 1];
1720     }
1721
1722     o_attr = [NSDictionary dictionaryWithObject: o_gray forKey: NSForegroundColorAttributeName];
1723     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s%s", item->psz_module, ppsz_type[i_type]] attributes: o_attr];
1724     [o_msg_arr addObject: [o_msg_color autorelease]];
1725
1726     o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type] forKey: NSForegroundColorAttributeName];
1727     o_msg_color = [[NSAttributedString alloc] initWithString: [NSString stringWithFormat: @"%s\n", item->psz_msg] attributes: o_attr];
1728     [o_msg_arr addObject: [o_msg_color autorelease]];
1729
1730     b_msg_arr_changed = YES;
1731     [o_msg_lock unlock];
1732 }
1733
1734 - (IBAction)saveDebugLog:(id)sender
1735 {
1736     NSOpenPanel * saveFolderPanel = [[NSSavePanel alloc] init];
1737
1738     [saveFolderPanel setCanChooseDirectories: NO];
1739     [saveFolderPanel setCanChooseFiles: YES];
1740     [saveFolderPanel setCanSelectHiddenExtension: NO];
1741     [saveFolderPanel setCanCreateDirectories: YES];
1742     [saveFolderPanel setAllowedFileTypes: [NSArray arrayWithObject:@"rtfd"]];
1743     [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];
1744 }
1745
1746 - (void)saveDebugLogAsRTF: (NSSavePanel *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1747 {
1748     BOOL b_returned;
1749     if( returnCode == NSOKButton )
1750     {
1751         b_returned = [o_messages writeRTFDToFile: [[sheet URL] path] atomically: YES];
1752         if(! b_returned )
1753             msg_Warn( p_intf, "Error while saving the debug log" );
1754     }
1755 }
1756
1757 #pragma mark -
1758 #pragma mark Playlist toggling
1759
1760 - (IBAction)togglePlaylist:(id)sender
1761 {
1762     NSLog( @"needs to be re-implemented" );
1763 }
1764
1765 - (void)updateTogglePlaylistState
1766 {
1767     [[self playlist] outlineViewSelectionDidChange: NULL];
1768 }
1769
1770 #pragma mark -
1771
1772 @end
1773
1774 @implementation VLCMain (Internal)
1775
1776 - (void)handlePortMessage:(NSPortMessage *)o_msg
1777 {
1778     id ** val;
1779     NSData * o_data;
1780     NSValue * o_value;
1781     NSInvocation * o_inv;
1782     NSConditionLock * o_lock;
1783
1784     o_data = [[o_msg components] lastObject];
1785     o_inv = *((NSInvocation **)[o_data bytes]);
1786     [o_inv getArgument: &o_value atIndex: 2];
1787     val = (id **)[o_value pointerValue];
1788     [o_inv setArgument: val[1] atIndex: 2];
1789     o_lock = *(val[0]);
1790
1791     [o_lock lock];
1792     [o_inv invoke];
1793     [o_lock unlockWithCondition: 1];
1794 }
1795 - (void)resetMediaKeyJump
1796 {
1797     b_mediakeyJustJumped = NO;
1798 }
1799 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
1800 {
1801     b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
1802     if (b_mediaKeySupport) {
1803         if (!o_mediaKeyController)
1804             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
1805         [o_mediaKeyController startWatchingMediaKeys];
1806     }
1807     else if (!b_mediaKeySupport && o_mediaKeyController)
1808     {
1809         int returnedValue = NSRunInformationalAlertPanel(_NS("Relaunch required"),
1810                                                _NS("To make sure that VLC no longer listens to your media key events, it needs to be restarted."),
1811                                                _NS("Relaunch VLC"), _NS("Ignore"), nil, nil);
1812         if( returnedValue == NSOKButton )
1813         {
1814             /* Relaunch now */
1815             const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1816
1817             /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1818             if(fork() != 0)
1819             {
1820                 exit(0);
1821                 return;
1822             }
1823             execl(path, path, NULL);
1824         }
1825     }
1826 }
1827
1828 @end
1829
1830 /*****************************************************************************
1831  * VLCApplication interface
1832  *****************************************************************************/
1833
1834 @implementation VLCApplication
1835 // when user selects the quit menu from dock it sends a terminate:
1836 // but we need to send a stop: to properly exits libvlc.
1837 // However, we are not able to change the action-method sent by this standard menu item.
1838 // thus we override terminat: to send a stop:
1839 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
1840 - (void)terminate:(id)sender
1841 {
1842     [self activateIgnoringOtherApps:YES];
1843     [self stop:sender];
1844 }
1845
1846 @end