PLModel.m 23.3 KB
Newer Older
David's avatar
David committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*****************************************************************************
 * PLItem.m: MacOS X interface module
 *****************************************************************************
 * Copyright (C) 2014 VLC authors and VideoLAN
 * $Id$
 *
 * 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.
 *****************************************************************************/

#import "PLModel.h"

24
#import "misc.h"    /* VLCByteCountFormatter */
David's avatar
David committed
25

26
#import "VLCPlaylist.h"
27
#import "StringUtility.h"
28 29 30
#import "intf.h"
#import "ControlsBar.h"
#import "MainMenu.h"
31
#import "VLCPlaylistInfo.h"
David's avatar
David committed
32
#import "VLCMainWindow.h"
33

34 35 36 37 38
#ifdef HAVE_CONFIG_H
# import "config.h"
#endif
#include <assert.h>

David's avatar
David committed
39 40
#include <vlc_playlist.h>
#include <vlc_input_item.h>
41
#include <vlc_input.h>
David's avatar
David committed
42 43
#include <vlc_url.h>

44 45 46 47
static int PLItemUpdated(vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param)
{
    @autoreleasepool {
48 49
        PLModel *model = (__bridge PLModel*)param;
        [model performSelectorOnMainThread:@selector(plItemUpdated) withObject:nil waitUntilDone:NO];
50 51 52 53 54 55 56 57 58 59 60

        return VLC_SUCCESS;
    }
}

static int PLItemAppended(vlc_object_t *p_this, const char *psz_var,
                          vlc_value_t oldval, vlc_value_t new_val, void *param)
{
    @autoreleasepool {
        playlist_add_t *p_add = new_val.p_address;
        NSArray *o_val = [NSArray arrayWithObjects:[NSNumber numberWithInt:p_add->i_node], [NSNumber numberWithInt:p_add->i_item], nil];
61 62
        PLModel *model = (__bridge PLModel*)param;
        [model performSelectorOnMainThread:@selector(plItemAppended:) withObject:o_val waitUntilDone:NO];
63 64 65 66 67 68 69 70 71 72

        return VLC_SUCCESS;
    }
}

static int PLItemRemoved(vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param)
{
    @autoreleasepool {
        NSNumber *o_val = [NSNumber numberWithInt:new_val.i_int];
73 74
        PLModel *model = (__bridge PLModel*)param;
        [model performSelectorOnMainThread:@selector(plItemRemoved:) withObject:o_val waitUntilDone:NO];
75 76 77 78 79 80 81 82 83

        return VLC_SUCCESS;
    }
}

static int PlaybackModeUpdated(vlc_object_t *p_this, const char *psz_var,
                               vlc_value_t oldval, vlc_value_t new_val, void *param)
{
    @autoreleasepool {
84 85
        PLModel *model = (__bridge PLModel*)param;
        [model performSelectorOnMainThread:@selector(playbackModeUpdated) withObject:nil waitUntilDone:NO];
86 87 88 89 90 91 92 93 94 95

        return VLC_SUCCESS;
    }
}

static int VolumeUpdated(vlc_object_t *p_this, const char *psz_var,
                         vlc_value_t oldval, vlc_value_t new_val, void *param)
{
    @autoreleasepool {
        dispatch_async(dispatch_get_main_queue(), ^{
96
            [[[VLCMain sharedInstance] mainWindow] updateVolumeSlider];
97 98 99 100 101 102
        });

        return VLC_SUCCESS;
    }
}

David's avatar
David committed
103 104
#pragma mark -

105 106 107
@interface PLModel ()
{
    playlist_t *p_playlist;
108
    __weak NSOutlineView *_outlineView;
109

110
    NSUInteger _retainedRowSelection;
111 112 113
}
@end

David's avatar
David committed
114 115
@implementation PLModel

116 117
#pragma mark -
#pragma mark Init and Stuff
David's avatar
David committed
118

