VLCMainWindow.m 46 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 "VLCVideoOutputProvider.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(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 155 156
    [self setDelegate:self];
    [self setRestorable:NO];
    [self setExcludedFromWindowsMenu:YES];
    [self setAcceptsMouseMovedEvents:YES];
157 158
    [self setFrameAutosaveName:@"mainwindow"];

159
    _nativeFullscreenMode = var_InheritBool(getIntf(), "macosx-nativefullscreenmode");
160
    b_dropzone_active = YES;
161

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

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

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

209
    /* interface builder action */
210
    CGFloat f_threshold_height = f_min_video_height + [self.controlsBar height];
211

212
    if ([[self contentView] frame].size.height < f_threshold_height)
213
        splitViewShouldBeHidden = YES;
214

215
    // Set that here as IB seems to be buggy
216
    [self setContentMinSize:NSMakeSize(604., f_min_window_height)];
217

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

222
        [_sidebarView expandItem:nil expandChildren:YES];
223

224 225 226 227 228 229
        NSAlert *albumArtAlert = [[NSAlert alloc] init];
        [albumArtAlert setMessageText:_NS("Check for album art and metadata?")];
        [albumArtAlert setInformativeText:_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.")];
        [albumArtAlert addButtonWithTitle:_NS("Enable Metadata Retrieval")];
        [albumArtAlert addButtonWithTitle:_NS("No, Thanks")];

230
        NSInteger returnValue = [albumArtAlert runModal];
231
        config_PutInt("metadata-network-access", returnValue == NSAlertFirstButtonReturn);
232 233
    }

234 235
    [_playlistScrollView setBorderType:NSNoBorder];
    [_sidebarScrollView setBorderType:NSNoBorder];
236

Felix Paul Kühne's avatar
Felix Paul Kühne committed
237 238 239
    [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];
240
    [defaultCenter addObserver: self selector: @selector(mainSplitViewDidResizeSubviews:) name: NSSplitViewDidResizeSubviewsNotification object:_splitView];
241

242 243
    if (splitViewShouldBeHidden) {
        [self hideSplitView:YES];
244
        f_lastSplitViewHeight = 300;
245
    }
246 247

    /* sanity check for the window size */
248
    NSRect frame = [self frame];
249 250
    NSSize screenSize = [[self screen] frame].size;
    if (screenSize.width <= frame.size.width || screenSize.height <= frame.size.height) {
251
        self.nativeVideoSize = screenSize;
252 253
        [self resizeWindow];
    }
254

255
    /* update fs button to reflect state for next startup */
256
    if (var_InheritBool(pl_Get(getIntf()), "fullscreen"))
257
        [self.controlsBar setFullscreenState:YES];
258 259

    /* restore split view */
260
    f_lastLeftSplitViewWidth = 200;
261
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem: ![_splitView isSubviewCollapsed:_splitViewLeft]];
262 263
}

264
#pragma mark -
265
#pragma mark appearance management
266

