1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
262
263
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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
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
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2008-09-14
 * Description : a presentation tool.
 *
 * SPDX-FileCopyrightText: 2008-2009 by Valerio Fuoglio <valerio dot fuoglio at gmail dot com>
 * SPDX-FileCopyrightText: 2012-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "presentation_audiopage.h"

// Qt includes

#include <QPointer>
#include <QIcon>
#include <QMessageBox>
#include <QDialogButtonBox>

// Local includes

#include "digikam_debug.h"
#include "presentation_mainpage.h"
#include "presentationcontainer.h"
#include "dfiledialog.h"

using namespace Digikam;

namespace DigikamGenericPresentationPlugin
{

SoundtrackPreview::SoundtrackPreview(QWidget* const parent,
                                     const QList<QUrl>& urls,
                                     PresentationContainer* const sharedData)
    : QDialog(parent)
{
    setModal(true);
    setWindowTitle(i18nc("@title:window", "Soundtrack Preview"));

    m_playbackWidget                  = new PresentationAudioWidget(this, urls, sharedData);
    QDialogButtonBox* const buttonBox = new QDialogButtonBox(QDialogButtonBox::Close, this);<--- Variable 'buttonBox' can be declared as pointer to const

    connect(buttonBox, &QDialogButtonBox::rejected,
            this, &QDialog::reject);

    QVBoxLayout* const layout = new QVBoxLayout(this);
    layout->addWidget(m_playbackWidget);
    layout->addWidget(buttonBox);
    setLayout(layout);
}

// ------------------------------------------------------------------------------------

class Q_DECL_HIDDEN PresentationAudioPage::Private
{
public:

    Private() = default;

public:

    QList<QUrl>                             urlList;
    PresentationContainer*                  sharedData = nullptr;
    QTime                                   totalTime;
    QTime                                   imageTime;
    QMap<QUrl, QTime>*                      tracksTime = nullptr;
    QMap<QUrl, PresentationAudioListItem*>* soundItems = nullptr;
    QMutex*                                 timeMutex  = nullptr;
};

PresentationAudioPage::PresentationAudioPage(QWidget* const parent,
                                             PresentationContainer* const sharedData)
    : QWidget(parent),
      d      (new Private)
{
    setupUi(this);

    d->sharedData = sharedData;
    d->totalTime  = QTime(0, 0, 0);
    d->imageTime  = QTime(0, 0, 0);
    d->tracksTime = new QMap<QUrl, QTime>();
    d->soundItems = new QMap<QUrl, PresentationAudioListItem*>();
    d->timeMutex  = new QMutex();

    m_soundtrackTimeLabel->setText(d->totalTime.toString());
    m_previewButton->setEnabled(false);

    m_rememberSoundtrack->setToolTip(i18n("If set, the soundtrack for the current album "
                                          "will be saved and restored automatically on the next startup."));

    // --------------------------------------------------------

    m_SoundFilesButtonUp->setIcon(QIcon::fromTheme(QLatin1String("go-up")));
    m_SoundFilesButtonDown->setIcon(QIcon::fromTheme(QLatin1String("go-down")));
    m_SoundFilesButtonAdd->setIcon(QIcon::fromTheme(QLatin1String("list-add")));
    m_SoundFilesButtonDelete->setIcon(QIcon::fromTheme(QLatin1String("list-remove")));
    m_SoundFilesButtonLoad->setIcon(QIcon::fromTheme(QLatin1String("document-open")));
    m_SoundFilesButtonSave->setIcon(QIcon::fromTheme(QLatin1String("document-save")));
    m_SoundFilesButtonReset->setIcon(QIcon::fromTheme(QLatin1String("edit-clear")));

    m_SoundFilesButtonUp->setText(QString());
    m_SoundFilesButtonDown->setText(QString());
    m_SoundFilesButtonAdd->setText(QString());
    m_SoundFilesButtonDelete->setText(QString());
    m_SoundFilesButtonLoad->setText(QString());
    m_SoundFilesButtonSave->setText(QString());
    m_SoundFilesButtonReset->setText(QString());

    m_SoundFilesButtonUp->setToolTip(i18n("Move the selected track up in the playlist."));
    m_SoundFilesButtonDown->setToolTip(i18n("Move the selected track down in the playlist."));
    m_SoundFilesButtonAdd->setToolTip(i18n("Add new tracks to the playlist."));
    m_SoundFilesButtonDelete->setToolTip(i18n("Delete the selected track from the playlist."));
    m_SoundFilesButtonLoad->setToolTip(i18n("Load playlist from a file."));
    m_SoundFilesButtonSave->setToolTip(i18n("Save playlist to a file."));
    m_SoundFilesButtonReset->setToolTip(i18n("Clear the playlist."));

    // --------------------------------------------------------

    connect(m_SoundFilesListBox, SIGNAL(currentRowChanged(int)),
            this, SLOT(slotSoundFilesSelected(int)));

    connect(m_SoundFilesListBox, SIGNAL(signalAddedDropItems(QList<QUrl>)),
            this, SLOT(slotAddDropItems(QList<QUrl>)));

    connect(m_SoundFilesButtonAdd, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonAdd()));

