mediaplaylist.cpp 42.2 KB
Newer Older
1
/*
2
 * Copyright 2015-2017 Matthieu Gallien <matthieu_gallien@yahoo.fr>
3
 *
4 5
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
6 7 8
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
9
 * This program is distributed in the hope that it will be useful,
10 11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Lesser General Public License for more details.
13
 *
14 15
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 17 18
 */

#include "mediaplaylist.h"
19
#include "databaseinterface.h"
20
#include "musicaudiotrack.h"
21
#include "musiclistenersmanager.h"
22

23 24 25
#include <QUrl>
#include <QPersistentModelIndex>
#include <QList>
26
#include <QMediaPlaylist>
27
#include <QFileInfo>
28 29
#include <QJsonArray>
#include <QJsonDocument>
30
#include <QDebug>
Alexander Stippich's avatar
Alexander Stippich committed
31
#include <QRandomGenerator>
32

33 34
#include <algorithm>

35 36 37 38
class MediaPlayListPrivate
{
public:

39
    QList<MediaPlayListEntry> mData;
40

41
    QList<DatabaseInterface::TrackDataType> mTrackData;
42

43 44
    MusicListenersManager* mMusicListenersManager = nullptr;

45 46
    QPersistentModelIndex mPreviousTrack;

47 48
    QPersistentModelIndex mCurrentTrack;

49 50
    QPersistentModelIndex mNextTrack;

51 52 53 54
    QVariantMap mPersistentState;

    QMediaPlaylist mLoadPlaylist;

55 56 57 58 59 60
    int mCurrentPlayListPosition = 0;

    bool mRandomPlay = false;

    bool mRepeatPlay = false;

61 62
    bool mForceUndo = false;

Alexander Stippich's avatar
Alexander Stippich committed
63 64
    QList<int> mRandomPositions = {0, 0, 0};

65 66
};

67
MediaPlayList::MediaPlayList(QObject *parent) : QAbstractListModel(parent), d(new MediaPlayListPrivate), dOld(new MediaPlayListPrivate)
68
{
69 70
    connect(&d->mLoadPlaylist, &QMediaPlaylist::loaded, this, &MediaPlayList::loadPlayListLoaded);
    connect(&d->mLoadPlaylist, &QMediaPlaylist::loadFailed, this, &MediaPlayList::loadPlayListLoadFailed);
71 72 73
}

MediaPlayList::~MediaPlayList()
74
= default;
75 76 77 78 79 80 81 82 83 84

int MediaPlayList::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    }

    return d->mData.size();
}

85 86 87 88 89
QHash<int, QByteArray> MediaPlayList::roleNames() const
{
    auto roles = QAbstractItemModel::roleNames();

    roles[static_cast<int>(ColumnsRoles::IsValidRole)] = "isValid";
90
    roles[static_cast<int>(ColumnsRoles::DatabaseIdRole)] = "databaseId";
91
    roles[static_cast<int>(ColumnsRoles::TitleRole)] = "title";
92
    roles[static_cast<int>(ColumnsRoles::StringDurationRole)] = "duration";
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    roles[static_cast<int>(ColumnsRoles::ArtistRole)] = "artist";
    roles[static_cast<int>(ColumnsRoles::AlbumArtistRole)] = "albumArtist";
    roles[static_cast<int>(ColumnsRoles::AlbumRole)] = "album";
    roles[static_cast<int>(ColumnsRoles::TrackNumberRole)] = "trackNumber";
    roles[static_cast<int>(ColumnsRoles::DiscNumberRole)] = "discNumber";
    roles[static_cast<int>(ColumnsRoles::RatingRole)] = "rating";
    roles[static_cast<int>(ColumnsRoles::GenreRole)] = "genre";
    roles[static_cast<int>(ColumnsRoles::LyricistRole)] = "lyricist";
    roles[static_cast<int>(ColumnsRoles::ComposerRole)] = "composer";
    roles[static_cast<int>(ColumnsRoles::CommentRole)] = "comment";
    roles[static_cast<int>(ColumnsRoles::YearRole)] = "year";
    roles[static_cast<int>(ColumnsRoles::ChannelsRole)] = "channels";
    roles[static_cast<int>(ColumnsRoles::BitRateRole)] = "bitRate";
    roles[static_cast<int>(ColumnsRoles::SampleRateRole)] = "sampleRate";
    roles[static_cast<int>(ColumnsRoles::CountRole)] = "count";
    roles[static_cast<int>(ColumnsRoles::IsPlayingRole)] = "isPlaying";
109
    roles[static_cast<int>(ColumnsRoles::IsSingleDiscAlbumRole)] = "isSingleDiscAlbum";
110 111 112 113 114
    roles[static_cast<int>(ColumnsRoles::SecondaryTextRole)] = "secondaryText";
    roles[static_cast<int>(ColumnsRoles::ImageUrlRole)] = "imageUrl";
    roles[static_cast<int>(ColumnsRoles::ShadowForImageRole)] = "shadowForImage";
    roles[static_cast<int>(ColumnsRoles::ResourceRole)] = "trackResource";
    roles[static_cast<int>(ColumnsRoles::TrackDataRole)] = "trackData";
115
    roles[static_cast<int>(ColumnsRoles::AlbumIdRole)] = "albumId";
116
    roles[static_cast<int>(ColumnsRoles::AlbumSectionRole)] = "albumSection";
117
    roles[static_cast<int>(ColumnsRoles::ElementTypeRole)] = "entryType";
118 119 120 121

    return roles;
}

