intf.m 75.3 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 12 13 14 15
 *
 * 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.
16
 *
17 18 19 20 21 22 23
 * 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
Antoine Cellerier's avatar
Antoine Cellerier committed
24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 26 27 28 29
 *****************************************************************************/

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

34 35 36
#include <stdlib.h>                                      /* malloc(), free() */
#include <sys/param.h>                                    /* for MAXPATHLEN */
#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 <unistd.h> /* execl() */
46

47
#import "CompatibilityFixes.h"
48
#import "intf.h"
49
#import "MainMenu.h"
50
#import "VideoView.h"
51 52
#import "prefs.h"
#import "playlist.h"
53
#import "playlistinfo.h"
54 55 56 57
#import "controls.h"
#import "open.h"
#import "wizard.h"
#import "bookmarks.h"
58
#import "coredialogs.h"
59
#import "AppleRemote.h"
60
#import "eyetv.h"
61
#import "simple_prefs.h"
62
#import "CoreInteraction.h"
63
#import "TrackSynchronization.h"
64

65
#import <AddressBook/AddressBook.h>         /* for crashlog send mechanism */
66
#import <Sparkle/Sparkle.h>                 /* we're the update delegate */
67

68 69 70
/*****************************************************************************
 * Local prototypes.
 *****************************************************************************/
71
static void Run ( intf_thread_t *p_intf );
72

73 74 75 76
static void updateProgressPanel (void *, const char *, float);
static bool checkProgressPanel (void *);
static void destroyProgressPanel (void *);

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

79 80 81 82 83 84 85 86 87 88 89
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 * );

90
#pragma mark -
91
#pragma mark VLC Interface Object Callbacks
92

93 94 95
/*****************************************************************************
 * OpenIntf: initialize interface
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
96
int OpenIntf ( vlc_object_t *p_this )
Jérome Decoodt's avatar
Jérome Decoodt committed
97
{
98 99
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
    [VLCApplication sharedApplication];
100

101 102 103 104
    intf_thread_t *p_intf = (intf_thread_t*) p_this;

    p_intf->p_sys = malloc( sizeof( intf_sys_t ) );
    if( p_intf->p_sys == NULL )
Jean-Paul Saman's avatar
Jean-Paul Saman committed
105
        return VLC_ENOMEM;
106 107

    memset( p_intf->p_sys, 0, sizeof( *p_intf->p_sys ) );
Jérome Decoodt's avatar
Jérome Decoodt committed
108

109
    /* subscribe to LibVLCCore's messages */
110
    vlc_Subscribe( &p_intf->p_sys->sub, MsgCallback, NULL );
111 112

    Run( p_intf );
113

114
    [o_pool release];
Jean-Paul Saman's avatar
Jean-Paul Saman committed
115
    return VLC_SUCCESS;
116 117 118 119 120
}

/*****************************************************************************
 * CloseIntf: destroy interface
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
121
void CloseIntf ( vlc_object_t *p_this )
122 123
{
    intf_thread_t *p_intf = (intf_thread_t*) p_this;
Jérome Decoodt's avatar
Jérome Decoodt committed
124

125 126 127
    free( p_intf->p_sys );
}

128 129 130 131
static int WindowControl( vout_window_t *, int i_query, va_list );

int WindowOpen( vout_window_t *p_wnd, const vout_window_cfg_t *cfg )
{
132
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
133 134 135 136 137 138 139 140 141 142 143 144 145 146
    intf_thread_t *p_intf = VLCIntf;
    if (!p_intf) {
        msg_Err( p_wnd, "Mac OS X interface not found" );
        return VLC_EGENERIC;
    }

    int i_x = cfg->x;
    int i_y = cfg->y;
    unsigned i_width = cfg->width;
    unsigned i_height = cfg->height;
    p_wnd->handle.nsobject = [[VLCMain sharedInstance] getVideoViewAtPositionX: &i_x Y: &i_y withWidth: &i_width andHeight: &i_height];

    if ( !p_wnd->handle.nsobject ) {
        msg_Err( p_wnd, "got no video view from the interface" );
147
        [o_pool release];
148 149 150
        return VLC_EGENERIC;
    }

151
    [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( cfg->width, cfg->height )];
152
    [[VLCMain sharedInstance] setActiveVideoPlayback: YES];
153 154
    p_wnd->control = WindowControl;
    p_wnd->sys = (vout_window_sys_t *)VLCIntf;
155
    [o_pool release];
156 157 158 159 160 161 162
    return VLC_SUCCESS;
}

static int WindowControl( vout_window_t *p_wnd, int i_query, va_list args )
{
    /* TODO */
    if( i_query == VOUT_WINDOW_SET_STATE )
