intf.m 72.2 KB
Newer Older
1
/*****************************************************************************
2
 * intf.m: MacOS X interface module
3
 *****************************************************************************
4
 * Copyright (C) 2002-2012 VLC authors and VideoLAN
5
 * $Id$
6
7
8
 *
 * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
 *          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
14
15
16
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
17
 *
18
19
20
21
22
23
24
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
dionoea's avatar
dionoea committed
25
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26
27
28
29
30
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
31
32
33
34
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

35
36
37
#include <stdlib.h>                                      /* malloc(), free() */
#include <sys/param.h>                                    /* for MAXPATHLEN */
#include <string.h>
hartman's avatar
hartman committed
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
53
#import "prefs.h"
#import "playlist.h"
54
#import "playlistinfo.h"
55
56
57
58
#import "controls.h"
#import "open.h"
#import "wizard.h"
#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 */
Rafaël Carré's avatar
Rafaël Carré committed
72
#import <Sparkle/Sparkle.h>                 /* we're the update delegate */
73

74
75
76
/*****************************************************************************
 * Local prototypes.
 *****************************************************************************/
77
static void Run (intf_thread_t *p_intf);
78

79
80
81
82
static void updateProgressPanel (void *, const char *, float);
static bool checkProgressPanel (void *);
static void destroyProgressPanel (void *);

83
static void MsgCallback(void *data, int type, const msg_item_t *item, const char *format, va_list ap);
84

85
86
87
88
89
90
91
92
93
94
static int InputEvent(vlc_object_t *, const char *,
                      vlc_value_t, vlc_value_t, void *);
static int PLItemChanged(vlc_object_t *, const char *,
                         vlc_value_t, vlc_value_t, void *);
static int PlaylistUpdated(vlc_object_t *, const char *,
                           vlc_value_t, vlc_value_t, void *);
static int PlaybackModeUpdated(vlc_object_t *, const char *,
                               vlc_value_t, vlc_value_t, void *);
static int VolumeUpdated(vlc_object_t *, const char *,
                         vlc_value_t, vlc_value_t, void *);
95

96
#pragma mark -
97
#pragma mark VLC Interface Object Callbacks
98

99
100
101
/*****************************************************************************
 * OpenIntf: initialize interface
 *****************************************************************************/
102
int OpenIntf (vlc_object_t *p_this)
Jérome Decoodt's avatar
Jérome Decoodt committed
103
{
104
105
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
    [VLCApplication sharedApplication];
106

107
108
    intf_thread_t *p_intf = (intf_thread_t*) p_this;

109
110
    p_intf->p_sys = malloc(sizeof(intf_sys_t));
    if (p_intf->p_sys == NULL)
Jean-Paul Saman's avatar
Jean-Paul Saman committed
111
        return VLC_ENOMEM;
112

113
    memset(p_intf->p_sys, 0, sizeof(*p_intf->p_sys));
Jérome Decoodt's avatar
Jérome Decoodt committed
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];
Jean-Paul Saman's avatar
Jean-Paul Saman committed
121
    return VLC_SUCCESS;
122
123
124
125
126
}

/*****************************************************************************
 * CloseIntf: destroy interface
 *****************************************************************************/
127
void CloseIntf (vlc_object_t *p_this)
128
129
{
    intf_thread_t *p_intf = (intf_thread_t*) p_this;
Jérome Decoodt's avatar
Jérome Decoodt committed
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
140
    intf_thread_t *p_intf = VLCIntf;
    if (!p_intf) {
141
        msg_Err(p_wnd, "Mac OS X interface not found");
142
143
        return VLC_EGENERIC;
    }
144
    NSRect proposedVideoViewPosition = NSMakeRect(cfg->x, cfg->y, cfg->width, cfg->height);
145

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    VLCVoutWindowController *o_vout_controller = [[VLCMain sharedInstance] voutController];
    SEL sel = @selector(setupVoutForWindow:withProposedVideoViewPosition:);
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[o_vout_controller methodSignatureForSelector:sel]];
    [inv setTarget:o_vout_controller];
    [inv setSelector:sel];
    [inv setArgument:&p_wnd atIndex:2]; // starting at 2!
    [inv setArgument:&proposedVideoViewPosition atIndex:3];

    [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
                       waitUntilDone:YES];

    VLCVoutView *videoView = nil;
    [inv getReturnValue:&videoView];

    if (!videoView) {
161
        msg_Err(p_wnd, "got no video view from the interface");
162
        [o_pool release];
163
164
165
        return VLC_EGENERIC;
    }