267 268 269
- (void)reloadSidebar
{
    BOOL isAReload = NO;
270
    if (o_sidebaritems)
271 272 273 274 275
        isAReload = YES;

    o_sidebaritems = [[NSMutableArray alloc] init];
    SideBarItem *libraryItem = [SideBarItem itemWithTitle:_NS("LIBRARY") identifier:@"library"];
    SideBarItem *playlistItem = [SideBarItem itemWithTitle:_NS("Playlist") identifier:@"playlist"];
276
    [playlistItem setIcon: imageFromRes(@"sidebar-playlist")];
277
    SideBarItem *medialibraryItem = [SideBarItem itemWithTitle:_NS("Media Library") identifier:@"medialibrary"];
278
    [medialibraryItem setIcon: imageFromRes(@"sidebar-playlist")];
279 280 281 282 283
    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"];

284
    /* SD subnodes, inspired by the Qt intf */
285 286
    char **ppsz_longnames = NULL;
    int *p_categories = NULL;
287
    char **ppsz_names = vlc_sd_GetNames(pl_Get(getIntf()), &ppsz_longnames, &p_categories);
288
    if (!ppsz_names)
289
        msg_Err(getIntf(), "no sd item found"); //TODO
290 291 292 293 294 295 296 297
    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++) {
298
        o_identifier = toNSStr(*ppsz_name);
299 300 301
        switch (*p_category) {
            case SD_CAT_INTERNET:
                [internetItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
302
                [[internetItems lastObject] setIcon: imageFromRes(@"sidebar-podcast")];
303 304 305 306
                [[internetItems lastObject] setSdtype: SD_CAT_INTERNET];
                break;
            case SD_CAT_DEVICES:
                [devicesItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
307
                [[devicesItems lastObject] setIcon: imageFromRes(@"sidebar-local")];
308 309 310 311
                [[devicesItems lastObject] setSdtype: SD_CAT_DEVICES];
                break;
            case SD_CAT_LAN:
                [lanItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
312
                [[lanItems lastObject] setIcon: imageFromRes(@"sidebar-local")];
313 314 315 316 317
                [[lanItems lastObject] setSdtype: SD_CAT_LAN];
                break;
            case SD_CAT_MYCOMPUTER:
                [mycompItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
                if (!strncmp(*ppsz_name, "video_dir", 9))
318
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-movie")];
319
                else if (!strncmp(*ppsz_name, "audio_dir", 9))
320
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-music")];
321
                else if (!strncmp(*ppsz_name, "picture_dir", 11))
322
                    [[mycompItems lastObject] setIcon: imageFromRes(@"sidebar-pictures")];
323 324 325 326 327
                else
                    [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
                [[mycompItems lastObject] setSdtype: SD_CAT_MYCOMPUTER];
                break;
            default:
328
                msg_Warn(getIntf(), "unknown SD type found, skipping (%s)", *ppsz_name);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                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];

354 355 356
    [_sidebarView reloadData];
    [_sidebarView setDropItem:playlistItem dropChildIndex:NSOutlineViewDropOnItemIndex];
    [_sidebarView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
357

358 359 360 361
    [_sidebarView setAutosaveName:@"mainwindow-sidebar"];
    [_sidebarView setDataSource:self];
    [_sidebarView setDelegate:self];
    [_sidebarView setAutosaveExpandedItems:YES];
362

363
    [_sidebarView expandItem:libraryItem expandChildren:YES];
364 365

    if (isAReload) {
366
        [_sidebarView expandItem:nil expandChildren:YES];
367 368 369
    }
}

370
// Show split view and hide the video view
371
- (void)makeSplitViewVisible//making the playlist view visible
372
{
373
    [self setContentMinSize: NSMakeSize(604., f_min_window_height)];
374 375

    NSRect old_frame = [self frame];
376
    CGFloat newHeight = [self minSize].height;
377
    if (old_frame.size.height < newHeight) {
378 379 380 381
        NSRect new_frame = old_frame;
        new_frame.origin.y = old_frame.origin.y + old_frame.size.height - newHeight;
        new_frame.size.height = newHeight;

382
        [[self animator] setFrame:new_frame display:YES animate:YES];
383 384
    }

385 386
    [self.videoView setHidden:YES];
    [_splitView setHidden:NO];
387
    if (self.nativeFullscreenMode && [self fullscreen]) {
388
        [self showControlsBar];
389
//        [self.fspanel setNonActive];
390 391
    }

392
    [self makeFirstResponder:_playlistScrollView];
393 394
}

395
// Hides the split view and makes the vout view in foreground
396 397
- (void)makeSplitViewHidden
{
398
    [self setContentMinSize: NSMakeSize(604., f_min_video_height)];
399

400 401
    [_splitView setHidden:YES];
    [self.videoView setHidden:NO];
402
    if (self.nativeFullscreenMode && [self fullscreen]) {
403
        [self hideControlsBar];
404
//        [self.fspanel setActive];
405
    }
406

407
    if ([[self.videoView subviews] count] > 0)
408
        [self makeFirstResponder: [[self.videoView subviews] firstObject]];
409 410
}

411
- (void)changePlaylistState:(VLCPlaylistStateEvent)event
412
{
413 414
    // Beware, this code is really ugly

415
    msg_Err(getIntf(), "toggle playlist from state: removed splitview %i, minimized view %i. Event %i", b_splitview_removed, b_minimized_view, event);
416 417
    if (![self isVisible] && event == psUserMenuEvent) {
        [self makeKeyAndOrderFront: nil];
418
        return;
419 420
    }

421
    BOOL b_activeVideo = [[VLCMain sharedInstance] activeVideoPlayback];
422
    BOOL b_restored = NO;
423

424
    // ignore alt if triggered through main menu shortcut
425
    BOOL b_have_alt_key = ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0;
426
    if (event == psUserMenuEvent)
427 428
        b_have_alt_key = NO;

429 430 431 432
    // eUserMenuEvent is now handled same as eUserEvent
    if(event == psUserMenuEvent)
        event = psUserEvent;

433
    if (b_dropzone_active && b_have_alt_key) {
434 435 436 437
        [self hideDropZone];
        return;
    }

438 439
    if (!(self.nativeFullscreenMode && self.fullscreen) && !b_splitview_removed && ((b_have_alt_key && b_activeVideo)
                                                                              || (self.nonembedded && event == psUserEvent)
440 441
                                                                              || (!b_activeVideo && event == psUserEvent)
                                                                              || (b_minimized_view && event == psVideoStartedOrStoppedEvent))) {
442 443
        // for starting playback, window is resized through resized events
        // for stopping playback, resize through reset to previous frame
444
        [self hideSplitView: event != psVideoStartedOrStoppedEvent];
445 446
        b_minimized_view = NO;
    } else {
447
        if (b_splitview_removed) {
448
            if (!self.nonembedded || (event == psUserEvent && self.nonembedded))
449
                [self showSplitView: event != psVideoStartedOrStoppedEvent];
450

451
            if (event != psUserEvent)
452 453 454 455 456 457
                b_minimized_view = YES;
            else
                b_minimized_view = NO;

            if (b_activeVideo)
                b_restored = YES;
458 459
        }

460 461
        if (!self.nonembedded) {
            if (([self.videoView isHidden] && b_activeVideo) || b_restored || (b_activeVideo && event != psUserEvent))
462
                [self makeSplitViewHidden];
463
            else
464
                [self makeSplitViewVisible];
465
        } else {
466 467
            [_splitView setHidden: NO];
            [_playlistScrollView setHidden: NO];
468
            [self.videoView setHidden: YES];
469
            [self showControlsBar];
470
        }
471
    }
472

473
    msg_Err(getIntf(), "toggle playlist to state: removed splitview %i, minimized view %i", b_splitview_removed, b_minimized_view);
474 475
}

476 477 478 479 480
- (IBAction)dropzoneButtonAction:(id)sender
{
    [[[VLCMain sharedInstance] open] openFileGeneric];
}

481 482 483
#pragma mark -
#pragma mark overwritten default functionality

484 485 486 487 488 489
- (void)windowDidMove:(NSNotification *)notification{
    [[self draggablepanel] centerPanel];
    msg_Err(getIntf(),"windowDidMove so I am re-centering the draggablepanel"); //Debug-Statement
    NSLog(@"%f",[self frame].origin.x); //Debug-Statement
}

490 491
- (void)windowResizedOrMoved:(NSNotification *)notification
{
492
    //What is this for? It does not get trigger on neither resize nor move. And it does not seem to be in apple documentation
493
    [self saveFrameUsingName:[self frameAutosaveName]];
494 495
}

496 497
- (void)applicationWillTerminate:(NSNotification *)notification
{
498
    [self saveFrameUsingName:[self frameAutosaveName]];
499 500
}

501

502 503
- (void)someWindowWillClose:(NSNotification *)notification
{
504
    id obj = [notification object];
505

506 507
    // hasActiveVideo is defined for VLCVideoWindowCommon and subclasses
    if ([obj respondsToSelector:@selector(hasActiveVideo)] && [obj hasActiveVideo]) {
508 509 510
        if ([[VLCMain sharedInstance] activeVideoPlayback])
            [[VLCCoreInteraction sharedInstance] stop];
    }
511 512 513 514
}

- (void)someWindowWillMiniaturize:(NSNotification *)notification
{
515
    if (config_GetInt("macosx-pause-minimized")) {
516
        id obj = [notification object];
517

518
        if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !self.nonembedded)) {
519
            if ([[VLCMain sharedInstance] activeVideoPlayback])
520 521
                [[VLCCoreInteraction sharedInstance] pause];
        }
522 523 524
    }
}

525 526
#pragma mark -
#pragma mark Update interface and respond to foreign events
527 528
- (void)showDropZone
{
529
    b_dropzone_active = YES;
530
    [_dropzoneView setHidden:NO];
531
    [_playlistScrollView setHidden:YES];
532 533 534 535
}

- (void)hideDropZone
{
536
    b_dropzone_active = NO;
537
    [_dropzoneView setHidden:YES];
538
    [_playlistScrollView setHidden:NO];
539 540
}

541
- (void)hideSplitView:(BOOL)resize
542
{
543
    if (resize) {
544
        NSRect winrect = [self frame];
545
        f_lastSplitViewHeight = [_splitView frame].size.height;
546 547
        winrect.size.height = winrect.size.height - f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y + f_lastSplitViewHeight;
548
        [self setFrame:winrect display:YES animate:YES];
549 550
    }

551 552
    [self setContentMinSize: NSMakeSize(604., [self.controlsBar height])];
    [self setContentMaxSize: NSMakeSize(FLT_MAX, [self.controlsBar height])];
553

554 555 556
    b_splitview_removed = YES;
}

557
- (void)showSplitView:(BOOL)resize
558
{
559
    [self updateWindow];
560
    [self setContentMinSize:NSMakeSize(604., f_min_window_height)];
561
    [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
562

563
    if (resize) {
564 565
        NSRect winrect;
        winrect = [self frame];
566 567
        winrect.size.height = winrect.size.height + f_lastSplitViewHeight;
        winrect.origin.y = winrect.origin.y - f_lastSplitViewHeight;
568
        [self setFrame:winrect display:YES animate:YES];
569
    }
570 571 572 573

    b_splitview_removed = NO;
}

574 575
- (void)updateTimeSlider
{
576
    [self.controlsBar updateTimeSlider];
577 578 579 580 581 582
//    [[[[VLCMain sharedInstance] voutProvider] fspanel] updatePositionAndTime];
    [self.draggablepanel updatePositionAndTime];

    [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
        [draggablepanel updatePositionAndTime];
    }];
583

584
    [[[VLCMain sharedInstance] voutProvider] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
585 586
        [controlsBar updateTimeSlider];
    }];
587 588

    [[VLCCoreInteraction sharedInstance] updateAtoB];
589 590
}

591
- (void)updateName
592
{
593
    input_thread_t *p_input;
594
    p_input = pl_CurrentInput(getIntf());
595
    if (p_input) {
596
        NSString *aString = @"";
597

598
        if (!config_GetPsz("video-title")) {
599
            char *format = var_InheritString(getIntf(), "input-title-format");
600
            if (format) {
601
                char *formated = vlc_strfinput(p_input, format);
602 603 604 605
                free(format);
                aString = toNSStr(formated);
                free(formated);
            }
606
        } else
607
            aString = toNSStr(config_GetPsz("video-title"));
608

609
        char *uri = input_item_GetURI(input_GetItem(p_input));
610

611
        NSURL * o_url = [NSURL URLWithString:toNSStr(uri)];
612
        if ([o_url isFileURL]) {
613
            [self setRepresentedURL: o_url];
614
            [[[VLCMain sharedInstance] voutProvider] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
615 616
                [o_window setRepresentedURL:o_url];
            }];
617
        } else {
618
            [self setRepresentedURL: nil];
619
            [[[VLCMain sharedInstance] voutProvider] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
620 621
                [o_window setRepresentedURL:nil];
            }];
622
        }
623
        free(uri);
624

625
        if ([aString isEqualToString:@""]) {
626 627 628 629
            if ([o_url isFileURL])
                aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
            else
                aString = [o_url absoluteString];
630
        }
631

632 633
        if ([aString length] > 0) {
            [self setTitle: aString];
634
            [[[VLCMain sharedInstance] voutProvider] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
635 636 637
                [o_window setTitle:aString];
            }];

638 639 640 641 642 643
//            [[[[VLCMain sharedInstance] voutProvider] fspanel] setStreamTitle: aString];
            [self.draggablepanel setStreamTitle: aString];
            [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
                [draggablepanel setStreamTitle: aString];
            }];

644
        } else {
645
            [self setTitle: _NS("VLC media player")];
646 647
            [self setRepresentedURL: nil];
        }
648

649 650
        vlc_object_release(p_input);
    } else {
651
        [self setTitle: _NS("VLC media player")];
652
        [self setRepresentedURL: nil];
653
    }