163
        msg_Dbg( p_wnd, "WindowControl:VOUT_WINDOW_SET_STATE" );
164
    else if( i_query == VOUT_WINDOW_SET_SIZE )
165 166 167 168 169
    {
        unsigned int i_width  = va_arg( args, unsigned int );
        unsigned int i_height = va_arg( args, unsigned int );
        [[VLCMain sharedInstance] setNativeVideoSize:NSMakeSize( i_width, i_height )];
    }
170
    else if( i_query == VOUT_WINDOW_SET_FULLSCREEN )
171 172
    {
        NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
173 174
        // we already have our playlist "fullscreen" callback, do not repeat the same call here
        //[[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject: nil waitUntilDone: NO];
175 176
        [o_pool release];
    }
177
    else
178
        msg_Dbg( p_wnd, "WindowControl: unknown query" );
179 180 181 182 183
    return VLC_SUCCESS;
}

void WindowClose( vout_window_t *p_wnd )
{
184
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
185
    [[VLCMain sharedInstance] setActiveVideoPlayback:NO];
186

187
    [o_pool release];
188 189
}

190 191 192
/*****************************************************************************
 * Run: main loop
 *****************************************************************************/
193
static NSLock * o_appLock = nil;    // controls access to f_appExit
194

195 196
static void Run( intf_thread_t *p_intf )
{
197
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
198
    [VLCApplication sharedApplication];
199

200 201
    o_appLock = [[NSLock alloc] init];

Derk-Jan Hartman's avatar
-  
Derk-Jan Hartman committed
202
    [[VLCMain sharedInstance] setIntf: p_intf];
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
203
    [NSBundle loadNibNamed: @"MainMenu" owner: NSApp];
204

205 206
    [NSApp run];
    [[VLCMain sharedInstance] applicationWillTerminate:nil];
207
    [o_appLock release];
208
    [o_pool release];
209 210

    raise(SIGTERM);
211 212
}

213 214
#pragma mark -
#pragma mark Variables Callback
215

216 217 218
/*****************************************************************************
 * 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
219
 * of this file.
220
 *****************************************************************************/
221
static void MsgCallback( void *data, int type, const msg_item_t *item, const char *format, va_list ap )
222 223
{
    int canc = vlc_savecancel();
224
    char *str;
225

226
    if (vasprintf( &str, format, ap ) == -1)
227 228
    {
        vlc_restorecancel( canc );
229
        return;
230
    }
231

232
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
233
    [[VLCMain sharedInstance] processReceivedlibvlcMessage: item ofType: type withStr: str];
234
    [o_pool release];
235

236
    vlc_restorecancel( canc );
237
    free( str );
238 239
}

240 241
static int InputEvent( vlc_object_t *p_this, const char *psz_var,
                       vlc_value_t oldval, vlc_value_t new_val, void *param )
242
{
243
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
244 245
    switch (new_val.i_int) {
        case INPUT_EVENT_STATE:
246
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackStatusUpdated) withObject: nil waitUntilDone:NO];
247 248
            break;
        case INPUT_EVENT_RATE:
249
            [[[VLCMain sharedInstance] mainMenu] performSelectorOnMainThread:@selector(updatePlaybackRate) withObject: nil waitUntilDone:NO];
250 251
            break;
        case INPUT_EVENT_POSITION:
252
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject: nil waitUntilDone:NO];
253 254 255
            break;
        case INPUT_EVENT_TITLE:
        case INPUT_EVENT_CHAPTER:
256
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
257 258
            break;
        case INPUT_EVENT_CACHE:
259
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainWindow) withObject: nil waitUntilDone: NO];
260 261 262 263 264 265 266 267 268 269 270 271 272 273
            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:
274
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
275
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
276
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateInfoandMetaPanel) withObject: nil waitUntilDone:NO];
277 278 279 280
            break;
        case INPUT_EVENT_BOOKMARK:
            break;
        case INPUT_EVENT_RECORD:
281
            [[VLCMain sharedInstance] updateRecordState: var_GetBool( p_this, "record" )];
282 283
            break;
        case INPUT_EVENT_PROGRAM:
