VLCMainWindow.m 45.5 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
    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;

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

82
static const float f_min_window_height = 307.;
83

84 85
@implementation VLCMainWindow

86 87 88
#pragma mark -
#pragma mark Initialization

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

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

98
    unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa:o_key];
99

100 101
    NSString * characters = [o_event charactersIgnoringModifiers];
    if ([characters length] > 0) {
102
        return [[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: o_key]] &&
103 104 105 106 107 108
                (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;
109 110
}

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

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

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

- (void)awakeFromNib
{
142 143
    [super awakeFromNib];

144 145 146 147 148 149 150 151
    /*
     * General setup
     */

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

    BOOL splitViewShouldBeHidden = NO;
152

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

163
    _nativeFullscreenMode = var_InheritBool(getIntf(), "macosx-nativefullscreenmode");
164
    b_dropzone_active = YES;
165

166
    // Playlist setup
167
    VLCPlaylist *playlist = [[VLCMain sharedInstance] playlist];
168 169
    [playlist setOutlineView:(VLCPlaylistView *)_outlineView];
    [playlist setPlaylistHeaderView:_outlineView.headerView];
170
    [self setNextResponder:playlist];
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

    // (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")];
187
    [_searchField.cell accessibilitySetOverrideValue:_NS("Search the playlist. Results will be selected in the table.")
188 189 190 191 192 193
                                        forAttribute:NSAccessibilityDescriptionAttribute];

    // Dropzone
    [_dropzoneLabel setStringValue:_NS("Drop media here")];
    [_dropzoneImageView setImage:imageFromRes(@"dropzone")];
    [_dropzoneButton setTitle:_NS("Open media...")];
194
    [_dropzoneButton.cell accessibilitySetOverrideValue:_NS("Open a dialog to select the media to play")
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
                                           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")];
212

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

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

226 227
    _fspanel = [[VLCFSPanelController alloc] init];
    [_fspanel showWindow:self];
228

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

233
        [_sidebarView expandItem:nil expandChildren:YES];
234

Felix Paul Kühne's avatar
Felix Paul Kühne committed
235
        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.")];
236
        NSInteger returnValue = [albumArtAlert runModal];
237
        config_PutInt(getIntf(), "metadata-network-access", returnValue == NSAlertDefaultReturn);
238 239
    }

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

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

250
        self.previousSavedFrame = [self frame];
251
    } else {
252 253
        [_playlistScrollView setBorderType:NSNoBorder];
        [_sidebarScrollView setBorderType:NSNoBorder];
254
    }
255

Felix Paul Kühne's avatar
Felix Paul Kühne committed
256 257 258
    [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];
259
    [defaultCenter addObserver: self selector: @selector(mainSplitViewDidResizeSubviews:) name: NSSplitViewDidResizeSubviewsNotification object:_splitView];
260

261 262
    if (splitViewShouldBeHidden) {
        [self hideSplitView:YES];
263
        f_lastSplitViewHeight = 300;
264
    }
265 266

    /* sanity check for the window size */
267
    NSRect frame = [self frame];
268 269
    NSSize screenSize = [[self screen] frame].size;
    if (screenSize.width <= frame.size.width || screenSize.height <= frame.size.height) {
270
        self.nativeVideoSize = screenSize;
271 272
        [self resizeWindow];
    }
273

274
    /* update fs button to reflect state for next startup */
275
    if (var_InheritBool(pl_Get(getIntf()), "fullscreen"))
276
        [self.controlsBar setFullscreenState:YES];
277 278

    /* restore split view */
279
    f_lastLeftSplitViewWidth = 200;
280
    /* trick NSSplitView implementation, which pretends to know better than us */
281
    if (!var_InheritBool(getIntf(), "macosx-show-sidebar"))
282
        [self performSelector:@selector(toggleLeftSubSplitView) withObject:nil afterDelay:0.05];
283 284
}

285
#pragma mark -
286
#pragma mark appearance management
287