122 123
QVariant MediaPlayList::data(const QModelIndex &index, int role) const
{
124 125
    auto result = QVariant();

126 127 128 129
    if (!index.isValid()) {
        return result;
    }

130
    if (d->mData[index.row()].mIsValid) {
131
        switch(role)
132 133
        {
        case ColumnsRoles::IsValidRole:
134 135
            result = d->mData[index.row()].mIsValid;
            break;
136 137 138
        case ColumnsRoles::IsPlayingRole:
            result = d->mData[index.row()].mIsPlaying;
            break;
139 140
        case ColumnsRoles::StringDurationRole:
        {
141
            QTime trackDuration = d->mTrackData[index.row()][TrackDataType::key_type::DurationRole].toTime();
142 143 144 145 146 147 148
            if (trackDuration.hour() == 0) {
                result = trackDuration.toString(QStringLiteral("mm:ss"));
            } else {
                result = trackDuration.toString();
            }
            break;
        }
149 150
        case ColumnsRoles::AlbumSectionRole:
            result = QJsonDocument{QJsonArray{d->mTrackData[index.row()][TrackDataType::key_type::AlbumRole].toString(),
151 152 153 154 155 156 157 158 159 160
                    d->mTrackData[index.row()][TrackDataType::key_type::AlbumArtistRole].toString(),
                    d->mTrackData[index.row()][TrackDataType::key_type::ImageUrlRole].toUrl().toString()}}.toJson();
    break;
    default:
        const auto &trackData = d->mTrackData[index.row()];
        auto roleEnum = static_cast<TrackDataType::key_type>(role);
        auto itData = trackData.find(roleEnum);
        if (itData != trackData.end()) {
            result = itData.value();
        } else {
Matthieu Gallien's avatar
Matthieu Gallien committed
161
            result = {};
162
        }
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}
} else {
switch(role)
{
    case ColumnsRoles::IsValidRole:
        result = d->mData[index.row()].mIsValid;
        break;
    case ColumnsRoles::TitleRole:
        result = d->mData[index.row()].mTitle;
        break;
    case ColumnsRoles::IsPlayingRole:
        result = d->mData[index.row()].mIsPlaying;
        break;
    case ColumnsRoles::ArtistRole:
        result = d->mData[index.row()].mArtist;
        break;
    case ColumnsRoles::AlbumArtistRole:
        result = d->mData[index.row()].mArtist;
        break;
    case ColumnsRoles::AlbumRole:
        result = d->mData[index.row()].mAlbum;
        break;
    case ColumnsRoles::TrackNumberRole:
        result = -1;
        break;
    case ColumnsRoles::IsSingleDiscAlbumRole:
        result = false;
        break;
    case Qt::DisplayRole:
        result = d->mData[index.row()].mTitle;
        break;
    case ColumnsRoles::ImageUrlRole:
        result = QUrl(QStringLiteral("image://icon/error"));
        break;
    case ColumnsRoles::ShadowForImageRole:
        result = false;
        break;
    case ColumnsRoles::AlbumSectionRole:
        result = QJsonDocument{QJsonArray{d->mData[index.row()].mAlbum.toString(),
                d->mData[index.row()].mArtist.toString(),
                QUrl(QStringLiteral("image://icon/error")).toString()}}.toJson();
break;
default:
result = {};
}
}
209

210
return result;
211 212 213 214
}

