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