284
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateMainMenu) withObject: nil waitUntilDone:NO];
285 286 287 288 289 290 291
            break;
        case INPUT_EVENT_ITEM_EPG:
            break;
        case INPUT_EVENT_SIGNAL:
            break;

        case INPUT_EVENT_ITEM_NAME:
292
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
293
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playlistUpdated) withObject: nil waitUntilDone:NO];
294 295 296 297
            break;

        case INPUT_EVENT_AUDIO_DELAY:
        case INPUT_EVENT_SUBTITLE_DELAY:
298
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateDelays) withObject:nil waitUntilDone:NO];
299 300 301
            break;

        case INPUT_EVENT_DEAD:
302
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
303
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
304 305 306
            break;

        case INPUT_EVENT_ABORT:
307
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateName) withObject: nil waitUntilDone:NO];
308
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updatePlaybackPosition) withObject:nil waitUntilDone:NO];
309 310 311 312 313
            break;

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

316
    [o_pool release];
317 318 319 320 321 322
    return VLC_SUCCESS;
}

static int PLItemChanged( vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param )
{
323
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
324 325
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(PlaylistItemChanged) withObject:nil waitUntilDone:NO];

326
    [o_pool release];
327 328 329 330 331 332
    return VLC_SUCCESS;
}

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

336
    [o_pool release];
337 338 339 340 341 342
    return VLC_SUCCESS;
}

static int PlaybackModeUpdated( vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param )
{
343
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
344
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
345

346
    [o_pool release];
347 348 349 350 351 352
    return VLC_SUCCESS;
}

static int VolumeUpdated( vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param )
{
353
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
354
    [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(updateVolume) withObject:nil waitUntilDone:NO];
355

356
    [o_pool release];
357 358 359 360 361 362 363 364 365 366 367 368
    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
 *****************************************************************************/
static int ShowController( vlc_object_t *p_this, const char *psz_variable,
                     vlc_value_t old_val, vlc_value_t new_val, void *param )
{
    intf_thread_t * p_intf = VLCIntf;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
369
    if( p_intf && p_intf->p_sys )
370
    {
371 372 373 374 375 376 377 378 379 380
        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 )
        {
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showFullscreenController) withObject:nil waitUntilDone:NO];
        }
        else
        {
            [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(showMainWindow) withObject:nil waitUntilDone:NO];
        }
381
    }
382 383 384
    return VLC_SUCCESS;
}

385 386 387 388
/*****************************************************************************
 * FullscreenChanged: Callback triggered by the fullscreen-change playlist
 * variable, to let the intf update the controller.
 *****************************************************************************/
389
static int FullscreenChanged( vlc_object_t *p_this, const char *psz_variable,
390 391 392
                     vlc_value_t old_val, vlc_value_t new_val, void *param )
{
    intf_thread_t * p_intf = VLCIntf;
393 394 395
    if (p_intf)
    {
        NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];
396
        [[VLCMain sharedInstance] performSelectorOnMainThread:@selector(fullscreenChanged) withObject:nil waitUntilDone:NO];
397 398
        [o_pool release];
    }
399 400 401
    return VLC_SUCCESS;
}

402
/*****************************************************************************
403
 * DialogCallback: Callback triggered by the "dialog-*" variables
404
 * to let the intf display error and interaction dialogs
405
 *****************************************************************************/