bool MediaPlayList::setData(const QModelIndex &index, const QVariant &value, int role)
{
215 216
    bool modelModified = false;

217
    if (!index.isValid()) {
218
        return modelModified;
219 220
    }

221
    if (index.row() < 0 || index.row() >= d->mData.size()) {
222
        return modelModified;
223 224
    }

225
    if (role < ColumnsRoles::IsValidRole || role > ColumnsRoles::IsPlayingRole) {
226
        return modelModified;
227 228
    }

229
    auto convertedRole = static_cast<ColumnsRoles>(role);
230 231 232 233

    switch(convertedRole)
    {
    case ColumnsRoles::IsPlayingRole:
234
    {
235
        modelModified = true;
236
        auto newState = static_cast<PlayState>(value.toInt());
237
        d->mData[index.row()].mIsPlaying = newState;
238
        Q_EMIT dataChanged(index, index, {role});
239 240 241 242 243

        if (!d->mCurrentTrack.isValid()) {
            resetCurrentTrack();
        }

244
        break;
245
    }
Jerome Guidon's avatar
Jerome Guidon committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    case ColumnsRoles::TitleRole:
    {
        modelModified = true;
        d->mData[index.row()].mTitle = value;
        d->mTrackData[index.row()][static_cast<TrackDataType::key_type>(role)] = value;
        Q_EMIT dataChanged(index, index, {role});

        if (!d->mCurrentTrack.isValid()) {
            resetCurrentTrack();
        }

        break;
    }
    case ColumnsRoles::ArtistRole:
    {
        modelModified = true;
        d->mData[index.row()].mArtist = value;
        d->mTrackData[index.row()][static_cast<TrackDataType::key_type>(role)] = value;
        Q_EMIT dataChanged(index, index, {role});

        if (!d->mCurrentTrack.isValid()) {
            resetCurrentTrack();
        }

        break;
    }
272 273 274 275 276 277 278 279 280 281
    default:
        modelModified = false;
    }

    return modelModified;
}

bool MediaPlayList::removeRows(int row, int count, const QModelIndex &parent)
{
    beginRemoveRows(parent, row, row + count - 1);
282

283 284
    for (int i = row, cpt = 0; cpt < count; ++i, ++cpt) {
        d->mData.removeAt(i);
285
        d->mTrackData.removeAt(i);
286 287 288
    }
    endRemoveRows();

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    if (!d->mCurrentTrack.isValid()) {
        d->mCurrentTrack = index(d->mCurrentPlayListPosition, 0);

        if (d->mCurrentTrack.isValid()) {
            notifyCurrentTrackChanged();
        }

        if (!d->mCurrentTrack.isValid()) {
            Q_EMIT playListFinished();
            resetCurrentTrack();
            if (!d->mCurrentTrack.isValid()) {
                notifyCurrentTrackChanged();
            }
        }
    }
304 305 306
    if (!d->mNextTrack.isValid() || !d->mPreviousTrack.isValid()) {
        notifyPreviousAndNextTracks();
    }
307 308 309 310 311

    if (!d->mCurrentTrack.isValid() && rowCount(parent) <= row) {
        resetCurrentTrack();
    }

Alexander Stippich's avatar
Alexander Stippich committed
312 313 314 315
    if (d->mRandomPlay) {
        createRandomList();
    }

316
    Q_EMIT tracksCountChanged();
317
    Q_EMIT remainingTracksChanged();
318
    Q_EMIT persistentStateChanged();
319

320 321 322
    return false;
}

323
bool MediaPlayList::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild)
324
{
325 326
    if (sourceParent != destinationParent) {
        return false;
327
    }
328

329 330 331 332 333 334 335
    if (!beginMoveRows(sourceParent, sourceRow, sourceRow + count - 1, destinationParent, destinationChild)) {
        return false;
    }

    for (auto cptItem = 0; cptItem < count; ++cptItem) {
        if (sourceRow < destinationChild) {
            d->mData.move(sourceRow, destinationChild - 1);
336
            d->mTrackData.move(sourceRow, destinationChild - 1);
337 338
        } else {
            d->mData.move(sourceRow, destinationChild);
339
            d->mTrackData.move(sourceRow, destinationChild);
340 341
        }
    }
342

343 344 345 346 347 348 349 350 351
    endMoveRows();

    Q_EMIT persistentStateChanged();

    return true;
}

void MediaPlayList::move(int from, int to, int n)
{
352 353 354 355 356
    if (from < to) {
        moveRows({}, from, n, {}, to + 1);
    } else {
        moveRows({}, from, n, {}, to);
    }
357 358
}

359
void MediaPlayList::enqueueRestoredEntry(const MediaPlayListEntry &newEntry)
360
{
361 362
    enqueueCommon();

363 364
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size());
    d->mData.push_back(newEntry);
365
    d->mTrackData.push_back({});
366 367 368 369 370 371 372 373
    endInsertRows();

    restorePlayListPosition();
    if (!d->mCurrentTrack.isValid()) {
        resetCurrentTrack();
    }

    Q_EMIT tracksCountChanged();
374
    Q_EMIT remainingTracksChanged();
