VLCMainWindow.m 46.3 KB
Newer Older
1
/*****************************************************************************
2
 * VLCMainWindow.m: MacOS X interface module
3
 *****************************************************************************
4
 * Copyright (C) 2002-2013 VLC authors and VideoLAN
5 6 7
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne -at- videolan -dot- org>
8 9 10
 *          Jon Lech Johansen <jon-vl@nanocrew.net>
 *          Christophe Massiot <massiot@via.ecp.fr>
 *          Derk-Jan Hartman <hartman at videolan.org>
11
 *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * 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.
 *
 * 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
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

28 29
#import "VLCMainWindow.h"

30
#import "VLCMain.h"
31
#import "CompatibilityFixes.h"
32
#import "VLCCoreInteraction.h"
33
#import "VLCAudioEffectsWindowController.h"
34
#import "VLCMainMenu.h"
35
#import "VLCOpenWindowController.h"
36
#import "VLCPlaylist.h"
37
#import "SideBarItem.h"
38
#import <math.h>
39
#import <vlc_playlist.h>
40 41
#import <vlc_url.h>
#import <vlc_strings.h>
42
#import <vlc_services_discovery.h>
43
#import "VLCPLModel.h"
44

45 46 47
#import "PXSourceList.h"
#import "PXSourceListDataSource.h"

48
#import "VLCMainWindowControlsBar.h"
49
#import "VLCVoutView.h"
50
#import "VLCVoutWindowController.h"
51 52


53
@interface VLCMainWindow() <PXSourceListDataSource, PXSourceListDelegate, NSOutlineViewDataSource, NSOutlineViewDelegate, NSWindowDelegate, NSAnimationDelegate, NSSplitViewDelegate>
54
{
55 56 57 58 59
    BOOL videoPlaybackEnabled;
    BOOL dropzoneActive;
    BOOL splitViewRemoved;
    BOOL minimizedView;

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    BOOL b_video_playback_enabled;
    BOOL b_dropzone_active;
    BOOL b_splitview_removed;
    BOOL b_minimized_view;

    CGFloat f_lastSplitViewHeight;
    CGFloat f_lastLeftSplitViewWidth;

    NSMutableArray *o_sidebaritems;

    /* this is only true, when we have NO video playing inside the main window */

    BOOL b_podcastView_displayed;

    VLCColorView * o_color_backdrop;

    NSRect frameBeforePlayback;
}
78 79
- (void)makeSplitViewVisible;
- (void)makeSplitViewHidden;
80 81
- (void)showPodcastControls;
- (void)hidePodcastControls;
82 83
@end

84
static const float f_min_window_height = 307.;
85

86 87
@implementation VLCMainWindow

88 89 90
#pragma mark -
#pragma mark Initialization

91 92 93 94 95
- (BOOL)isEvent:(NSEvent *)o_event forKey:(const char *)keyString
{
    char *key;
    NSString *o_key;

96
    key = config_GetPsz(getIntf(), keyString);
97
    o_key = [NSString stringWithFormat:@"%s", key];
98
    FREENULL(key);
99

100
    unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa:o_key];
101

102 103
    NSString * characters = [o_event charactersIgnoringModifiers];
    if ([characters length] > 0) {
104
        return [[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: o_key]] &&
105 106 107 108 109 110
                (i_keyModifiers & NSShiftKeyMask)     == ([o_event modifierFlags] & NSShiftKeyMask) &&
                (i_keyModifiers & NSControlKeyMask)   == ([o_event modifierFlags] & NSControlKeyMask) &&
                (i_keyModifiers & NSAlternateKeyMask) == ([o_event modifierFlags] & NSAlternateKeyMask) &&
                (i_keyModifiers & NSCommandKeyMask)   == ([o_event modifierFlags] & NSCommandKeyMask);
    }
    return NO;
111 112
}

113 114
- (BOOL)performKeyEquivalent:(NSEvent *)o_event
{
115
    BOOL b_force = NO;
116
    // these are key events which should be handled by vlc core, but are attached to a main menu item
117
    if (![self isEvent: o_event forKey: "key-vol-up"] &&
118
        ![self isEvent: o_event forKey: "key-vol-down"] &&
119 120 121 122 123
        ![self isEvent: o_event forKey: "key-vol-mute"] &&
        ![self isEvent: o_event forKey: "key-prev"] &&
        ![self isEvent: o_event forKey: "key-next"] &&
        ![self isEvent: o_event forKey: "key-jump+short"] &&
        ![self isEvent: o_event forKey: "key-jump-short"]) {
124 125
        /* We indeed want to prioritize some Cocoa key equivalent against libvlc,
         so we perform the menu equivalent now. */
126
        if ([[NSApp mainMenu] performKeyEquivalent:o_event])
127 128
            return TRUE;
    }
129 130
    else
        b_force = YES;
131

132 133 134
    VLCCoreInteraction *coreInteraction = [VLCCoreInteraction sharedInstance];
    return [coreInteraction hasDefinedShortcutKey:o_event force:b_force] ||
           [coreInteraction keyEvent:o_event];
135 136 137 138
}

