]> git.sesse.net Git - vlc/blob - modules/gui/macosx/intf.m
macosx: respect 'playlist-autostart' (close #7272)
[vlc] / modules / gui / macosx / intf.m
1 /*****************************************************************************
2  * intf.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Derk-Jan Hartman <hartman at videolan.org>
9  *          Felix Paul Kühne <fkuehne at videolan dot org>
10  *          Pierre d'Herbemont <pdherbemont # videolan org>
11  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 /*****************************************************************************
29  * Preamble
30  *****************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <stdlib.h>                                      /* malloc(), free() */
36 #include <sys/param.h>                                    /* for MAXPATHLEN */
37 #include <string.h>
38 #include <vlc_common.h>
39 #include <vlc_keys.h>
40 #include <vlc_dialog.h>
41 #include <vlc_url.h>
42 #include <vlc_modules.h>
43 #include <vlc_plugin.h>
44 #include <vlc_vout_display.h>
45 #include <unistd.h> /* execl() */
46
47 #import "CompatibilityFixes.h"
48 #import "intf.h"
49 #import "StringUtility.h"
50 #import "MainMenu.h"
51 #import "VideoView.h"
52 #import "prefs.h"
53 #import "playlist.h"
54 #import "playlistinfo.h"
55 #import "controls.h"
56 #import "open.h"
57 #import "wizard.h"
58 #import "bookmarks.h"
59 #import "coredialogs.h"
60 #import "AppleRemote.h"
61 #import "eyetv.h"
62 #import "simple_prefs.h"
63 #import "CoreInteraction.h"
64 #import "TrackSynchronization.h"
65 #import "VLCVoutWindowController.h"
66 #import "ExtensionsManager.h"
67
68 #import "VideoEffects.h"
69 #import "AudioEffects.h"
70
71 #import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
72 #import <Sparkle/Sparkle.h>                 /* we're the update delegate */
73
74 #import "iTunes.h"
75
76 /*****************************************************************************
77  * Local prototypes.
78  *****************************************************************************/
79 static void Run (intf_thread_t *p_intf);
80
81 static void updateProgressPanel (void *, const char *, float);
82 static bool checkProgressPanel (void *);
83 static void destroyProgressPanel (void *);
84
85 static void MsgCallback(void *data, int type, const vlc_log_t *item, const char *format, va_list ap);
86
87 static int InputEvent(vlc_object_t *, const char *,
88                       vlc_value_t, vlc_value_t, void *);
89 static int PLItemChanged(vlc_object_t *, const char *,
90                          vlc_value_t, vlc_value_t, void *);
91 static int PlaylistUpdated(vlc_object_t *, const char *,
92                            vlc_value_t, vlc_value_t, void *);
93 static int PlaybackModeUpdated(vlc_object_t *, const char *,
94                                vlc_value_t, vlc_value_t, void *);
95 static int VolumeUpdated(vlc_object_t *, const char *,
96                          vlc_value_t, vlc_value_t, void *);
97 static int BossCallback(vlc_object_t *, const char *,
98                          vlc_value_t, vlc_value_t, void *);
99
100 #pragma mark -
101 #pragma mark VLC Interface Object Callbacks
102
103 /*****************************************************************************
104  * OpenIntf: initialize interface
105  *****************************************************************************/
106 int OpenIntf (vlc_object_t *p_this)
107 {
108     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
109     [VLCApplication sharedApplication];
110
111     intf_thread_t *p_intf = (intf_thread_t*) p_this;
112
113     p_intf->p_sys = malloc(sizeof(intf_sys_t));
114     if (p_intf->p_sys == NULL)
115         return VLC_ENOMEM;
116
117     memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
118
119     Run(p_intf);
120
121     [o_pool release];
122     return VLC_SUCCESS;
123 }
124
125 /*****************************************************************************
126  * CloseIntf: destroy interface
127  *****************************************************************************/
128 void CloseIntf (vlc_object_t *p_this)
129 {
130     intf_thread_t *p_intf = (intf_thread_t*) p_this;
131
132     free(p_intf->p_sys);
133 }
134
135 static NSLock * o_vout_provider_lock = nil;
136
137 static int WindowControl(vout_window_t *, int i_query, va_list);
138
139 int WindowOpen(vout_window_t *p_wnd, const vout_window_cfg_t *cfg)
140 {
141     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
142     intf_thread_t *p_intf = VLCIntf;
143     if (!p_intf) {
144         msg_Err(p_wnd, "Mac OS X interface not found");
145         [o_pool release];
146         return VLC_EGENERIC;
147     }
148     NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
149
150     [o_vout_provider_lock lock];
151     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
152     if (!o_vout_controller) {
153         [o_vout_provider_lock unlock];
154         [o_pool release];
155         return VLC_EGENERIC;
156     }
157
158     SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
159     NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
160     [inv setTarget:o_vout_controller];
161     [inv setSelector:sel];
162     [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
163     [inv setArgument:&proposedVideoViewPosition atIndex:3];
164
165     [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
166                        waitUntilDone:YES];
167
168     VLCVoutView *videoView = nil;
169     [inv getReturnValue:&videoView];
170
171     if (!videoView) {
172         msg_Err(p_wnd, "got no video view from the interface");
173         [o_vout_provider_lock unlock];
174         [o_pool release];
175         return VLC_EGENERIC;
176     }
177
178     msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
179     p_wnd->handle.nsobject = videoView;
180
181     [o_vout_provider_lock unlock];
182
183     [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
184     p_wnd->control = WindowControl;
185
186     [o_pool release];
187     return VLC_SUCCESS;
188 }
189
190 static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
191 {
192     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
193
194     [o_vout_provider_lock lock];
195     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
196     if (!o_vout_controller) {
197         [o_vout_provider_lock unlock];
198         [o_pool release];
199         return VLC_EGENERIC;
200     }
201
202     switch(i_query) {
203         case VOUT_WINDOW_SET_STATE:
204         {
205             unsigned i_state = va_arg(args, unsigned);
206
207             NSInteger i_cooca_level = NSNormalWindowLevel;
208             if (i_state & VOUT_WINDOW_STATE_ABOVE)
209                 i_cooca_level = NSStatusWindowLevel;
210
211             SEL sel = @selector(setWindowLevel:forWindow:);
212             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
213             [inv setTarget:o_vout_controller];
214             [inv setSelector:sel];
215             [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
216             [inv setArgument:&p_wnd atIndex:3];
217             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
218                                waitUntilDone:NO];
219
220             break;
221         }
222         case VOUT_WINDOW_SET_SIZE:
223         {
224
225             unsigned int i_width  = va_arg(args, unsigned int);
226             unsigned int i_height = va_arg(args, unsigned int);
227
228             NSSize newSize = NSMakeSize(i_width, i_height);
229             SEL sel = @selector(setNativeVideoSize:forWindow:);
230             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
231             [inv setTarget:o_vout_controller];
232             [inv setSelector:sel];
233             [inv setArgument:&newSize atIndex:2]; // starting at 2!
234             [inv setArgument:&p_wnd atIndex:3];
235             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
236                                waitUntilDone:NO];
237
238             break;
239         }
240         case VOUT_WINDOW_SET_FULLSCREEN:
241         {
242             NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
243             int i_full = va_arg(args, int);
244
245             SEL sel = @selector(setFullscreen:forWindow:);
246             NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
247             [inv setTarget:o_vout_controller];
248             [inv setSelector:sel];
249             [inv setArgument:&i_full atIndex:2]; // starting at 2!
250             [inv setArgument:&p_wnd atIndex:3];
251             [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
252                                waitUntilDone:NO];
253
254             break;
255         }
256         default:
257         {
258             msg_Warn(p_wnd, "unsupported control query");
259             [o_vout_provider_lock unlock];
260             [o_pool release];
261             return VLC_EGENERIC;
262         }
263     }
264
265     [o_vout_provider_lock unlock];
266     [o_pool release];
267     return VLC_SUCCESS;
268 }
269
270 void WindowClose(vout_window_t *p_wnd)
271 {
272     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
273
274     [o_vout_provider_lock lock];
275     VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
276     if (!o_vout_controller) {
277         [o_vout_provider_lock unlock];
278         [o_pool release];
279         return;
280     }
281
282     [o_vout_controller performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];
283     [o_vout_provider_lock unlock];
284
285     [o_pool release];
286 }
287
288 /*****************************************************************************
289  * Run: main loop
290  *****************************************************************************/
291 static NSLock * o_appLock = nil;    // controls access to f_appExit
292 static NSLock * o_plItemChangedLock = nil;
293
294 static void Run(intf_thread_t *p_intf)
295 {
296     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
297     [VLCApplication sharedApplication];
298
299     o_appLock = [[NSLock alloc] init];
300     o_plItemChangedLock = [[NSLock alloc] init];
301     o_vout_provider_lock = [[NSLock alloc] init];
302
303     [[VLCMain sharedInstance] setIntf: p_intf];
304
305     [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
306
307     [NSApp run];
308     [[VLCMain sharedInstance] applicationWillTerminate:nil];
309     [o_plItemChangedLock release];
310     [o_appLock release];
311     [o_vout_provider_lock release];
312     o_vout_provider_lock = nil;
313     [o_pool release];
314
315     raise(SIGTERM);
316 }
317
318 #pragma mark -
319 #pragma mark Variables Callback
320
321 /*****************************************************************************
322  * MsgCallback: Callback triggered by the core once a new debug message is
323  * ready to be displayed. We store everything in a NSArray in our Cocoa part
324  * of this file.
325  *****************************************************************************/
326 static void MsgCallback(void *data, int type, const vlc_log_t *item, const char *format, va_list ap)
327 {
328     int canc = vlc_savecancel();
329     char *str;
330
331     if (vasprintf(&str, format, ap) == -1) {
332         vlc_restorecancel(canc);
333         return;
334     }
335
336     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
337     [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
338     [o_pool release];
339
340     vlc_restorecancel(canc);
341     free(str);
342 }
343
344 static int InputEvent(vlc_object_t *p_this, const char *psz_var,
345                        vlc_value_t oldval, vlc_value_t new_val, void *param)
346 {
347     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
348     switch (new_val.i_int) {
349         case INPUT_EVENT_STATE:
350             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
351             break;
352         case INPUT_EVENT_RATE:
353             [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
354             break;
355         case INPUT_EVENT_POSITION:
356             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
357             break;
358         case INPUT_EVENT_TITLE:
359         case INPUT_EVENT_CHAPTER:
360             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
361             break;
362         case INPUT_EVENT_CACHE:
363             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
364             break;
365         case INPUT_EVENT_STATISTICS:
366             [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
367             break;
368         case INPUT_EVENT_ES:
369             break;
370         case INPUT_EVENT_TELETEXT:
371             break;
372         case INPUT_EVENT_AOUT:
373             break;
374         case INPUT_EVENT_VOUT:
375             break;
376         case INPUT_EVENT_ITEM_META:
377         case INPUT_EVENT_ITEM_INFO:
378             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
379             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
380             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
381             break;
382         case INPUT_EVENT_BOOKMARK:
383             break;
384         case INPUT_EVENT_RECORD:
385             [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
386             break;
387         case INPUT_EVENT_PROGRAM:
388             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
389             break;
390         case INPUT_EVENT_ITEM_EPG:
391             break;
392         case INPUT_EVENT_SIGNAL:
393             break;
394
395         case INPUT_EVENT_ITEM_NAME:
396             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
397             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
398             break;
399
400         case INPUT_EVENT_AUDIO_DELAY:
401         case INPUT_EVENT_SUBTITLE_DELAY:
402             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
403             break;
404
405         case INPUT_EVENT_DEAD:
406             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
407             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
408             break;
409
410         case INPUT_EVENT_ABORT:
411             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
412             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
413             break;
414
415         default:
416             //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
417             break;
418     }
419
420     [o_pool release];
421     return VLC_SUCCESS;
422 }
423
424 static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
425                          vlc_value_t oldval, vlc_value_t new_val, void *param)
426 {
427     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
428
429     /* Due to constraints within NSAttributedString's main loop runtime handling
430      * and other issues, we need to wait for -PlaylistItemChanged to finish and
431      * then -informInputChanged on this non-main thread. */
432     [o_plItemChangedLock lock];
433     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES];
434     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(informInputChanged) withObject:nil waitUntilDone:YES];
435     [o_plItemChangedLock unlock];
436
437     [o_pool release];
438     return VLC_SUCCESS;
439 }
440
441 static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
442                          vlc_value_t oldval, vlc_value_t new_val, void *param)
443 {
444     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
445
446     /* Avoid event queue flooding with playlistUpdated selectors, leading to UI freezes.
447      * Therefore, only enqueue if no selector already enqueued.
448      */
449     VLCMain *o_main = [VLCMain sharedInstance];
450     @synchronized(o_main) {
451         if(![o_main playlistUpdatedSelectorInQueue]) {
452             [o_main setPlaylistUpdatedSelectorInQueue:YES];
453             [o_main performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];
454         }
455     }
456
457     [o_pool release];
458     return VLC_SUCCESS;
459 }
460
461 static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
462                          vlc_value_t oldval, vlc_value_t new_val, void *param)
463 {
464     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
465     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
466
467     [o_pool release];
468     return VLC_SUCCESS;
469 }
470
471 static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
472                          vlc_value_t oldval, vlc_value_t new_val, void *param)
473 {
474     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
475     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
476
477     [o_pool release];
478     return VLC_SUCCESS;
479 }
480
481 static int BossCallback(vlc_object_t *p_this, const char *psz_var,
482                         vlc_value_t oldval, vlc_value_t new_val, void *param)
483 {
484     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
485
486     [[VLCCoreInteraction sharedInstance] performSelectorOnMainThread:@selector(pause) withObject:nil waitUntilDone:NO];
487     [[VLCApplication sharedApplication] hide:nil];
488
489     [o_pool release];
490     return VLC_SUCCESS;
491 }
492
493 /*****************************************************************************
494  * ShowController: Callback triggered by the show-intf playlist variable
495  * through the ShowIntf-control-intf, to let us show the controller-win;
496  * usually when in fullscreen-mode
497  *****************************************************************************/
498 static int ShowController(vlc_object_t *p_this, const char *psz_variable,
499                      vlc_value_t old_val, vlc_value_t new_val, void *param)
500 {
501     intf_thread_t * p_intf = VLCIntf;
502     if (p_intf && p_intf->p_sys) {
503         playlist_t * p_playlist = pl_Get(p_intf);
504         BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
505         if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
506             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
507         else
508             [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
509     }
510     return VLC_SUCCESS;
511 }
512
513 /*****************************************************************************
514  * DialogCallback: Callback triggered by the "dialog-*" variables
515  * to let the intf display error and interaction dialogs
516  *****************************************************************************/
517 static int DialogCallback(vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data)
518 {
519     NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
520     VLCMain *interface = (VLCMain *)data;
521
522     if ([@(type) isEqualToString: @"dialog-progress-bar"]) {
523         /* the progress panel needs to update itself and therefore wants special treatment within this context */
524         dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;
525
526         p_dialog->pf_update = updateProgressPanel;
527         p_dialog->pf_check = checkProgressPanel;
528         p_dialog->pf_destroy = destroyProgressPanel;
529         p_dialog->p_sys = VLCIntf->p_libvlc;
530     }
531
532     NSValue *o_value = [NSValue valueWithPointer:value.p_address];
533     [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
534
535     [o_pool release];
536     return VLC_SUCCESS;
537 }
538
539 void updateProgressPanel (void *priv, const char *text, float value)
540 {
541     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
542
543     NSString *o_txt;
544     if (text != NULL)
545         o_txt = @(text);
546     else
547         o_txt = @"";
548
549     [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];
550
551     [o_pool release];
552 }
553
554 void destroyProgressPanel (void *priv)
555 {
556     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
557
558     if ([[NSApplication sharedApplication] isRunning])
559         [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];
560
561     [o_pool release];
562 }
563
564 bool checkProgressPanel (void *priv)
565 {
566     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
567     return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
568     [o_pool release];
569 }
570
571 #pragma mark -
572 #pragma mark Helpers
573
574 input_thread_t *getInput(void)
575 {
576     intf_thread_t *p_intf = VLCIntf;
577     if (!p_intf)
578         return NULL;
579     return pl_CurrentInput(p_intf);
580 }
581
582 vout_thread_t *getVout(void)
583 {
584     input_thread_t *p_input = getInput();
585     if (!p_input)
586         return NULL;
587     vout_thread_t *p_vout = input_GetVout(p_input);
588     vlc_object_release(p_input);
589     return p_vout;
590 }
591
592 vout_thread_t *getVoutForActiveWindow(void)
593 {
594     vout_thread_t *p_vout = nil;
595
596     id currentWindow = [NSApp keyWindow];
597     if ([currentWindow respondsToSelector:@selector(videoView)]) {
598         VLCVoutView *videoView = [currentWindow videoView];
599         if (videoView) {
600             p_vout = [videoView voutThread];
601         }
602     }
603
604     if (!p_vout)
605         p_vout = getVout();
606
607     return p_vout;
608 }
609
610 audio_output_t *getAout(void)
611 {
612     intf_thread_t *p_intf = VLCIntf;
613     if (!p_intf)
614         return NULL;
615     return playlist_GetAout(pl_Get(p_intf));
616 }
617
618 #pragma mark -
619 #pragma mark Private
620
621 @interface VLCMain ()
622 - (void)removeOldPreferences;
623 @end
624
625 @interface VLCMain (Internal)
626 - (void)handlePortMessage:(NSPortMessage *)o_msg;
627 - (void)resetMediaKeyJump;
628 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
629 @end
630
631 /*****************************************************************************
632  * VLCMain implementation
633  *****************************************************************************/
634 @implementation VLCMain
635
636 @synthesize voutController=o_vout_controller;
637 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
638 @synthesize playlistUpdatedSelectorInQueue=b_playlist_updated_selector_in_queue;
639
640 #pragma mark -
641 #pragma mark Initialization
642
643 static VLCMain *_o_sharedMainInstance = nil;
644
645 + (VLCMain *)sharedInstance
646 {
647     return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
648 }
649
650 - (id)init
651 {
652     if (_o_sharedMainInstance) {
653         [self dealloc];
654         return _o_sharedMainInstance;
655     } else
656         _o_sharedMainInstance = [super init];
657
658     p_intf = NULL;
659     p_current_input = p_input_changed = NULL;
660
661     o_msg_lock = [[NSLock alloc] init];
662     o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
663
664     o_open = [[VLCOpen alloc] init];
665     o_coredialogs = [[VLCCoreDialogProvider alloc] init];
666     o_info = [[VLCInfo alloc] init];
667     o_mainmenu = [[VLCMainMenu alloc] init];
668     o_coreinteraction = [[VLCCoreInteraction alloc] init];
669     o_eyetv = [[VLCEyeTVController alloc] init];
670     o_mainwindow = [[VLCMainWindow alloc] init];
671
672     /* announce our launch to a potential eyetv plugin */
673     [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
674                                                                    object: @"VLCEyeTVSupport"
675                                                                  userInfo: NULL
676                                                        deliverImmediately: YES];
677
678     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
679     NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
680     [defaults registerDefaults:appDefaults];
681
682     o_vout_controller = [[VLCVoutWindowController alloc] init];
683
684     return _o_sharedMainInstance;
685 }
686
687 - (void)setIntf: (intf_thread_t *)p_mainintf
688 {
689     p_intf = p_mainintf;
690 }
691
692 - (intf_thread_t *)intf
693 {
694     return p_intf;
695 }
696
697 - (void)awakeFromNib
698 {
699     playlist_t *p_playlist;
700     vlc_value_t val;
701     if (!p_intf) return;
702     var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
703
704     /* Check if we already did this once. Opening the other nibs calls it too,
705      because VLCMain is the owner */
706     if (nib_main_loaded)
707         return;
708
709     [o_msgs_panel setExcludedFromWindowsMenu: YES];
710     [o_msgs_panel setDelegate: self];
711
712     p_playlist = pl_Get(p_intf);
713
714     val.b_bool = false;
715
716     var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
717     var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
718     var_AddCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
719     //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
720     var_AddCallback(p_playlist, "activity", PLItemChanged, self);
721     var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
722     var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
723     var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
724     var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
725     var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
726     var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
727     var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
728     var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
729
730     if (!OSX_SNOW_LEOPARD) {
731         if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
732             var_SetBool(p_playlist, "fullscreen", YES);
733     }
734
735     /* load our Core and Shared Dialogs nibs */
736     nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
737     [NSBundle loadNibNamed:@"SharedDialogs" owner: NSApp];
738
739     /* subscribe to various interactive dialogues */
740     var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
741     var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
742     var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
743     var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
744     var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
745     var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
746     var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
747     var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
748     var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
749     var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
750     dialog_Register(p_intf);
751
752     /* init Apple Remote support */
753     o_remote = [[AppleRemote alloc] init];
754     [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
755     [o_remote setDelegate: _o_sharedMainInstance];
756
757     [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
758
759     /* yeah, we are done */
760     b_nativeFullscreenMode = NO;
761 #ifdef MAC_OS_X_VERSION_10_7
762     if (!OSX_SNOW_LEOPARD)
763         b_nativeFullscreenMode = var_InheritBool(p_intf, "macosx-nativefullscreenmode");
764 #endif
765
766     if (config_GetInt(VLCIntf, "macosx-icon-change")) {
767         /* After day 354 of the year, the usual VLC cone is replaced by another cone
768          * wearing a Father Xmas hat.
769          * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
770          */
771         NSCalendar *gregorian =
772         [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
773         NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
774         [gregorian release];
775
776         if (dayOfYear >= 354)
777             [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
778     }
779
780     [self initStrings];
781
782     nib_main_loaded = TRUE;
783 }
784
785 - (void)applicationWillFinishLaunching:(NSNotification *)aNotification
786 {
787     playlist_t * p_playlist = pl_Get(VLCIntf);
788     PL_LOCK;
789     items_at_launch = p_playlist->p_local_category->i_children;
790     PL_UNLOCK;
791 }
792
793 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
794 {
795     launched = YES;
796
797     if (!p_intf)
798         return;
799
800     [self updateCurrentlyUsedHotkeys];
801
802     /* init media key support */
803     b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
804     if (b_mediaKeySupport) {
805         o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
806         [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
807                                                                  [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
808                                                                  nil]];
809     }
810     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];
811
812     [self removeOldPreferences];
813
814     /* Handle sleep notification */
815     [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
816            name:NSWorkspaceWillSleepNotification object:nil];
817
818     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
819
820     /* we will need this, so let's load it here so the interface appears to be more responsive */
821     nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
822
823     /* update the main window */
824     [o_mainwindow updateWindow];
825     [o_mainwindow updateTimeSlider];
826     [o_mainwindow updateVolumeSlider];
827
828     playlist_t * p_playlist = pl_Get(VLCIntf);
829     PL_LOCK;
830     BOOL kidsAround = p_playlist->p_local_category->i_children;
831     PL_UNLOCK;
832     if (kidsAround && var_GetBool(p_playlist, "playlist-autostart"))
833         [[self playlist] playItem:nil];
834 }
835
836 - (void)initStrings
837 {
838     if (!p_intf)
839         return;
840
841     /* messages panel */
842     [o_msgs_panel setTitle: _NS("Messages")];
843     [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
844     [o_msgs_save_btn setTitle: _NS("Save this Log...")];
845
846     /* crash reporter panel */
847     [o_crashrep_send_btn setTitle: _NS("Send")];
848     [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
849     [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
850     [o_crashrep_win setTitle: _NS("VLC crashed previously")];
851     [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, ...")];
852     [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
853     [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
854     [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
855 }
856
857 #pragma mark -
858 #pragma mark Termination
859
860 - (void)applicationWillTerminate:(NSNotification *)notification
861 {
862     /* don't allow a double termination call. If the user has
863      * already invoked the quit then simply return this time. */
864     static bool f_appExit = false;
865     bool isTerminating;
866
867     [o_appLock lock];
868     isTerminating = f_appExit;
869     f_appExit = true;
870     [o_appLock unlock];
871
872     if (isTerminating)
873         return;
874
875     [self resumeItunesPlayback:nil];
876
877     if (notification == nil)
878         [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
879
880     playlist_t * p_playlist = pl_Get(p_intf);
881     int returnedValue = 0;
882
883     /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
884     if (b_nativeFullscreenMode) {
885         [o_mainwindow toggleFullScreen: self];
886         [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
887     }
888
889     /* save current video and audio profiles */
890     [[VLCVideoEffects sharedInstance] saveCurrentProfile];
891     [[VLCAudioEffects sharedInstance] saveCurrentProfile];
892
893     /* Save some interface state in configuration, at module quit */
894     config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
895     config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
896     config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
897
898     msg_Dbg(p_intf, "Terminating");
899
900     /* unsubscribe from the interactive dialogues */
901     dialog_Unregister(p_intf);
902     var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
903     var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
904     var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
905     var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
906     var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
907     //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
908     var_DelCallback(p_playlist, "activity", PLItemChanged, self);
909     var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
910     var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
911     var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
912     var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
913     var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
914     var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
915     var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
916     var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
917     var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
918     var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
919     var_DelCallback(p_intf->p_libvlc, "intf-boss", BossCallback, self);
920
921     if (p_current_input) {
922         var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
923         vlc_object_release(p_current_input);
924         p_current_input = NULL;
925     }
926
927     /* remove global observer watching for vout device changes correctly */
928     [[NSNotificationCenter defaultCenter] removeObserver: self];
929
930     [o_vout_provider_lock lock];
931     // release before o_info!
932     [o_vout_controller release];
933     o_vout_controller = nil;
934     [o_vout_provider_lock unlock];
935
936     /* release some other objects here, because it isn't sure whether dealloc
937      * will be called later on */
938     if (o_sprefs)
939         [o_sprefs release];
940
941     if (o_prefs)
942         [o_prefs release];
943
944     [o_open release];
945
946     if (o_info)
947         [o_info release];
948
949     if (o_wizard)
950         [o_wizard release];
951
952     [crashLogURLConnection cancel];
953     [crashLogURLConnection release];
954
955     [o_coredialogs release];
956     [o_eyetv release];
957
958     /* unsubscribe from libvlc's debug messages */
959     vlc_LogSet(p_intf->p_libvlc, NULL, NULL);
960
961     [o_msg_arr removeAllObjects];
962     [o_msg_arr release];
963     o_msg_arr = NULL;
964     [o_usedHotkeys release];
965     o_usedHotkeys = NULL;
966
967     [o_mediaKeyController release];
968
969     [o_msg_lock release];
970
971     /* write cached user defaults to disk */
972     [[NSUserDefaults standardUserDefaults] synchronize];
973
974
975     [o_mainmenu release];
976
977     libvlc_Quit(p_intf->p_libvlc);
978
979     [o_mainwindow release];
980     o_mainwindow = NULL;
981
982     [self setIntf:nil];
983 }
984
985 #pragma mark -
986 #pragma mark Sparkle delegate
987 /* received directly before the update gets installed, so let's shut down a bit */
988 - (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
989 {
990     [NSApp activateIgnoringOtherApps:YES];
991     [o_remote stopListening: self];
992     [[VLCCoreInteraction sharedInstance] stop];
993 }
994
995 #pragma mark -
996 #pragma mark Media Key support
997
998 -(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
999 {
1000     if (b_mediaKeySupport) {
1001         assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);
1002
1003         int keyCode = (([event data1] & 0xFFFF0000) >> 16);
1004         int keyFlags = ([event data1] & 0x0000FFFF);
1005         int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
1006         int keyRepeat = (keyFlags & 0x1);
1007
1008         if (keyCode == NX_KEYTYPE_PLAY && keyState == 0)
1009             [[VLCCoreInteraction sharedInstance] playOrPause];
1010
1011         if ((keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped) {
1012             if (keyState == 0 && keyRepeat == 0)
1013                 [[VLCCoreInteraction sharedInstance] next];
1014             else if (keyRepeat == 1) {
1015                 [[VLCCoreInteraction sharedInstance] forwardShort];
1016                 b_mediakeyJustJumped = YES;
1017                 [self performSelector:@selector(resetMediaKeyJump)
1018                            withObject: NULL
1019                            afterDelay:0.25];
1020             }
1021         }
1022
1023         if ((keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped) {
1024             if (keyState == 0 && keyRepeat == 0)
1025                 [[VLCCoreInteraction sharedInstance] previous];
1026             else if (keyRepeat == 1) {
1027                 [[VLCCoreInteraction sharedInstance] backwardShort];
1028                 b_mediakeyJustJumped = YES;
1029                 [self performSelector:@selector(resetMediaKeyJump)
1030                            withObject: NULL
1031                            afterDelay:0.25];
1032             }
1033         }
1034     }
1035 }
1036
1037 #pragma mark -
1038 #pragma mark Other notification
1039
1040 /* Listen to the remote in exclusive mode, only when VLC is the active
1041    application */
1042 - (void)applicationDidBecomeActive:(NSNotification *)aNotification
1043 {
1044     if (!p_intf)
1045         return;
1046     if (var_InheritBool(p_intf, "macosx-appleremote") == YES)
1047         [o_remote startListening: self];
1048 }
1049 - (void)applicationDidResignActive:(NSNotification *)aNotification
1050 {
1051     if (!p_intf)
1052         return;
1053     [o_remote stopListening: self];
1054 }
1055
1056 /* Triggered when the computer goes to sleep */
1057 - (void)computerWillSleep: (NSNotification *)notification
1058 {
1059     [[VLCCoreInteraction sharedInstance] pause];
1060 }
1061
1062 #pragma mark -
1063 #pragma mark File opening over dock icon
1064
1065 - (void)application:(NSApplication *)o_app openFiles:(NSArray *)o_names
1066 {
1067     char *psz_uri = vlc_path2uri([[o_names objectAtIndex:0] UTF8String], "file");
1068
1069     if (launched == NO) {
1070         if (items_at_launch) {
1071             int items = [o_names count];
1072             if (items > items_at_launch)
1073                 items_at_launch = 0;
1074             else
1075                 items_at_launch -= items;
1076             return;
1077         }
1078     }
1079
1080     // try to add file as subtitle
1081     if ([o_names count] == 1 && psz_uri) {
1082         input_thread_t * p_input = pl_CurrentInput(VLCIntf);
1083         if (p_input) {
1084             BOOL b_returned = NO;
1085             b_returned = input_AddSubtitle(p_input, psz_uri, true);
1086             vlc_object_release(p_input);
1087             if (!b_returned) {
1088                 free(psz_uri);
1089                 return;
1090             }
1091         }
1092     }
1093     free(psz_uri);
1094
1095     NSArray *o_sorted_names = [o_names sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1096     NSMutableArray *o_result = [NSMutableArray arrayWithCapacity: [o_sorted_names count]];
1097     for (int i = 0; i < [o_sorted_names count]; i++) {
1098         psz_uri = vlc_path2uri([[o_sorted_names objectAtIndex:i] UTF8String], "file");
1099         if (!psz_uri)
1100             continue;
1101
1102         NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1103         free(psz_uri);
1104         [o_result addObject: o_dic];
1105     }
1106
1107     [o_playlist appendArray: o_result atPos: -1 enqueue: !config_GetInt(VLCIntf, "macosx-autoplay")];
1108
1109     return;
1110 }
1111
1112 /* When user click in the Dock icon our double click in the finder */
1113 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
1114 {
1115     if (!hasVisibleWindows)
1116         [o_mainwindow makeKeyAndOrderFront:self];
1117
1118     return YES;
1119 }
1120
1121 #pragma mark -
1122 #pragma mark Apple Remote Control
1123
1124 /* Helper method for the remote control interface in order to trigger forward/backward and volume
1125    increase/decrease as long as the user holds the left/right, plus/minus button */
1126 - (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
1127 {
1128     if (b_remote_button_hold) {
1129         switch([buttonIdentifierNumber intValue]) {
1130             case kRemoteButtonRight_Hold:
1131                 [[VLCCoreInteraction sharedInstance] forward];
1132                 break;
1133             case kRemoteButtonLeft_Hold:
1134                 [[VLCCoreInteraction sharedInstance] backward];
1135                 break;
1136             case kRemoteButtonVolume_Plus_Hold:
1137                 if (p_intf)
1138                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1139                 break;
1140             case kRemoteButtonVolume_Minus_Hold:
1141                 if (p_intf)
1142                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1143                 break;
1144         }
1145         if (b_remote_button_hold) {
1146             /* trigger event */
1147             [self performSelector:@selector(executeHoldActionForRemoteButton:)
1148                          withObject:buttonIdentifierNumber
1149                          afterDelay:0.25];
1150         }
1151     }
1152 }
1153
1154 /* Apple Remote callback */
1155 - (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
1156                pressedDown: (BOOL) pressedDown
1157                 clickCount: (unsigned int) count
1158 {
1159     switch(buttonIdentifier) {
1160         case k2009RemoteButtonFullscreen:
1161             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1162             break;
1163         case k2009RemoteButtonPlay:
1164             [[VLCCoreInteraction sharedInstance] playOrPause];
1165             break;
1166         case kRemoteButtonPlay:
1167             if (count >= 2)
1168                 [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1169             else
1170                 [[VLCCoreInteraction sharedInstance] playOrPause];
1171             break;
1172         case kRemoteButtonVolume_Plus:
1173             if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1174                 [NSSound increaseSystemVolume];
1175             else
1176                 if (p_intf)
1177                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_UP);
1178             break;
1179         case kRemoteButtonVolume_Minus:
1180             if (config_GetInt(VLCIntf, "macosx-appleremote-sysvol"))
1181                 [NSSound decreaseSystemVolume];
1182             else
1183                 if (p_intf)
1184                     var_SetInteger(p_intf->p_libvlc, "key-action", ACTIONID_VOL_DOWN);
1185             break;
1186         case kRemoteButtonRight:
1187             if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1188                 [[VLCCoreInteraction sharedInstance] forward];
1189             else
1190                 [[VLCCoreInteraction sharedInstance] next];
1191             break;
1192         case kRemoteButtonLeft:
1193             if (config_GetInt(VLCIntf, "macosx-appleremote-prevnext"))
1194                 [[VLCCoreInteraction sharedInstance] backward];
1195             else
1196                 [[VLCCoreInteraction sharedInstance] previous];
1197             break;
1198         case kRemoteButtonRight_Hold:
1199         case kRemoteButtonLeft_Hold:
1200         case kRemoteButtonVolume_Plus_Hold:
1201         case kRemoteButtonVolume_Minus_Hold:
1202             /* simulate an event as long as the user holds the button */
1203             b_remote_button_hold = pressedDown;
1204             if (pressedDown) {
1205                 NSNumber* buttonIdentifierNumber = @(buttonIdentifier);
1206                 [self performSelector:@selector(executeHoldActionForRemoteButton:)
1207                            withObject:buttonIdentifierNumber];
1208             }
1209             break;
1210         case kRemoteButtonMenu:
1211             [o_controls showPosition: self]; //FIXME
1212             break;
1213         case kRemoteButtonPlay_Sleep:
1214         {
1215             NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to sleep"];
1216             [script executeAndReturnError:nil];
1217             [script release];
1218             break;
1219         }
1220         default:
1221             /* Add here whatever you want other buttons to do */
1222             break;
1223     }
1224 }
1225
1226 #pragma mark -
1227 #pragma mark Key Shortcuts
1228
1229 /*****************************************************************************
1230  * hasDefinedShortcutKey: Check to see if the key press is a defined VLC
1231  * shortcut key.  If it is, pass it off to VLC for handling and return YES,
1232  * otherwise ignore it and return NO (where it will get handled by Cocoa).
1233  *****************************************************************************/
1234 - (BOOL)hasDefinedShortcutKey:(NSEvent *)o_event force:(BOOL)b_force
1235 {
1236     unichar key = 0;
1237     vlc_value_t val;
1238     unsigned int i_pressed_modifiers = 0;
1239
1240     val.i_int = 0;
1241     i_pressed_modifiers = [o_event modifierFlags];
1242
1243     if (i_pressed_modifiers & NSControlKeyMask)
1244         val.i_int |= KEY_MODIFIER_CTRL;
1245
1246     if (i_pressed_modifiers & NSAlternateKeyMask)
1247         val.i_int |= KEY_MODIFIER_ALT;
1248
1249     if (i_pressed_modifiers & NSShiftKeyMask)
1250         val.i_int |= KEY_MODIFIER_SHIFT;
1251
1252     if (i_pressed_modifiers & NSCommandKeyMask)
1253         val.i_int |= KEY_MODIFIER_COMMAND;
1254
1255     NSString * characters = [o_event charactersIgnoringModifiers];
1256     if ([characters length] > 0) {
1257         key = [[characters lowercaseString] characterAtIndex: 0];
1258
1259         /* handle Lion's default key combo for fullscreen-toggle in addition to our own hotkeys */
1260         if (key == 'f' && i_pressed_modifiers & NSControlKeyMask && i_pressed_modifiers & NSCommandKeyMask) {
1261             [[VLCCoreInteraction sharedInstance] toggleFullscreen];
1262             return YES;
1263         }
1264
1265         if (!b_force) {
1266             switch(key) {
1267                 case NSDeleteCharacter:
1268                 case NSDeleteFunctionKey:
1269                 case NSDeleteCharFunctionKey:
1270                 case NSBackspaceCharacter:
1271                 case NSUpArrowFunctionKey:
1272                 case NSDownArrowFunctionKey:
1273                 case NSEnterCharacter:
1274                 case NSCarriageReturnCharacter:
1275                     return NO;
1276             }
1277         }
1278
1279         val.i_int |= CocoaKeyToVLC(key);
1280
1281         BOOL b_found_key = NO;
1282         for (int i = 0; i < [o_usedHotkeys count]; i++) {
1283             NSString *str = [o_usedHotkeys objectAtIndex:i];
1284             unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa: str];
1285
1286             if ([[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: str]] &&
1287                (i_keyModifiers & NSShiftKeyMask)     == (i_pressed_modifiers & NSShiftKeyMask) &&
1288                (i_keyModifiers & NSControlKeyMask)   == (i_pressed_modifiers & NSControlKeyMask) &&
1289                (i_keyModifiers & NSAlternateKeyMask) == (i_pressed_modifiers & NSAlternateKeyMask) &&
1290                (i_keyModifiers & NSCommandKeyMask)   == (i_pressed_modifiers & NSCommandKeyMask)) {
1291                 b_found_key = YES;
1292                 break;
1293             }
1294         }
1295
1296         if (b_found_key) {
1297             var_SetInteger(p_intf->p_libvlc, "key-pressed", val.i_int);
1298             return YES;
1299         }
1300     }
1301
1302     return NO;
1303 }
1304
1305 - (void)updateCurrentlyUsedHotkeys
1306 {
1307     NSMutableArray *o_tempArray = [[NSMutableArray alloc] init];
1308     /* Get the main Module */
1309     module_t *p_main = module_get_main();
1310     assert(p_main);
1311     unsigned confsize;
1312     module_config_t *p_config;
1313
1314     p_config = module_config_get (p_main, &confsize);
1315
1316     for (size_t i = 0; i < confsize; i++) {
1317         module_config_t *p_item = p_config + i;
1318
1319         if (CONFIG_ITEM(p_item->i_type) && p_item->psz_name != NULL
1320            && !strncmp(p_item->psz_name , "key-", 4)
1321            && !EMPTY_STR(p_item->psz_text)) {
1322             if (p_item->value.psz)
1323                 [o_tempArray addObject: @(p_item->value.psz)];
1324         }
1325     }
1326     module_config_free (p_config);
1327
1328     if (o_usedHotkeys)
1329         [o_usedHotkeys release];
1330     o_usedHotkeys = [[NSArray alloc] initWithArray: o_tempArray copyItems: YES];
1331     [o_tempArray release];
1332 }
1333
1334 #pragma mark -
1335 #pragma mark Interface updaters
1336
1337 - (void)PlaylistItemChanged
1338 {
1339     if (p_current_input && (p_current_input->b_dead || !vlc_object_alive(p_current_input))) {
1340         var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1341         p_input_changed = p_current_input;
1342         p_current_input = NULL;
1343
1344         [o_mainmenu setRateControlsEnabled: NO];
1345     }
1346     else if (!p_current_input) {
1347         // object is hold here and released then it is dead
1348         p_current_input = playlist_CurrentInput(pl_Get(VLCIntf));
1349         if (p_current_input) {
1350             var_AddCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
1351             [self playbackStatusUpdated];
1352             [o_mainmenu setRateControlsEnabled: YES];
1353             if ([self activeVideoPlayback] && [[o_mainwindow videoView] isHidden])
1354                 [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject: nil waitUntilDone:NO];
1355             p_input_changed = vlc_object_hold(p_current_input);
1356         }
1357     }
1358
1359     [o_playlist updateRowSelection];
1360     [o_mainwindow updateWindow];
1361     [self updateDelays];
1362     [self updateMainMenu];
1363 }
1364
1365 - (void)informInputChanged
1366 {
1367     if (p_input_changed) {
1368         [[ExtensionsManager getInstance:p_intf] inputChanged:p_input_changed];
1369         vlc_object_release(p_input_changed);
1370         p_input_changed = NULL;
1371     }
1372 }
1373
1374 - (void)updateMainMenu
1375 {
1376     [o_mainmenu setupMenus];
1377     [o_mainmenu updatePlaybackRate];
1378     [[VLCCoreInteraction sharedInstance] resetAtoB];
1379 }
1380
1381 - (void)updateMainWindow
1382 {
1383     [o_mainwindow updateWindow];
1384 }
1385
1386 - (void)showMainWindow
1387 {
1388     [o_mainwindow performSelectorOnMainThread:@selector(makeKeyAndOrderFront:) withObject:nil waitUntilDone:NO];
1389 }
1390
1391 - (void)showFullscreenController
1392 {
1393     // defer selector here (possibly another time) to ensure that keyWindow is set properly
1394     // (needed for NSApplicationDidBecomeActiveNotification)
1395     [o_mainwindow performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
1396 }
1397
1398 - (void)updateDelays
1399 {
1400     [[VLCTrackSynchronization sharedInstance] performSelectorOnMainThread: @selector(updateValues) withObject: nil waitUntilDone:NO];
1401 }
1402
1403 - (void)updateName
1404 {
1405     [o_mainwindow updateName];
1406 }
1407
1408 - (void)updatePlaybackPosition
1409 {
1410     [o_mainwindow updateTimeSlider];
1411     [[VLCCoreInteraction sharedInstance] updateAtoB];
1412 }
1413
1414 - (void)updateVolume
1415 {
1416     [o_mainwindow updateVolumeSlider];
1417 }
1418
1419 - (void)playlistUpdated
1420 {
1421     @synchronized(self) {
1422         b_playlist_updated_selector_in_queue = NO;
1423     }
1424
1425     [self playbackStatusUpdated];
1426     [o_playlist playlistUpdated];
1427     [o_mainwindow updateWindow];
1428     [o_mainwindow updateName];
1429
1430     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1431                                                         object: nil
1432                                                       userInfo: nil];
1433 }
1434
1435 - (void)updateRecordState: (BOOL)b_value
1436 {
1437     [o_mainmenu updateRecordState:b_value];
1438 }
1439
1440 - (void)updateInfoandMetaPanel
1441 {
1442     [o_playlist outlineViewSelectionDidChange:nil];
1443 }
1444
1445 - (void)resumeItunesPlayback:(id)sender
1446 {
1447     if (b_has_itunes_paused && var_InheritInteger(p_intf, "macosx-control-itunes") > 1) {
1448         iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1449         if (iTunesApp && [iTunesApp isRunning]) {
1450             if ([iTunesApp playerState] == iTunesEPlSPaused) {
1451                 msg_Dbg(p_intf, "Unpause iTunes...");
1452                 [iTunesApp playpause];
1453             }
1454         }
1455
1456     }
1457
1458     b_has_itunes_paused = NO;
1459     o_itunes_play_timer = nil;
1460 }
1461
1462 - (void)playbackStatusUpdated
1463 {
1464     int state = -1;
1465     if (p_current_input) {
1466         state = var_GetInteger(p_current_input, "state");
1467     }
1468
1469     int i_control_itunes = var_InheritInteger(p_intf, "macosx-control-itunes");
1470     // cancel itunes timer if next item starts playing
1471     if (state > -1 && state != END_S && i_control_itunes > 0) {
1472         if (o_itunes_play_timer) {
1473             [o_itunes_play_timer invalidate];
1474             o_itunes_play_timer = nil;
1475         }
1476     }
1477
1478     if (state == PLAYING_S) {
1479         // pause iTunes
1480         if (i_control_itunes > 0 && !b_has_itunes_paused) {
1481             iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
1482             if (iTunesApp && [iTunesApp isRunning]) {
1483                 if ([iTunesApp playerState] == iTunesEPlSPlaying) {
1484                     msg_Dbg(p_intf, "Pause iTunes...");
1485                     [iTunesApp pause];
1486                     b_has_itunes_paused = YES;
1487                 }
1488             }
1489         }
1490
1491
1492         /* Declare user activity.
1493          This wakes the display if it is off, and postpones display sleep according to the users system preferences
1494          Available from 10.7.3 */
1495 #ifdef MAC_OS_X_VERSION_10_7
1496         if ([self activeVideoPlayback] && IOPMAssertionDeclareUserActivity)
1497         {
1498             CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1499             IOPMAssertionDeclareUserActivity(reasonForActivity,
1500                                              kIOPMUserActiveLocal,
1501                                              &userActivityAssertionID);
1502             CFRelease(reasonForActivity);
1503         }
1504 #endif
1505
1506         /* prevent the system from sleeping */
1507         if (systemSleepAssertionID > 0) {
1508             msg_Dbg(VLCIntf, "releasing old sleep blocker (%i)" , systemSleepAssertionID);
1509             IOPMAssertionRelease(systemSleepAssertionID);
1510         }
1511
1512         IOReturn success;
1513         /* work-around a bug in 10.7.4 and 10.7.5, so check for 10.7.x < 10.7.4, 10.8 and 10.6 */
1514         if ((NSAppKitVersionNumber >= 1115.2 && NSAppKitVersionNumber < 1138.45) || OSX_MOUNTAIN_LION || OSX_SNOW_LEOPARD) {
1515             CFStringRef reasonForActivity = CFStringCreateWithCString(kCFAllocatorDefault, _("VLC media playback"), kCFStringEncodingUTF8);
1516             if ([self activeVideoPlayback])
1517                 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1518             else
1519                 success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, reasonForActivity, &systemSleepAssertionID);
1520             CFRelease(reasonForActivity);
1521         } else {
1522             /* fall-back on the 10.5 mode, which also works on 10.7.4 and 10.7.5 */
1523             if ([self activeVideoPlayback])
1524                 success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1525             else
1526                 success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &systemSleepAssertionID);
1527         }
1528
1529         if (success == kIOReturnSuccess)
1530             msg_Dbg(VLCIntf, "prevented sleep through IOKit (%i)", systemSleepAssertionID);
1531         else
1532             msg_Warn(VLCIntf, "failed to prevent system sleep through IOKit");
1533
1534         [[self mainMenu] setPause];
1535         [o_mainwindow setPause];
1536     } else {
1537         [o_mainmenu setSubmenusEnabled: FALSE];
1538         [[self mainMenu] setPlay];
1539         [o_mainwindow setPlay];
1540
1541         /* allow the system to sleep again */
1542         if (systemSleepAssertionID > 0) {
1543             msg_Dbg(VLCIntf, "releasing sleep blocker (%i)" , systemSleepAssertionID);
1544             IOPMAssertionRelease(systemSleepAssertionID);
1545         }
1546
1547         if (state == END_S || state == -1) {
1548             if (i_control_itunes > 0) {
1549                 if (o_itunes_play_timer) {
1550                     [o_itunes_play_timer invalidate];
1551                 }
1552                 o_itunes_play_timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
1553                                                                        target: self
1554                                                                      selector: @selector(resumeItunesPlayback:)
1555                                                                      userInfo: nil
1556                                                                       repeats: NO];
1557             }
1558         }
1559     }
1560
1561     [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
1562     [self performSelectorOnMainThread:@selector(sendDistributedNotificationWithUpdatedPlaybackStatus) withObject: nil waitUntilDone: NO];
1563 }
1564
1565 - (void)sendDistributedNotificationWithUpdatedPlaybackStatus
1566 {
1567     [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"VLCPlayerStateDidChange"
1568                                                                    object:nil
1569                                                                  userInfo:nil
1570                                                        deliverImmediately:YES];
1571 }
1572
1573 - (void)playbackModeUpdated
1574 {
1575     vlc_value_t looping,repeating;
1576     playlist_t * p_playlist = pl_Get(VLCIntf);
1577
1578     bool loop = var_GetBool(p_playlist, "loop");
1579     bool repeat = var_GetBool(p_playlist, "repeat");
1580     if (repeat) {
1581         [[o_mainwindow controlsBar] setRepeatOne];
1582         [o_mainmenu setRepeatOne];
1583     } else if (loop) {
1584         [[o_mainwindow controlsBar] setRepeatAll];
1585         [o_mainmenu setRepeatAll];
1586     } else {
1587         [[o_mainwindow controlsBar] setRepeatOff];
1588         [o_mainmenu setRepeatOff];
1589     }
1590
1591     [[o_mainwindow controlsBar] setShuffle];
1592     [o_mainmenu setShuffle];
1593 }
1594
1595 #pragma mark -
1596 #pragma mark Window updater
1597
1598 - (void)setActiveVideoPlayback:(BOOL)b_value
1599 {
1600     b_active_videoplayback = b_value;
1601     if (o_mainwindow) {
1602         [o_mainwindow performSelectorOnMainThread:@selector(setVideoplayEnabled) withObject:nil waitUntilDone:YES];
1603         [o_mainwindow performSelectorOnMainThread:@selector(togglePlaylist:) withObject:nil waitUntilDone:NO];
1604     }
1605
1606     // update sleep blockers
1607     [self performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject:nil waitUntilDone:NO];
1608 }
1609
1610 #pragma mark -
1611 #pragma mark Other objects getters
1612
1613 - (id)mainMenu
1614 {
1615     return o_mainmenu;
1616 }
1617
1618 - (VLCMainWindow *)mainWindow
1619 {
1620     return o_mainwindow;
1621 }
1622
1623 - (id)controls
1624 {
1625     if (o_controls)
1626         return o_controls;
1627
1628     return nil;
1629 }
1630
1631 - (id)bookmarks
1632 {
1633     if (!o_bookmarks)
1634         o_bookmarks = [[VLCBookmarks alloc] init];
1635
1636     if (!nib_bookmarks_loaded)
1637         nib_bookmarks_loaded = [NSBundle loadNibNamed:@"Bookmarks" owner: NSApp];
1638
1639     return o_bookmarks;
1640 }
1641
1642 - (id)open
1643 {
1644     if (!o_open)
1645         return nil;
1646
1647     if (!nib_open_loaded)
1648         nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
1649
1650     return o_open;
1651 }
1652
1653 - (id)simplePreferences
1654 {
1655     if (!o_sprefs)
1656         o_sprefs = [[VLCSimplePrefs alloc] init];
1657
1658     if (!nib_prefs_loaded)
1659         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1660
1661     return o_sprefs;
1662 }
1663
1664 - (id)preferences
1665 {
1666     if (!o_prefs)
1667         o_prefs = [[VLCPrefs alloc] init];
1668
1669     if (!nib_prefs_loaded)
1670         nib_prefs_loaded = [NSBundle loadNibNamed:@"Preferences" owner: NSApp];
1671
1672     return o_prefs;
1673 }
1674
1675 - (id)playlist
1676 {
1677     if (o_playlist)
1678         return o_playlist;
1679
1680     return nil;
1681 }
1682
1683 - (id)info
1684 {
1685     if (! nib_info_loaded)
1686         nib_info_loaded = [NSBundle loadNibNamed:@"MediaInfo" owner: NSApp];
1687
1688     if (o_info)
1689         return o_info;
1690
1691     return nil;
1692 }
1693
1694 - (id)wizard
1695 {
1696     if (!o_wizard)
1697         o_wizard = [[VLCWizard alloc] init];
1698
1699     if (!nib_wizard_loaded) {
1700         nib_wizard_loaded = [NSBundle loadNibNamed:@"Wizard" owner: NSApp];
1701         [o_wizard initStrings];
1702     }
1703     return o_wizard;
1704 }
1705
1706 - (id)coreDialogProvider
1707 {
1708     if (o_coredialogs)
1709         return o_coredialogs;
1710
1711     return nil;
1712 }
1713
1714 - (id)eyeTVController
1715 {
1716     if (o_eyetv)
1717         return o_eyetv;
1718
1719     return nil;
1720 }
1721
1722 - (id)appleRemoteController
1723 {
1724     return o_remote;
1725 }
1726
1727 - (BOOL)activeVideoPlayback
1728 {
1729     return b_active_videoplayback;
1730 }
1731
1732 #pragma mark -
1733 #pragma mark Crash Log
1734 - (void)sendCrashLog:(NSString *)crashLog withUserComment:(NSString *)userComment
1735 {
1736     NSString *urlStr = @"http://crash.videolan.org/crashlog/sendcrashreport.php";
1737     NSURL *url = [NSURL URLWithString:urlStr];
1738
1739     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
1740     [req setHTTPMethod:@"POST"];
1741
1742     NSString * email;
1743     if ([o_crashrep_includeEmail_ckb state] == NSOnState) {
1744         ABPerson * contact = [[ABAddressBook sharedAddressBook] me];
1745         ABMultiValue *emails = [contact valueForProperty:kABEmailProperty];
1746         email = [emails valueAtIndex:[emails indexForIdentifier:
1747                     [emails primaryIdentifier]]];
1748     }
1749     else
1750         email = [NSString string];
1751
1752     NSString *postBody;
1753     postBody = [NSString stringWithFormat:@"CrashLog=%@&Comment=%@&Email=%@\r\n",
1754             [crashLog stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1755             [userComment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
1756             [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
1757
1758     [req setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
1759
1760     /* Released from delegate */
1761     crashLogURLConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
1762 }
1763
1764 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
1765 {
1766     msg_Dbg(p_intf, "crash report successfully sent");
1767     [crashLogURLConnection release];
1768     crashLogURLConnection = nil;
1769 }
1770
1771 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1772 {
1773     msg_Warn (p_intf, "Error when sending the crash report: %s (%li)", [[error localizedDescription] UTF8String], [error code]);
1774     [crashLogURLConnection release];
1775     crashLogURLConnection = nil;
1776 }
1777
1778 - (NSString *)latestCrashLogPathPreviouslySeen:(BOOL)previouslySeen
1779 {
1780     NSString * crashReporter;
1781     if (OSX_MOUNTAIN_LION)
1782         crashReporter = [@"~/Library/Logs/DiagnosticReports" stringByExpandingTildeInPath];
1783     else
1784         crashReporter = [@"~/Library/Logs/CrashReporter" stringByExpandingTildeInPath];
1785     NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:crashReporter];
1786     NSString *fname;
1787     NSString * latestLog = nil;
1788     NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1789     int year  = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportYear"] : 0;
1790     int month = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportMonth"]: 0;
1791     int day   = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportDay"]  : 0;
1792     int hours = !previouslySeen ? [defaults integerForKey:@"LatestCrashReportHours"]: 0;
1793
1794     while (fname = [direnum nextObject]) {
1795         [direnum skipDescendents];
1796         if ([fname hasPrefix:@"VLC"] && [fname hasSuffix:@"crash"]) {
1797             NSArray * compo = [fname componentsSeparatedByString:@"_"];
1798             if ([compo count] < 3)
1799                 continue;
1800             compo = [[compo objectAtIndex:1] componentsSeparatedByString:@"-"];
1801             if ([compo count] < 4)
1802                 continue;
1803
1804             // Dooh. ugly.
1805             if (year < [[compo objectAtIndex:0] intValue] ||
1806                 (year ==[[compo objectAtIndex:0] intValue] &&
1807                  (month < [[compo objectAtIndex:1] intValue] ||
1808                   (month ==[[compo objectAtIndex:1] intValue] &&
1809                    (day   < [[compo objectAtIndex:2] intValue] ||
1810                     (day   ==[[compo objectAtIndex:2] intValue] &&
1811                       hours < [[compo objectAtIndex:3] intValue])))))) {
1812                 year  = [[compo objectAtIndex:0] intValue];
1813                 month = [[compo objectAtIndex:1] intValue];
1814                 day   = [[compo objectAtIndex:2] intValue];
1815                 hours = [[compo objectAtIndex:3] intValue];
1816                 latestLog = [crashReporter stringByAppendingPathComponent:fname];
1817             }
1818         }
1819     }
1820
1821     if (!(latestLog && [[NSFileManager defaultManager] fileExistsAtPath:latestLog]))
1822         return nil;
1823
1824     if (!previouslySeen) {
1825         [defaults setInteger:year  forKey:@"LatestCrashReportYear"];
1826         [defaults setInteger:month forKey:@"LatestCrashReportMonth"];
1827         [defaults setInteger:day   forKey:@"LatestCrashReportDay"];
1828         [defaults setInteger:hours forKey:@"LatestCrashReportHours"];
1829     }
1830     return latestLog;
1831 }
1832
1833 - (NSString *)latestCrashLogPath
1834 {
1835     return [self latestCrashLogPathPreviouslySeen:YES];
1836 }
1837
1838 - (void)lookForCrashLog
1839 {
1840     NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
1841     // This pref key doesn't exists? this VLC is an upgrade, and this crash log come from previous version
1842     NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1843     BOOL areCrashLogsTooOld = ![defaults integerForKey:@"LatestCrashReportYear"];
1844     NSString * latestLog = [self latestCrashLogPathPreviouslySeen:NO];
1845     if (latestLog && !areCrashLogsTooOld) {
1846         if ([defaults integerForKey:@"AlwaysSendCrashReports"] > 0)
1847             [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1848         else if ([defaults integerForKey:@"AlwaysSendCrashReports"] == 0)
1849             [NSApp runModalForWindow: o_crashrep_win];
1850         // bail out, the user doesn't want us to send reports
1851     }
1852
1853     [o_pool release];
1854 }
1855
1856 - (IBAction)crashReporterAction:(id)sender
1857 {
1858     if (sender == o_crashrep_send_btn) {
1859         [self sendCrashLog:[NSString stringWithContentsOfFile: [self latestCrashLogPath] encoding: NSUTF8StringEncoding error: NULL] withUserComment: [o_crashrep_fld string]];
1860         if ([o_crashrep_dontaskagain_ckb state])
1861             [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"AlwaysSendCrashReports"];
1862     } else {
1863         if ([o_crashrep_dontaskagain_ckb state])
1864             [[NSUserDefaults standardUserDefaults] setInteger:-1 forKey:@"AlwaysSendCrashReports"];
1865     }
1866
1867     [NSApp stopModal];
1868     [o_crashrep_win orderOut: sender];
1869 }
1870
1871 - (IBAction)openCrashLog:(id)sender
1872 {
1873     NSString * latestLog = [self latestCrashLogPath];
1874     if (latestLog) {
1875         [[NSWorkspace sharedWorkspace] openFile: latestLog withApplication: @"Console"];
1876     } else {
1877         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."));
1878     }
1879 }
1880
1881 #pragma mark -
1882 #pragma mark Remove old prefs
1883
1884 - (void)removeOldPreferences
1885 {
1886     static NSString * kVLCPreferencesVersion = @"VLCPreferencesVersion";
1887     static const int kCurrentPreferencesVersion = 3;
1888     NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
1889     int version = [defaults integerForKey:kVLCPreferencesVersion];
1890     if (version >= kCurrentPreferencesVersion)
1891         return;
1892
1893     if (version == 1) {
1894         [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1895         [defaults synchronize];
1896
1897         if (![[VLCCoreInteraction sharedInstance] fixPreferences])
1898             return;
1899         else
1900             config_SaveConfigFile(VLCIntf); // we need to do manually, since we won't quit libvlc cleanly
1901     } else if (version == 2) {
1902         /* version 2 (used by VLC 2.0.x and early versions of 2.1) can lead to exceptions within 2.1 or later
1903          * so we reset the OS X specific prefs here - in practice, no user will notice */
1904         [NSUserDefaults resetStandardUserDefaults];
1905
1906         [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1907         [defaults synchronize];
1908     } else {
1909         NSArray *libraries = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
1910             NSUserDomainMask, YES);
1911         if (!libraries || [libraries count] == 0) return;
1912         NSString * preferences = [[libraries objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];
1913
1914         /* File not found, don't attempt anything */
1915         if (![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc"]] &&
1916            ![[NSFileManager defaultManager] fileExistsAtPath:[preferences stringByAppendingPathComponent:@"org.videolan.vlc.plist"]]) {
1917             [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1918             return;
1919         }
1920
1921         int res = NSRunInformationalAlertPanel(_NS("Remove old preferences?"),
1922                     _NS("We just found an older version of VLC's preferences files."),
1923                     _NS("Move To Trash and Relaunch VLC"), _NS("Ignore"), nil, nil);
1924         if (res != NSOKButton) {
1925             [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1926             return;
1927         }
1928
1929         NSArray * ourPreferences = @[@"org.videolan.vlc.plist", @"VLC", @"org.videolan.vlc"];
1930
1931         /* Move the file to trash so that user can find them later */
1932         [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:preferences destination:nil files:ourPreferences tag:0];
1933
1934         /* really reset the defaults from now on */
1935         [NSUserDefaults resetStandardUserDefaults];
1936
1937         [defaults setInteger:kCurrentPreferencesVersion forKey:kVLCPreferencesVersion];
1938         [defaults synchronize];
1939     }
1940
1941     /* Relaunch now */
1942     const char * path = [[[NSBundle mainBundle] executablePath] UTF8String];
1943
1944     /* For some reason we need to fork(), not just execl(), which reports a ENOTSUP then. */
1945     if (fork() != 0) {
1946         exit(0);
1947         return;
1948     }
1949     execl(path, path, NULL);
1950 }
1951
1952 #pragma mark -
1953 #pragma mark Errors, warnings and messages
1954 - (IBAction)updateMessagesPanel:(id)sender
1955 {
1956     [self windowDidBecomeKey:nil];
1957 }
1958
1959 - (IBAction)showMessagesPanel:(id)sender
1960 {
1961     /* subscribe to LibVLCCore's messages */
1962     vlc_LogSet(p_intf->p_libvlc, MsgCallback, NULL);
1963
1964     /* show panel */
1965     [o_msgs_panel makeKeyAndOrderFront: sender];
1966 }
1967
1968 - (void)windowDidBecomeKey:(NSNotification *)o_notification
1969 {
1970     [o_msgs_table reloadData];
1971     [o_msgs_table scrollRowToVisible: [o_msg_arr count] - 1];
1972 }
1973
1974 - (void)windowWillClose:(NSNotification *)o_notification
1975 {
1976     /* unsubscribe from LibVLCCore's messages */
1977     vlc_LogSet( p_intf->p_libvlc, NULL, NULL );
1978 }
1979
1980 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
1981 {
1982     if (aTableView == o_msgs_table)
1983         return [o_msg_arr count];
1984     return 0;
1985 }
1986
1987 - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
1988 {
1989     NSMutableAttributedString *result = NULL;
1990
1991     [o_msg_lock lock];
1992     if (rowIndex < [o_msg_arr count])
1993         result = [o_msg_arr objectAtIndex:rowIndex];
1994     [o_msg_lock unlock];
1995
1996     if (result != NULL)
1997         return result;
1998     else
1999         return @"";
2000 }
2001
2002 - (void)processReceivedlibvlcMessage:(const vlc_log_t *) item ofType: (int)i_type withStr: (char *)str
2003 {
2004     if (o_msg_arr) {
2005         NSColor *o_white = [NSColor whiteColor];
2006         NSColor *o_red = [NSColor redColor];
2007         NSColor *o_yellow = [NSColor yellowColor];
2008         NSColor *o_gray = [NSColor grayColor];
2009         NSString * firstString, * secondString;
2010
2011         NSColor * pp_color[4] = { o_white, o_red, o_yellow, o_gray };
2012         static const char * ppsz_type[4] = { ": ", " error: ", " warning: ", " debug: " };
2013
2014         NSDictionary *o_attr;
2015         NSMutableAttributedString *o_msg_color;
2016
2017         [o_msg_lock lock];
2018
2019         if ([o_msg_arr count] > 600) {
2020             [o_msg_arr removeObjectAtIndex: 0];
2021             [o_msg_arr removeObjectAtIndex: 1];
2022         }
2023         if (!item->psz_module)
2024             return;
2025         if (!str)
2026             return;
2027
2028         firstString = [NSString stringWithFormat:@"%s%s", item->psz_module, ppsz_type[i_type]];
2029         secondString = [NSString stringWithFormat:@"%@%s\n", firstString, str];
2030
2031         o_attr = [NSDictionary dictionaryWithObject: pp_color[i_type]  forKey: NSForegroundColorAttributeName];
2032         o_msg_color = [[NSMutableAttributedString alloc] initWithString: secondString attributes: o_attr];
2033         o_attr = [NSDictionary dictionaryWithObject: pp_color[3] forKey: NSForegroundColorAttributeName];
2034         [o_msg_color setAttributes: o_attr range: NSMakeRange(0, [firstString length])];
2035         [o_msg_arr addObject: [o_msg_color autorelease]];
2036
2037         b_msg_arr_changed = YES;
2038         [o_msg_lock unlock];
2039     }
2040 }
2041
2042 - (IBAction)saveDebugLog:(id)sender
2043 {
2044     NSSavePanel * saveFolderPanel = [[NSSavePanel alloc] init];
2045
2046     [saveFolderPanel setCanSelectHiddenExtension: NO];
2047     [saveFolderPanel setCanCreateDirectories: YES];
2048     [saveFolderPanel setAllowedFileTypes: @[@"rtf"]];
2049     [saveFolderPanel setNameFieldStringValue:[NSString stringWithFormat: _NS("VLC Debug Log (%s).rtf"), VERSION_MESSAGE]];
2050     [saveFolderPanel beginSheetModalForWindow: o_msgs_panel completionHandler:^(NSInteger returnCode) {
2051         if (returnCode == NSOKButton) {
2052             NSUInteger count = [o_msg_arr count];
2053             NSMutableAttributedString * string = [[NSMutableAttributedString alloc] init];
2054             for (NSUInteger i = 0; i < count; i++)
2055                 [string appendAttributedString: [o_msg_arr objectAtIndex:i]];
2056
2057             NSData *data = [string RTFFromRange:NSMakeRange(0, [string length])
2058                              documentAttributes:[NSDictionary dictionaryWithObject: NSRTFTextDocumentType forKey: NSDocumentTypeDocumentAttribute]];
2059
2060             if ([data writeToFile: [[saveFolderPanel URL] path] atomically: YES] == NO)
2061                 msg_Warn(p_intf, "Error while saving the debug log");
2062
2063             [string release];
2064         }
2065     }];
2066     [saveFolderPanel release];
2067 }
2068
2069 #pragma mark -
2070 #pragma mark Playlist toggling
2071
2072 - (void)updateTogglePlaylistState
2073 {
2074     [[self playlist] outlineViewSelectionDidChange: NULL];
2075 }
2076
2077 #pragma mark -
2078
2079 @end
2080
2081 @implementation VLCMain (Internal)
2082
2083 - (void)handlePortMessage:(NSPortMessage *)o_msg
2084 {
2085     id ** val;
2086     NSData * o_data;
2087     NSValue * o_value;
2088     NSInvocation * o_inv;
2089     NSConditionLock * o_lock;
2090
2091     o_data = [[o_msg components] lastObject];
2092     o_inv = *((NSInvocation **)[o_data bytes]);
2093     [o_inv getArgument: &o_value atIndex: 2];
2094     val = (id **)[o_value pointerValue];
2095     [o_inv setArgument: val[1] atIndex: 2];
2096     o_lock = *(val[0]);
2097
2098     [o_lock lock];
2099     [o_inv invoke];
2100     [o_lock unlockWithCondition: 1];
2101 }
2102
2103 - (void)resetMediaKeyJump
2104 {
2105     b_mediakeyJustJumped = NO;
2106 }
2107
2108 - (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification
2109 {
2110     b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
2111     if (b_mediaKeySupport) {
2112         if (!o_mediaKeyController)
2113             o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
2114
2115         if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot]->i_children > 0 ||
2116             p_current_input)
2117             [o_mediaKeyController startWatchingMediaKeys];
2118         else
2119             [o_mediaKeyController stopWatchingMediaKeys];
2120     }
2121     else if (!b_mediaKeySupport && o_mediaKeyController)
2122         [o_mediaKeyController stopWatchingMediaKeys];
2123 }
2124
2125 @end
2126
2127 /*****************************************************************************
2128  * VLCApplication interface
2129  *****************************************************************************/
2130
2131 @implementation VLCApplication
2132 // when user selects the quit menu from dock it sends a terminate:
2133 // but we need to send a stop: to properly exits libvlc.
2134 // However, we are not able to change the action-method sent by this standard menu item.
2135 // thus we override terminate: to send a stop:
2136 // see [af97f24d528acab89969d6541d83f17ce1ecd580] that introduced the removal of setjmp() and longjmp()
2137 - (void)terminate:(id)sender
2138 {
2139     [self activateIgnoringOtherApps:YES];
2140     [self stop:sender];
2141 }
2142
2143 @end