654 655
}

656 657
- (void)updateWindow
{
658
    [self.controlsBar updateControls];
659
    [[[VLCMain sharedInstance] voutProvider] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
660 661
        [controlsBar updateControls];
    }];
662

663 664
    bool b_seekable = false;

665
    playlist_t *p_playlist = pl_Get(getIntf());
666
    input_thread_t *p_input = playlist_CurrentInput(p_playlist);
667
    if (p_input) {
668
        /* seekable streams */
669
        b_seekable = var_GetBool(p_input, "can-seek");
670

671
        vlc_object_release(p_input);
672 673
    }

674
    [self updateTimeSlider];
675 676 677 678 679 680 681 682
    if ([self.draggablepanel respondsToSelector:@selector(setSeekable:)])
        [self.draggablepanel setSeekable: b_seekable];
    [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
        if ([draggablepanel respondsToSelector:@selector(setSeekable:)])
            [draggablepanel setSeekable: b_seekable];
    }];
//    if ([ [ [[VLCMain sharedInstance] voutProvider] fspanel] respondsToSelector:@selector(setSeekable:) ])
//        [[[[VLCMain sharedInstance] voutProvider] fspanel] setSeekable: b_seekable];
683 684

    PL_LOCK;
685 686
    if ([[[[VLCMain sharedInstance] playlist] model] currentRootType] != ROOT_TYPE_PLAYLIST ||
        [[[[VLCMain sharedInstance] playlist] model] hasChildren])