- (void)dealloc
{
139
    [[NSNotificationCenter defaultCenter] removeObserver: self];
140 141 142 143
}

- (void)awakeFromNib
{
144 145
    [super awakeFromNib];

146 147 148 149 150 151 152 153
    /*
     * General setup
     */

    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    BOOL splitViewShouldBeHidden = NO;
154

155 156
    [self setDelegate:self];
    [self setRestorable:NO];
157 158 159
    // TODO: useOptimizedDrawing deprecated since 10.10, but no
    // documentation provided what do use instead.
    // see radar://23047516
160 161 162
    [self useOptimizedDrawing:YES];
    [self setExcludedFromWindowsMenu:YES];
    [self setAcceptsMouseMovedEvents:YES];
163 164
    [self setFrameAutosaveName:@"mainwindow"];

165
    _nativeFullscreenMode = var_InheritBool(getIntf(), "macosx-nativefullscreenmode");
166
    b_dropzone_active = YES;
167

168
    // Playlist setup
169
    VLCPlaylist *playlist = [[VLCMain sharedInstance] playlist];
170 171
    [playlist setOutlineView:(VLCPlaylistView *)_outlineView];
    [playlist setPlaylistHeaderView:_outlineView.headerView];
172
    [self setNextResponder:playlist];
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    // (Re)load sidebar for the first time and select first item
    [self reloadSidebar];
    [_sidebarView selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO];


    /*
     * Set up translatable strings for the UI elements
     */

    // Window title
    [self setTitle:_NS("VLC media player")];

    // Search Field
    [_searchField setToolTip:_NS("Search in Playlist")];
    [_searchField.cell setPlaceholderString:_NS("Search")];
    [_searchField.cell accessibilitySetOverrideValue:_NS("Enter a term to search the playlist. Results will be selected in the table.")
                                        forAttribute:NSAccessibilityDescriptionAttribute];

    // Dropzone
    [_dropzoneLabel setStringValue:_NS("Drop media here")];
    [_dropzoneImageView setImage:imageFromRes(@"dropzone")];
    [_dropzoneButton setTitle:_NS("Open media...")];
    [_dropzoneButton.cell accessibilitySetOverrideValue:_NS("Click to open an advanced dialog to select the media to play. You can also drop files here to play.")
                                           forAttribute:NSAccessibilityDescriptionAttribute];

    // Podcast view
    [_podcastAddButton setTitle:_NS("Subscribe")];
    [_podcastRemoveButton setTitle:_NS("Unsubscribe")];

    // Podcast subscribe window
    [_podcastSubscribeTitle setStringValue:_NS("Subscribe to a podcast")];
    [_podcastSubscribeSubtitle setStringValue:_NS("Enter URL of the podcast to subscribe to:")];
    [_podcastSubscribeOkButton setTitle:_NS("Subscribe")];
    [_podcastSubscribeCancelButton setTitle:_NS("Cancel")];

    // Podcast unsubscribe window
    [_podcastUnsubscirbeTitle setStringValue:_NS("Unsubscribe from a podcast")];
    [_podcastUnsubscribeSubtitle setStringValue:_NS("Select the podcast you would like to unsubscribe from:")];
    [_podcastUnsubscribeOkButton setTitle:_NS("Unsubscribe")];
    [_podcastUnsubscribeCancelButton setTitle:_NS("Cancel")];
214

215
    /* interface builder action */
216
    CGFloat f_threshold_height = f_min_video_height + [self.controlsBar height];
217
    if (self.darkInterface)
218
        f_threshold_height += [self.titlebarView frame].size.height;
219
    if ([[self contentView] frame].size.height < f_threshold_height)
220
        splitViewShouldBeHidden = YES;
221

222
    // Set that here as IB seems to be buggy
223
    if (self.darkInterface)
224
        [self setContentMinSize:NSMakeSize(604., f_min_window_height + [self.titlebarView frame].size.height)];
225
    else
226
        [self setContentMinSize:NSMakeSize(604., f_min_window_height)];
227

228 229
    _fspanel = [[VLCFSPanelController alloc] init];
    [_fspanel showWindow:self];
230

231
    /* make sure we display the desired default appearance when VLC launches for the first time */
232
    if (![defaults objectForKey:@"VLCFirstRun"]) {
233 234
        [defaults setObject:[NSDate date] forKey:@"VLCFirstRun"];

235
        [_sidebarView expandItem:nil expandChildren:YES];
236

Felix Paul Kühne's avatar
Felix Paul Kühne committed
237
        NSAlert *albumArtAlert = [NSAlert alertWithMessageText:_NS("Check for album art and metadata?") defaultButton:_NS("Enable Metadata Retrieval") alternateButton:_NS("No, Thanks") otherButton:nil informativeTextWithFormat:@"%@",_NS("VLC can check online for album art and metadata to enrich your playback experience, e.g. by providing track information when playing Audio CDs. To provide this functionality, VLC will send information about your contents to trusted services in an anonymized form.")];
238
        NSInteger returnValue = [albumArtAlert runModal];
239
        config_PutInt(getIntf(), "metadata-network-access", returnValue == NSAlertDefaultReturn);
240 241
    }

242
    if (self.darkInterface) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
243 244
        [defaultCenter addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidResizeNotification object: nil];
        [defaultCenter addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidMoveNotification object: nil];
245

246 247
        [self setBackgroundColor: [NSColor clearColor]];
        [self setOpaque: NO];
248 249
        [self display];
        [self setHasShadow:NO];
250
        [self setHasShadow:YES];
251

252
        self.previousSavedFrame = [self frame];
253

254 255
        o_color_backdrop = [[VLCColorView alloc] initWithFrame:_splitView.frame];
        [[self contentView] addSubview:o_color_backdrop positioned:NSWindowBelow relativeTo:_splitView];
256
        [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
257
    } else {
258 259
        [_playlistScrollView setBorderType:NSNoBorder];
        [_sidebarScrollView setBorderType:NSNoBorder];
260
    }
261

Felix Paul Kühne's avatar
Felix Paul Kühne committed
262 263 264
    [defaultCenter addObserver: self selector: @selector(someWindowWillClose:) name: NSWindowWillCloseNotification object: nil];
    [defaultCenter addObserver: self selector: @selector(someWindowWillMiniaturize:) name: NSWindowWillMiniaturizeNotification object:nil];
    [defaultCenter addObserver: self selector: @selector(applicationWillTerminate:) name: NSApplicationWillTerminateNotification object: nil];
265
    [defaultCenter addObserver: self selector: @selector(mainSplitViewDidResizeSubviews:) name: NSSplitViewDidResizeSubviewsNotification object:_splitView];
266

267 268
    if (splitViewShouldBeHidden) {
        [self hideSplitView:YES];
269
        f_lastSplitViewHeight = 300;
270
    }
271 272

    /* sanity check for the window size */
273
    NSRect frame = [self frame];
274 275
    NSSize screenSize = [[self screen] frame].size;
    if (screenSize.width <= frame.size.width || screenSize.height <= frame.size.height) {
276
        self.nativeVideoSize = screenSize;
277 278
        [self resizeWindow];
    }
279

280
    /* update fs button to reflect state for next startup */
281
    if (var_InheritBool(pl_Get(getIntf()), "fullscreen"))
282
        [self.controlsBar setFullscreenState:YES];
283 284

    /* restore split view */
285
    f_lastLeftSplitViewWidth = 200;
286
    /* trick NSSplitView implementation, which pretends to know better than us */
287
    if (!var_InheritBool(getIntf(), "macosx-show-sidebar"))
288
        [self performSelector:@selector(toggleLeftSubSplitView) withObject:nil afterDelay:0.05];
289 290
}