288 289 290
- (void)reloadSidebar
{
    BOOL isAReload = NO;
291
    if (o_sidebaritems)
292 293 294 295 296
        isAReload = YES;

    o_sidebaritems = [[NSMutableArray alloc] init];
    SideBarItem *libraryItem = [SideBarItem itemWithTitle:_NS("LIBRARY") identifier:@"library"];
    SideBarItem *playlistItem = [SideBarItem itemWithTitle:_NS("Playlist") identifier:@"playlist"];
297
    [playlistItem setIcon: imageFromRes(@"sidebar-playlist")];
298
    SideBarItem *medialibraryItem = [SideBarItem itemWithTitle:_NS("Media Library") identifier:@"medialibrary"];
299
    [medialibraryItem setIcon: imageFromRes(@"sidebar-playlist")];
300 301 302 303 304
    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"];

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

379 380 381
    [_sidebarView reloadData];
    [_sidebarView setDropItem:playlistItem dropChildIndex:NSOutlineViewDropOnItemIndex];
    [_sidebarView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
382

383 384 385 386
    [_sidebarView setAutosaveName:@"mainwindow-sidebar"];
    [_sidebarView setDataSource:self];
    [_sidebarView setDelegate:self];
    [_sidebarView setAutosaveExpandedItems:YES];
387

388
    [_sidebarView expandItem:libraryItem expandChildren:YES];
389 390

    if (isAReload) {
391
        [_sidebarView expandItem:nil expandChildren:YES];
392 393 394
    }
}

395
// Show split view and hide the video view
396 397
- (void)makeSplitViewVisible
{
398
    if (self.darkInterface)
399
        [self setContentMinSize: NSMakeSize(604., f_min_window_height + [self.titlebarView frame].size.height)];
400
    else
401
        [self setContentMinSize: NSMakeSize(604., f_min_window_height)];
402 403

    NSRect old_frame = [self frame];
404
    CGFloat newHeight = [self minSize].height;
405
    if (old_frame.size.height < newHeight) {
406 407 408 409
        NSRect new_frame = old_frame;
        new_frame.origin.y = old_frame.origin.y + old_frame.size.height - newHeight;
        new_frame.size.height = newHeight;

410
        [[self animator] setFrame:new_frame display:YES animate:YES];
411 412
    }

413 414
    [self.videoView setHidden:YES];
    [_splitView setHidden:NO];
415
    if (self.nativeFullscreenMode && [self fullscreen]) {
416
        [self showControlsBar];
417
        [self.fspanel setNonActive];
418 419
    }

420
    [self makeFirstResponder:_playlistScrollView];
421 422
}

423
// Hides the split view and makes the vout view in foreground
424 425
- (void)makeSplitViewHidden
{
426
    if (self.darkInterface)
427
        [self setContentMinSize: NSMakeSize(604., f_min_video_height + [self.titlebarView frame].size.height)];
428
    else
429
        [self setContentMinSize: NSMakeSize(604., f_min_video_height)];
430

431 432
    [_splitView setHidden:YES];
    [self.videoView setHidden:NO];
433
    if (self.nativeFullscreenMode && [self fullscreen]) {
434
        [self hideControlsBar];
435
        [self.fspanel setActive];
436
    }
437

438
    if ([[self.videoView subviews] count] > 0)
439
        [self makeFirstResponder: [[self.videoView subviews] firstObject]];
440 441
}

442 443

- (void)changePlaylistState:(VLCPlaylistStateEvent)event
444
{
445 446
    // Beware, this code is really ugly

447
    msg_Dbg(getIntf(), "toggle playlist from state: removed splitview %i, minimized view %i. Event %i", b_splitview_removed, b_minimized_view, event);
448 449
    if (![self isVisible] && event == psUserMenuEvent) {
        [self makeKeyAndOrderFront: nil];
450
        return;
451 452
    }

453
    BOOL b_activeVideo = [[VLCMain sharedInstance] activeVideoPlayback];
454
    BOOL b_restored = NO;
455

456
    // ignore alt if triggered through main menu shortcut
457
    BOOL b_have_alt_key = ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0;
458
    if (event == psUserMenuEvent)
459 460
        b_have_alt_key = NO;

461 462 463 464
    // eUserMenuEvent is now handled same as eUserEvent
    if(event == psUserMenuEvent)
        event = psUserEvent;

465
    if (b_dropzone_active && b_have_alt_key) {
466 467 468 469
        [self hideDropZone];
        return;
    }

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

483
            if (event != psUserEvent)
484 485 486 487 488 489
                b_minimized_view = YES;
            else
                b_minimized_view = NO;

            if (b_activeVideo)
                b_restored = YES;
490 491
        }

492 493
        if (!self.nonembedded) {
            if (([self.videoView isHidden] && b_activeVideo) || b_restored || (b_activeVideo && event != psUserEvent))
494
                [self makeSplitViewHidden];
495
            else
496
                [self makeSplitViewVisible];
497
        } else {
498 499
            [_splitView setHidden: NO];
            [_playlistScrollView setHidden: NO];
500
            [self.videoView setHidden: YES];
501
            [self showControlsBar];
502
        }
503
    }
