summaryrefslogtreecommitdiffstats
path: root/src/designer/src/lib/shared/qtresourcemodel.cpp
blob: acee5cc9814af6ec59b23040b6c08f0b2cc0f0d5 (plain)
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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "qtresourcemodel_p.h"
#include "rcc_p.h"

#include <QtCore/qstringlist.h>
#include <QtCore/qhash.h>
#include <QtCore/qmap.h>
#include <QtCore/qresource.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qiodevice.h>
#include <QtCore/qdir.h>
#include <QtCore/qdebug.h>
#include <QtCore/qbuffer.h>
#include <QtCore/qfilesystemwatcher.h>

QT_BEGIN_NAMESPACE

enum { debugResourceModel = 0 };

// ------------------- QtResourceSetPrivate
class QtResourceSetPrivate
{
    QtResourceSet *q_ptr;
    Q_DECLARE_PUBLIC(QtResourceSet)
public:
    QtResourceSetPrivate(QtResourceModel *model = nullptr);

    QtResourceModel *m_resourceModel;
};

QtResourceSetPrivate::QtResourceSetPrivate(QtResourceModel *model) :
   q_ptr(nullptr),
   m_resourceModel(model)
{
}

// -------------------- QtResourceModelPrivate
class QtResourceModelPrivate
{
    QtResourceModel *q_ptr = nullptr;
    Q_DECLARE_PUBLIC(QtResourceModel)
    Q_DISABLE_COPY_MOVE(QtResourceModelPrivate)
public:
    QtResourceModelPrivate();
    void activate(QtResourceSet *resourceSet, const QStringList &newPaths, int *errorCount = nullptr, QString *errorMessages = nullptr);
    void removeOldPaths(QtResourceSet *resourceSet, const QStringList &newPaths);

    QMap<QString, bool> m_pathToModified;
    QHash<QtResourceSet *, QStringList> m_resourceSetToPaths;
    QHash<QtResourceSet *, bool> m_resourceSetToReload; // while path is recreated it needs to be reregistered
                                                        // (it is - in the new current resource set, but when the path was used in
                                                        // other resource set
                                                        // then later when that resource set is activated it needs to be reregistered)
    QHash<QtResourceSet *, bool> m_newlyCreated; // all created but not activated yet
                                                 // (if was active at some point and it's not now it will not be on that map)
    QMap<QString, QList<QtResourceSet *>> m_pathToResourceSet;
    QtResourceSet                         *m_currentResourceSet = nullptr;

    QMap<QString, const QByteArray *> m_pathToData;

    QMap<QString, QStringList> m_pathToContents; // qrc path to its contents.
    QMap<QString, QString>     m_fileToQrc; // this map contains the content of active resource set only.
                                            // Activating different resource set changes the contents.

    QFileSystemWatcher *m_fileWatcher = nullptr;
    bool m_fileWatcherEnabled = true;
    QMap<QString, bool> m_fileWatchedMap;
private:
    void registerResourceSet(QtResourceSet *resourceSet);
    void unregisterResourceSet(QtResourceSet *resourceSet);
    void setWatcherEnabled(const QString &path, bool enable);
    void addWatcher(const QString &path);
    void removeWatcher(const QString &path);

    void slotFileChanged(const QString &);

    const QByteArray *createResource(const QString &path, QStringList *contents, int *errorCount, QIODevice &errorDevice) const;
    void deleteResource(const QByteArray *data) const;
};

QtResourceModelPrivate::QtResourceModelPrivate() = default;

// --------------------- QtResourceSet
QtResourceSet::QtResourceSet() :
    d_ptr(new QtResourceSetPrivate)
{
    d_ptr->q_ptr = this;
}

QtResourceSet::QtResourceSet(QtResourceModel *model) :
     d_ptr(new QtResourceSetPrivate(model))
{
    d_ptr->q_ptr = this;
}

QtResourceSet::~QtResourceSet() = default;

QStringList QtResourceSet::activeResourceFilePaths() const
{
    QtResourceSet *that = const_cast<QtResourceSet *>(this);
    return d_ptr->m_resourceModel->d_ptr->m_resourceSetToPaths.value(that);
}