166
167
168
    msg_Dbg(VLCIntf, "returning videoview with proposed position x=%i, y=%i, width=%i, height=%i", cfg->x, cfg->y, cfg->width, cfg->height);
    p_wnd->handle.nsobject = videoView;

169

170
171
172
173
174
175
176
177
178
179
180
181
182
183
    // TODO: find a cleaner way for "start in fullscreen"
    if (var_GetBool(pl_Get(VLCIntf), "fullscreen")) {
        int i_full = 1;

        SEL sel = @selector(setFullscreen:forWindow:);
        NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
        [inv setTarget:[VLCMain sharedInstance]];
        [inv setSelector:sel];
        [inv setArgument:&i_full atIndex:2];
        [inv setArgument:&p_wnd atIndex:3];
        [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
                           waitUntilDone:NO];
    }

184
    [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
185
    p_wnd->control = WindowControl;
186

187
    [o_pool release];
188
189
190
    return VLC_SUCCESS;
}

191
static int WindowControl(vout_window_t *p_wnd, int i_query, va_list args)
192
{
193
    switch(i_query) {
194
195
        case VOUT_WINDOW_SET_STATE:
        {
196
            unsigned i_state = va_arg(args, unsigned);
197
198
199
200
201
202
203
204
205
206
207
208
209
210

            NSInteger i_cooca_level = NSNormalWindowLevel;
            if (i_state & VOUT_WINDOW_STATE_ABOVE)
                i_cooca_level = NSStatusWindowLevel;

            SEL sel = @selector(setWindowLevel:forWindow:);
            NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
            [inv setTarget:[[VLCMain sharedInstance] voutController]];
            [inv setSelector:sel];
            [inv setArgument:&i_cooca_level atIndex:2]; // starting at 2!
            [inv setArgument:&p_wnd atIndex:3];
            [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
                               waitUntilDone:NO];

211
212
213
214
            return VLC_SUCCESS;
        }
        case VOUT_WINDOW_SET_SIZE:
        {
215
216
            NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];

217
218
            unsigned int i_width  = va_arg(args, unsigned int);
            unsigned int i_height = va_arg(args, unsigned int);
219

220
            NSSize newSize = NSMakeSize(i_width, i_height);
221
222
223
224
225
226
227
228
229
230
            SEL sel = @selector(setNativeVideoSize:forWindow:);
            NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[[VLCMain sharedInstance] voutController] methodSignatureForSelector:sel]];
            [inv setTarget:[[VLCMain sharedInstance] voutController]];
            [inv setSelector:sel];
            [inv setArgument:&newSize atIndex:2]; // starting at 2!
            [inv setArgument:&p_wnd atIndex:3];
            [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
                               waitUntilDone:NO];

            [o_pool release];
231
232
233
234
235
            return VLC_SUCCESS;
        }
        case VOUT_WINDOW_SET_FULLSCREEN:
        {
            NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
236
            int i_full = va_arg(args, int);
237
238
239
240
241
242
243
244
245
246

            SEL sel = @selector(setFullscreen:forWindow:);
            NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[[VLCMain sharedInstance] methodSignatureForSelector:sel]];
            [inv setTarget:[VLCMain sharedInstance]];
            [inv setSelector:sel];
            [inv setArgument:&i_full atIndex:2]; // starting at 2!
            [inv setArgument:&p_wnd atIndex:3];
            [inv performSelectorOnMainThread:@selector(invoke) withObject:nil
                               waitUntilDone:NO];