504

505
    msg_Dbg(getIntf(), "toggle playlist to state: removed splitview %i, minimized view %i", b_splitview_removed, b_minimized_view);
506 507
}

508 509 510 511 512
- (IBAction)dropzoneButtonAction:(id)sender
{
    [[[VLCMain sharedInstance] open] openFileGeneric];
}

513 514 515
#pragma mark -
#pragma mark overwritten default functionality

516 517
- (void)windowResizedOrMoved:(NSNotification *)notification
{
518
    [self saveFrameUsingName:[self frameAutosaveName]];
519 520
}

521 522
- (void)applicationWillTerminate:(NSNotification *)notification
{
523
    config_PutInt(getIntf(), "macosx-show-sidebar", ![_splitView isSubviewCollapsed:_splitViewLeft]);
524
    [self saveFrameUsingName:[self frameAutosaveName]];
525 526
}

527

528 529
- (void)someWindowWillClose:(NSNotification *)notification
{
530
    id obj = [notification object];
531

532 533
    // hasActiveVideo is defined for VLCVideoWindowCommon and subclasses
    if ([obj respondsToSelector:@selector(hasActiveVideo)] && [obj hasActiveVideo]) {
534 535 536
        if ([[VLCMain sharedInstance] activeVideoPlayback])
            [[VLCCoreInteraction sharedInstance] stop];
    }
537 538 539 540
}

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

544
        if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !self.nonembedded)) {
545
            if ([[VLCMain sharedInstance] activeVideoPlayback])
546 547
                [[VLCCoreInteraction sharedInstance] pause];
        }
548 549 550
    }
}

551 552
#pragma mark -
#pragma mark Update interface and respond to foreign events
553 554
- (void)showDropZone
{
555
    b_dropzone_active = YES;
556
    [_dropzoneView setHidden:NO];
557
    [_playlistScrollView setHidden:YES];
558 559 560 561
}

- (void)hideDropZone
{
562
    b_dropzone_active = NO;
563
    [_dropzoneView setHidden:YES];
564
    [_playlistScrollView setHidden:NO];
565 566
}

567
- (void)hideSplitView:(BOOL)resize
568
{
569
    if (resize) {
570
        NSRect winrect = [self frame];
571
        f_lastSplitViewHeight = [_splitView frame].size.height;
572 573
        winrect.size.height = winrect.size.height - f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y + f_lastSplitViewHeight;
574
        [self setFrame:winrect display:YES animate:YES];
575 576
    }

577
    if (self.darkInterface) {
578 579
        [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)];
580
    } else {
581 582
        [self setContentMinSize: NSMakeSize(604., [self.controlsBar height])];
        [self setContentMaxSize: NSMakeSize(FLT_MAX, [self.controlsBar height])];
583
    }
584

585 586 587
    b_splitview_removed = YES;
}