406
static int DialogCallback( vlc_object_t *p_this, const char *type, vlc_value_t previous, vlc_value_t value, void *data )
407 408
{
    NSAutoreleasePool * o_pool = [[NSAutoreleasePool alloc] init];
409 410
    VLCMain *interface = (VLCMain *)data;

411 412 413 414 415 416 417 418 419 420
    if( [[NSString stringWithUTF8String: type] isEqualToString: @"dialog-progress-bar"] )
    {
        /* 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;
    }
421

422
    NSValue *o_value = [NSValue valueWithPointer:value.p_address];
423
    [[VLCCoreDialogProvider sharedInstance] performEventWithObject: o_value ofType: type];
424

425 426 427
    [o_pool release];
    return VLC_SUCCESS;
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
void updateProgressPanel (void *priv, const char *text, float value)
{
    NSAutoreleasePool *o_pool = [[NSAutoreleasePool alloc] init];

    NSString *o_txt;
    if( text != NULL )
        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];
447
    [[[VLCMain sharedInstance] coreDialogProvider] performSelectorOnMainThread:@selector(destroyProgressPanel) withObject:nil waitUntilDone:NO];
448 449 450 451 452 453 454 455 456 457
    [o_pool release];
}

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

458 459 460 461 462 463
#pragma mark -
#pragma mark Helpers

input_thread_t *getInput(void)
{
    intf_thread_t *p_intf = VLCIntf;
464 465
    if (!p_intf)
        return NULL;
466
    return pl_CurrentInput(p_intf);
467 468 469 470 471
}

vout_thread_t *getVout(void)
{
    input_thread_t *p_input = getInput();
472 473
    if (!p_input)
        return NULL;
474 475 476 477 478
    vout_thread_t *p_vout = input_GetVout(p_input);
    vlc_object_release(p_input);
    return p_vout;
}

479
audio_output_t *getAout(void)
480 481
{
    input_thread_t *p_input = getInput();
482 483
    if (!p_input)
        return NULL;
484
    audio_output_t *p_aout = input_GetAout(p_input);
485 486 487 488
    vlc_object_release(p_input);
    return p_aout;
}

489
#pragma mark -
490 491 492 493 494
#pragma mark Private

@interface VLCMain ()
- (void)_removeOldPreferences;
@end
495

496
/*****************************************************************************
Jérome Decoodt's avatar
Jérome Decoodt committed
497
 * VLCMain implementation
498 499 500
 *****************************************************************************/
@implementation VLCMain

501 502 503
#pragma mark -
#pragma mark Initialization

Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
504 505 506 507 508 509 510
static VLCMain *_o_sharedMainInstance = nil;

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

Jérome Decoodt's avatar
Jérome Decoodt committed
511
- (id)init
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
512
{
513
    if( _o_sharedMainInstance)
514
    {
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
515
        [self dealloc];
516
        return _o_sharedMainInstance;
517
    }
518
    else
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
519
        _o_sharedMainInstance = [super init];
520

521
    p_intf = NULL;
522
    p_current_input = NULL;
523

524
    o_msg_lock = [[NSLock alloc] init];
525
    o_msg_arr = [[NSMutableArray arrayWithCapacity: 600] retain];
526

527
    o_open = [[VLCOpen alloc] init];
528
    //o_embedded_list = [[VLCEmbeddedList alloc] init];
529
    o_coredialogs = [[VLCCoreDialogProvider alloc] init];
530
    o_info = [[VLCInfo alloc] init];
531
    o_mainmenu = [[VLCMainMenu alloc] init];
532
    o_coreinteraction = [[VLCCoreInteraction alloc] init];
533
    o_eyetv = [[VLCEyeTVController alloc] init];
534
    o_mainwindow = [[VLCMainWindow alloc] init];
535 536 537 538 539 540

    /* announce our launch to a potential eyetv plugin */
    [[NSDistributedNotificationCenter defaultCenter] postNotificationName: @"VLCOSXGUIInit"
                                                                   object: @"VLCEyeTVSupport"
                                                                 userInfo: NULL
                                                       deliverImmediately: YES];
541 542 543 544 545

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

Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
546 547 548 549 550 551 552
    return _o_sharedMainInstance;
}

- (void)setIntf: (intf_thread_t *)p_mainintf {
    p_intf = p_mainintf;
}

553
- (intf_thread_t *)intf {
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
554 555 556
    return p_intf;
}

557 558
- (void)awakeFromNib
{
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 565 566 567
    /* Check if we already did this once. Opening the other nibs calls it too,
     because VLCMain is the owner */
    if( nib_main_loaded ) return;

568 569
    [o_msgs_panel setExcludedFromWindowsMenu: YES];
    [o_msgs_panel setDelegate: self];
570

571
    p_playlist = pl_Get( p_intf );
572

573
    val.b_bool = false;
574

575
    var_AddCallback(p_playlist, "fullscreen", FullscreenChanged, self);
576
    var_AddCallback( p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
577 578
    var_AddCallback( p_intf->p_libvlc, "intf-show", ShowController, self);
    //    var_AddCallback(p_playlist, "item-change", PLItemChanged, self);
579 580 581 582 583 584 585 586 587 588
    var_AddCallback(p_playlist, "item-current", PLItemChanged, self);
    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);
589

590 591
    if (OSX_LION)
    {
592
        if ([NSApp currentSystemPresentationOptions] & NSApplicationPresentationFullScreen)
593 594
            var_SetBool( p_playlist, "fullscreen", YES );
    }
595

596 597
    /* load our Core Dialogs nib */
    nib_coredialogs_loaded = [NSBundle loadNibNamed:@"CoreDialogs" owner: NSApp];
598

599
    /* subscribe to various interactive dialogues */
600 601 602 603
    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 );
604 605 606 607 608 609
    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 );
610
    dialog_Register( p_intf );
611

612 613 614 615 616
    /* init Apple Remote support */
    o_remote = [[AppleRemote alloc] init];
    [o_remote setClickCountEnabledButtons: kRemoteButtonPlay];
    [o_remote setDelegate: _o_sharedMainInstance];

617
    [o_msgs_refresh_btn setImage: [NSImage imageNamed: NSImageNameRefreshTemplate]];
618

619
     BOOL b_video_deco = config_GetInt( VLCIntf, "video-deco" );
620
    /* yeah, we are done */
621 622
    b_nativeFullscreenMode = NO;
#ifdef MAC_OS_X_VERSION_10_7
623
    if( OSX_LION && b_video_deco )
624
        b_nativeFullscreenMode = config_GetInt( p_intf, "macosx-nativefullscreenmode" );
625
#endif
626 627 628 629 630 631 632

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

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
    if (config_GetInt( VLCIntf, "macosx-icon-change"))
    {
        /* 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"]];
    }

648
    nib_main_loaded = TRUE;
649 650
}

651
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
652
{
653 654
    if( !p_intf ) return;

655 656
    [self updateCurrentlyUsedHotkeys];

657 658 659 660 661
    [o_mainwindow updateWindow];
    [o_mainwindow updateTimeSlider];
    [o_mainwindow updateVolumeSlider];
    [o_mainwindow makeKeyAndOrderFront: self];

662 663
    /* init media key support */
    b_mediaKeySupport = config_GetInt( VLCIntf, "macosx-mediakeys" );
664 665 666 667 668 669 670 671
    if( b_mediaKeySupport )
    {
        o_mediaKeyController = [[SPMediaKeyTap alloc] initWithDelegate:self];
        [o_mediaKeyController startWatchingMediaKeys];
        [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                 [SPMediaKeyTap defaultMediaKeyUserBundleIdentifiers], kMediaKeyUsingBundleIdentifiersDefaultsKey,
                                                                 nil]];
    }
672 673
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(coreChangedMediaKeySupportSetting:) name: @"VLCMediaKeySupportSettingChanged" object: nil];

