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