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