119
- (id)initWithOutlineView:(NSOutlineView *)outlineView playlist:(playlist_t *)pl rootItem:(playlist_item_t *)root;
David's avatar
David committed
120 121
{
    self = [super init];
122
    if (self) {
David's avatar
David committed
123
        p_playlist = pl;
124
        _outlineView = outlineView;
David's avatar
David committed
125

David's avatar
David committed
126
        msg_Dbg(getIntf(), "Initializing playlist model");
127 128 129 130 131 132
        var_AddCallback(p_playlist, "item-change", PLItemUpdated, (__bridge void *)self);
        var_AddCallback(p_playlist, "playlist-item-append", PLItemAppended, (__bridge void *)self);
        var_AddCallback(p_playlist, "playlist-item-deleted", PLItemRemoved, (__bridge void *)self);
        var_AddCallback(p_playlist, "random", PlaybackModeUpdated, (__bridge void *)self);
        var_AddCallback(p_playlist, "repeat", PlaybackModeUpdated, (__bridge void *)self);
        var_AddCallback(p_playlist, "loop", PlaybackModeUpdated, (__bridge void *)self);
133 134
        var_AddCallback(p_playlist, "volume", VolumeUpdated, (__bridge void *)self);
        var_AddCallback(p_playlist, "mute", VolumeUpdated, (__bridge void *)self);
135

David's avatar
David committed
136
        PL_LOCK;
137
        _rootItem = [[PLItem alloc] initWithPlaylistItem:root];
David's avatar
David committed
138 139 140 141 142 143 144
        [self rebuildPLItem:_rootItem];
        PL_UNLOCK;
    }

    return self;
}

145 146
- (void)dealloc
{
David's avatar
David committed
147
    msg_Dbg(getIntf(), "Deinitializing playlist model");
148 149 150 151 152 153
    var_DelCallback(p_playlist, "item-change", PLItemUpdated, (__bridge void *)self);
    var_DelCallback(p_playlist, "playlist-item-append", PLItemAppended, (__bridge void *)self);
    var_DelCallback(p_playlist, "playlist-item-deleted", PLItemRemoved, (__bridge void *)self);
    var_DelCallback(p_playlist, "random", PlaybackModeUpdated, (__bridge void *)self);
    var_DelCallback(p_playlist, "repeat", PlaybackModeUpdated, (__bridge void *)self);
    var_DelCallback(p_playlist, "loop", PlaybackModeUpdated, (__bridge void *)self);
154 155
    var_DelCallback(p_playlist, "volume", VolumeUpdated, (__bridge void *)self);
    var_DelCallback(p_playlist, "mute", VolumeUpdated, (__bridge void *)self);
156 157
}

David's avatar
David committed
158 159 160
- (void)changeRootItem:(playlist_item_t *)p_root;
{
    PL_ASSERT_LOCKED;
161
    _rootItem = [[PLItem alloc] initWithPlaylistItem:p_root];
David's avatar
David committed
162
    [self rebuildPLItem:_rootItem];
163

David's avatar
David committed
164
    [_outlineView reloadData];
165
    [_outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
David's avatar
David committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

- (BOOL)hasChildren
{
    return [[_rootItem children] count] > 0;
}

- (PLRootType)currentRootType
{
    int i_root_id = [_rootItem plItemId];
    if (i_root_id == p_playlist->p_playing->i_id)
        return ROOT_TYPE_PLAYLIST;
    if (p_playlist->p_media_library && i_root_id == p_playlist->p_media_library->i_id)
        return ROOT_TYPE_MEDIALIBRARY;

    return ROOT_TYPE_OTHER;
}

- (BOOL)editAllowed
{
    return [self currentRootType] == ROOT_TYPE_MEDIALIBRARY ||
    [self currentRootType] == ROOT_TYPE_PLAYLIST;
}

190
- (void)deleteSelectedItem
David's avatar
David committed
191
{
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    // check if deletion is allowed
    if (![self editAllowed])
        return;

    NSIndexSet *selectedIndexes = [_outlineView selectedRowIndexes];
    _retainedRowSelection = [selectedIndexes firstIndex];
    if (_retainedRowSelection == NSNotFound)
        _retainedRowSelection = 0;

    [selectedIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        PLItem *item = [_outlineView itemAtRow: idx];
        if (!item)
            return;

        // model deletion is done via callback
        playlist_DeleteFromInput(p_playlist, [item input], pl_Unlocked);
    }];
}

- (void)rebuildPLItem:(PLItem *)item
{
    [item clear];
    playlist_item_t *p_item = playlist_ItemGetById(p_playlist, [item plItemId]);
David's avatar
David committed
215
    if (p_item) {
216
        int currPos = 0;
David's avatar
David committed
217
        for(int i = 0; i < p_item->i_children; ++i) {
218 219 220 221 222
            playlist_item_t *p_child = p_item->pp_children[i];

            if (p_child->i_flags & PLAYLIST_DBL_FLAG)
                continue;

223 224
            PLItem *child = [[PLItem alloc] initWithPlaylistItem:p_child];
            [item addChild:child atPos:currPos++];
David's avatar
David committed
225

226
            if (p_child->i_children >= 0) {
227
                [self rebuildPLItem:child];
David's avatar
David committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            }

        }
    }

}

- (PLItem *)findItemByPlaylistId:(int)i_pl_id
{
    return [self findItemInnerByPlaylistId:i_pl_id node:_rootItem];
}

- (PLItem *)findItemInnerByPlaylistId:(int)i_pl_id node:(PLItem *)node
{
    if ([node plItemId] == i_pl_id) {
        return node;
    }

    for (NSUInteger i = 0; i < [[node children] count]; ++i) {
        PLItem *o_sub_item = [[node children] objectAtIndex:i];
        if ([o_sub_item plItemId] == i_pl_id) {
            return o_sub_item;
        }

        if (![o_sub_item isLeaf]) {
            PLItem *o_returned = [self findItemInnerByPlaylistId:i_pl_id node:o_sub_item];
            if (o_returned)
                return o_returned;
        }
    }

    return nil;
}

262 263
#pragma mark -
#pragma mark Core events
David's avatar
David committed
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

- (void)plItemAppended:(NSArray *)valueArray
{
    int i_node = [[valueArray firstObject] intValue];
    int i_item = [valueArray[1] intValue];

    [self addItem:i_item withParentNode:i_node];

    // update badge in sidebar
    [[[VLCMain sharedInstance] mainWindow] updateWindow];

    [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
                                                        object: nil
                                                      userInfo: nil];
}

- (void)plItemRemoved:(NSNumber *)value
{
    int i_item = [value intValue];

    [self removeItem:i_item];
    // retain selection before deletion
    [_outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:_retainedRowSelection] byExtendingSelection:NO];

    // update badge in sidebar
    [[[VLCMain sharedInstance] mainWindow] updateWindow];

    [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
                                                        object: nil
                                                      userInfo: nil];
}