void QtResourceSet::activateResourceFilePaths(const QStringList &paths, int *errorCount, QString *errorMessages)
{
    d_ptr->m_resourceModel->d_ptr->activate(this, paths, errorCount, errorMessages);
}

bool QtResourceSet::isModified(const QString &path) const
{
    return d_ptr->m_resourceModel->isModified(path);
}

void QtResourceSet::setModified(const QString &path)
{
    d_ptr->m_resourceModel->setModified(path);
}

// ------------------- QtResourceModelPrivate
const QByteArray *QtResourceModelPrivate::createResource(const QString &path, QStringList *contents, int *errorCount, QIODevice &errorDevice) const
{
    using ResourceDataFileMap = RCCResourceLibrary::ResourceDataFileMap;
    const QByteArray *rc = nullptr;
    *errorCount = -1;
    contents->clear();
    do {
        // run RCC
        RCCResourceLibrary library(3);
        library.setVerbose(true);
        library.setInputFiles(QStringList(path));
        library.setFormat(RCCResourceLibrary::Binary);

        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        if (!library.readFiles(/* ignore errors*/ true, errorDevice))
            break;
        // return code cannot be fully trusted, might still be empty
        const ResourceDataFileMap resMap = library.resourceDataFileMap();
        if (!library.output(buffer, buffer /* tempfile, unused */, errorDevice))
            break;

        *errorCount = library.failedResources().size();
        *contents = resMap.keys();

        if (resMap.isEmpty())
            break;

        buffer.close();
        rc = new QByteArray(buffer.data());
    } while (false);

    if (debugResourceModel)
        qDebug() << "createResource" << path << "returns data=" << rc << " hasWarnings=" << *errorCount;
    return rc;
}

void QtResourceModelPrivate::deleteResource(const QByteArray *data) const
{
    if (data) {
        if (debugResourceModel)
            qDebug() << "deleteResource";
        delete data;
    }
}

void QtResourceModelPrivate::registerResourceSet(QtResourceSet *resourceSet)
{
    if (!resourceSet)
        return;

    // unregister old paths (all because the order of registration is important), later it can be optimized a bit
    const QStringList toRegister = resourceSet->activeResourceFilePaths();
    for (const QString &path : toRegister) {
        if (debugResourceModel)
            qDebug() << "registerResourceSet " << path;
        const auto itRcc = m_pathToData.constFind(path);
        if (itRcc != m_pathToData.constEnd()) { // otherwise data was not created yet
            const QByteArray *data = itRcc.value();
            if (data) {
                if (!QResource::registerResource(reinterpret_cast<const uchar *>(data->constData()))) {
                    qWarning() << "** WARNING: Failed to register " << path << " (QResource failure).";
                } else {
                    const QStringList contents = m_pathToContents.value(path);
                    for (const QString &filePath : contents) {
                        if (!m_fileToQrc.contains(filePath)) // the first loaded resource has higher priority in qt resource system
                            m_fileToQrc.insert(filePath, path);
                    }
                }
            }
        }
    }
}

void QtResourceModelPrivate::unregisterResourceSet(QtResourceSet *resourceSet)
{
    if (!resourceSet)
        return;

    // unregister old paths (all because the order of registration is importans), later it can be optimized a bit
    const QStringList toUnregister = resourceSet->activeResourceFilePaths();
    for (const QString &path : toUnregister) {
        if (debugResourceModel)
            qDebug() << "unregisterResourceSet " << path;
        const auto itRcc = m_pathToData.constFind(path);
        if (itRcc != m_pathToData.constEnd()) { // otherwise data was not created yet
            const QByteArray *data = itRcc.value();
            if (data) {
                if (!QResource::unregisterResource(reinterpret_cast<const uchar *>(itRcc.value()->constData())))
                    qWarning() << "** WARNING: Failed to unregister " << path << " (QResource failure).";
            }
        }
    }
    m_fileToQrc.clear();
}