687 688 689 690
        [self hideDropZone];
    else
        [self showDropZone];
    PL_UNLOCK;
691
    [_sidebarView setNeedsDisplay:YES];
692 693

    [self _updatePlaylistTitle];
694 695 696 697
}

- (void)setPause
{
698
    [self.controlsBar setPause];
699 700
//    [[[[VLCMain sharedInstance] voutProvider] fspanel] setPause];
    [self.draggablepanel setPause];
701

702
    [[[VLCMain sharedInstance] voutProvider] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
703 704
        [controlsBar setPause];
    }];
705 706 707
    [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
        [draggablepanel setPause];
    }];
708 709 710 711
}

- (void)setPlay
{
712
    [self.controlsBar setPlay];
713 714
    [self.draggablepanel setPlay];
//    [[[[VLCMain sharedInstance] voutProvider] fspanel] setPlay];
715

716
    [[[VLCMain sharedInstance] voutProvider] updateControlsBarsUsingBlock:^(VLCControlsBarCommon *controlsBar) {
717 718
        [controlsBar setPlay];
    }];
719 720 721
    [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
        [draggablepanel setPlay];
    }];
722 723
}

724
- (void)updateVolumeSlider
725
{
726
    [(VLCMainWindowControlsBar *)[self controlsBar] updateVolumeSlider];
727 728 729 730 731 732 733 734
//    [self.fspanel setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume]];
    [self.draggablepanel setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume]];
    [[[VLCMain sharedInstance] voutProvider] updateDraggablePanelsUsingBlock:^(VLCFSPanelController *draggablepanel) {
        [draggablepanel setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume]];
    }];