    connect(m_SoundFilesButtonDelete, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonDelete()));

    connect(m_SoundFilesButtonUp, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonUp()));

    connect(m_SoundFilesButtonDown, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonDown()));

    connect(m_SoundFilesButtonLoad, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonLoad()));

    connect(m_SoundFilesButtonSave, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonSave()));

    connect(m_SoundFilesButtonReset, SIGNAL(clicked()),
            this, SLOT(slotSoundFilesButtonReset()));

    connect(m_previewButton, SIGNAL(clicked()),
            this, SLOT(slotPreviewButtonClicked()));

    connect(d->sharedData->mainPage, SIGNAL(signalTotalTimeChanged(QTime)),
            this, SLOT(slotImageTotalTimeChanged(QTime)));
}

PresentationAudioPage::~PresentationAudioPage()
{
    delete d->tracksTime;
    delete d->soundItems;
    delete d->timeMutex;
    delete d;
}

void PresentationAudioPage::readSettings()
{
    m_rememberSoundtrack->setChecked(d->sharedData->soundtrackRememberPlaylist);
    m_loopCheckBox->setChecked(d->sharedData->soundtrackLoop);
    m_playCheckBox->setChecked(d->sharedData->soundtrackPlay);

    connect(d->sharedData->mainPage, SIGNAL(signalTotalTimeChanged(QTime)),
            this, SLOT(slotImageTotalTimeChanged(QTime)));

    // if tracks are already set in d->sharedData, add them now

    if (!d->sharedData->soundtrackUrls.isEmpty())
    {
        addItems(d->sharedData->soundtrackUrls);
    }

    updateFileList();
    updateTracksNumber();
}

void PresentationAudioPage::saveSettings()
{
    d->sharedData->soundtrackRememberPlaylist = m_rememberSoundtrack->isChecked();
    d->sharedData->soundtrackLoop             = m_loopCheckBox->isChecked();
    d->sharedData->soundtrackPlay             = m_playCheckBox->isChecked();
    d->sharedData->soundtrackUrls             = d->urlList;
}

void PresentationAudioPage::addItems(const QList<QUrl>& fileList)
{
    if (fileList.isEmpty())
    {
        return;
    }

    QList<QUrl> Files = fileList;

    for (QList<QUrl>::ConstIterator it = Files.constBegin() ; it != Files.constEnd() ; ++it)
    {
        QUrl currentFile                      = *it;
        d->sharedData->soundtrackPath         = currentFile;
        PresentationAudioListItem* const item = new PresentationAudioListItem(m_SoundFilesListBox, currentFile);
        item->setName(currentFile.fileName());
        m_SoundFilesListBox->insertItem(m_SoundFilesListBox->count() - 1, item);

        d->soundItems->insert(currentFile, item);

        connect(d->soundItems->value(currentFile), SIGNAL(signalTotalTimeReady(QUrl,QTime)),
                this, SLOT(slotAddNewTime(QUrl,QTime)));

        d->urlList.append(currentFile);
    }

    m_SoundFilesListBox->setCurrentItem(m_SoundFilesListBox->item(m_SoundFilesListBox->count() - 1)) ;

    slotSoundFilesSelected(m_SoundFilesListBox->currentRow());
    m_SoundFilesListBox->scrollToItem(m_SoundFilesListBox->currentItem());
    m_previewButton->setEnabled(true);
}