375 376 377
    Q_EMIT persistentStateChanged();

    if (!newEntry.mIsValid) {
Jerome Guidon's avatar
Jerome Guidon committed
378 379 380
        if (newEntry.mEntryType == ElisaUtils::Radio) {
            Q_EMIT newEntryInList(newEntry.mId, {}, ElisaUtils::Radio);
        } else if (newEntry.mTrackUrl.isValid()) {
381 382
            auto entryURL = newEntry.mTrackUrl.toUrl();
            if (entryURL.isLocalFile()) {
383 384
                auto entryString =  entryURL.toLocalFile();
                QFileInfo newTrackFile(entryString);
385 386 387
                if (newTrackFile.exists()) {
                    d->mData.last().mIsValid = true;
                }
388
                Q_EMIT newEntryInList(0, entryString, ElisaUtils::FileName);
389 390
            }
        } else {
391 392 393 394 395
            Q_EMIT newTrackByNameInList(newEntry.mTitle,
                                        newEntry.mArtist,
                                        newEntry.mAlbum,
                                        newEntry.mTrackNumber,
                                        newEntry.mDiscNumber);
396 397
        }
    } else {
398
        Q_EMIT newEntryInList(newEntry.mId, {}, ElisaUtils::Track);
399 400 401
    }

    if (!newEntry.mIsValid) {
402
        Q_EMIT dataChanged(index(rowCount() - 1, 0), index(rowCount() - 1, 0), {MediaPlayList::IsPlayingRole});
403 404 405 406 407 408 409

        if (!d->mCurrentTrack.isValid()) {
            resetCurrentTrack();
        }
    }
}

410
void MediaPlayList::enqueueArtist(const QString &artistName)
411
{
412 413 414 415 416
    enqueueCommon();

    auto newEntry = MediaPlayListEntry{artistName};
    newEntry.mEntryType = ElisaUtils::Artist;

417
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size());
418
    d->mData.push_back(newEntry);
419 420
    d->mTrackData.push_back({});
    endInsertRows();
421

422 423 424 425 426
    restorePlayListPosition();
    if (!d->mCurrentTrack.isValid()) {
        resetCurrentTrack();
    }

427
    Q_EMIT tracksCountChanged();
428
    Q_EMIT remainingTracksChanged();
429
    Q_EMIT newEntryInList(0, artistName, newEntry.mEntryType);
430
    Q_EMIT persistentStateChanged();
431 432
}

433
void MediaPlayList::enqueueFilesList(const ElisaUtils::EntryDataList &newEntries)
434
{
435 436
    enqueueCommon();

437 438 439
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size() + newEntries.size() - 1);
    for (const auto &oneTrackUrl : newEntries) {
        auto newEntry = MediaPlayListEntry(QUrl::fromLocalFile(std::get<1>(oneTrackUrl)));
440
        newEntry.mEntryType = ElisaUtils::FileName;
441 442 443 444 445 446 447 448 449 450
        d->mData.push_back(newEntry);
        d->mTrackData.push_back({});
        if (newEntry.mTrackUrl.isValid()) {
            auto entryURL = newEntry.mTrackUrl.toUrl();
            if (entryURL.isLocalFile()) {
                auto entryString =  entryURL.toLocalFile();
                QFileInfo newTrackFile(entryString);
                if (newTrackFile.exists()) {
                    d->mData.last().mIsValid = true;
                }
451
                Q_EMIT newEntryInList(0, entryString, newEntry.mEntryType);
452 453 454 455
            }
        }
    }
    endInsertRows();
456

457 458 459
    restorePlayListPosition();
    if (!d->mCurrentTrack.isValid()) {
        resetCurrentTrack();
460
    }
461 462

    Q_EMIT tracksCountChanged();
463
    Q_EMIT remainingTracksChanged();
464 465
    Q_EMIT persistentStateChanged();

466
    Q_EMIT dataChanged(index(rowCount() - 1, 0), index(rowCount() - 1, 0), {MediaPlayList::IsPlayingRole});
467 468
}

Jerome Guidon's avatar
Jerome Guidon committed
469
void MediaPlayList::enqueueTracksListById(const ElisaUtils::EntryDataList &newEntries, ElisaUtils::PlayListEntryType type)
470
{
471 472
    enqueueCommon();

473 474
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size() + newEntries.size() - 1);
    for (const auto &newTrack : newEntries) {
Jerome Guidon's avatar
Jerome Guidon committed
475
        auto newMediaPlayListEntry = MediaPlayListEntry{std::get<0>(newTrack), std::get<1>(newTrack), type};
476
        d->mData.push_back(newMediaPlayListEntry);
477
        d->mTrackData.push_back({});
478
        Q_EMIT newEntryInList(newMediaPlayListEntry.mId, newMediaPlayListEntry.mTitle.toString(), newMediaPlayListEntry.mEntryType);
479 480 481 482 483 484 485 486 487
    }
    endInsertRows();

    restorePlayListPosition();
    if (!d->mCurrentTrack.isValid()) {
        resetCurrentTrack();
    }

    Q_EMIT tracksCountChanged();
488
    Q_EMIT remainingTracksChanged();
489 490
    Q_EMIT persistentStateChanged();

491
    Q_EMIT dataChanged(index(rowCount() - 1, 0), index(rowCount() - 1, 0), {MediaPlayList::IsPlayingRole});
492 493
}