void QtResourceModelPrivate::activate(QtResourceSet *resourceSet, const QStringList &newPaths, int *errorCountPtr, QString *errorMessages)
{
    if (debugResourceModel)
        qDebug() << "activate " << resourceSet;
    if (errorCountPtr)
        *errorCountPtr = 0;
    if (errorMessages)
        errorMessages->clear();

    QBuffer errorStream;
    errorStream.open(QIODevice::WriteOnly);

    int errorCount = 0;
    int generatedCount = 0;
    bool newResourceSetChanged = false;

    if (resourceSet && resourceSet->activeResourceFilePaths() != newPaths && !m_newlyCreated.contains(resourceSet))
        newResourceSetChanged = true;

    auto newPathToData = m_pathToData;

    for (const QString &path : newPaths) {
        if (resourceSet && !m_pathToResourceSet[path].contains(resourceSet))
            m_pathToResourceSet[path].append(resourceSet);
        const auto itMod = m_pathToModified.find(path);
        if (itMod == m_pathToModified.end() || itMod.value()) { // new path or path is already created, but needs to be recreated
            QStringList contents;
            int qrcErrorCount;
            generatedCount++;
            const QByteArray *data = createResource(path, &contents, &qrcErrorCount, errorStream);

            newPathToData.insert(path, data);
            if (qrcErrorCount) // Count single failed files as sort of 1/2 error
                errorCount++;
            addWatcher(path);

            m_pathToModified.insert(path, false);
            m_pathToContents.insert(path, contents);
            newResourceSetChanged = true;
            const auto itReload = m_pathToResourceSet.find(path);
            if (itReload != m_pathToResourceSet.end()) {
                const auto resources = itReload.value();
                for (QtResourceSet *res : resources) {
                    if (res != resourceSet) {
                        m_resourceSetToReload[res] = true;
                    }
                }
            }
        } else { // path is already created, don't need to recreate
        }
    }

    const auto oldData = m_pathToData.values();
    const auto newData = newPathToData.values();

    QList<const QByteArray *> toDelete;
    for (const QByteArray *array : oldData) {
        if (array && !newData.contains(array))
            toDelete.append(array);
    }

    // Nothing can fail below here?
    if (generatedCount) {
        if (errorCountPtr)
            *errorCountPtr = errorCount;
        errorStream.close();
        const QString stderrOutput = QString::fromUtf8(errorStream.data());
        if (debugResourceModel)
            qDebug() << "Output: (" << errorCount << ")\n" << stderrOutput;
        if (errorMessages)
            *errorMessages = stderrOutput;
    }
    // register
    const auto itReload = m_resourceSetToReload.find(resourceSet);
    if (itReload != m_resourceSetToReload.end()) {
        if (itReload.value()) {
            newResourceSetChanged = true;
            m_resourceSetToReload.insert(resourceSet, false);
        }
    }

    QStringList oldActivePaths;
    if (m_currentResourceSet)
        oldActivePaths = m_currentResourceSet->activeResourceFilePaths();

    const bool needReregister = (oldActivePaths != newPaths) || newResourceSetChanged;

    const auto itNew = m_newlyCreated.find(resourceSet);
    if (itNew != m_newlyCreated.end()) {
        m_newlyCreated.remove(resourceSet);
        if (needReregister)
            newResourceSetChanged = true;
    }

    if (!newResourceSetChanged && !needReregister && (m_currentResourceSet == resourceSet)) {
        for (const QByteArray *data : std::as_const(toDelete))
            deleteResource(data);

        return; // nothing changed
    }

    if (needReregister)
        unregisterResourceSet(m_currentResourceSet);

    for (const QByteArray *data : std::as_const(toDelete))
        deleteResource(data);

    m_pathToData = newPathToData;
    m_currentResourceSet = resourceSet;

    if (resourceSet)
        removeOldPaths(resourceSet, newPaths);

    if (needReregister)
        registerResourceSet(m_currentResourceSet);

    emit q_ptr->resourceSetActivated(m_currentResourceSet, newResourceSetChanged);

    // deactivates the paths from old current resource set
    // add new paths to the new current resource set
    // reloads all paths which are marked as modified from the current resource set;
    // activates the paths from current resource set
    // emits resourceSetActivated() (don't emit only in case when old resource set is the same as new one
    // AND no path was reloaded AND the list of paths is exactly the same)
}