291
#pragma mark -
292
#pragma mark appearance management
293

294 295 296
- (void)reloadSidebar
{
    BOOL isAReload = NO;
297
    if (o_sidebaritems)
298 299 300 301 302
        isAReload = YES;

    o_sidebaritems = [[NSMutableArray alloc] init];
    SideBarItem *libraryItem = [SideBarItem itemWithTitle:_NS("LIBRARY") identifier:@"library"];
    SideBarItem *playlistItem = [SideBarItem itemWithTitle:_NS("Playlist") identifier:@"playlist"];
303
    [playlistItem setIcon: imageFromRes(@"sidebar-playlist")];
304
    SideBarItem *medialibraryItem = [SideBarItem itemWithTitle:_NS("Media Library") identifier:@"medialibrary"];
305
    [medialibraryItem setIcon: imageFromRes(@"sidebar-playlist")];
306 307 308 309 310
    SideBarItem *mycompItem = [SideBarItem itemWithTitle:_NS("MY COMPUTER") identifier:@"mycomputer"];
    SideBarItem *devicesItem = [SideBarItem itemWithTitle:_NS("DEVICES") identifier:@"devices"];
    SideBarItem *lanItem = [SideBarItem itemWithTitle:_NS("LOCAL NETWORK") identifier:@"localnetwork"];
    SideBarItem *internetItem = [SideBarItem itemWithTitle:_NS("INTERNET") identifier:@"internet"];

311
    /* SD subnodes, inspired by the Qt intf */
312 313
    char **ppsz_longnames = NULL;
    int *p_categories = NULL;
314
    char **ppsz_names = vlc_sd_GetNames(pl_Get(getIntf()), &ppsz_longnames, &p_categories);
315
    if (!ppsz_names)
316
        msg_Err(getIntf(), "no sd item found"); //TODO
317 318 319 320 321 322 323 324
    char **ppsz_name = ppsz_names, **ppsz_longname = ppsz_longnames;
    int *p_category = p_categories;
    NSMutableArray *internetItems = [[NSMutableArray alloc] init];
    NSMutableArray *devicesItems = [[NSMutableArray alloc] init];
    NSMutableArray *lanItems = [[NSMutableArray alloc] init];
    NSMutableArray *mycompItems = [[NSMutableArray alloc] init];
    NSString *o_identifier;
    for (; ppsz_name && *ppsz_name; ppsz_name++, ppsz_longname++, p_category++) {
325
        o_identifier = toNSStr(*ppsz_name);
326 327 328
        switch (*p_category) {
            case SD_CAT_INTERNET:
                [internetItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
329
                [[internetItems lastObject] setIcon: imageFromRes(@"sidebar-podcast")];
330
                [[internetItems lastObject] setSdtype: SD_CAT_INTERNET];
331
                [[internetItems lastObject] setUntranslatedTitle: toNSStr(*ppsz_longname)];
332 333 334
                break;
            case SD_CAT_DEVICES:
                [devicesItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
335
                [[devicesItems lastObject] setIcon: imageFromRes(@"sidebar-local")];
336
                [[devicesItems lastObject] setSdtype: SD_CAT_DEVICES];
337
                [[devicesItems lastObject] setUntranslatedTitle: toNSStr(*ppsz_longname)];
338 339 340
                break;
            case SD_CAT_LAN:
                [lanItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
341
                [[lanItems lastObject] setIcon: imageFromRes(@"sidebar-local")];
342
                [[lanItems lastObject] setSdtype: SD_CAT_LAN];
343
                [[lanItems lastObject] setUntranslatedTitle: toNSStr(*ppsz_longname)];
344 345 346 347
                break;
            case SD_CAT_MYCOMPUTER:
                [mycompItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
                if (!strncmp(*ppsz_name, "video_dir", 9))
348
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-movie")];
349
                else if (!strncmp(*ppsz_name, "audio_dir", 9))
350
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-music")];
351
                else if (!strncmp(*ppsz_name, "picture_dir", 11))
352
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-pictures")];
353 354
                else
                    [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
355
                [[mycompItems lastObject] setUntranslatedTitle: toNSStr(*ppsz_longname)];
356 357 358
                [[mycompItems lastObject] setSdtype: SD_CAT_MYCOMPUTER];
                break;
            default:
359
                msg_Warn(getIntf(), "unknown SD type found, skipping (%s)", *ppsz_name);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
                break;
        }

        free(*ppsz_name);
        free(*ppsz_longname);
    }
    [mycompItem setChildren: [NSArray arrayWithArray: mycompItems]];
    [devicesItem setChildren: [NSArray arrayWithArray: devicesItems]];
    [lanItem setChildren: [NSArray arrayWithArray: lanItems]];
    [internetItem setChildren: [NSArray arrayWithArray: internetItems]];
    free(ppsz_names);
    free(ppsz_longnames);
    free(p_categories);

    [libraryItem setChildren: [NSArray arrayWithObjects:playlistItem, medialibraryItem, nil]];
    [o_sidebaritems addObject: libraryItem];
    if ([mycompItem hasChildren])
        [o_sidebaritems addObject: mycompItem];
    if ([devicesItem hasChildren])
        [o_sidebaritems addObject: devicesItem];
    if ([lanItem hasChildren])
        [o_sidebaritems addObject: lanItem];
    if ([internetItem hasChildren])
        [o_sidebaritems addObject: internetItem];

385 386 387
    [_sidebarView reloadData];
    [_sidebarView setDropItem:playlistItem dropChildIndex:NSOutlineViewDropOnItemIndex];
    [_sidebarView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
388

389 390 391 392
    [_sidebarView setAutosaveName:@"mainwindow-sidebar"];
    [_sidebarView setDataSource:self];
    [_sidebarView setDelegate:self];
    [_sidebarView setAutosaveExpandedItems:YES];
393

394
    [_sidebarView expandItem:libraryItem expandChildren:YES];
395 396

    if (isAReload) {
397
        [_sidebarView expandItem:nil expandChildren:YES];
398 399 400
    }
}

401
// Show split view and hide the video view
402 403
- (void)makeSplitViewVisible
{
404
    if (self.darkInterface)
405
        [self setContentMinSize: NSMakeSize(604., f_min_window_height + [self.titlebarView frame].size.height)];
406
    else
407
        [self setContentMinSize: NSMakeSize(604., f_min_window_height)];
408 409

    NSRect old_frame = [self frame];
410
    CGFloat newHeight = [self minSize].height;
411
    if (old_frame.size.height < newHeight) {
412 413 414 415
        NSRect new_frame = old_frame;
        new_frame.origin.y = old_frame.origin.y + old_frame.size.height - newHeight;
        new_frame.size.height = newHeight;

416
        [[self animator] setFrame:new_frame display:YES animate:YES];
417 418
    }

419 420
    [self.videoView setHidden:YES];
    [_splitView setHidden:NO];
421
    if (self.nativeFullscreenMode && [self fullscreen]) {
422
        [self showControlsBar];
423
        [self.fspanel setNonActive];
424 425
    }

426
    [self makeFirstResponder:_playlistScrollView];
427 428
}

429
// Hides the split view and makes the vout view in foreground
430 431
- (void)makeSplitViewHidden
{
432
    if (self.darkInterface)
433
        [self setContentMinSize: NSMakeSize(604., f_min_video_height + [self.titlebarView frame].size.height)];
434
    else
435
        [self setContentMinSize: NSMakeSize(604., f_min_video_height)];
436

437 438
    [_splitView setHidden:YES];
    [self.videoView setHidden:NO];
439
    if (self.nativeFullscreenMode && [self fullscreen]) {
440
        [self hideControlsBar];
441
        [self.fspanel setActive];
442
    }
443

444
    if ([[self.videoView subviews] count] > 0)
445
        [self makeFirstResponder: [[self.videoView subviews] firstObject]];
446 447
}

448 449

- (void)changePlaylistState:(VLCPlaylistStateEvent)event
450
{
451 452
    // Beware, this code is really ugly

453
    msg_Dbg(getIntf(), "toggle playlist from state: removed splitview %i, minimized view %i. Event %i", b_splitview_removed, b_minimized_view, event);
454 455
    if (![self isVisible] && event == psUserMenuEvent) {
        [self makeKeyAndOrderFront: nil];
456
        return;
457 458
    }

459
    BOOL b_activeVideo = [[VLCMain sharedInstance] activeVideoPlayback];
460
    BOOL b_restored = NO;
461

462
    // ignore alt if triggered through main menu shortcut
463
    BOOL b_have_alt_key = ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0;
464
    if (event == psUserMenuEvent)
465 466
        b_have_alt_key = NO;

467 468 469 470
    // eUserMenuEvent is now handled same as eUserEvent
    if(event == psUserMenuEvent)
        event = psUserEvent;

471
    if (b_dropzone_active && b_have_alt_key) {
472 473 474 475
        [self hideDropZone];
        return;
    }

476 477
    if (!(self.nativeFullscreenMode && self.fullscreen) && !b_splitview_removed && ((b_have_alt_key && b_activeVideo)
                                                                              || (self.nonembedded && event == psUserEvent)
478 479
                                                                              || (!b_activeVideo && event == psUserEvent)
                                                                              || (b_minimized_view && event == psVideoStartedOrStoppedEvent))) {
480 481
        // for starting playback, window is resized through resized events
        // for stopping playback, resize through reset to previous frame
482
        [self hideSplitView: event != psVideoStartedOrStoppedEvent];
483 484
        b_minimized_view = NO;
    } else {
485
        if (b_splitview_removed) {
486
            if (!self.nonembedded || (event == psUserEvent && self.nonembedded))
487
                [self showSplitView: event != psVideoStartedOrStoppedEvent];
488

489
            if (event != psUserEvent)
490 491 492 493 494 495
                b_minimized_view = YES;
            else
                b_minimized_view = NO;

            if (b_activeVideo)
                b_restored = YES;
496 497
        }

498 499
        if (!self.nonembedded) {
            if (([self.videoView isHidden] && b_activeVideo) || b_restored || (b_activeVideo && event != psUserEvent))
500
                [self makeSplitViewHidden];
501
            else
502
                [self makeSplitViewVisible];
503
        } else {
504 505
            [_splitView setHidden: NO];
            [_playlistScrollView setHidden: NO];
506
            [self.videoView setHidden: YES];
507
            [self showControlsBar];
508
        }
509
    }
510

511
    msg_Dbg(getIntf(), "toggle playlist to state: removed splitview %i, minimized view %i", b_splitview_removed, b_minimized_view);
512 513
}

514 515 516 517 518
- (IBAction)dropzoneButtonAction:(id)sender
{
    [[[VLCMain sharedInstance] open] openFileGeneric];
}

519 520 521
#pragma mark -
#pragma mark overwritten default functionality

522 523
- (void)windowResizedOrMoved:(NSNotification *)notification
{
524
    [self saveFrameUsingName:[self frameAutosaveName]];
525 526
}

527 528
- (void)applicationWillTerminate:(NSNotification *)notification
{
529
    config_PutInt(getIntf(), "macosx-show-sidebar", ![_splitView isSubviewCollapsed:_splitViewLeft]);
530
    [self saveFrameUsingName:[self frameAutosaveName]];
531 532
}

533

534 535
- (void)someWindowWillClose:(NSNotification *)notification
{
536
    id obj = [notification object];
537

538 539
    // hasActiveVideo is defined for VLCVideoWindowCommon and subclasses
    if ([obj respondsToSelector:@selector(hasActiveVideo)] && [obj hasActiveVideo]) {
540 541 542
        if ([[VLCMain sharedInstance] activeVideoPlayback])
            [[VLCCoreInteraction sharedInstance] stop];
    }
543 544 545 546
}

- (void)someWindowWillMiniaturize:(NSNotification *)notification
{
547
    if (config_GetInt(getIntf(), "macosx-pause-minimized")) {
548
        id obj = [notification object];
549

550
        if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !self.nonembedded)) {
551
            if ([[VLCMain sharedInstance] activeVideoPlayback])
552 553
                [[VLCCoreInteraction sharedInstance] pause];
        }
554 555 556
    }
}

557 558
#pragma mark -
#pragma mark Update interface and respond to foreign events
559 560
- (void)showDropZone
{
561
    b_dropzone_active = YES;
562
    [_dropzoneView setHidden:NO];
563
    [_playlistScrollView setHidden:YES];
564 565 566 567
}

- (void)hideDropZone
{
568
    b_dropzone_active = NO;
569
    [_dropzoneView setHidden:YES];
570
    [_playlistScrollView setHidden:NO];
571 572
}

573
- (void)hideSplitView:(BOOL)resize
574
{
575
    if (resize) {
576
        NSRect winrect = [self frame];
577
        f_lastSplitViewHeight = [_splitView frame].size.height;
578 579
        winrect.size.height = winrect.size.height - f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y + f_lastSplitViewHeight;
580
        [self setFrame:winrect display:YES animate:YES];
581 582
    }

583
    if (self.darkInterface) {
584 585
        [self setContentMinSize: NSMakeSize(604., [self.controlsBar height] + [self.titlebarView frame].size.height)];
        [self setContentMaxSize: NSMakeSize(FLT_MAX, [self.controlsBar height] + [self.titlebarView frame].size.height)];
586
    } else {
587 588
        [self setContentMinSize: NSMakeSize(604., [self.controlsBar height])];
        [self setContentMaxSize: NSMakeSize(FLT_MAX, [self.controlsBar height])];
589
    }
590

591 592 593
    b_splitview_removed = YES;
}

594
- (void)showSplitView:(BOOL)resize
595
{
596
    [self updateWindow];
597
    if (self.darkInterface)
598
        [self setContentMinSize:NSMakeSize(604., f_min_window_height + [self.titlebarView frame].size.height)];
599
    else
600
        [self setContentMinSize:NSMakeSize(604., f_min_window_height)];
601
    [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
602

603
    if (resize) {
604 605
        NSRect winrect;
        winrect = [self frame];
606 607
        winrect.size.height = winrect.size.height + f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y - f_lastSplitViewHeight;
608
        [self setFrame:winrect display:YES animate:YES];
609
    }
610 611 612 613

    b_splitview_removed = NO;
}

614 615
- (void)updateTimeSlider
{
616 617
    [self.controlsBar updateTimeSlider];
    [self.fspanel updatePositionAndTime];
618

619 620 621
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar updateTimeSlider];
    }];
622 623

    [[VLCCoreInteraction sharedInstance] updateAtoB];
624 625
}

626
- (void)updateName
627
{
628
    input_thread_t *p_input;
629
    p_input = pl_CurrentInput(getIntf());
630
    if (p_input) {
631
        NSString *aString = @"";
632

633 634
        if (!config_GetPsz(getIntf(), "video-title")) {
            char *format = var_InheritString(getIntf(), "input-title-format");
635
            if (format) {
636
                char *formated = vlc_strfinput(p_input, format);
637 638 639 640
                free(format);
                aString = toNSStr(formated);
                free(formated);
            }
641
        } else
642
            aString = toNSStr(config_GetPsz(getIntf(), "video-title"));
643

644
        char *uri = input_item_GetURI(input_GetItem(p_input));
645

646
        NSURL * o_url = [NSURL URLWithString:toNSStr(uri)];
647
        if ([o_url isFileURL]) {
648
            [self setRepresentedURL: o_url];
649 650 651
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setRepresentedURL:o_url];
            }];
652
        } else {
653
            [self setRepresentedURL: nil];
654 655 656
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setRepresentedURL:nil];
            }];