- (void)plItemUpdated
David's avatar
David committed
298
{
299 300 301
    VLCMain *instance = [VLCMain sharedInstance];
    [[instance mainWindow] updateName];

302
    [[instance currentMediaInfoPanel] updateMetadata];
303
}
David's avatar
David committed
304

305 306
- (void)addItem:(int)i_item withParentNode:(int)i_node
{
David's avatar
David committed
307 308 309 310 311 312 313 314 315
    PLItem *o_parent = [self findItemByPlaylistId:i_node];
    if (!o_parent) {
        return;
    }

    PL_LOCK;
    playlist_item_t *p_item = playlist_ItemGetById(p_playlist, i_item);
    if (!p_item || p_item->i_flags & PLAYLIST_DBL_FLAG)
    {
316 317
        PL_UNLOCK;
        return;
David's avatar
David committed
318 319 320 321 322 323 324
    }

    int pos;
    for(pos = p_item->p_parent->i_children - 1; pos >= 0; pos--)
        if(p_item->p_parent->pp_children[pos] == p_item)
            break;

325
    PLItem *o_new_item = [[PLItem alloc] initWithPlaylistItem:p_item];
David's avatar
David committed
326 327 328 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
    PL_UNLOCK;
    if (pos < 0)
        return;

    [o_parent addChild:o_new_item atPos:pos];

    if ([o_parent plItemId] == [_rootItem plItemId])
        [_outlineView reloadData];
    else // only reload leafs this way, doing it with nil collapses width of title column
        [_outlineView reloadItem:o_parent reloadChildren:YES];
}

- (void)removeItem:(int)i_item
{
    PLItem *o_item = [self findItemByPlaylistId:i_item];
    if (!o_item) {
        return;
    }

    PLItem *o_parent = [o_item parent];
    [o_parent deleteChild:o_item];

    if ([o_parent plItemId] == [_rootItem plItemId])
        [_outlineView reloadData];
    else
        [_outlineView reloadItem:o_parent reloadChildren:YES];
}

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
- (void)updateItem:(input_item_t *)p_input_item
{
    PL_LOCK;
    playlist_item_t *pl_item = playlist_ItemGetByInput(p_playlist, p_input_item);
    if (!pl_item) {
        PL_UNLOCK;
        return;
    }
    PLItem *item = [self findItemByPlaylistId:pl_item->i_id];
    PL_UNLOCK;

    if (!item)
        return;

    NSInteger row = [_outlineView rowForItem:item];
    if (row == -1)
        return;

    [_outlineView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:row]
                            columnIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [[_outlineView tableColumns] count])]];

}