588
- (void)showSplitView:(BOOL)resize
589
{
590
    [self updateWindow];
591
    if (self.darkInterface)
592
        [self setContentMinSize:NSMakeSize(604., f_min_window_height + [self.titlebarView frame].size.height)];
593
    else
594
        [self setContentMinSize:NSMakeSize(604., f_min_window_height)];
595
    [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
596

597
    if (resize) {
598 599
        NSRect winrect;
        winrect = [self frame];
600 601
        winrect.size.height = winrect.size.height + f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y - f_lastSplitViewHeight;
602
        [self setFrame:winrect display:YES animate:YES];
603
    }
604 605 606 607

    b_splitview_removed = NO;
}

608 609
- (void)updateTimeSlider
{
610 611
    [self.controlsBar updateTimeSlider];
    [self.fspanel updatePositionAndTime];
612

613 614 615
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar updateTimeSlider];
    }];
616 617

    [[VLCCoreInteraction sharedInstance] updateAtoB];
618 619
}

620
- (void)updateName
621
{
622
    input_thread_t *p_input;
623
    p_input = pl_CurrentInput(getIntf());
624
    if (p_input) {
625
        NSString *aString = @"";
626

627 628
        if (!config_GetPsz(getIntf(), "video-title")) {
            char *format = var_InheritString(getIntf(), "input-title-format");
629
            if (format) {
630
                char *formated = vlc_strfinput(p_input, format);
631 632 633 634
                free(format);
                aString = toNSStr(formated);
                free(formated);
            }
635
        } else
636
            aString = toNSStr(config_GetPsz(getIntf(), "video-title"));
637

638
        char *uri = input_item_GetURI(input_GetItem(p_input));
639

640
        NSURL * o_url = [NSURL URLWithString:toNSStr(uri)];
641
        if ([o_url isFileURL]) {
642
            [self setRepresentedURL: o_url];
643 644 645
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setRepresentedURL:o_url];
            }];
646
        } else {
647
            [self setRepresentedURL: nil];
648 649 650
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setRepresentedURL:nil];
            }];
651
        }
652
        free(uri);
653

654
        if ([aString isEqualToString:@""]) {
655 656 657 658
            if ([o_url isFileURL])
                aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
            else
                aString = [o_url absoluteString];
659
        }
660

661 662 663 664 665 666
        if ([aString length] > 0) {
            [self setTitle: aString];
            [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
                [o_window setTitle:aString];
            }];

667
            [self.fspanel setStreamTitle: aString];
668
        } else {
669
            [self setTitle: _NS("VLC media player")];
670 671
            [self setRepresentedURL: nil];
        }
672

673 674
        vlc_object_release(p_input);
    } else {
675
        [self setTitle: _NS("VLC media player")];
676
        [self setRepresentedURL: nil];
677
    }
678 679
}

680 681
- (void)updateWindow
{
682
    [self.controlsBar updateControls];
683 684 685
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar updateControls];
    }];
686

687 688
    bool b_seekable = false;

689
    playlist_t *p_playlist = pl_Get(getIntf());
690
    input_thread_t *p_input = playlist_CurrentInput(p_playlist);
691
    if (p_input) {
692
        /* seekable streams */
693
        b_seekable = var_GetBool(p_input, "can-seek");
694

695
        vlc_object_release(p_input);
696 697
    }

698
    [self updateTimeSlider];
699 700
    if ([self.fspanel respondsToSelector:@selector(setSeekable:)])
        [self.fspanel setSeekable: b_seekable];
701 702

    PL_LOCK;
703 704
    if ([[[[VLCMain sharedInstance] playlist] model] currentRootType] != ROOT_TYPE_PLAYLIST ||
        [[[[VLCMain sharedInstance] playlist] model] hasChildren])
705 706 707 708
        [self hideDropZone];
    else
        [self showDropZone];
    PL_UNLOCK;
709
    [_sidebarView setNeedsDisplay:YES];
710 711

    [self _updatePlaylistTitle];
712 713 714 715
}

- (void)setPause
{
716 717
    [self.controlsBar setPause];
    [self.fspanel setPause];
718

719 720 721
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar setPause];
    }];
722 723 724 725
}

- (void)setPlay
{
726 727
    [self.controlsBar setPlay];
    [self.fspanel setPlay];
728

729 730 731
    [[[VLCMain sharedInstance] voutController] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
        [controlsBar setPlay];
    }];
732 733
}

734
- (void)updateVolumeSlider
735
{
736
    [(VLCMainWindowControlsBar *)[self controlsBar] updateVolumeSlider];
737
    [self.fspanel setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume]];
