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
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2016-08-14
 * Description : An unit test to read or write metadata through multi-core threads.
 *
 * SPDX-FileCopyrightText: 2016-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "metareaderthread_utest.h"

// Qt includes

#include <QDirIterator>
#include <QApplication>
#include <QSignalSpy>
#include <QScopedPointer>
#include <QSettings>

// Local includes

#include "digikam_debug.h"
#include "digikam_globals.h"
#include "dmetadata.h"
#include "metaengine_previews.h"

Mytask::Mytask(QObject* const parent)
    : ActionJob(parent),
      direction(MetaReaderThread::READ_INFO_FROM_FILE),
      settings ()
{
}

void Mytask::run()
{
    qCDebug(DIGIKAM_TESTS_LOG) << "Processing:" << url.path();
    bool processed = false;

    if (direction != MetaReaderThread::READ_PREVIEW_FROM_FILE)
    {
        QScopedPointer<DMetadata> meta(new DMetadata);
        meta->setSettings(settings);

        if (meta->load(url.toLocalFile()))
        {
            // NOTE: only process data here without to generate extra debug statements,
            //       for performance purpose.

            switch (direction)
            {
                case (MetaReaderThread::READ_INFO_FROM_FILE):
                {

                    // Get most important info used to populate the core-database

                    meta->getItemDimensions();
                    meta->getItemComments();
                    meta->getItemTitles();
                    meta->getCreatorContactInfo();
                    meta->getIptcCoreLocation();
                    meta->getIptcCoreSubjects();
                    meta->getPhotographInformation();
                    QStringList tmp;
                    meta->getItemTagsPath(tmp);
                    meta->getXmpKeywords();
                    meta->getXmpSubjects();
                    meta->getXmpSubCategories();
                    processed = true;
                    break;
                }

                default: // WRITE_INFO_TO_SIDECAR
                {
                    // Just create sidecar files with these info which will touch Exif, Iptc, and Xmp metadata

                    meta->setItemDimensions(QSize(256, 256));
                    meta->setImageDateTime(QDateTime::currentDateTime());
                    meta->setComments(QString::fromLatin1("MetaReaderThread").toLatin1());
                    meta->setItemRating(1);
                    meta->setItemPickLabel(2);
                    meta->setItemColorLabel(3);
                    meta->setItemTagsPath(QStringList() << QLatin1String("digiKam/Unit Tests/Metadata Engine/MetaReaderThread"));

                    // This stage will write a sidecar in temporary directory without to touch original file.

                    meta->save(tempDir + QString::fromUtf8("/%1").arg(url.path().remove(QLatin1Char('/'))));
                    processed = true;
                    break;
                }
            }
        }
    }
    else
    {
        MetaEnginePreviews previews(url.path());
        processed = !previews.isEmpty();
    }

    Q_EMIT signalStats(url, processed);

    qCDebug(DIGIKAM_TESTS_LOG) << "Processed:" << url.path();

    Q_EMIT signalDone();
}

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

MetaReaderThread::MetaReaderThread(QObject* const parent)
    : ActionThreadBase(parent)
{
    setObjectName(QLatin1String("MetaReaderThread"));
}

MetaReaderThread::~MetaReaderThread()
{
}

QString MetaReaderThread::directionToString(Direction direction)
{
    QString ret;

    switch (direction)
    {
        case (MetaReaderThread::READ_INFO_FROM_FILE):
        {
             ret = QLatin1String("Read info from file");
             break;
        }

        case (MetaReaderThread::READ_PREVIEW_FROM_FILE):
        {
             ret = QLatin1String("Read preview from file");
             break;
        }

        default: // WRITE_INFO_TO_SIDECAR
        {
             ret = QLatin1String("Write info to side-car");
             break;
        }
     }

     return ret;
}

void MetaReaderThread::readMetadata(const QList<QUrl>& list,
                                    Direction direction,
                                    const MetaEngineSettingsContainer& settings,
                                    const QString& temp)
{
    ActionJobCollection collection;

    for (const QUrl& url : std::as_const(list))
    {
        Mytask* const job = new Mytask();
        job->url          = url;
        job->direction    = direction;
        job->settings     = settings;
        job->tempDir      = temp;
        collection.insert(job, 0);

        connect(job, SIGNAL(signalStats(QUrl,bool)),
                this, SLOT(slotStats(QUrl,bool)));
    }

    appendJobs(collection);
    m_timer.start();
}

void MetaReaderThread::slotStats(const QUrl& url, bool p)
{
    m_stats.insert(url, p);
}

void MetaReaderThread::slotJobFinished()<--- Derived function 'MetaReaderThread::slotJobFinished'
{
    ActionThreadBase::slotJobFinished();

    qCDebug(DIGIKAM_TESTS_LOG) << "Pending items to process:" << pendingCount();
    qCDebug(DIGIKAM_TESTS_LOG) << "Elaspsed time in seconds:" << m_timer.elapsed() / 1000.0;

    if (isEmpty())
    {
        Q_EMIT done();
    }
}

QString MetaReaderThread::stats(const QStringList& mimeTypes)
{
    QString out;
    QStringList list;
    int count       = 0;
    const auto urls = m_stats.keys();

    for (const QUrl& url : urls)
    {
        list << QFileInfo(url.path()).suffix();
    }

    for (QString mt : std::as_const(mimeTypes))
    {
        mt.remove(QLatin1String("*."));
        count  = list.count(mt);
        count += list.count(mt.toUpper());

        if (count != 0)
        {
            out.append(QString::fromLatin1("%1(%2) ").arg(mt).arg(count));
        }
    }

    count = m_stats.values().count(false);
    out.append(QString::fromLatin1("Failed(%1 - %2%) ")
        .arg(count)
        .arg((m_stats.count() > 0) ? (count * 100.0 / m_stats.count())
                                   : 0)
    );

    return out;
}

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