247
248
249
250
            [o_pool release];
            return VLC_SUCCESS;
        }
        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
261
    [[[VLCMain sharedInstance] voutController] performSelectorOnMainThread:@selector(removeVoutforDisplay:) withObject:[NSValue valueWithPointer:p_wnd] waitUntilDone:NO];

262
    [o_pool release];
263
264
}

265
266
267
/*****************************************************************************
 * Run: main loop
 *****************************************************************************/
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

hartman's avatar
-    
hartman committed
279
    [[VLCMain sharedInstance] setIntf: p_intf];
hartman's avatar
hartman committed
280
    [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
281

282
283
    [NSApp run];
    [[VLCMain sharedInstance] applicationWillTerminate:nil];
284
    [o_plItemChangedLock release];
285
    [o_appLock release];
286
    [o_pool release];
287
288

    raise(SIGTERM);
289
290
}

291
292
#pragma mark -
#pragma mark Variables Callback
293

294
295
296
/*****************************************************************************
 * MsgCallback: Callback triggered by the core once a new debug message is
 * 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
305
    if (vasprintf(&str, format, ap) == -1) {
        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
314
    vlc_restorecancel(canc);
    free(str);
315
316
}

317
318
static int InputEvent(vlc_object_t *p_this, const char *psz_var,
                       vlc_value_t oldval, vlc_value_t new_val, void *param)
319
{
320
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
321
322
    switch (new_val.i_int) {
        case INPUT_EVENT_STATE:
323
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
324
325
            break;
        case INPUT_EVENT_RATE:
326
            [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
327
328
            break;
        case INPUT_EVENT_POSITION:
329
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
330
331
332
            break;
        case INPUT_EVENT_TITLE:
        case INPUT_EVENT_CHAPTER:
333
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
334
335
            break;
        case INPUT_EVENT_CACHE:
336
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
337
338
339
340
341
342
343
344
345
346
347
348
349
350
            break;
        case INPUT_EVENT_STATISTICS:
            [[[VLCMain sharedInstance] info] performSelectorOnMainThread:@selector(updateStatistics) withObject: nil waitUntilDone: NO];
            break;
        case INPUT_EVENT_ES:
            break;
        case INPUT_EVENT_TELETEXT:
            break;
        case INPUT_EVENT_AOUT:
            break;
        case INPUT_EVENT_VOUT:
            break;
        case INPUT_EVENT_ITEM_META:
        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
355
356
357
            break;
        case INPUT_EVENT_BOOKMARK:
            break;
        case INPUT_EVENT_RECORD:
358
            [[VLCMain sharedInstance] updateRecordState: var_GetBool(p_this, "record")];
359
360
            break;
        case INPUT_EVENT_PROGRAM:
361
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
362
363
364
365
366
367
368
            break;
        case INPUT_EVENT_ITEM_EPG:
            break;
        case INPUT_EVENT_SIGNAL:
            break;

        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
372
373
374
            break;

        case INPUT_EVENT_AUDIO_DELAY:
        case INPUT_EVENT_SUBTITLE_DELAY:
375
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
376
377
378
            break;

        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
382
383
            break;

        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
387
388
            break;

        default:
389
            //msg_Warn(p_this, "unhandled input event (%lld)", new_val.i_int);
390
            break;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
391
    }
392

393
    [o_pool release];
394
395
396
    return VLC_SUCCESS;
}

397
398
static int PLItemChanged(vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param)
399
{
400
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
401
402
403
404
405
406
407
408

    /* Due to constraints within NSAttributedString's main loop runtime handling
     * and other issues, we need to wait for -PlaylistItemChanged to finish and
     * then -informInputChanged on this non-main thread. */
    [o_plItemChangedLock lock];
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:YES];
    [[VLCMain sharedInstance] informInputChanged];
    [o_plItemChangedLock unlock];