void QtResourceModelPrivate::removeOldPaths(QtResourceSet *resourceSet, const QStringList &newPaths)
{
    const QStringList oldPaths = m_resourceSetToPaths.value(resourceSet);
    if (oldPaths != newPaths) {
        // remove old
        for (const QString &oldPath : oldPaths) {
            if (!newPaths.contains(oldPath)) {
                const auto itRemove = m_pathToResourceSet.find(oldPath);
                if (itRemove != m_pathToResourceSet.end()) {
                    const int idx = itRemove.value().indexOf(resourceSet);
                    if (idx >= 0)
                        itRemove.value().removeAt(idx);
                    if (itRemove.value().isEmpty()) {
                        const auto it = m_pathToData.find(oldPath);
                        if (it != m_pathToData.end())
                            deleteResource(it.value());
                        m_pathToResourceSet.erase(itRemove);
                        m_pathToModified.remove(oldPath);
                        m_pathToContents.remove(oldPath);
                        m_pathToData.remove(oldPath);
                        removeWatcher(oldPath);
                    }
                }
            }
        }
        m_resourceSetToPaths[resourceSet] = newPaths;
    }
}

void QtResourceModelPrivate::setWatcherEnabled(const QString &path, bool enable)
{
    if (!enable) {
        m_fileWatcher->removePath(path);
        return;
    }

    QFileInfo fi(path);
    if (fi.exists())
        m_fileWatcher->addPath(path);
}

void QtResourceModelPrivate::addWatcher(const QString &path)
{
    const auto it = m_fileWatchedMap.constFind(path);
    if (it != m_fileWatchedMap.constEnd() && !it.value())
        return;

    m_fileWatchedMap.insert(path, true);
    if (!m_fileWatcherEnabled)
        return;
    setWatcherEnabled(path, true);
}

void QtResourceModelPrivate::removeWatcher(const QString &path)
{
    if (!m_fileWatchedMap.contains(path))
        return;

    m_fileWatchedMap.remove(path);
    if (!m_fileWatcherEnabled)
        return;
    setWatcherEnabled(path, false);
}

void QtResourceModelPrivate::slotFileChanged(const QString &path)
{
    setWatcherEnabled(path, false);
    emit q_ptr->qrcFileModifiedExternally(path);
    setWatcherEnabled(path, true); //readd
}

// ----------------------- QtResourceModel
QtResourceModel::QtResourceModel(QObject *parent) :
    QObject(parent),
    d_ptr(new QtResourceModelPrivate)
{
    d_ptr->q_ptr = this;

    d_ptr->m_fileWatcher = new QFileSystemWatcher(this);
    connect(d_ptr->m_fileWatcher, &QFileSystemWatcher::fileChanged,
            this, [this](const QString &fileName) { d_ptr->slotFileChanged(fileName); });
}

QtResourceModel::~QtResourceModel()
{
    blockSignals(true);
    const auto resourceList = resourceSets();
    for (QtResourceSet *rs : resourceList)
        removeResourceSet(rs);
    blockSignals(false);
}

QStringList QtResourceModel::loadedQrcFiles() const
{
    return d_ptr->m_pathToModified.keys();
}

bool QtResourceModel::isModified(const QString &path) const
{
    return d_ptr->m_pathToModified.value(path, true);
}

void QtResourceModel::setModified(const QString &path)
{
    if (!d_ptr->m_pathToModified.contains(path))
        return;

    d_ptr->m_pathToModified[path] = true;
    const auto it = d_ptr->m_pathToResourceSet.constFind(path);
    if (it == d_ptr->m_pathToResourceSet.constEnd())
        return;

    const auto resourceList = it.value();
    for (QtResourceSet *rs : resourceList)
        d_ptr->m_resourceSetToReload.insert(rs, true);
}