674 675
    [self _removeOldPreferences];

676 677 678 679
    /* Handle sleep notification */
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(computerWillSleep:)
           name:NSWorkspaceWillSleepNotification object:nil];

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

682 683
    /* 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];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
684
    [self initStrings];
685 686
}

687
- (void)initStrings
688
{
689 690
    if( !p_intf ) return;

Jérome Decoodt's avatar
Jérome Decoodt committed
691
    /* messages panel */
692
    [o_msgs_panel setTitle: _NS("Messages")];
693 694
    [o_msgs_crashlog_btn setTitle: _NS("Open CrashLog...")];
    [o_msgs_save_btn setTitle: _NS("Save this Log...")];
695

696 697 698 699 700 701
    /* 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, ...")];
702 703
    [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.")];
704 705
}

706 707 708 709
#pragma mark -
#pragma mark Termination

- (void)applicationWillTerminate:(NSNotification *)notification
710
{
711 712
    /* don't allow a double termination call. If the user has
     * already invoked the quit then simply return this time. */
713 714
    static bool f_appExit = false;
    bool isTerminating;
715 716

    [o_appLock lock];
717 718
    isTerminating = f_appExit;
    f_appExit = true;
719 720 721 722
    [o_appLock unlock];

    if (isTerminating)
        return;
723

724 725
    if (notification == nil)
        [[NSNotificationCenter defaultCenter] postNotificationName: NSApplicationWillTerminateNotification object: nil];
726

727
    playlist_t * p_playlist = pl_Get( p_intf );
728 729
    int returnedValue = 0;

730
    /* always exit fullscreen on quit, otherwise we get ugly artifacts on the next launch */
731
    if (b_nativeFullscreenMode)
732 733 734 735 736
    {
        [o_mainwindow toggleFullScreen: self];
        [NSApp setPresentationOptions:(NSApplicationPresentationDefault)];
    }

737 738 739 740 741 742
    /* Save some interface state in configuration, at module quit */
    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" ) );

    msg_Dbg( p_intf, "Terminating" );