409

410
    [o_pool release];
411
412
413
    return VLC_SUCCESS;
}

414
415
static int PlaylistUpdated(vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param)
416
{
417
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
418
419
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject:nil waitUntilDone:NO];

420
    [o_pool release];
421
422
423
    return VLC_SUCCESS;
}

424
425
static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
                         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
432
433
    return VLC_SUCCESS;
}

434
435
static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
                         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
442
443
444
445
446
447
448
    return VLC_SUCCESS;
}

/*****************************************************************************
 * ShowController: Callback triggered by the show-intf playlist variable
 * through the ShowIntf-control-intf, to let us show the controller-win;
 * usually when in fullscreen-mode
 *****************************************************************************/
449
450
static int ShowController(vlc_object_t *p_this, const char *psz_variable,
                     vlc_value_t old_val, vlc_value_t new_val, void *param)
451
452
{
    intf_thread_t * p_intf = VLCIntf;
453
454
455
456
    if (p_intf && p_intf->p_sys) {
        playlist_t * p_playlist = pl_Get(p_intf);
        BOOL b_fullscreen = var_GetBool(p_playlist, "fullscreen");
        if (strcmp(psz_variable, "intf-toggle-fscontrol") || b_fullscreen)
457
458
459
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
        else
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
460
    }
461
462
463
    return VLC_SUCCESS;
}

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
472
    VLCMain *interface = (VLCMain *)data;