494
void MediaPlayList::enqueueOneEntry(const ElisaUtils::EntryData &entryData, ElisaUtils::PlayListEntryType type)
Alexander Stippich's avatar
Alexander Stippich committed
495
{
496 497
    enqueueCommon();

498 499 500 501 502 503 504
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size());
    d->mData.push_back(MediaPlayListEntry{std::get<0>(entryData), std::get<1>(entryData), type});
    d->mTrackData.push_back({});
    Q_EMIT newEntryInList(std::get<0>(entryData), std::get<1>(entryData), type);
    endInsertRows();

    Q_EMIT tracksCountChanged();
505
    Q_EMIT remainingTracksChanged();
506 507 508 509 510
    Q_EMIT persistentStateChanged();
}

void MediaPlayList::enqueueMultipleEntries(const ElisaUtils::EntryDataList &entriesData, ElisaUtils::PlayListEntryType type)
{
511 512
    enqueueCommon();

513 514 515 516 517
    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size() + entriesData.size() - 1);
    for (const auto &entryData : entriesData) {
        d->mData.push_back(MediaPlayListEntry{std::get<0>(entryData), std::get<1>(entryData), type});
        d->mTrackData.push_back({});
        Q_EMIT newEntryInList(std::get<0>(entryData), std::get<1>(entryData), type);
Alexander Stippich's avatar
Alexander Stippich committed
518
    }
519 520 521
    endInsertRows();

    Q_EMIT tracksCountChanged();
522
    Q_EMIT remainingTracksChanged();
523
    Q_EMIT persistentStateChanged();
Alexander Stippich's avatar
Alexander Stippich committed
524 525
}

526
void MediaPlayList::replaceAndPlay(const ElisaUtils::EntryData &newEntry,
527
                                   ElisaUtils::PlayListEntryType databaseIdType)
528
{
529
    enqueue(newEntry, databaseIdType, ElisaUtils::PlayListEnqueueMode::ReplacePlayList, ElisaUtils::PlayListEnqueueTriggerPlay::TriggerPlay);
530 531
}

532
void MediaPlayList::clearPlayList(bool prepareUndo)
533
{
534 535 536 537
    if (d->mData.isEmpty()) {
        return;
    }

538 539 540 541 542
    if(prepareUndo){
        Q_EMIT clearPlayListPlayer();
        this->copyD();
    }

543
    beginRemoveRows({}, 0, d->mData.count() - 1);
544
    d->mData.clear();
545
    d->mTrackData.clear();
546
    endRemoveRows();
547

548 549 550 551
    d->mCurrentPlayListPosition = 0;
    d->mCurrentTrack = QPersistentModelIndex{};
    notifyCurrentTrackChanged();

552 553
    displayOrHideUndoInline(true);
    Q_EMIT tracksCountChanged();
554
    Q_EMIT remainingTracksChanged();
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    Q_EMIT persistentStateChanged();
}

void MediaPlayList::clearPlayList()
{
    this->clearPlayList(true);
}

void MediaPlayList::undoClearPlayList()
{
    clearPlayList(false);

    beginInsertRows(QModelIndex(), d->mData.size(), d->mData.size() + dOld->mData.size() - 1);
    for (auto &newTrack : dOld->mData) {
        d->mData.push_back(newTrack);
        d->mTrackData.push_back({});

        if (ElisaUtils::FileName == newTrack.mEntryType  && newTrack.mTrackUrl.isValid()) {
            auto entryURL = newTrack.mTrackUrl.toUrl();
            if (entryURL.isLocalFile()) {
                auto entryString =  entryURL.toLocalFile();
                QFileInfo newTrackFile(entryString);
                if (newTrackFile.exists()) {
                    d->mData.last().mIsValid = true;
                }
                Q_EMIT newEntryInList(0, entryString, newTrack.mEntryType);
            }
        }
        else if(ElisaUtils::Artist == newTrack.mEntryType){
            Q_EMIT newEntryInList(0, newTrack.mArtist.toString(), newTrack.mEntryType);
        }
        else{
            Q_EMIT newEntryInList(newTrack.mId, newTrack.mTitle.toString(), newTrack.mEntryType);
        }
    }
    endInsertRows();

    d->mMusicListenersManager = dOld->mMusicListenersManager;
    d->mPersistentState = dOld->mPersistentState;
    d->mCurrentPlayListPosition = dOld->mCurrentPlayListPosition;
    d->mRandomPlay = dOld->mRandomPlay;
    d->mRepeatPlay = dOld->mRepeatPlay;

    auto candidateTrack = index(dOld->mCurrentPlayListPosition, 0);

    if (candidateTrack.isValid() && candidateTrack.data(ColumnsRoles::IsValidRole).toBool()) {
        d->mCurrentTrack = candidateTrack;
        notifyCurrentTrackChanged();
    }

605
    Q_EMIT tracksCountChanged();
606
    Q_EMIT remainingTracksChanged();
607
    Q_EMIT persistentStateChanged();
608 609 610 611 612 613

    Q_EMIT dataChanged(index(rowCount() - 1, 0), index(rowCount() - 1, 0), {MediaPlayList::IsPlayingRole});
    displayOrHideUndoInline(false);
    Q_EMIT undoClearPlayListPlayer();
}