743

744 745
    /* unsubscribe from the interactive dialogues */
    dialog_Unregister( p_intf );
746 747
    var_DelCallback( p_intf, "dialog-error", DialogCallback, self );
    var_DelCallback( p_intf, "dialog-critical", DialogCallback, self );
748 749 750
    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 );
751 752 753 754 755 756 757 758 759 760 761
    //var_DelCallback(p_playlist, "item-change", PLItemChanged, self);
    var_DelCallback(p_playlist, "item-current", 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);
762 763
    var_DelCallback(p_playlist, "fullscreen", FullscreenChanged, self);
    var_DelCallback(p_intf->p_libvlc, "intf-toggle-fscontrol", ShowController, self);
764
    var_DelCallback(p_intf->p_libvlc, "intf-show", ShowController, self);
765

766
    if( p_current_input )
767
    {
768 769 770
        var_DelCallback( p_current_input, "intf-event", InputEvent, [VLCMain sharedInstance] );
        vlc_object_release( p_current_input );
        p_current_input = NULL;
771 772
    }

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

776 777
    /* release some other objects here, because it isn't sure whether dealloc
     * will be called later on */
778
    if( o_sprefs )
779 780
        [o_sprefs release];

781 782
    if( o_prefs )
        [o_prefs release];
783

784
    [o_open release];
785 786 787

    if( o_info )
        [o_info release];
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
788

789
    if( o_wizard )
790 791 792 793
        [o_wizard release];

    [crashLogURLConnection cancel];
    [crashLogURLConnection release];
794

795
    [o_embedded_list release];
796
    [o_coredialogs release];
797 798
    [o_eyetv release];

799
    /* unsubscribe from libvlc's debug messages */
800
    vlc_Unsubscribe( &p_intf->p_sys->sub );
801

802 803
    [o_msg_arr removeAllObjects];
    [o_msg_arr release];
804
    o_msg_arr = NULL;
805 806
    [o_usedHotkeys release];
    o_usedHotkeys = NULL;
807 808 809 810 811 812

    [o_msg_lock release];

    /* write cached user defaults to disk */
    [[NSUserDefaults standardUserDefaults] synchronize];

813
    /* Make sure the Menu doesn't have any references to vlc objects anymore */
814 815
    //FIXME: this should be moved to VLCMainMenu
    [o_mainmenu releaseRepresentedObjects:[NSApp mainMenu]];
816
    [o_mainmenu release];
817

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
818
    libvlc_Quit( p_intf->p_libvlc );
819

820 821 822
    [o_mainwindow release];
    o_mainwindow = NULL;

823
    [self setIntf:nil];
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
824 825
}

826 827 828 829 830
#pragma mark -
#pragma mark Sparkle delegate
/* received directly before the update gets installed, so let's shut down a bit */
- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
{
831
    [NSApp activateIgnoringOtherApps:YES];
832
    [o_remote stopListening: self];
833
    [[VLCCoreInteraction sharedInstance] stop];
834 835
}

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
#pragma mark -
#pragma mark Media Key support

-(void)mediaKeyTap:(SPMediaKeyTap*)keyTap receivedMediaKeyEvent:(NSEvent*)event
{
    if( b_mediaKeySupport )
       {
        assert([event type] == NSSystemDefined && [event subtype] == SPSystemDefinedEventMediaKeys);

        int keyCode = (([event data1] & 0xFFFF0000) >> 16);
        int keyFlags = ([event data1] & 0x0000FFFF);
        int keyState = (((keyFlags & 0xFF00) >> 8)) == 0xA;
        int keyRepeat = (keyFlags & 0x1);

        if( keyCode == NX_KEYTYPE_PLAY && keyState == 0 )
851
            [[VLCCoreInteraction sharedInstance] play];
852

853
        if( (keyCode == NX_KEYTYPE_FAST || keyCode == NX_KEYTYPE_NEXT) && !b_mediakeyJustJumped )
854 855
        {
            if( keyState == 0 && keyRepeat == 0 )
856
                [[VLCCoreInteraction sharedInstance] next];
857 858
            else if( keyRepeat == 1 )
            {
859
                [[VLCCoreInteraction sharedInstance] forwardShort];
860 861 862 863 864 865 866
                b_mediakeyJustJumped = YES;
                [self performSelector:@selector(resetMediaKeyJump)
                           withObject: NULL
                           afterDelay:0.25];
            }
        }

867
        if( (keyCode == NX_KEYTYPE_REWIND || keyCode == NX_KEYTYPE_PREVIOUS) && !b_mediakeyJustJumped )
868 869
        {
            if( keyState == 0 && keyRepeat == 0 )
870
                [[VLCCoreInteraction sharedInstance] previous];
871 872
            else if( keyRepeat == 1 )
            {
873
                [[VLCCoreInteraction sharedInstance] backwardShort];
874 875 876 877 878 879 880 881 882
                b_mediakeyJustJumped = YES;
                [self performSelector:@selector(resetMediaKeyJump)
                           withObject: NULL
                           afterDelay:0.25];
            }
        }
    }
}