473
    if ([[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"]) {
474
475
476
477
478
479
480
481
        /* the progress panel needs to update itself and therefore wants special treatment within this context */
        dialog_progress_bar_t *p_dialog = (dialog_progress_bar_t *)value.p_address;

        p_dialog->pf_update = updateProgressPanel;
        p_dialog->pf_check = checkProgressPanel;
        p_dialog->pf_destroy = destroyProgressPanel;
        p_dialog->p_sys = VLCIntf->p_libvlc;
    }
482

483
    NSValue *o_value = [NSValue valueWithPointer:value.p_address];
484
    [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
485

486
487
488
    [o_pool release];
    return VLC_SUCCESS;
}
bigben's avatar
bigben committed
489

490
491
492
493
494
void updateProgressPanel (void *priv, const char *text, float value)
{
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];

    NSString *o_txt;
495
    if (text != NULL)
496
497
498
499
500
501
502
503
504
505
506
507
        o_txt = [NSString stringWithUTF8String: text];
    else
        o_txt = @"";

    [[[VLCMain sharedInstance] coreDialogProvider] updateProgressPanelWithText: o_txt andNumber: (double)(value * 1000.)];

    [o_pool release];
}

void destroyProgressPanel (void *priv)
{
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
508
509
510
511

    if ([[NSApplication sharedApplication] isRunning])
        [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:YES];

512
513
514
515
516
517
518
519
520
521
    [o_pool release];
}

bool checkProgressPanel (void *priv)
{
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
    return [[[VLCMain sharedInstance] coreDialogProvider] progressCancelled];
    [o_pool release];
}

522
523
524
525
526
527
#pragma mark -
#pragma mark Helpers

input_thread_t *getInput(void)
{
    intf_thread_t *p_intf = VLCIntf;
528
529
    if (!p_intf)
        return NULL;
530
    return pl_CurrentInput(p_intf);
531
532
533
534
535
}

vout_thread_t *getVout(void)
{
    input_thread_t *p_input = getInput();
536
537
    if (!p_input)
        return NULL;
538
539
540
541
542
    vout_thread_t *p_vout = input_GetVout(p_input);
    vlc_object_release(p_input);
    return p_vout;
}

543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
vout_thread_t *getVoutForActiveWindow(void)
{
    vout_thread_t *p_vout = nil;

    id currentWindow = [NSApp keyWindow];
    if ([currentWindow respondsToSelector:@selector(videoView)]) {
        VLCVoutView *videoView = [currentWindow videoView];
        if (videoView) {
            p_vout = [videoView voutThread];
        }
    }

    if (!p_vout)
        p_vout = getVout();

    return p_vout;
}

561
audio_output_t *getAout(void)
562
{
563
564
    intf_thread_t *p_intf = VLCIntf;
    if (!p_intf)
565
        return NULL;
566
    return playlist_GetAout(pl_Get(p_intf));
567
568
}

569
#pragma mark -
570
571
572
#pragma mark Private

@interface VLCMain ()
573
574
575
576
577
578
579
- (void)removeOldPreferences;
@end

@interface VLCMain (Internal)
- (void)handlePortMessage:(NSPortMessage *)o_msg;
- (void)resetMediaKeyJump;
- (void)coreChangedMediaKeySupportSetting: (NSNotification *)o_notification;
580
@end
581

582
/*****************************************************************************
Jérome Decoodt's avatar
Jérome Decoodt committed
583
 * VLCMain implementation
584
585
586
 *****************************************************************************/
@implementation VLCMain

587
@synthesize voutController=o_vout_controller;
588
@synthesize nativeFullscreenMode=b_nativeFullscreenMode;
589

590
591
592
#pragma mark -
#pragma mark Initialization

hartman's avatar
hartman committed
593
594
595
596
597
598
599
static VLCMain *_o_sharedMainInstance = nil;

+ (VLCMain *)sharedInstance
{
    return _o_sharedMainInstance ? _o_sharedMainInstance : [[self alloc] init];
}

Jérome Decoodt's avatar
Jérome Decoodt committed
600
- (id)init
hartman's avatar
hartman committed
601
{
602
    if (_o_sharedMainInstance) {
hartman's avatar
hartman committed
603
        [self dealloc];
604
        return _o_sharedMainInstance;
605
    } else
hartman's avatar
hartman committed
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
623
624
625
626

    /* announce our launch to a potential eyetv plugin */
    [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
                                                                   object: @"VLCEyeTVSupport"
                                                                 userInfo: NULL
                                                       deliverImmediately: YES];
627
628
629
630
631

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"LiveUpdateTheMessagesPanel"];
    [defaults registerDefaults:appDefaults];

632
633
    o_vout_controller = [[VLCVoutWindowController alloc] init];

hartman's avatar
hartman committed
634
635
636
    return _o_sharedMainInstance;
}

637
638
- (void)setIntf: (intf_thread_t *)p_mainintf
{
hartman's avatar
hartman committed
639
640
641
    p_intf = p_mainintf;
}

642
643
- (intf_thread_t *)intf
{
hartman's avatar
hartman committed
644
645
646
    return p_intf;
}

647
648
- (void)awakeFromNib
{
649
    playlist_t *p_playlist;
650
    vlc_value_t val;
651
652
    if (!p_intf) return;
    var_Create(p_intf, "intf-change", VLC_VAR_BOOL);
653

654
655
    /* Check if we already did this once. Opening the other nibs calls it too,
     because VLCMain is the owner */
656
657
    if (nib_main_loaded)
        return;
658

659
660
    [o_msgs_panel setExcludedFromWindowsMenu: YES];
    [o_msgs_panel setDelegate: self];
661

662
    p_playlist = pl_Get(p_intf);
hartman's avatar
hartman committed
663

664
    val.b_bool = false;
bigben's avatar
bigben committed
665

666
667
    var_AddCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
    var_AddCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
668
    //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
669
670
671
672
673
674
675
676
677
    var_AddCallback(p_playlist, "activity", PLItemChanged, self);
    var_AddCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
    var_AddCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
    var_AddCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
    var_AddCallback(p_playlist, "random", PlaybackModeUpdated, self);
    var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
    var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, self);
    var_AddCallback(p_playlist, "volume", VolumeUpdated, self);
    var_AddCallback(p_playlist, "mute", VolumeUpdated, self);