David's avatar
David committed
377 378 379 380 381 382 383 384 385 386 387 388
- (PLItem *)currentlyPlayingItem
{
    PLItem *item = nil;

    PL_LOCK;
    playlist_item_t *p_current = playlist_CurrentPlayingItem(p_playlist);
    if (p_current)
        item = [self findItemByPlaylistId:p_current->i_id];
    PL_UNLOCK;
    return item;
}

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
- (void)playbackModeUpdated
{
    bool loop = var_GetBool(p_playlist, "loop");
    bool repeat = var_GetBool(p_playlist, "repeat");

    VLCMainWindowControlsBar *controlsBar = (VLCMainWindowControlsBar *)[[[VLCMain sharedInstance] mainWindow] controlsBar];
    VLCMainMenu *mainMenu = [[VLCMain sharedInstance] mainMenu];
    if (repeat) {
        [controlsBar setRepeatOne];
        [mainMenu setRepeatOne];
    } else if (loop) {
        [controlsBar setRepeatAll];
        [mainMenu setRepeatAll];
    } else {
        [controlsBar setRepeatOff];
        [mainMenu setRepeatOff];
    }

    [controlsBar setShuffle];
    [mainMenu setShuffle];
}

411 412 413
#pragma mark -
#pragma mark Sorting / Searching

David's avatar
David committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
- (void)sortForColumn:(NSString *)o_column withMode:(int)i_mode
{
    int i_column = 0;
    if ([o_column isEqualToString:TRACKNUM_COLUMN])
        i_column = SORT_TRACK_NUMBER;
    else if ([o_column isEqualToString:TITLE_COLUMN])
        i_column = SORT_TITLE;
    else if ([o_column isEqualToString:ARTIST_COLUMN])
        i_column = SORT_ARTIST;
    else if ([o_column isEqualToString:GENRE_COLUMN])
        i_column = SORT_GENRE;
    else if ([o_column isEqualToString:DURATION_COLUMN])
        i_column = SORT_DURATION;
    else if ([o_column isEqualToString:ALBUM_COLUMN])
        i_column = SORT_ALBUM;
    else if ([o_column isEqualToString:DESCRIPTION_COLUMN])
        i_column = SORT_DESCRIPTION;
    else if ([o_column isEqualToString:URI_COLUMN])
        i_column = SORT_URI;
    else
        return;

    PL_LOCK;
    playlist_item_t *p_root = playlist_ItemGetById(p_playlist, [_rootItem plItemId]);
    if (!p_root) {
        PL_UNLOCK;
        return;
    }

    playlist_RecursiveNodeSort(p_playlist, p_root, i_column, i_mode);

    [self rebuildPLItem:_rootItem];
    [_outlineView reloadData];
    PL_UNLOCK;
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
- (void)searchUpdate:(NSString *)o_search
{
    PL_LOCK;
    playlist_item_t *p_root = playlist_ItemGetById(p_playlist, [_rootItem plItemId]);
    if (!p_root) {
        PL_UNLOCK;
        return;
    }
    playlist_LiveSearchUpdate(p_playlist, p_root, [o_search UTF8String],
                              true);
    [self rebuildPLItem:_rootItem];
    [_outlineView reloadData];
    PL_UNLOCK;
}

David's avatar
David committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
@end

#pragma mark -
#pragma mark Outline view data source

@implementation PLModel(NSOutlineViewDataSource)

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
    return !item ? [[_rootItem children] count] : [[item children] count];
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
    return !item ? YES : [[item children] count] > 0;
}

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item
{
    id obj = !item ? _rootItem : item;
    return [[obj children] objectAtIndex:index];
}

- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
    id o_value = nil;
491
    char *psz_value;