883 884 885
#pragma mark -
#pragma mark Other notification

886 887 888 889
/* Listen to the remote in exclusive mode, only when VLC is the active
   application */
- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
890
    if( !p_intf ) return;
891 892
    if( config_GetInt( p_intf, "macosx-appleremote" ) == YES )
        [o_remote startListening: self];
893 894 895
}
- (void)applicationDidResignActive:(NSNotification *)aNotification
{
896
    if( !p_intf ) return;
897 898 899
    [o_remote stopListening: self];
}

900 901 902
/* Triggered when the computer goes to sleep */
- (void)computerWillSleep: (NSNotification *)notification
{
903
    [[VLCCoreInteraction sharedInstance] pause];
904 905
}

906 907 908 909 910 911
#pragma mark -
#pragma mark File opening

- (BOOL)application:(NSApplication *)o_app openFile:(NSString *)o_filename
{
    BOOL b_autoplay = config_GetInt( VLCIntf, "macosx-autoplay" );
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
912
    char *psz_uri = make_URI([o_filename UTF8String], "file" );
913 914 915
    if( !psz_uri )
        return( FALSE );

916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
    input_thread_t * p_input = pl_CurrentInput( VLCIntf );
    BOOL b_returned = NO;

    if (p_input)
    {
        b_returned = input_AddSubtitle( p_input, psz_uri, true );
        vlc_object_release( p_input );
        if(!b_returned)
        {
            free( psz_uri );
            return YES;
        }
    }
    else if( p_input )
        vlc_object_release( p_input );

932 933 934 935
    NSDictionary *o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];

    free( psz_uri );

936 937 938 939 940 941 942 943 944 945
    if( b_autoplay )
        [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: NO];
    else
        [o_playlist appendArray: [NSArray arrayWithObject: o_dic] atPos: -1 enqueue: YES];

    return( TRUE );
}

/* When user click in the Dock icon our double click in the finder */
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)hasVisibleWindows
946
{
947
    if(!hasVisibleWindows)
948
        [o_mainwindow makeKeyAndOrderFront:self];
949 950 951 952 953 954 955

    return YES;
}

#pragma mark -
#pragma mark Apple Remote Control

956 957
/* Helper method for the remote control interface in order to trigger forward/backward and volume
   increase/decrease as long as the user holds the left/right, plus/minus button */
958
- (void) executeHoldActionForRemoteButton: (NSNumber*) buttonIdentifierNumber
959
{
960
    if(b_remote_button_hold)
961
    {
962
        switch([buttonIdentifierNumber intValue])
963
        {
964
            case kRemoteButtonRight_Hold:
965
                [[VLCCoreInteraction sharedInstance] forward];
966
                break;
967
            case kRemoteButtonLeft_Hold:
968
                [[VLCCoreInteraction sharedInstance] backward];
969
                break;
970
            case kRemoteButtonVolume_Plus_Hold:
971
                [[VLCCoreInteraction sharedInstance] volumeUp];
972
                break;
973
            case kRemoteButtonVolume_Minus_Hold:
974
                [[VLCCoreInteraction sharedInstance] volumeDown];
975
                break;
976
        }
977
        if(b_remote_button_hold)
978
        {
979
            /* trigger event */
980
            [self performSelector:@selector(executeHoldActionForRemoteButton:)
981
                         withObject:buttonIdentifierNumber
982
                         afterDelay:0.25];
983 984 985 986
        }
    }
}

987
/* Apple Remote callback */
988 989 990
- (void) appleRemoteButton: (AppleRemoteEventIdentifier)buttonIdentifier
               pressedDown: (BOOL) pressedDown
                clickCount: (unsigned int) count
991 992 993
{
    switch( buttonIdentifier )
    {