void PresentationAudioPage::updateTracksNumber()
{
    QTime displayTime(0, 0, 0);
    int number = m_SoundFilesListBox->count();

    if (number > 0)
    {
        displayTime = displayTime.addMSecs(1000 * (number - 1));

        for (QMap<QUrl, QTime>::iterator it = d->tracksTime->begin() ; it != d->tracksTime->end() ; ++it)
        {
            int hours = it.value().hour()   + displayTime.hour();
            int mins  = it.value().minute() + displayTime.minute();
            int secs  = it.value().second() + displayTime.second();

            /*
             * QTime doesn't get a overflow value in input. They need
             * to be cut down to size.
             */

            mins        = mins + (int)(secs / 60);
            secs        = secs % 60;
            hours       = hours + (int)(mins / 60);
            displayTime = QTime(hours, mins, secs);
        }
    }

    m_timeLabel->setText(i18ncp("number of tracks and running time", "1 track [%2]", "%1 tracks [%2]", number, displayTime.toString()));

    m_soundtrackTimeLabel->setText(displayTime.toString());

    d->totalTime = displayTime;

    compareTimes();
}

void PresentationAudioPage::updateFileList()
{
    d->urlList = m_SoundFilesListBox->fileUrls();

    m_SoundFilesButtonUp->setEnabled(!d->urlList.isEmpty());
    m_SoundFilesButtonDown->setEnabled(!d->urlList.isEmpty());
    m_SoundFilesButtonDelete->setEnabled(!d->urlList.isEmpty());
    m_SoundFilesButtonSave->setEnabled(!d->urlList.isEmpty());
    m_SoundFilesButtonReset->setEnabled(!d->urlList.isEmpty());

    d->sharedData->soundtrackPlayListNeedsUpdate = true;
}

void PresentationAudioPage::compareTimes()
{
    QFont statusBarFont = m_statusBarLabel->font();

    if (d->imageTime > d->totalTime)
    {
        m_statusBarLabel->setText(i18n("Slide time is greater than soundtrack time. Suggestion: add more sound files."));


        QPalette paletteStatusBar = m_statusBarLabel->palette();
        paletteStatusBar.setColor(QPalette::WindowText, Qt::red);
        m_statusBarLabel->setPalette(paletteStatusBar);

        QPalette paletteTimeLabel = m_soundtrackTimeLabel->palette();
        paletteTimeLabel.setColor(QPalette::WindowText, Qt::red);
        m_soundtrackTimeLabel->setPalette(paletteTimeLabel);

        statusBarFont.setItalic(true);
    }
    else
    {
        m_statusBarLabel->setText(QLatin1String(""));

        QPalette paletteStatusBar = m_statusBarLabel->palette();
        paletteStatusBar.setColor(QPalette::WindowText, Qt::red);
        m_statusBarLabel->setPalette(paletteStatusBar);

        QPalette paletteTimeLabel = m_soundtrackTimeLabel->palette();

        if (d->imageTime < d->totalTime)
        {
            paletteTimeLabel.setColor(QPalette::WindowText, Qt::black);
        }
        else
        {
            paletteTimeLabel.setColor(QPalette::WindowText, Qt::green);
        }

        m_soundtrackTimeLabel->setPalette(paletteTimeLabel);

        statusBarFont.setItalic(false);
    }

    m_statusBarLabel->setFont(statusBarFont);
}

void PresentationAudioPage::slotAddNewTime(const QUrl& url, const QTime& trackTime)
{
    d->timeMutex->lock();
    d->tracksTime->insert(url, trackTime);
    updateTracksNumber();
    d->timeMutex->unlock();
}