Jerome Guidon's avatar
Jerome Guidon committed
614 615 616 617 618 619 620 621
void MediaPlayList::updateRadioData(const QVariant &value, int role)
{
    auto convertedRole = static_cast<ColumnsRoles>(role);
    if (d->mCurrentTrack.data(convertedRole) != value) {
        this->setData(d->mCurrentTrack, value, role);
    }
}

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
void MediaPlayList::enqueueCommon()
{
    displayOrHideUndoInline(false);
}

void MediaPlayList::copyD()
{
    dOld->mData = d->mData;
    dOld->mTrackData = d->mTrackData;
    dOld->mMusicListenersManager = d->mMusicListenersManager;
    dOld->mCurrentTrack = d->mCurrentTrack;
    dOld->mPersistentState = d->mPersistentState;
    dOld->mCurrentPlayListPosition = d->mCurrentPlayListPosition;
    dOld->mRandomPlay = d->mRandomPlay;
    dOld->mRepeatPlay = d->mRepeatPlay;
637 638
}

639 640 641 642 643 644
void MediaPlayList::loadPlaylist(const QString &localFileName)
{
    d->mLoadPlaylist.clear();
    d->mLoadPlaylist.load(QUrl::fromLocalFile(localFileName), "m3u");
}

645 646 647 648 649 650
void MediaPlayList::loadPlaylist(const QUrl &fileName)
{
    d->mLoadPlaylist.clear();
    d->mLoadPlaylist.load(fileName, "m3u");
}

651 652 653 654 655 656 657 658 659 660
void MediaPlayList::enqueue(const ElisaUtils::EntryData &newEntry, ElisaUtils::PlayListEntryType databaseIdType)
{
    enqueue(newEntry, databaseIdType, ElisaUtils::PlayListEnqueueMode::AppendPlayList, ElisaUtils::PlayListEnqueueTriggerPlay::DoNotTriggerPlay);
}

void MediaPlayList::enqueue(const ElisaUtils::EntryDataList &newEntries, ElisaUtils::PlayListEntryType databaseIdType)
{
    enqueue(newEntries, databaseIdType, ElisaUtils::PlayListEnqueueMode::AppendPlayList, ElisaUtils::PlayListEnqueueTriggerPlay::DoNotTriggerPlay);
}

661 662
void MediaPlayList::enqueue(qulonglong newEntryDatabaseId,
                            const QString &newEntryTitle,
663 664 665
                            ElisaUtils::PlayListEntryType databaseIdType,
                            ElisaUtils::PlayListEnqueueMode enqueueMode,
                            ElisaUtils::PlayListEnqueueTriggerPlay triggerPlay)
666
{
667
    enqueue(ElisaUtils::EntryData{newEntryDatabaseId, newEntryTitle}, databaseIdType, enqueueMode, triggerPlay);
668 669
}

670
void MediaPlayList::enqueue(const ElisaUtils::EntryData &newEntry,
671 672 673
                            ElisaUtils::PlayListEntryType databaseIdType,
                            ElisaUtils::PlayListEnqueueMode enqueueMode,
                            ElisaUtils::PlayListEnqueueTriggerPlay triggerPlay)
674
{
675
    if (enqueueMode == ElisaUtils::ReplacePlayList) {
676 677 678
        if(d->mData.size()>0){
            d->mForceUndo = true;
        }
679 680 681
        clearPlayList();
    }

682 683
    enqueueCommon();

684 685
    switch (databaseIdType)
    {
686
    case ElisaUtils::Album:
687
    case ElisaUtils::Artist:
688
    case ElisaUtils::Genre:
689
    case ElisaUtils::Track:
Jerome Guidon's avatar
Jerome Guidon committed
690
    case ElisaUtils::Radio:
691
        enqueueOneEntry(newEntry, databaseIdType);
692
        break;
693 694 695
    case ElisaUtils::FileName:
        enqueueFilesList({newEntry});
        break;
696 697
    case ElisaUtils::Lyricist:
    case ElisaUtils::Composer:
698 699 700 701 702 703
    case ElisaUtils::Unknown:
        break;
    }

    if (triggerPlay == ElisaUtils::TriggerPlay) {
        Q_EMIT ensurePlay();
704
    }
705 706 707 708

    if (enqueueMode == ElisaUtils::ReplacePlayList) {
        d->mForceUndo = false;
    }
709 710
}