//    msg_Err(getIntf(), "DAX WAS HERE #10 updateVolumeSlider");
//    [[[[VLCMain sharedInstance] voutProvider] fspanel] setVolumeLevel:[[VLCCoreInteraction sharedInstance] volume] ];

735 736
}

737 738
#pragma mark -
#pragma mark Video Output handling
739

740 741
- (void)videoplayWillBeStarted
{
742
    if (!self.fullscreen)
743 744 745
        frameBeforePlayback = [self frame];
}

746
- (void)setVideoplayEnabled
747
{
748
    NSLog(@"Hey there, check this out! :D");
749
    BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
750

751
    //b_videoPlayback (here) is same as b_activeVideo (changePlaylistState)
752
    if (!b_videoPlayback) {
753 754 755
        msg_Err(getIntf(), "Going from VIDEO TO PLAYLIST");//Debug-Statement
        NSLog(@"Active Video: %hhd, setting Titled Window",b_videoPlayback);//Debug-Statement
        //Issue-3
756 757 758
        self.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask;
        [[[[[[VLCMain sharedInstance] mainWindow] standardWindowButton:NSWindowCloseButton] superview] animator] setAlphaValue:1];
        [self showControlsBar];
759 760


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

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

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

772
            }
773 774 775
        }

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

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