void PresentationAudioPage::slotSoundFilesSelected(int row)
{
    QListWidgetItem* const item = m_SoundFilesListBox->item(row);<--- Variable 'item' can be declared as pointer to const

    if (!item || (m_SoundFilesListBox->count() == 0))
    {
        return;
    }
}

void PresentationAudioPage::slotAddDropItems(const QList<QUrl>& filesUrl)
{
    if (!filesUrl.isEmpty())
    {
        addItems(filesUrl);
        updateFileList();
    }
}

void PresentationAudioPage::slotSoundFilesButtonAdd()
{
    QPointer<DFileDialog> dlg = new DFileDialog(this,
                                                i18nc("@title:window", "Select Sound Files"),
                                                d->sharedData->soundtrackPath.adjusted(QUrl::RemoveFilename).toLocalFile());

    QStringList atm;
    atm << QLatin1String("audio/mp3");
    atm << QLatin1String("audio/wav");
    atm << QLatin1String("audio/ogg");
    atm << QLatin1String("audio/flac");
    dlg->setMimeTypeFilters(atm);
    dlg->setAcceptMode(QFileDialog::AcceptOpen);
    dlg->setFileMode(QFileDialog::ExistingFiles);
    dlg->exec();

    if (dlg->hasAcceptedUrls())
    {
        addItems(dlg->selectedUrls());
        updateFileList();
    }

    delete dlg;
}

void PresentationAudioPage::slotSoundFilesButtonDelete()
{
    int index = m_SoundFilesListBox->currentRow();

    if (index < 0)
    {
        return;
    }

    PresentationAudioListItem* const pitem = static_cast<PresentationAudioListItem*>(m_SoundFilesListBox->takeItem(index));
    d->urlList.removeAll(pitem->url());
    d->soundItems->remove(pitem->url());
    d->timeMutex->lock();
    d->tracksTime->remove(pitem->url());
    updateTracksNumber();
    d->timeMutex->unlock();
    delete pitem;
    slotSoundFilesSelected(m_SoundFilesListBox->currentRow());

    if (m_SoundFilesListBox->count() == 0)
    {
        m_previewButton->setEnabled(false);
    }

    updateFileList();
}

void PresentationAudioPage::slotSoundFilesButtonUp()
{
    int cpt = 0;

    for (int i = 0 ; i < m_SoundFilesListBox->count() ; ++i)
    {
        if (m_SoundFilesListBox->currentRow() == i)
        {
            ++cpt;
        }
    }

    if (cpt == 0)
    {
        return;
    }

    if (cpt > 1)
    {
        QMessageBox::critical(this, QString(), i18n("You can only move image files up one at a time."));
        return;
    }

    unsigned int index = m_SoundFilesListBox->currentRow();

    if (index == 0)
    {
        return;
    }

    PresentationAudioListItem* const pitem = static_cast<PresentationAudioListItem*>(m_SoundFilesListBox->takeItem(index));

    m_SoundFilesListBox->insertItem(((index > 0) ? index - 1 : index), pitem);
    m_SoundFilesListBox->setCurrentItem(pitem);

    updateFileList();
}

void PresentationAudioPage::slotSoundFilesButtonDown()
{
    int cpt = 0;

    for (int i = 0 ; i < m_SoundFilesListBox->count() ; ++i)
    {
        if (m_SoundFilesListBox->currentRow() == i)
        {
            ++cpt;
        }
    }

    if (cpt == 0)
    {
        return;
    }

    if (cpt > 1)
    {
        QMessageBox::critical(this, QString(), i18n("You can only move files down one at a time."));
        return;
    }

    int index = m_SoundFilesListBox->currentRow();

    if (index == m_SoundFilesListBox->count())
    {
        return;
    }

    PresentationAudioListItem* const pitem = static_cast<PresentationAudioListItem*>(m_SoundFilesListBox->takeItem(index));

    m_SoundFilesListBox->insertItem(index + 1, pitem);
    m_SoundFilesListBox->setCurrentItem(pitem);

    updateFileList();
}