QTEST_MAIN(MetaReaderThreadTest)

MetaReaderThreadTest::MetaReaderThreadTest(QObject* const parent)
    : AbstractUnitTest(parent)
{
}

void MetaReaderThreadTest::testMetaReaderThread()
{
    MetaEngineSettingsContainer settings;
    settings.useXMPSidecar4Reading        = false;
    settings.metadataWritingMode          = DMetadata::WRITE_TO_SIDECAR_ONLY;

    QString filters;
    supportedImageMimeTypes(QIODevice::ReadOnly, filters);              // By defaults, all mime-types supported by digiKam.
    int threadsToUse                      = 0;                          // By default all cpu cores.
    QString path                          = m_originalImageFolder;      // By default the unit-tests data dir.

    // Read configuration from ~/.config/MetaReaderThreadTest.conf
    // Template file can be found at core/tests/metadataengine/data/

    QSettings conf(QLatin1String("MetaReaderThreadTest"));
    qCDebug(DIGIKAM_TESTS_LOG) << "Check custom configuration file" << conf.fileName();

    if (!QFileInfo::exists(conf.fileName()))
    {
        qCDebug(DIGIKAM_TESTS_LOG) << "Configuration file do not exists.";
        qCDebug(DIGIKAM_TESTS_LOG) << "You can customize this unit-test to copy the template file from";
        qCDebug(DIGIKAM_TESTS_LOG) << m_originalImageFolder << "in your home directory...";
    }
    else
    {
        bool useConf = conf.value(QLatin1String("Enable"), 0).toInt();

        // If configuration file is used, only one unit-test will be processed accordingly with the settings.

        if (useConf)
        {
            qCDebug(DIGIKAM_TESTS_LOG) << "We will use custom configuration file with this unit-test...";

            threadsToUse        = conf.value(QLatin1String("ThreadsToUse"), 0).toInt();
            QString confFilters = conf.value(QLatin1String("Filters"), QString()).toString();

            if (!confFilters.isEmpty())
            {
                filters = confFilters;
            }

            QString confPath = conf.value(QLatin1String("Path"), QString()).toString();

            if (!confPath.isEmpty())
            {
                path = confPath;
            }

            MetaReaderThread::Direction direction = (MetaReaderThread::Direction)conf.value(QLatin1String("Direction"),
                                                    (int)MetaReaderThread::NOT_DEFINED).toInt();

            if (direction == MetaReaderThread::NOT_DEFINED)
            {
                direction = MetaReaderThread::READ_INFO_FROM_FILE;
            }

            runMetaReader(path, filters.split(QLatin1Char(' ')), direction, settings, threadsToUse);

            return;
        }
    }

    // Standard unit-tests

    QStringList mimeTypes = filters.split(QLatin1Char(' '));

    runMetaReader(path, mimeTypes, MetaReaderThread::READ_INFO_FROM_FILE,    settings, threadsToUse);
    runMetaReader(path, mimeTypes, MetaReaderThread::READ_PREVIEW_FROM_FILE, settings, threadsToUse);
    runMetaReader(path, mimeTypes, MetaReaderThread::WRITE_INFO_TO_SIDECAR,  settings, threadsToUse);
}

void MetaReaderThreadTest::runMetaReader(const QString& path,
                                         const QStringList& mimeTypes,
                                         MetaReaderThread::Direction direction,
                                         const MetaEngineSettingsContainer& settings,
                                         int threadsToUse)
{
    qCDebug(DIGIKAM_TESTS_LOG) << "-- Start to process" << path << "------------------------------";

    QList<QUrl> list;
    QDirIterator it(path, mimeTypes,
                    QDir::Files,
                    QDirIterator::Subdirectories);

    while (it.hasNext())
    {
        QString path2 = it.next();
        list.append(QUrl::fromLocalFile(path2));
    }

    if (list.isEmpty())
    {
        qCDebug(DIGIKAM_TESTS_LOG) << "Files list to process is empty!";
        return;
    }

    MetaReaderThread* const thread = new MetaReaderThread(this);

    if (threadsToUse > 0)
    {
        thread->setMaximumNumberOfThreads(threadsToUse);
    }

    thread->readMetadata(list, direction, settings, m_tempDir.absolutePath());

    QSignalSpy spy(thread, SIGNAL(done()));

    thread->start();

    while (!spy.wait(1000));  // Time-out in milliseconds

    qCDebug(DIGIKAM_TESTS_LOG) << Qt::endl << "Scan have been completed:"                                                    << Qt::endl
             <<         "    Processing duration:" << thread->m_timer.elapsed() / 1000.0 << " seconds" << Qt::endl
             <<         "    Root path          :" << path                                             << Qt::endl
             <<         "    Number of files    :" << list.size()                                      << Qt::endl
             <<         "    Number of threads  :" << thread->maximumNumberOfThreads()                 << Qt::endl
             <<         "    Direction          :" << MetaReaderThread::directionToString(direction)   << Qt::endl
             <<         "    Type-mimes         :" << mimeTypes.join(QLatin1Char(' '))                 << Qt::endl
             <<         "    Engine settings    :" << settings                                         << Qt::endl
             <<         "    Statistics         :" << thread->stats(mimeTypes)                         << Qt::endl;

    thread->cancel();
    delete thread;
}

#include "moc_metareaderthread_utest.cpp"