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