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