738 739
}

740 741
#pragma mark -
#pragma mark Video Output handling
742

743 744
- (void)videoplayWillBeStarted
{
745
    if (!self.fullscreen)
746 747 748
        frameBeforePlayback = [self frame];
}

749
- (void)setVideoplayEnabled
750
{
751
    BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
752

753
    if (!b_videoPlayback) {
754
        if (!self.nonembedded && (!self.nativeFullscreenMode || (self.nativeFullscreenMode && !self.fullscreen)) && frameBeforePlayback.size.width > 0 && frameBeforePlayback.size.height > 0) {
755 756

            // only resize back to minimum view of this is still desired final state
757
            CGFloat f_threshold_height = f_min_video_height + [self.controlsBar height];
758
            if(frameBeforePlayback.size.height > f_threshold_height || b_minimized_view) {
759 760 761 762 763 764

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

765
            }
766 767 768
        }

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

770
        // update fs button to reflect state for next startup
771
        if (var_InheritBool(getIntf(), "fullscreen") || var_GetBool(pl_Get(getIntf()), "fullscreen")) {
772
            [self.controlsBar setFullscreenState:YES];
773 774
        }

775
        [self makeFirstResponder: _playlistScrollView];
776
        [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
777

778 779 780
        // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
        [self setAlphaValue:1.0];
    }
781

782
    if (self.nativeFullscreenMode) {
783 784
        if ([self hasActiveVideo] && [self fullscreen] && b_videoPlayback) {
            [self hideControlsBar];
785
            [self.fspanel setActive];
786
        } else {
787
            [self showControlsBar];
788
            [self.fspanel setNonActive];
789
        }
790
    }
791
}
792

793 794
#pragma mark -
#pragma mark Fullscreen support
795

796 797
- (void)showFullscreenController
{
798 799
    id currentWindow = [NSApp keyWindow];
    if ([currentWindow respondsToSelector:@selector(hasActiveVideo)] && [currentWindow hasActiveVideo]) {
800
        if ([currentWindow respondsToSelector:@selector(fullscreen)] && [currentWindow fullscreen] && ![[currentWindow videoView] isHidden]) {
801 802

            if ([[VLCMain sharedInstance] activeVideoPlayback])
803
                [self.fspanel fadeIn];
804 805
        }
    }
806

807 808
}

809
#pragma mark -
810 811 812 813
#pragma mark split view delegate
- (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
{
    if (dividerIndex == 0)
814
        return 300.;
815 816 817 818
    else
        return proposedMax;
}

819 820 821 822 823 824 825 826
- (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
{
    if (dividerIndex == 0)
        return 100.;
    else
        return proposedMin;
}

827 828
- (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview
{
829
    return ([subview isEqual:_splitViewLeft]);
830 831
}

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

837
- (void)mainSplitViewDidResizeSubviews:(id)object
838
{
839
    f_lastLeftSplitViewWidth = [_splitViewLeft frame].size.width;
840
    config_PutInt(getIntf(), "macosx-show-sidebar", ![_splitView isSubviewCollapsed:_splitViewLeft]);
841 842 843 844 845
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
}

- (void)toggleLeftSubSplitView
{
846 847 848
    [_splitView adjustSubviews];
    if ([_splitView isSubviewCollapsed:_splitViewLeft])
        [_splitView setPosition:f_lastLeftSplitViewWidth ofDividerAtIndex:0];
849
    else
850
        [_splitView setPosition:[_splitView minPossiblePositionOfDividerAtIndex:0] ofDividerAtIndex:0];
851
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
852 853
}

854 855 856 857
#pragma mark -
#pragma mark private playlist magic
- (void)_updatePlaylistTitle
{
858
    PLRootType root = [[[[VLCMain sharedInstance] playlist] model] currentRootType];
859
    playlist_t *p_playlist = pl_Get(getIntf());
860

861 862
    PL_LOCK;
    if (root == ROOT_TYPE_PLAYLIST)
863
        [_categoryLabel setStringValue: [_NS("Playlist") stringByAppendingString:[self _playbackDurationOfNode:p_playlist->p_playing]]];
864
    else if (root == ROOT_TYPE_MEDIALIBRARY)
865
        [_categoryLabel setStringValue: [_NS("Media Library") stringByAppendingString:[self _playbackDurationOfNode:p_playlist->p_media_library]]];
866 867

    PL_UNLOCK;
868 869 870 871 872 873 874
}

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

875
    playlist_t * p_playlist = pl_Get(getIntf());
876 877
    PL_ASSERT_LOCKED;

878 879 880 881 882 883 884
    mtime_t mt_duration = playlist_GetNodeDuration( node );

    if (mt_duration < 1)
        return @"";

    mt_duration = mt_duration / 1000000;

885 886 887 888
    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;

    NSString* outputString = [formatter stringFromTimeInterval:mt_duration];
889

890
    return [NSString stringWithFormat:@" — %@", outputString];
891 892
}

893 894
- (IBAction)searchItem:(id)sender
{
895
    [[[[VLCMain sharedInstance] playlist] model] searchUpdate:[_searchField stringValue]];
896 897
}

898 899 900 901 902
- (IBAction)highlightSearchField:(id)sender
{
    [_searchField selectText:sender];
}

903
#pragma mark -
904 905 906 907
#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
{
908
    //Works the same way as the NSOutlineView data source: `nil` means a parent item
909
    if (item==nil)
910 911 912
        return [o_sidebaritems count];
    else
        return [[item children] count];
913 914 915 916 917 918
}


- (id)sourceList:(PXSourceList*)aSourceList child:(NSUInteger)index ofItem:(id)item
{
    //Works the same way as the NSOutlineView data source: `nil` means a parent item
919
    if (item==nil)
920
        return [o_sidebaritems objectAtIndex:index];
921
    else
922
        return [[item children] objectAtIndex:index];
923 924 925 926 927
}


- (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
{
928
    return [item title];
929 930 931 932
}

- (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
{
933
    [item setTitle:object];
934 935 936 937
}

- (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
{
938
    return [item hasChildren];
939 940 941 942 943
}


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

947
    return [item hasBadge];
948 949 950 951 952
}


- (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
{
953
    playlist_t * p_playlist = pl_Get(getIntf());
954
    NSInteger i_playlist_size = 0;
955

956
    if ([[item identifier] isEqualToString: @"playlist"]) {
957
        PL_LOCK;
958
        i_playlist_size = p_playlist->p_playing->i_children;
959 960 961 962
        PL_UNLOCK;

        return i_playlist_size;
    }
963
    if ([[item identifier] isEqualToString: @"medialibrary"]) {
964
        PL_LOCK;
965 966
        if (p_playlist->p_media_library)
            i_playlist_size = p_playlist->p_media_library->i_children;
967 968 969 970
        PL_UNLOCK;

        return i_playlist_size;
    }
971 972

    return [item badgeValue];
973 974 975 976 977
}


- (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
{
978
    return [item hasIcon];
979 980 981 982 983
}


- (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
{
984
    return [item icon];
985 986 987 988
}

- (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
{
989 990
    if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
        if (item != nil) {
991 992
            if ([item sdtype] > 0)
            {
993
                NSMenu *m = [[NSMenu alloc] init];
994
                playlist_t * p_playlist = pl_Get(getIntf());
995
                BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
996 997 998 999 1000
                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]];
1001
                return m;
1002 1003
            }
        }
1004 1005 1006
    }

    return nil;
1007 1008
}

1009 1010 1011
- (IBAction)sdmenuhandler:(id)sender
{
    NSString * identifier = [sender representedObject];
1012
    if ([identifier length] > 0 && ![identifier isEqualToString:@"lua{sd='freebox',longname='Freebox TV'}"]) {
1013
        playlist_t * p_playlist = pl_Get(getIntf());
1014
        BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [identifier UTF8String]);
1015 1016

        if (!sd_loaded)
1017
            playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
1018
        else
1019
            playlist_ServicesDiscoveryRemove(p_playlist, [identifier UTF8String]);
1020 1021 1022
    }
}

Felix Paul Kühne's avatar