657
        }
658
        free(uri);
659

660
        if ([aString isEqualToString:@""]) {
661 662 663 664
            if ([o_url isFileURL])
                aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
            else
                aString = [o_url absoluteString];
665
        }
666

667 668 669 670 671 672
        if ([aString length] > 0) {
            [self setTitle: aString];
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setTitle:aString];
            }];

673
            [self.fspanel setStreamTitle: aString];
674
        } else {
675
            [self setTitle: _NS("VLC media player")];
676 677
            [self setRepresentedURL: nil];
        }
678

679 680
        vlc_object_release(p_input);
    } else {
681
        [self setTitle: _NS("VLC media player")];
682
        [self setRepresentedURL: nil];
683
    }
684 685
}

686 687
- (void)updateWindow
{
688
    [self.controlsBar updateControls];
689 690 691
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar updateControls];
    }];
692

693 694
    bool b_seekable = false;

695
    playlist_t *p_playlist = pl_Get(getIntf());
696
    input_thread_t *p_input = playlist_CurrentInput(p_playlist);
697
    if (p_input) {
698
        /* seekable streams */
699
        b_seekable = var_GetBool(p_input, "can-seek");
700

701
        vlc_object_release(p_input);
702 703
    }

704
    [self updateTimeSlider];
705 706
    if ([self.fspanel respondsToSelector:@selector(setSeekable:)])
        [self.fspanel setSeekable: b_seekable];