782
        [self makeFirstResponder: _playlistScrollView];
783
        [[[VLCMain sharedInstance] voutProvider] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
784

785 786 787
        // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
        [self setAlphaValue:1.0];
    }
788 789
    else{
        NSLog(@"Active Video: %hhd, setting FullSize Window",b_videoPlayback);//Debug-Statement
790 791 792
//        self.styleMask |= NSFullSizeContentViewWindowMask;
//        [self hideControlsBar];

793
    }
794
}
795

796 797
#pragma mark -
#pragma mark Fullscreen support
798

799 800
- (void)showFullscreenController
{
801 802 803 804 805
    //see if we need it...
//    id currentWindow = [NSApp keyWindow];
//    if ([currentWindow respondsToSelector:@selector(hasActiveVideo)] && [currentWindow hasActiveVideo]) {
//        [self.draggablepanel setActive];
//    }
806 807
}

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

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

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

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

836
- (void)mainSplitViewDidResizeSubviews:(id)object
837
{
838 839 840 841
    [[self draggablepanel] centerPanel];
    msg_Err(getIntf(),"Heyyy, I am trying");
    NSLog(@"%f",[self frame].origin.x); //Debug-Statement

842
    f_lastLeftSplitViewWidth = [_splitViewLeft frame].size.width;
843
    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem: ![_splitView isSubviewCollapsed:_splitViewLeft]];
844 845 846 847
}