bigben's avatar
bigben committed
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
690
691
692
693
694
695
696
697
698
699
    var_Create(p_intf, "dialog-error", VLC_VAR_ADDRESS);
    var_AddCallback(p_intf, "dialog-error", DialogCallback, self);
    var_Create(p_intf, "dialog-critical", VLC_VAR_ADDRESS);
    var_AddCallback(p_intf, "dialog-critical", DialogCallback, self);
    var_Create(p_intf, "dialog-login", VLC_VAR_ADDRESS);
    var_AddCallback(p_intf, "dialog-login", DialogCallback, self);
    var_Create(p_intf, "dialog-question", VLC_VAR_ADDRESS);
    var_AddCallback(p_intf, "dialog-question", DialogCallback, self);
    var_Create(p_intf, "dialog-progress-bar", VLC_VAR_ADDRESS);
    var_AddCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
    dialog_Register(p_intf);
700

701
702
703
704
705
    /* init Apple Remote support */
    o_remote = [[AppleRemote alloc] init];
    [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
    [o_remote setDelegate: _o_sharedMainInstance];

706
    [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
707

708
    /* yeah, we are done */
709
710
    b_nativeFullscreenMode = NO;
#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
716

    /* recover stored audio device, if set
     * in case it was unplugged in the meantime, auhal will fall back on the default */
717
    int i_value = config_GetInt(p_intf, "macosx-audio-device");
718
    if (i_value > 0)
719
        var_SetInteger(pl_Get(VLCIntf), "audio-device", i_value);
720

721
    if (config_GetInt(VLCIntf, "macosx-icon-change")) {
722
723
724
725
726
727
728
729
730
731
732
733
734
        /* After day 354 of the year, the usual VLC cone is replaced by another cone
         * wearing a Father Xmas hat.
         * Note: this icon doesn't represent an endorsement of The Coca-Cola Company.
         */
        NSCalendar *gregorian =
        [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
        [gregorian release];

        if (dayOfYear >= 354)
            [[VLCApplication sharedApplication] setApplicationIconImage: [NSImage imageNamed:@"vlc-xmas"]];
    }

735
736
    [self initStrings];

737
    nib_main_loaded = TRUE;
738
739
}

740
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
741
{
742
743
    if (!p_intf)
        return;
744

745
746
    [self updateCurrentlyUsedHotkeys];

747
    /* init media key support */
748
749
    b_mediaKeySupport = var_InheritBool(VLCIntf, "macosx-mediakeys");
    if (b_mediaKeySupport) {
750
751
752
753
754
755
        o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
        [o_mediaKeyController startWatchingMediaKeys];
        [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
                                                                 nil]];
    }
756
757
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];

758
    [self removeOldPreferences];
759

760
761
762
763
    /* Handle sleep notification */
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
           name:NSWorkspaceWillSleepNotification object:nil];

764
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(lookForCrashLog) withObject:nil waitUntilDone:NO];
765

766
767
    /* we will need this, so let's load it here so the interface appears to be more responsive */
    nib_open_loaded = [NSBundle loadNibNamed:@"Open" owner: NSApp];
768
769
770
771
772

    /* update the main window */
    [o_mainwindow updateWindow];
    [o_mainwindow updateTimeSlider];
    [o_mainwindow updateVolumeSlider];
773
774
}

