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