- (void)toggleLeftSubSplitView
{
848 849 850
    [_splitView adjustSubviews];
    if ([_splitView isSubviewCollapsed:_splitViewLeft])
        [_splitView setPosition:f_lastLeftSplitViewWidth ofDividerAtIndex:0];
851
    else
852
        [_splitView setPosition:[_splitView minPossiblePositionOfDividerAtIndex:0] ofDividerAtIndex:0];
853 854

    [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem: ![_splitView isSubviewCollapsed:_splitViewLeft]];
855 856
}

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

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

    PL_UNLOCK;
871 872 873 874 875 876 877
}

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

878
    playlist_t * p_playlist = pl_Get(getIntf());
879 880
    PL_ASSERT_LOCKED;

881 882 883 884 885
    mtime_t mt_duration = playlist_GetNodeDuration( node );

    if (mt_duration < 1)
        return @"";

886
    mt_duration = mt_duration / CLOCK_FREQ;
887

888 889 890 891
    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;

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

893
    return [NSString stringWithFormat:@" — %@", outputString];
894 895
}

896 897
- (IBAction)searchItem:(id)sender
{
898
    [[[[VLCMain sharedInstance] playlist] model] searchUpdate:[_searchField stringValue]];
899 900
}

901 902 903 904 905
- (IBAction)highlightSearchField:(id)sender
{
    [_searchField selectText:sender];
}

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


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


- (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
{
931
    return [item title];
932 933 934 935
}

- (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
{
936
    [item setTitle:object];
937 938 939 940
}

- (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
{
941
    return [item hasChildren];
942 943 944 945 946
}


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

950
    return [item hasBadge];
951 952 953 954 955
}


- (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
{
956
    playlist_t * p_playlist = pl_Get(getIntf());
957
    NSInteger i_playlist_size = 0;
958

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

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

        return i_playlist_size;
    }
974 975

    return [item badgeValue];
976 977 978 979 980
}


- (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
{
981
    return [item hasIcon];
982 983 984 985 986
}


- (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
{
987
    return [item icon];
988 989 990 991
}

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

    return nil;
1010 1011
}

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

        if (!sd_loaded)
1020
            playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
1021
        else
1022
            playlist_ServicesDiscoveryRemove(p_playlist, [identifier UTF8String]);
1023 1024 1025
    }
}

1026 1027 1028 1029 1030
#pragma mark -
#pragma mark Side Bar Delegate Methods
/* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
- (BOOL)sourceList:(PXSourceList*)aSourceList isGroupAlwaysExpanded:(id)group
{
1031 1032 1033
    if ([[group identifier] isEqualToString:@"library"])
        return YES;

1034
    return NO;
1035 1036 1037 1038
}

- (void)sourceListSelectionDidChange:(NSNotification *)notification
{
1039
    playlist_t * p_playlist = pl_Get(getIntf());
1040

1041 1042
    NSIndexSet *selectedIndexes = [_sidebarView selectedRowIndexes];
    id item = [_sidebarView itemAtRow:[selectedIndexes firstIndex]];
1043

1044
    //Set the label text to represent the new selection
1045 1046
    if ([item sdtype] > -1 && [[item identifier] length] > 0) {
        BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1047
        if (!sd_loaded)
1048
            playlist_ServicesDiscoveryAdd(p_playlist, [[item identifier] UTF8String]);
1049
    }
1050

1051
    [_categoryLabel setStringValue:[item title]];
1052

1053
    if ([[item identifier] isEqualToString:@"playlist"]) {
1054 1055 1056 1057 1058 1059
        PL_LOCK;
        [[[[VLCMain sharedInstance] playlist] model] changeRootItem:p_playlist->p_playing];
        PL_UNLOCK;

        [self _updatePlaylistTitle];

1060
    } else if ([[item identifier] isEqualToString:@"medialibrary"]) {
1061
        if (p_playlist->p_media_library) {
1062 1063 1064 1065 1066 1067 1068

            PL_LOCK;
            [[[[VLCMain sharedInstance] playlist] model] changeRootItem:p_playlist->p_media_library];

            PL_UNLOCK;

            [self _updatePlaylistTitle];
1069
        }