711 712 713 714
void MediaPlayList::enqueue(const ElisaUtils::EntryDataList &newEntries,
                            ElisaUtils::PlayListEntryType databaseIdType,
                            ElisaUtils::PlayListEnqueueMode enqueueMode,
                            ElisaUtils::PlayListEnqueueTriggerPlay triggerPlay)
715 716 717 718 719
{
    if (newEntries.isEmpty()) {
        return;
    }

720
    if (enqueueMode == ElisaUtils::ReplacePlayList) {
721 722 723
        if(d->mData.size()>0){
            d->mForceUndo = true;
        }
724 725 726
        clearPlayList();
    }

727 728
    enqueueCommon();

729 730
    switch (databaseIdType)
    {
731
    case ElisaUtils::Track:
Jerome Guidon's avatar
Jerome Guidon committed
732 733
    case ElisaUtils::Radio:
        enqueueTracksListById(newEntries, databaseIdType);
734
        break;
735
    case ElisaUtils::FileName:
736 737
        enqueueFilesList(newEntries);
        break;
738 739 740 741 742
    case ElisaUtils::Album:
    case ElisaUtils::Artist:
    case ElisaUtils::Genre:
        enqueueMultipleEntries(newEntries, databaseIdType);
        break;
743 744
    case ElisaUtils::Lyricist:
    case ElisaUtils::Composer:
745 746 747 748 749 750
    case ElisaUtils::Unknown:
        break;
    }

    if (triggerPlay == ElisaUtils::TriggerPlay) {
        Q_EMIT ensurePlay();
751
    }
752 753 754 755

    if (enqueueMode == ElisaUtils::ReplacePlayList) {
        d->mForceUndo = false;
    }
756 757
}

758 759 760 761 762 763 764 765
bool MediaPlayList::savePlaylist(const QUrl &fileName)
{
    QMediaPlaylist savePlaylist;

    for (int i = 0; i < d->mData.size(); ++i) {
        const auto &oneTrack = d->mData.at(i);
        const auto &oneTrackData = d->mTrackData.at(i);
        if (oneTrack.mIsValid) {
766
            savePlaylist.addMedia(oneTrackData.resourceURI());
767 768 769 770 771 772
        }
    }

    return savePlaylist.save(fileName, "m3u");
}

773
QVariantMap MediaPlayList::persistentState() const
774
{
775
    auto currentState = QVariantMap();
776 777
    auto result = QList<QVariant>();

778
    for (int trackIndex = 0; trackIndex < d->mData.size(); ++trackIndex) {
779
        auto oneData = QList<QString>();
780 781 782
        const auto &oneEntry = d->mData[trackIndex];
        if (oneEntry.mIsValid) {
            const auto &oneTrack = d->mTrackData[trackIndex];
783

Jerome Guidon's avatar
Jerome Guidon committed
784
            oneData.push_back(QString::number(oneTrack.databaseId()));
785
            oneData.push_back(oneTrack.title());
786
            oneData.push_back(oneTrack.artist());
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
            if (oneTrack.hasAlbum()) {
                oneData.push_back(oneTrack.album());
            } else {
                oneData.push_back({});
            }
            if (oneTrack.hasTrackNumber()) {
                oneData.push_back(QString::number(oneTrack.trackNumber()));
            } else {
                oneData.push_back({});
            }
            if (oneTrack.hasDiscNumber()) {
                oneData.push_back(QString::number(oneTrack.discNumber()));
            } else {
                oneData.push_back({});
            }
802
            oneData.push_back(QString::number(oneEntry.mEntryType));
803

804 805
            result.push_back(QVariant(oneData));
        }
806 807
    }

808 809 810 811 812 813
    currentState[QStringLiteral("playList")] = result;
    currentState[QStringLiteral("currentTrack")] = d->mCurrentPlayListPosition;
    currentState[QStringLiteral("randomPlay")] = d->mRandomPlay;
    currentState[QStringLiteral("repeatPlay")] = d->mRepeatPlay;

    return currentState;
814 815
}

816
MusicListenersManager *MediaPlayList::musicListenersManager() const
817
{
818
    return d->mMusicListenersManager;
819 820
}

821 822 823 824 825
int MediaPlayList::tracksCount() const
{
    return rowCount();
}

826 827 828 829 830
QPersistentModelIndex MediaPlayList::previousTrack() const
{
    return d->mPreviousTrack;
}

831 832 833 834 835
QPersistentModelIndex MediaPlayList::currentTrack() const
{
    return d->mCurrentTrack;
}

836 837 838 839 840
QPersistentModelIndex MediaPlayList::nextTrack() const
{
    return d->mNextTrack;
}

841 842 843 844 845 846
int MediaPlayList::currentTrackRow() const
{
    return d->mCurrentTrack.row();
}

bool MediaPlayList::randomPlay() const
847
{
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    return d->mRandomPlay;
}

bool MediaPlayList::repeatPlay() const
{
    return d->mRepeatPlay;
}