David's avatar
David committed
492 493 494 495 496 497 498

    input_item_t *p_input = [item input];

    NSString * o_identifier = [tableColumn identifier];

    if ([o_identifier isEqualToString:TRACKNUM_COLUMN]) {
        psz_value = input_item_GetTrackNumber(p_input);
499 500 501
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
502
    } else if ([o_identifier isEqualToString:TITLE_COLUMN]) {
503 504 505 506
        psz_value = input_item_GetTitleFbName(p_input);
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
507 508
    } else if ([o_identifier isEqualToString:ARTIST_COLUMN]) {
        psz_value = input_item_GetArtist(p_input);
509 510 511 512
        o_value = toNSStr(psz_value);
        free(psz_value);

    } else if ([o_identifier isEqualToString:DURATION_COLUMN]) {
David's avatar
David committed
513 514 515 516
        char psz_duration[MSTRTIME_MAX_SIZE];
        mtime_t dur = input_item_GetDuration(p_input);
        if (dur != -1) {
            secstotimestr(psz_duration, dur/1000000);
517
            o_value = toNSStr(psz_duration);
David's avatar
David committed
518 519 520
        }
        else
            o_value = @"--:--";
521

David's avatar
David committed
522 523
    } else if ([o_identifier isEqualToString:GENRE_COLUMN]) {
        psz_value = input_item_GetGenre(p_input);
524 525 526
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
527 528
    } else if ([o_identifier isEqualToString:ALBUM_COLUMN]) {
        psz_value = input_item_GetAlbum(p_input);
529 530 531
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
532 533
    } else if ([o_identifier isEqualToString:DESCRIPTION_COLUMN]) {
        psz_value = input_item_GetDescription(p_input);
534 535 536
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
537 538
    } else if ([o_identifier isEqualToString:DATE_COLUMN]) {
        psz_value = input_item_GetDate(p_input);
539 540 541
        o_value = toNSStr(psz_value);
        free(psz_value);

David's avatar
David committed
542 543
    } else if ([o_identifier isEqualToString:LANGUAGE_COLUMN]) {
        psz_value = input_item_GetLanguage(p_input);
544 545 546 547
        o_value = toNSStr(psz_value);
        free(psz_value);

    } else if ([o_identifier isEqualToString:URI_COLUMN]) {
548
        psz_value = vlc_uri_decode(input_item_GetURI(p_input));
549 550 551 552
        o_value = toNSStr(psz_value);
        free(psz_value);

    } else if ([o_identifier isEqualToString:FILESIZE_COLUMN]) {
553
        psz_value = input_item_GetURI(p_input);
554 555 556 557 558 559
        if (!psz_value)
            return @"";
        NSURL *url = [NSURL URLWithString:toNSStr(psz_value)];
        free(psz_value);
        if (![url isFileURL])
            return @"";
David's avatar
David committed
560

561 562 563 564 565 566 567 568 569 570 571 572
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL b_isDir;
        if (![fileManager fileExistsAtPath:[url path] isDirectory:&b_isDir] || b_isDir)
            return @"";

        NSDictionary *attributes = [fileManager attributesOfItemAtPath:[url path] error:nil];
        if (!attributes)
            return @"";

        o_value = [VLCByteCountFormatter stringFromByteCount:[attributes fileSize] countStyle:NSByteCountFormatterCountStyleDecimal];

    } else if ([o_identifier isEqualToString:STATUS_COLUMN]) {
David's avatar
David committed
573 574 575 576 577 578 579 580 581
        if (input_item_HasErrorWhenReading(p_input)) {
            o_value = [[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kAlertCautionIcon)];
            [o_value setSize: NSMakeSize(16,16)];
        }
    }

    return o_value;
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
#pragma mark -
#pragma mark Drag and Drop support

