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