void MediaPlayList::setPersistentState(const QVariantMap &persistentStateValue)
{
    if (d->mPersistentState == persistentStateValue) {
        return;
    }

    qDebug() << "MediaPlayList::setPersistentState" << persistentStateValue;

    d->mPersistentState = persistentStateValue;

    auto persistentState = d->mPersistentState[QStringLiteral("playList")].toList();
867

868
    for (auto &oneData : persistentState) {
869
        auto trackData = oneData.toStringList();
Jerome Guidon's avatar
Jerome Guidon committed
870
        if (trackData.size() != 7) {
871 872 873
            continue;
        }

Jerome Guidon's avatar
Jerome Guidon committed
874 875 876 877 878 879
        auto restoredId = trackData[0].toULongLong();
        auto restoredTitle = trackData[1];
        auto restoredArtist = trackData[2];
        auto restoredAlbum = trackData[3];
        auto restoredTrackNumber = trackData[4];
        auto restoredDiscNumber = trackData[5];
880

Jerome Guidon's avatar
Jerome Guidon committed
881
        auto mEntryType = static_cast<ElisaUtils::PlayListEntryType>(trackData[6].toInt());
882

Jerome Guidon's avatar
Jerome Guidon committed
883
        enqueueRestoredEntry({restoredId, restoredTitle, restoredArtist, restoredAlbum, restoredTrackNumber, restoredDiscNumber, mEntryType});
884
    }
885

886 887 888 889 890
    restorePlayListPosition();
    restoreRandomPlay();
    restoreRepeatPlay();

    Q_EMIT persistentStateChanged();
891 892
}

893 894 895 896 897 898 899
void MediaPlayList::removeSelection(QList<int> selection)
{
    std::sort(selection.begin(), selection.end());
    std::reverse(selection.begin(), selection.end());
    for (auto oneItem : selection) {
        removeRow(oneItem);
    }
Alexander Stippich's avatar
Alexander Stippich committed
900 901 902
    if (d->mRandomPlay) {
        createRandomList();
    }
903 904
}

905 906 907 908
void MediaPlayList::tracksListAdded(qulonglong newDatabaseId,
                                    const QString &entryTitle,
                                    ElisaUtils::PlayListEntryType databaseIdType,
                                    const ListTrackDataType &tracks)
909
{
910 911
    for (int playListIndex = 0; playListIndex < d->mData.size(); ++playListIndex) {
        auto &oneEntry = d->mData[playListIndex];
912 913 914 915 916
        if (oneEntry.mEntryType != databaseIdType) {
            continue;
        }

        if (oneEntry.mTitle != entryTitle) {
917 918
            continue;
        }
919

920
        if (newDatabaseId != 0 && oneEntry.mId != newDatabaseId) {
921
            continue;
922 923
        }

924 925 926
        d->mTrackData[playListIndex] = tracks.first();
        oneEntry.mId = tracks.first().databaseId();
        oneEntry.mIsValid = true;
927
        oneEntry.mEntryType = ElisaUtils::Track;
928

929
        Q_EMIT dataChanged(index(playListIndex, 0), index(playListIndex, 0), {});
930

931 932 933 934
        if (!d->mCurrentTrack.isValid()) {
            resetCurrentTrack();
        }

935 936 937
        if (tracks.size() > 1) {
            beginInsertRows(QModelIndex(), playListIndex + 1, playListIndex - 1 + tracks.size());
            for (int trackIndex = 1; trackIndex < tracks.size(); ++trackIndex) {
938 939 940
                auto newEntry = MediaPlayListEntry{tracks[trackIndex]};
                newEntry.mEntryType = ElisaUtils::Track;
                d->mData.push_back(newEntry);
941 942 943 944
                d->mTrackData.push_back(tracks[trackIndex]);
            }
            endInsertRows();

945 946 947 948 949
            restorePlayListPosition();
            if (!d->mCurrentTrack.isValid()) {
                resetCurrentTrack();
            }

950
            Q_EMIT tracksCountChanged();
951
            Q_EMIT remainingTracksChanged();
952 953 954 955 956
        }
        Q_EMIT persistentStateChanged();
    }
}

957
void MediaPlayList::trackChanged(const TrackDataType &track)
958 959 960 961
{
    for (int i = 0; i < d->mData.size(); ++i) {
        auto &oneEntry = d->mData[i];

962
        if (oneEntry.mEntryType != ElisaUtils::Artist && oneEntry.mIsValid) {
963
            if (oneEntry.mTrackUrl.toUrl().isValid() && track.resourceURI() != oneEntry.mTrackUrl.toUrl()) {
964 965 966
                continue;
            }

967
            if (!oneEntry.mTrackUrl.toUrl().isValid() && (oneEntry.mId == 0 || track.databaseId() != oneEntry.mId)) {
968 969 970
                continue;
            }

971
            const auto &trackData = d->mTrackData[i];
972

973 974
            if (!trackData.