hartman's avatar
hartman committed
775
- (void)initStrings
776
{
777
778
    if (!p_intf)
        return;
779

Jérome Decoodt's avatar
Jérome Decoodt committed
780
    /* messages panel */
781
    [o_msgs_panel setTitle: _NS("Messages")];
782
783
    [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
    [o_msgs_save_btn setTitle: _NS("Save this Log...")];
784

785
786
787
788
789
790
    /* crash reporter panel */
    [o_crashrep_send_btn setTitle: _NS("Send")];
    [o_crashrep_dontSend_btn setTitle: _NS("Don't Send")];
    [o_crashrep_title_txt setStringValue: _NS("VLC crashed previously")];
    [o_crashrep_win setTitle: _NS("VLC crashed previously")];
    [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, ...")];
791
792
    [o_crashrep_includeEmail_ckb setTitle: _NS("I agree to be possibly contacted about this bugreport.")];
    [o_crashrep_includeEmail_txt setStringValue: _NS("Only your default E-Mail address will be submitted, including no further information.")];
793
    [o_crashrep_dontaskagain_ckb setTitle: _NS("Don't ask again")];
794
795
}

796
797
798
799
#pragma mark -
#pragma mark Termination

- (void)applicationWillTerminate:(NSNotification *)notification
800
{
801
802
    /* don't allow a double termination call. If the user has
     * already invoked the quit then simply return this time. */
803
804
    static bool f_appExit = false;
    bool isTerminating;
805
806

    [o_appLock lock];
807
808
    isTerminating = f_appExit;
    f_appExit = true;
809
810
811
812
    [o_appLock unlock];

    if (isTerminating)
        return;
813

814
815
    if (notification == nil)
        [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
816

817
    playlist_t * p_playlist = pl_Get(p_intf);
818
819
    int returnedValue = 0;

820
    /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
821
    if (b_nativeFullscreenMode) {
822
823
824
825
        [o_mainwindow toggleFullScreen: self];
        [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
    }

826
    /* save current video and audio profiles */
827
    [[VLCVideoEffects sharedInstance] saveCurrentProfile];
828
    [[VLCAudioEffects sharedInstance] saveCurrentProfile];
829

830
    /* Save some interface state in configuration, at module quit */
831
832
833
    config_PutInt(p_intf, "random", var_GetBool(p_playlist, "random"));
    config_PutInt(p_intf, "loop", var_GetBool(p_playlist, "loop"));
    config_PutInt(p_intf, "repeat", var_GetBool(p_playlist, "repeat"));
834

835
    msg_Dbg(p_intf, "Terminating");
836

837
    /* unsubscribe from the interactive dialogues */
838
839
840
841
842
843
    dialog_Unregister(p_intf);
    var_DelCallback(p_intf, "dialog-error", DialogCallback, self);
    var_DelCallback(p_intf, "dialog-critical", DialogCallback, self);
    var_DelCallback(p_intf, "dialog-login", DialogCallback, self);
    var_DelCallback(p_intf, "dialog-question", DialogCallback, self);
    var_DelCallback(p_intf, "dialog-progress-bar", DialogCallback, self);
844
845
846
847
848
849
850
851
852
853
    //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
    var_DelCallback(p_playlist, "activity", PLItemChanged, self);
    var_DelCallback(p_playlist, "leaf-to-parent", PlaylistUpdated, self);
    var_DelCallback(p_playlist, "playlist-item-append", PlaylistUpdated, self);
    var_DelCallback(p_playlist, "playlist-item-deleted", PlaylistUpdated, self);
    var_DelCallback(p_playlist, "random", PlaybackModeUpdated, self);
    var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, self);
    var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, self);
    var_DelCallback(p_playlist, "volume", VolumeUpdated, self);
    var_DelCallback(p_playlist, "mute", VolumeUpdated, self);
854
    var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
855
    var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
856

857
858
859
    if (p_current_input) {
        var_DelCallback(p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance]);
        vlc_object_release(p_current_input);
860
        p_current_input = NULL;
861
862
    }

863
864
    /* remove global observer watching for vout device changes correctly */
    [[NSNotificationCenter defaultCenter] removeObserver: self];
Jérome Decoodt's avatar
Jérome Decoodt committed
865

866
867
868
869
    // release before o_info!
    [o_vout_controller release];
    o_vout_controller = nil;

870
871
    /* release some other objects here, because it isn't sure whether dealloc
     * will be called later on */
872
    if (o_sprefs)