void PresentationAudioPage::slotSoundFilesButtonLoad()
{
    QPointer<DFileDialog> dlg = new DFileDialog(this, i18nc("@title:window", "Load Playlist"),
                                                QString(), i18n("Playlist (*.m3u)"));
    dlg->setAcceptMode(QFileDialog::AcceptOpen);
    dlg->setFileMode(QFileDialog::ExistingFile);
    dlg->exec();

    if (!dlg->hasAcceptedUrls())
    {
        delete dlg;

        return;
    }

    QString filename = dlg->selectedFiles().first();

    if (!filename.isEmpty())
    {
        QFile file(filename);

        if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            QTextStream in(&file);
            QList<QUrl> playlistFiles;

            while (!in.atEnd())
            {
                QString line = in.readLine();

                // we ignore the extended information of the m3u playlist file

                if (line.startsWith(QLatin1Char('#')) || line.isEmpty())
                {
                    continue;
                }

                QUrl fUrl = QUrl::fromLocalFile(line);

                if (fUrl.isValid() && fUrl.isLocalFile())
                {
                    playlistFiles << fUrl;
                }
            }

            file.close();

            if (!playlistFiles.isEmpty())
            {
                m_SoundFilesListBox->clear();
                addItems(playlistFiles);
                updateFileList();
            }
        }
    }

    delete dlg;
}

void PresentationAudioPage::slotSoundFilesButtonSave()
{
    QPointer<DFileDialog> dlg = new DFileDialog(this, i18nc("@title:window", "Save Playlist"),
                                                QString(), i18n("Playlist (*.m3u)"));
    dlg->setAcceptMode(QFileDialog::AcceptSave);
    dlg->setFileMode(QFileDialog::AnyFile);
    dlg->exec();

    if (!dlg->hasAcceptedUrls())
    {
        delete dlg;

        return;
    }

    QString filename = dlg->selectedFiles().first();

    if (!filename.isEmpty())
    {
        QFile file(filename);

        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file);
            QList<QUrl> playlistFiles = m_SoundFilesListBox->fileUrls();

            for (int i = 0 ; i < playlistFiles.count() ; ++i)
            {
                QUrl fUrl(playlistFiles.at(i));

                if (fUrl.isValid() && fUrl.isLocalFile())
                {
                    out << fUrl.toLocalFile() << Qt::endl;
                }
            }

            file.close();
        }
    }

    delete dlg;
}

void PresentationAudioPage::slotSoundFilesButtonReset()
{
    m_SoundFilesListBox->clear();
    updateFileList();
}

void PresentationAudioPage::slotPreviewButtonClicked()
{
    QList<QUrl> urlList;

    for (int i = 0 ; i < m_SoundFilesListBox->count() ; ++i)
    {
        PresentationAudioListItem* const pitem = dynamic_cast<PresentationAudioListItem*>(m_SoundFilesListBox->item(i));<--- Variable 'pitem' can be declared as pointer to const

        if (pitem)
        {
            QString path = pitem->url().toLocalFile();

            if (!QFile::exists(path))
            {
                QMessageBox::critical(this, QString(), i18n("Cannot access file \"%1\". Please check the path is correct.", path));
                return;
            }

            urlList << pitem->url();
        }
    }

    if (urlList.isEmpty())
    {
        QMessageBox::critical(this, QString(), i18n("Cannot create a preview of an empty file list."));
        return;
    }

    // Update PresentationContainer from interface

    saveSettings();

    qCDebug(DIGIKAM_DPLUGIN_GENERIC_LOG) << "Tracks : " << urlList;

    QPointer<SoundtrackPreview> preview = new SoundtrackPreview(this, urlList, d->sharedData);
    preview->exec();

    delete preview;
}

void PresentationAudioPage::slotImageTotalTimeChanged(const QTime& imageTotalTime)
{
    d->imageTime = imageTotalTime;
    m_slideTimeLabel->setText(imageTotalTime.toString());
    compareTimes();
}

} // namespace DigikamGenericPresentationPlugin

#include "moc_presentation_audiopage.cpp"