707 708

    PL_LOCK;
709 710
    if ([[[[VLCMain sharedInstance] playlist] model] currentRootType] != ROOT_TYPE_PLAYLIST ||
        [[[[VLCMain sharedInstance] playlist] model] hasChildren])
711 712 713 714
        [self hideDropZone];
    else
        [self showDropZone];
    PL_UNLOCK;
715
    [_sidebarView setNeedsDisplay:YES];
716 717

    [self _updatePlaylistTitle];
718 719 720 721
}

- (void)setPause
{
722 723
    [self.controlsBar setPause];
    [self.fspanel setPause];
724

725 726 727
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar setPause];
    }];
728 729 730 731
}

- (void)setPlay
{
732 733
    [self.controlsBar setPlay];
    [self.fspanel setPlay];
734

735 736 737
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar setPlay];
    }];
738 739
}

740
- (void)updateVolumeSlider
741
{
742
    [(VLCMainWindowControlsBar *)[self controlsBar] updateVolumeSlider];
743
    [self.fspanel setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume]];
744 745
}

746 747
#pragma mark -
#pragma mark Video Output handling
748

749 750
- (void)videoplayWillBeStarted
{
751
    if (!self.fullscreen)
752 753 754
        frameBeforePlayback = [self frame];
}

755
- (void)setVideoplayEnabled
756
{
757
    BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
758

759
    if (!b_videoPlayback) {
760
        if (!self.nonembedded && (!self.nativeFullscreenMode || (self.nativeFullscreenMode && !self.fullscreen)) && frameBeforePlayback.size.width > 0 && frameBeforePlayback.size.height > 0) {
761 762

            // only resize back to minimum view of this is still desired final state
763
            CGFloat f_threshold_height = f_min_video_height + [self.controlsBar height];
764
            if(frameBeforePlayback.size.height > f_threshold_height || b_minimized_view) {
765 766 767 768 769 770

                if ([[VLCMain sharedInstance] isTerminating])
                    [self setFrame:frameBeforePlayback display:YES];
                else
                    [[self animator] setFrame:frameBeforePlayback display:YES];

771
            }
772 773 774
        }

        frameBeforePlayback = NSMakeRect(0, 0, 0, 0);
775

776
        // update fs button to reflect state for next startup
777
        if (var_InheritBool(getIntf(), "fullscreen") || var_GetBool(pl_Get(getIntf()), "fullscreen")) {
778
            [self.controlsBar setFullscreenState:YES];
779 780
        }

781
        [self makeFirstResponder: _playlistScrollView];
782
        [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
783

784 785 786
        // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
        [self setAlphaValue:1.0];
    }
787

788
    if (self.nativeFullscreenMode) {
789 790
        if ([self hasActiveVideo] && [self fullscreen] && b_videoPlayback) {
            [self hideControlsBar];
791
            [self.fspanel setActive];
792
        } else {
793
            [self showControlsBar];
794
            [self.fspanel setNonActive];
795
        }
796
    }
797
}
798

799 800
#pragma mark -
#pragma mark Fullscreen support
801

802 803
- (void)showFullscreenController
{
804 805
    id currentWindow = [NSApp keyWindow];
    if ([currentWindow respondsToSelector:@selector(hasActiveVideo)] && [currentWindow hasActiveVideo]) {
806
        if ([currentWindow respondsToSelector:@selector(fullscreen)] && [currentWindow fullscreen] && ![[currentWindow videoView] isHidden]) {
807 808

            if ([[VLCMain sharedInstance] activeVideoPlayback])
809
                [self.fspanel fadeIn];
810 811
        }
    }
812

813 814
}

815
#pragma mark -
816 817 818 819
#pragma mark split view delegate
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
{
    if (dividerIndex == 0)
820
        return 300.;
821 822 823 824
    else
        return proposedMax;
}

825 826 827 828 829 830 831 832
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
{
    if (dividerIndex == 0)
        return 100.;
    else
        return proposedMin;
}

833 834
- (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview
{
835
    return ([subview isEqual:_splitViewLeft]);
836 837
}

838 839
- (BOOL)splitView:(NSSplitView *)splitView shouldAdjustSizeOfSubview:(NSView *)subview
{
840
    return (![subview isEqual:_splitViewLeft]);
841 842
}

843
- (void)mainSplitViewDidResizeSubviews:(id)object
844
{
845
    f_lastLeftSplitViewWidth = [_splitViewLeft frame].size.width;
846
    config_PutInt(getIntf(), "macosx-show-sidebar", ![_splitView isSubviewCollapsed:_splitViewLeft]);
847 848 849 850 851
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
}

- (void)toggleLeftSubSplitView
{
852 853 854
    [_splitView adjustSubviews];
    if ([_splitView isSubviewCollapsed:_splitViewLeft])
        [_splitView setPosition:f_lastLeftSplitViewWidth ofDividerAtIndex:0];
855
    else
856
        [_splitView setPosition:[_splitView minPossiblePositionOfDividerAtIndex:0] ofDividerAtIndex:0];
857
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
858 859
}

860 861 862 863
#pragma mark -
#pragma mark private playlist magic
- (void)_updatePlaylistTitle
{
864
    PLRootType root = [[[[VLCMain sharedInstance] playlist] model] currentRootType];
865
    playlist_t *p_playlist = pl_Get(getIntf());
866

867 868
    PL_LOCK;
    if (root == ROOT_TYPE_PLAYLIST)
869
        [_categoryLabel setStringValue: [_NS("Playlist") stringByAppendingString:[self _playbackDurationOfNode:p_playlist->p_playing]]];
870
    else if (root == ROOT_TYPE_MEDIALIBRARY)
871
        [_categoryLabel setStringValue: [_NS("Media Library") stringByAppendingString:[self _playbackDurationOfNode:p_playlist->p_media_library]]];
872 873

    PL_UNLOCK;
874 875 876 877 878 879 880
}

- (NSString *)_playbackDurationOfNode:(playlist_item_t*)node
{
    if (!node)
        return @"";

881
    playlist_t * p_playlist = pl_Get(getIntf());
882 883
    PL_ASSERT_LOCKED;

884 885 886 887 888 889 890 891 892
    mtime_t mt_duration = playlist_GetNodeDuration( node );

    if (mt_duration < 1)
        return @"";

    mt_duration = mt_duration / 1000000;

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:mt_duration];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
893 894 895 896 897
    if (mt_duration >= 86400) {
        [formatter setDateFormat:@"dd:HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"HH:mm:ss"];
    }
898 899
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

900
    return [NSString stringWithFormat:@" — %@",[formatter stringFromDate:date]];
901 902
}

903 904
- (IBAction)searchItem:(id)sender
{
905
    [[[[VLCMain sharedInstance] playlist] model] searchUpdate:[_searchField stringValue]];
906 907
}

908 909 910 911 912
- (IBAction)highlightSearchField:(id)sender
{
    [_searchField selectText:sender];
}

913
#pragma mark -
914 915 916 917
#pragma mark Side Bar Data handling
/* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
- (NSUInteger)sourceList:(PXSourceList*)sourceList numberOfChildrenOfItem:(id)item
{
918
    //Works the same way as the NSOutlineView data source: `nil` means a parent item
919
    if (item==nil)
920 921 922
        return [o_sidebaritems count];
    else
        return [[item children] count];
923 924 925 926 927 928
}


- (id)sourceList:(PXSourceList*)aSourceList child:(NSUInteger)index ofItem:(id)item
{
    //Works the same way as the NSOutlineView data source: `nil` means a parent item
929
    if (item==nil)
930
        return [o_sidebaritems objectAtIndex:index];
931
    else
932
        return [[item children] objectAtIndex:index];
933 934 935 936 937
}


- (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
{
938
    return [item title];
939 940 941 942
}

- (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
{
943
    [item setTitle:object];
944 945 946 947
}

- (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
{
948
    return [item hasChildren];
949 950 951 952 953
}


- (BOOL)sourceList:(PXSourceList*)aSourceList itemHasBadge:(id)item
{
954
    if ([[item identifier] isEqualToString: @"playlist"] || [[item identifier] isEqualToString: @"medialibrary"])
955 956
        return YES;

957
    return [item hasBadge];
958 959 960 961 962
}


- (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
{
963
    playlist_t * p_playlist = pl_Get(getIntf());
964
    NSInteger i_playlist_size = 0;
965

966
    if ([[item identifier] isEqualToString: @"playlist"]) {
967
        PL_LOCK;
968
        i_playlist_size = p_playlist->p_playing->i_children;
969 970 971 972
        PL_UNLOCK;

        return i_playlist_size;
    }
973
    if ([[item identifier] isEqualToString: @"medialibrary"]) {
974
        PL_LOCK;
975 976
        if (p_playlist->p_media_library)
            i_playlist_size = p_playlist->p_media_library->i_children;
977 978 979 980
        PL_UNLOCK;

        return i_playlist_size;
    }
981 982

    return [item badgeValue];
983 984 985 986 987
}


- (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
{
988
    return [item hasIcon];
989 990 991 992 993
}


- (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
{
994
    return [item icon];
995 996 997 998
}

- (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
{
999 1000
    if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
        if (item != nil) {
1001 1002
            if ([item sdtype] > 0)
            {
1003
                NSMenu *m = [[NSMenu alloc] init];
1004
                playlist_t * p_playlist = pl_Get(getIntf());
1005
                BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1006 1007 1008 1009 1010
                if (!sd_loaded)
                    [m addItemWithTitle:_NS("Enable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
                else
                    [m addItemWithTitle:_NS("Disable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
                [[m itemAtIndex:0] setRepresentedObject: [item identifier]];
1011
                return m;
1012 1013
            }
        }
1014 1015 1016
    }

    return nil;
1017 1018
}

1019 1020 1021
- (IBAction)sdmenuhandler:(id)sender
{
    NSString * identifier = [sender representedObject];
1022
    if ([identifier length] > 0 && ![identifier isEqualToString:@"lua{sd='freebox',longname='Freebox TV'}"]) {
1023
        playlist_t * p_playlist = pl_Get(getIntf());
1024
        BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [identifier UTF8String]);
1025 1026

        if (!sd_loaded)
1027
            playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
1028
        else