QList<QtResourceSet *> QtResourceModel::resourceSets() const
{
    return d_ptr->m_resourceSetToPaths.keys();
}

QtResourceSet *QtResourceModel::currentResourceSet() const
{
    return d_ptr->m_currentResourceSet;
}

void QtResourceModel::setCurrentResourceSet(QtResourceSet *resourceSet, int *errorCount, QString *errorMessages)
{
    d_ptr->activate(resourceSet, d_ptr->m_resourceSetToPaths.value(resourceSet), errorCount, errorMessages);
}

QtResourceSet *QtResourceModel::addResourceSet(const QStringList &paths)
{
    QtResourceSet *newResource = new QtResourceSet(this);
    d_ptr->m_resourceSetToPaths.insert(newResource, paths);
    d_ptr->m_resourceSetToReload.insert(newResource, false);
    d_ptr->m_newlyCreated.insert(newResource, true);
    for (const QString &path : paths)
        d_ptr->m_pathToResourceSet[path].append(newResource);
    return newResource;
}

// TODO
void QtResourceModel::removeResourceSet(QtResourceSet *resourceSet)
{
    if (!resourceSet)
        return;
    if (currentResourceSet() == resourceSet)
        setCurrentResourceSet(nullptr);

    // remove rcc files for those paths which are not used in any other resource set
    d_ptr->removeOldPaths(resourceSet, QStringList());

    d_ptr->m_resourceSetToPaths.remove(resourceSet);
    d_ptr->m_resourceSetToReload.remove(resourceSet);
    d_ptr->m_newlyCreated.remove(resourceSet);
    delete resourceSet;
}

void QtResourceModel::reload(const QString &path, int *errorCount, QString *errorMessages)
{
    setModified(path);

    d_ptr->activate(d_ptr->m_currentResourceSet, d_ptr->m_resourceSetToPaths.value(d_ptr->m_currentResourceSet), errorCount, errorMessages);
}

void QtResourceModel::reload(int *errorCount, QString *errorMessages)
{
    for (auto it = d_ptr->m_pathToModified.begin(), end = d_ptr->m_pathToModified.end(); it != end; ++it)
        it.value() = true;

    // empty resourceSets could be omitted here
    for (auto itReload = d_ptr->m_resourceSetToReload.begin(), end = d_ptr->m_resourceSetToReload.end(); itReload != end; ++itReload)
        itReload.value() = true;

    d_ptr->activate(d_ptr->m_currentResourceSet, d_ptr->m_resourceSetToPaths.value(d_ptr->m_currentResourceSet), errorCount, errorMessages);
}

QMap<QString, QString> QtResourceModel::contents() const
{
    return d_ptr->m_fileToQrc;
}

QString QtResourceModel::qrcPath(const QString &file) const
{
    return d_ptr->m_fileToQrc.value(file);
}

void QtResourceModel::setWatcherEnabled(bool enable)
{
    if (d_ptr->m_fileWatcherEnabled == enable)
        return;

    d_ptr->m_fileWatcherEnabled = enable;

    if (!d_ptr->m_fileWatchedMap.isEmpty())
        d_ptr->setWatcherEnabled(d_ptr->m_fileWatchedMap.firstKey(), d_ptr->m_fileWatcherEnabled);
}

bool QtResourceModel::isWatcherEnabled() const
{
    return d_ptr->m_fileWatcherEnabled;
}

void QtResourceModel::setWatcherEnabled(const QString &path, bool enable)
{
    const auto it = d_ptr->m_fileWatchedMap.find(path);
    if (it == d_ptr->m_fileWatchedMap.end())
        return;

    if (it.value() == enable)
        return;

    it.value() = enable;

    if (!d_ptr->m_fileWatcherEnabled)
        return;

    d_ptr->setWatcherEnabled(it.key(), enable);
}

bool QtResourceModel::isWatcherEnabled(const QString &path)
{
    return d_ptr->m_fileWatchedMap.value(path, false);
}

QT_END_NAMESPACE

#include "moc_qtresourcemodel_p.cpp"