- (BOOL)isItem: (PLItem *)p_item inNode: (PLItem *)p_node
{
    while(p_item) {
        if ([p_item plItemId] == [p_node plItemId]) {
            return YES;
        }

        p_item = [p_item parent];
    }

    return NO;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
{
    NSUInteger itemCount = [items count];
    _draggedItems = [[NSMutableArray alloc] initWithArray:items];

    /* Add the data to the pasteboard object. */
    [pboard declareTypes: [NSArray arrayWithObject:VLCPLItemPasteboadType] owner: self];
    [pboard setData:[NSData data] forType:VLCPLItemPasteboadType];

    return YES;
}

- (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
{
    NSPasteboard *o_pasteboard = [info draggingPasteboard];

    /* Dropping ON items is not allowed if item is not a node */
    if (item) {
        if (index == NSOutlineViewDropOnItemIndex && [item isLeaf]) {
            return NSDragOperationNone;
        }
    }

    if (![self editAllowed])
        return NSDragOperationNone;

    /* Drop from the Playlist */
    if ([[o_pasteboard types] containsObject:VLCPLItemPasteboadType]) {
        NSUInteger count = [_draggedItems count];
        for (NSUInteger i = 0 ; i < count ; i++) {
            /* We refuse to Drop in a child of an item we are moving */
            if ([self isItem: item inNode: [_draggedItems objectAtIndex:i]]) {
                return NSDragOperationNone;
            }
        }
        return NSDragOperationMove;
    }
    /* Drop from the Finder */
    else if ([[o_pasteboard types] containsObject: NSFilenamesPboardType]) {
        return NSDragOperationGeneric;
    }
    return NSDragOperationNone;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)targetItem childIndex:(NSInteger)index
{
    NSPasteboard *o_pasteboard = [info draggingPasteboard];

646 647 648 649
    if (targetItem == nil) {
        targetItem = _rootItem;
    }

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
    /* Drag & Drop inside the playlist */
    if ([[o_pasteboard types] containsObject:VLCPLItemPasteboadType]) {

        NSMutableArray *o_filteredItems = [NSMutableArray arrayWithArray:_draggedItems];
        const NSUInteger draggedItemsCount = [_draggedItems count];
        for (NSInteger i = 0; i < [o_filteredItems count]; i++) {
            for (NSUInteger j = 0; j < draggedItemsCount; j++) {
                PLItem *itemToCheck = [o_filteredItems objectAtIndex:i];
                PLItem *nodeToTest = [_draggedItems objectAtIndex:j];
                if ([itemToCheck plItemId] == [nodeToTest plItemId])
                    continue;

                if ([self isItem:itemToCheck inNode:nodeToTest]) {
                    [o_filteredItems removeObjectAtIndex:i];
                    --i;
                    break;
                }
            }
        }

        NSUInteger count = [o_filteredItems count];
        if (count == 0)
            return NO;

        playlist_item_t **pp_items = (playlist_item_t **)calloc(count, sizeof(playlist_item_t*));
        if (!pp_items)
            return NO;

        PL_LOCK;
        playlist_item_t *p_new_parent = playlist_ItemGetById(p_playlist, [targetItem plItemId]);
        if (!p_new_parent) {
            PL_UNLOCK;
            return NO;
        }

        NSUInteger j = 0;
        for (NSUInteger i = 0; i < count; i++) {
            playlist_item_t *p_item = playlist_ItemGetById(p_playlist, [[o_filteredItems objectAtIndex:i] plItemId]);
            if (p_item)
                pp_items[j++] = p_item;
        }

692 693 694 695
        // drop on a node itself will append entries at the end
        if (index == NSOutlineViewDropOnItemIndex)
            index = p_new_parent->i_children;

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        if (playlist_TreeMoveMany(p_playlist, j, pp_items, p_new_parent, index) != VLC_SUCCESS) {
            PL_UNLOCK;
            free(pp_items);
            return NO;
        }

        PL_UNLOCK;
        free(pp_items);

        // rebuild our model
        NSUInteger filteredItemsCount = [o_filteredItems count];
        for(NSUInteger i = 0; i < filteredItemsCount; ++i) {
            PLItem *o_item = [o_filteredItems objectAtIndex:i];
            NSLog(@"delete child from parent %p", [o_item parent]);
            [[o_item parent] deleteChild:o_item];
            [targetItem addChild:o_item atPos:index + i];
        }

        [_outlineView reloadData];

        NSMutableIndexSet *selectedIndexes = [[NSMutableIndexSet alloc] init];
        for(NSUInteger i = 0; i < draggedItemsCount; ++i) {
            NSInteger row = [_outlineView rowForItem:[_draggedItems objectAtIndex:i]];
            if (row < 0)
                continue;

            [selectedIndexes addIndex:row];
        }

        if ([selectedIndexes count] == 0)
            [selectedIndexes addIndex:[_outlineView rowForItem:targetItem]];

        [_outlineView selectRowIndexes:selectedIndexes byExtendingSelection:NO];

        return YES;
    }

733
    // try file drop
734

735 736
    // drop on a node itself will append entries at the end
    static_assert(NSOutlineViewDropOnItemIndex == -1, "Expect NSOutlineViewDropOnItemIndex to be -1");
737

738 739 740
    NSArray *items = [[[VLCMain sharedInstance] playlist] createItemsFromExternalPasteboard:o_pasteboard];
    if (items.count == 0)
        return NO;
741

742 743 744 745 746
    [[[VLCMain sharedInstance] playlist] addPlaylistItems:items
                                         withParentItemId:[targetItem plItemId]
                                                    atPos:index
                                            startPlayback:NO];
    return YES;
747 748
}

David's avatar
David committed
749
@end