aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp
blob: 9375d43fd4f67eb7faf95a029987afae0ff85488 (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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "contentlibrarywidget.h"

#include "contentlibraryeffect.h"
#include "contentlibraryeffectsmodel.h"
#include "contentlibrarymaterial.h"
#include "contentlibrarymaterialsmodel.h"
#include "contentlibrarytexture.h"
#include "contentlibrarytexturesmodel.h"
#include "contentlibraryiconprovider.h"
#include "contentlibraryusermodel.h"

#include "utils/filedownloader.h"
#include "utils/fileextractor.h"
#include "utils/multifiledownloader.h"

#include <coreplugin/icore.h>
#include <designerpaths.h>
#include <qmldesignerconstants.h>
#include <qmldesignerplugin.h>

#include <studioquickwidget.h>
#include <theme.h>

#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>

#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMimeData>
#include <QMouseEvent>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQuickItem>
#include <QQuickWidget>
#include <QRegularExpression>
#include <QShortcut>
#include <QStandardPaths>
#include <QVBoxLayout>

namespace QmlDesigner {

constexpr int TextureBundleMetadataVersion = 1;

static QString propertyEditorResourcesPath()
{
#ifdef SHARE_QML_PATH
    if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE"))
        return QLatin1String(SHARE_QML_PATH) + "/propertyEditorQmlSources";
#endif
    return Core::ICore::resourcePath("qmldesigner/propertyEditorQmlSources").toString();
}

bool ContentLibraryWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::FocusOut) {
        if (obj == m_quickWidget->quickWidget())
            QMetaObject::invokeMethod(m_quickWidget->rootObject(), "closeContextMenu");
    } else if (event->type() == QMouseEvent::MouseMove) {
        DesignDocument *document = QmlDesignerPlugin::instance()->currentDesignDocument();
        QTC_ASSERT(document, return false);
        Model *model = document->currentModel();
        QTC_ASSERT(model, return false);

        if (m_effectToDrag) {
            QMouseEvent *me = static_cast<QMouseEvent *>(event);
            if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 20) {
                QByteArray data;
                QMimeData *mimeData = new QMimeData;
                QDataStream stream(&data, QIODevice::WriteOnly);
                stream << m_effectToDrag->type();
                mimeData->setData(Constants::MIME_TYPE_BUNDLE_EFFECT, data);

                emit bundleEffectDragStarted(m_effectToDrag);
                model->startDrag(mimeData, m_effectToDrag->icon().toLocalFile());
                m_effectToDrag = nullptr;
            }
        } else if (m_materialToDrag) {
            QMouseEvent *me = static_cast<QMouseEvent *>(event);
            if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20
                && m_materialToDrag->isDownloaded()) {
                QByteArray data;
                QMimeData *mimeData = new QMimeData;
                QDataStream stream(&data, QIODevice::WriteOnly);
                stream << m_materialToDrag->type();
                mimeData->setData(Constants::MIME_TYPE_BUNDLE_MATERIAL, data);
                mimeData->removeFormat("text/plain");

                emit bundleMaterialDragStarted(m_materialToDrag);
                model->startDrag(mimeData, m_materialToDrag->icon().toLocalFile());
                m_materialToDrag = nullptr;
            }
        } else if (m_textureToDrag) {
            QMouseEvent *me = static_cast<QMouseEvent *>(event);
            if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20
                && m_textureToDrag->isDownloaded()) {
                QMimeData *mimeData = new QMimeData;
                mimeData->setData(Constants::MIME_TYPE_BUNDLE_TEXTURE,
                                  {m_textureToDrag->texturePath().toUtf8()});

                // Allows standard file drag-n-drop. As of now needed to drop on Assets view
                mimeData->setUrls({QUrl::fromLocalFile(m_textureToDrag->texturePath())});

                emit bundleTextureDragStarted(m_textureToDrag);
                model->startDrag(mimeData, m_textureToDrag->icon().toLocalFile());
                m_textureToDrag = nullptr;
            }
        }
    } else if (event->type() == QMouseEvent::MouseButtonRelease) {
        m_effectToDrag = nullptr;
        m_materialToDrag = nullptr;
        m_textureToDrag = nullptr;
        setIsDragging(false);
    }

    return QObject::eventFilter(obj, event);
}

ContentLibraryWidget::ContentLibraryWidget()
    : m_quickWidget(new StudioQuickWidget(this))
    , m_materialsModel(new ContentLibraryMaterialsModel(this))
    , m_texturesModel(new ContentLibraryTexturesModel("Textures", this))
    , m_environmentsModel(new ContentLibraryTexturesModel("Environments", this))
    , m_effectsModel(new ContentLibraryEffectsModel(this))
    , m_userModel(new ContentLibraryUserModel(this))
{
    qmlRegisterType<QmlDesigner::FileDownloader>("WebFetcher", 1, 0, "FileDownloader");
    qmlRegisterType<QmlDesigner::FileExtractor>("WebFetcher", 1, 0, "FileExtractor");

    setWindowTitle(tr("Content Library", "Title of content library widget"));
    setMinimumWidth(120);

    m_quickWidget->quickWidget()->setObjectName(Constants::OBJECT_NAME_CONTENT_LIBRARY);
    m_quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
    m_quickWidget->engine()->addImageProvider(QStringLiteral("contentlibrary"),
                                              new Internal::ContentLibraryIconProvider);
    m_quickWidget->engine()->addImportPath(propertyEditorResourcesPath() + "/imports");
    m_quickWidget->setClearColor(Theme::getColor(Theme::Color::DSpanelBackground));

    m_textureBundleUrl = QmlDesignerPlugin::settings()
                    .value(DesignerSettingsKey::DOWNLOADABLE_BUNDLES_URL).toString() + "/textures";

    m_bundlePath = Paths::bundlesPathSetting();

    loadTextureBundles();

    Theme::setupTheme(m_quickWidget->engine());
    m_quickWidget->quickWidget()->installEventFilter(this);

    auto layout = new QVBoxLayout(this);
    layout->setContentsMargins({});
    layout->setSpacing(0);
    layout->addWidget(m_quickWidget.data());

    updateSearch();

    setStyleSheet(Theme::replaceCssColors(
        QString::fromUtf8(Utils::FileReader::fetchQrc(":/qmldesigner/stylesheet.css"))));

    m_qmlSourceUpdateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_F11), this);
    connect(m_qmlSourceUpdateShortcut, &QShortcut::activated, this, &ContentLibraryWidget::reloadQmlSource);

    QmlDesignerPlugin::trackWidgetFocusTime(this, Constants::EVENT_CONTENTLIBRARY_TIME);

    auto map = m_quickWidget->registerPropertyMap("ContentLibraryBackend");

    map->setProperties({{"rootView",          QVariant::fromValue(this)},
                        {"materialsModel",    QVariant::fromValue(m_materialsModel.data())},
                        {"texturesModel",     QVariant::fromValue(m_texturesModel.data())},
                        {"environmentsModel", QVariant::fromValue(m_environmentsModel.data())},
                        {"effectsModel",      QVariant::fromValue(m_effectsModel.data())},
                        {"userModel",         QVariant::fromValue(m_userModel.data())}});

    reloadQmlSource();
}

QVariantMap ContentLibraryWidget::readTextureBundleJson()
{
    QVariantMap jsonData;
    QFile jsonFile(m_bundlePath + "/texture_bundle.json");
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
        jsonData = QJsonDocument::fromJson(jsonFile.readAll()).toVariant().toMap();

    int version = jsonData["version"].toInt();
    if (version > TextureBundleMetadataVersion) {
        qWarning() << "Unrecognized texture metadata file version: " << version;
        return {};
    }

    return jsonData;
}

void ContentLibraryWidget::loadTextureBundles()
{
    QDir bundleDir{m_bundlePath};

    if (fetchTextureBundleJson(bundleDir) && fetchTextureBundleIcons(bundleDir))
        populateTextureBundleModels();
}

std::tuple<QVariantMap, QVariantMap, QVariantMap> ContentLibraryWidget::compareTextureMetaFiles(
    const QString &existingMetaFilePath, const QString downloadedMetaFilePath)
{
    QVariantMap existingMeta;
    QFile existingFile(existingMetaFilePath);
    if (existingFile.open(QIODeviceBase::ReadOnly | QIODeviceBase::Text))
        existingMeta = QJsonDocument::fromJson(existingFile.readAll()).toVariant().toMap();

    QVariantMap downloadedMeta;
    QFile downloadedFile(downloadedMetaFilePath);
    if (downloadedFile.open(QIODeviceBase::ReadOnly | QIODeviceBase::Text))
        downloadedMeta = QJsonDocument::fromJson(downloadedFile.readAll()).toVariant().toMap();

    int existingVersion = existingMeta["version"].toInt();
    int downloadedVersion = downloadedMeta["version"].toInt();

    if (existingVersion != downloadedVersion) {
        qWarning() << "We're not comparing local vs downloaded textures metadata because they are "
                      "of different versions";
        return {};
    }

    QVariantMap existingItems = existingMeta["image_items"].toMap();
    QVariantMap downloadedItems = downloadedMeta["image_items"].toMap();

    QStringList existingKeys = existingItems.keys();
    QStringList downloadedKeys = downloadedItems.keys();

    QSet<QString> existing(existingKeys.cbegin(), existingKeys.cend());
    QSet<QString> downloaded(downloadedKeys.cbegin(), downloadedKeys.cend());

    const QSet<QString> newFiles = downloaded - existing;
    const QSet<QString> commonFiles = downloaded & existing;

    QVariantMap modifiedFileEntries;

    for (const QString &file: commonFiles) {
        QString existingCsum = existingItems[file].toMap()["checksum"].toString();
        QString downloadedCsum = downloadedItems[file].toMap()["checksum"].toString();

        if (existingCsum != downloadedCsum)
            modifiedFileEntries[file] = downloadedItems[file];
    }

    QVariantMap newFileEntries;
    for (const QString &path: newFiles)
        newFileEntries[path] = downloadedItems[path];

    return std::make_tuple(existingItems, newFileEntries, modifiedFileEntries);
}

void ContentLibraryWidget::fetchNewTextureIcons(const QVariantMap &existingFiles,
                                                const QVariantMap &newFiles,
                                                const QString &existingMetaFilePath,
                                                const QDir &bundleDir)
{
    QStringList fileList = Utils::transform<QList>(newFiles.keys(), [](const QString &file) -> QString {
        return file + ".png";
    });

    auto multidownloader = new MultiFileDownloader(this);
    multidownloader->setBaseUrl(QString(m_textureBundleUrl + "/icons"));
    multidownloader->setFiles(fileList);
    multidownloader->setTargetDirPath(m_bundlePath + "/TextureBundleIcons");

    auto downloader = new FileDownloader(this);
    downloader->setDownloadEnabled(true);
    downloader->setProbeUrl(false);

    downloader->setUrl(multidownloader->nextUrl());
    downloader->setTargetFilePath(multidownloader->nextTargetPath());

    QObject::connect(multidownloader, &MultiFileDownloader::nextUrlChanged, downloader, [=]() {
        downloader->setUrl(multidownloader->nextUrl());
    });

    QObject::connect(multidownloader, &MultiFileDownloader::nextTargetPathChanged, downloader, [=]() {
        downloader->setTargetFilePath(multidownloader->nextTargetPath());
    });

    multidownloader->setDownloader(downloader);

    QVariantMap files = existingFiles;
    files.insert(newFiles);

    QObject::connect(multidownloader, &MultiFileDownloader::finishedChanged, this,
                     [multidownloader, files, existingMetaFilePath, this, bundleDir]() {
        multidownloader->deleteLater();

        QVariantMap newMap;
        newMap["version"] = TextureBundleMetadataVersion;
        newMap["image_items"] = files;

        QJsonObject jobj = QJsonObject::fromVariantMap(newMap);
        QJsonDocument doc(jobj);
        QByteArray data = doc.toJson();

        QFile existingFile(existingMetaFilePath);
        if (existingFile.open(QIODeviceBase::WriteOnly | QIODeviceBase::Text)) {
            existingFile.write(data);
            existingFile.flush();
        }

        if (fetchTextureBundleIcons(bundleDir))
            populateTextureBundleModels();
    });

    multidownloader->start();
}

QStringList ContentLibraryWidget::saveNewTextures(const QDir &bundleDir, const QStringList &newFiles)
{
    int newFileExpirationDays = QmlDesignerPlugin::settings()
                                    .value(DesignerSettingsKey::CONTENT_LIBRARY_NEW_FLAG_EXPIRATION_DAYS)
                                    .toInt();

    int newFileExpirationSecs = newFileExpirationDays * 24 * 3600;

    QString newFilesPath = bundleDir.filePath(".new_textures_on_server.json");

    QFile jsonFile(newFilesPath);
    if (jsonFile.exists()) {
        jsonFile.open(QFile::ReadOnly | QFile::Text);

        qint64 now = QDateTime::currentSecsSinceEpoch();
        QByteArray existingData = jsonFile.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(existingData);
        jsonFile.close();

        QJsonObject mainObj = doc.object();
        if (mainObj.value("version").toInt() > TextureBundleMetadataVersion) {
            qDebug() << "Existing version of cached 'New Items' does not have a known version.";

            // TODO: do simple save new file
            return newFiles;
        }

        QJsonValue jsonValue = mainObj.value("image_items");
        QJsonArray imageItems = jsonValue.toArray();

        // remove those files that are older than N days (configurable via QSettings)
        imageItems = Utils::filtered(imageItems, [newFileExpirationSecs, now](const QJsonValue &v) {
            qint64 time = v["time"].toInt();
            if (now - time >= newFileExpirationSecs)
                return false;

            return true;
        });

        QStringList pruned = Utils::transform<QStringList>(imageItems, [](const QJsonValue &value) -> QString {
            return value.toObject()["file"].toString();
        });

        // filter out files from newFiles that already exist in the document

        QStringList newFilesNow = Utils::filtered(newFiles, [&imageItems](const QString &file) {
            bool contains = Utils::anyOf(imageItems, [file](const QJsonValue &v) {
                if (!v.isObject())
                    return false;

                QJsonObject o = v.toObject();
                if (!o.contains("file"))
                    return false;

                bool hasFile = (o["file"] == file);
                return hasFile;

                return false;
            });
            return !contains;
        });

        // add the filtered out files to the doc.
        for (const QString &file: newFilesNow) {
            QJsonObject obj({{"file", file}, {"time", now}});
            imageItems.push_back(obj);
        }

        mainObj["image_items"] = imageItems;

        // save the json file.
        doc.setObject(mainObj);
        QByteArray data = doc.toJson();

        jsonFile.open(QFile::WriteOnly | QFile::Text);
        jsonFile.write(data);
        jsonFile.close();

        return newFilesNow + pruned;
    } else {
        qint64 now = QDateTime::currentSecsSinceEpoch();

        QJsonArray texturesFoundNow = Utils::transform<QJsonArray>(newFiles, [now](const QString &file) {
            QJsonObject obj({{"file", file}, {"time", now}});
            return QJsonValue(obj);
        });

        QVariantMap varMap;
        varMap["version"] = TextureBundleMetadataVersion;
        varMap["image_items"] = texturesFoundNow;

        QJsonObject mainObj({{"version", TextureBundleMetadataVersion},
                             {"image_items", texturesFoundNow}});

        QJsonDocument doc(mainObj);
        QByteArray data = doc.toJson();

        jsonFile.open(QFile::WriteOnly | QFile::Text);
        jsonFile.write(data);
        jsonFile.close();

        return newFiles;
    }
}

bool ContentLibraryWidget::fetchTextureBundleJson(const QDir &bundleDir)
{
    QString filePath = bundleDir.filePath("texture_bundle.json");

    QFileInfo fi(filePath);
    bool jsonFileExists = fi.exists() && fi.size() > 0;

    QString bundleZipUrl = m_textureBundleUrl + "/texture_bundle.zip";
    FileDownloader *downloader = new FileDownloader(this);
    downloader->setUrl(bundleZipUrl);
    downloader->setProbeUrl(false);
    downloader->setDownloadEnabled(true);
    downloader->start();

    QObject::connect(downloader, &FileDownloader::downloadFailed, this,
                     [this, jsonFileExists, bundleDir] {
        if (jsonFileExists) {
            if (fetchTextureBundleIcons(bundleDir))
                populateTextureBundleModels();
        }
    });

    QObject::connect(downloader, &FileDownloader::finishedChanged, this,
                     [this, downloader, bundleDir, jsonFileExists, filePath] {
        FileExtractor *extractor = new FileExtractor(this);
        extractor->setArchiveName(downloader->completeBaseName());
        extractor->setSourceFile(downloader->outputFile());
        if (!jsonFileExists)
            extractor->setTargetPath(bundleDir.absolutePath());

        extractor->setAlwaysCreateDir(false);
        extractor->setClearTargetPathContents(false);

        QObject::connect(extractor, &FileExtractor::finishedChanged, this,
                         [this, downloader, bundleDir, extractor, jsonFileExists, filePath] {
            downloader->deleteLater();
            extractor->deleteLater();

            if (jsonFileExists) {
                QVariantMap newFiles, existing;
                QVariantMap modifiedFilesEntries;

                std::tie(existing, newFiles, modifiedFilesEntries) =
                    compareTextureMetaFiles(filePath, extractor->targetPath() + "/texture_bundle.json");

                const QStringList newFilesKeys = newFiles.keys();
                const QStringList actualNewFiles = saveNewTextures(bundleDir, newFilesKeys);

                m_texturesModel->setModifiedFileEntries(modifiedFilesEntries);
                m_texturesModel->setNewFileEntries(actualNewFiles);

                m_environmentsModel->setModifiedFileEntries(modifiedFilesEntries);
                m_environmentsModel->setNewFileEntries(actualNewFiles);

                if (newFiles.count() > 0) {
                    fetchNewTextureIcons(existing, newFiles, filePath, bundleDir);
                    return;
                }
            }

            if (fetchTextureBundleIcons(bundleDir))
                populateTextureBundleModels();
        });

        extractor->extract();
    });

    return false;
}

void ContentLibraryWidget::populateTextureBundleModels()
{
    QVariantMap jsonData = readTextureBundleJson();

    QString bundleIconPath = m_bundlePath + "/TextureBundleIcons";

    m_texturesModel->loadTextureBundle(m_textureBundleUrl, bundleIconPath, jsonData);
    m_environmentsModel->loadTextureBundle(m_textureBundleUrl, bundleIconPath, jsonData);
}

bool ContentLibraryWidget::fetchTextureBundleIcons(const QDir &bundleDir)
{
    QString iconsPath = bundleDir.filePath("TextureBundleIcons");

    QDir iconsDir(iconsPath);
    if (iconsDir.exists() && !iconsDir.isEmpty())
        return true;

    QString zipFileUrl = m_textureBundleUrl + "/icons.zip";

    FileDownloader *downloader = new FileDownloader(this);
    downloader->setUrl(zipFileUrl);
    downloader->setProbeUrl(false);
    downloader->setDownloadEnabled(true);

    QObject::connect(downloader, &FileDownloader::finishedChanged, this,
                     [this, downloader, bundleDir] {
        FileExtractor *extractor = new FileExtractor(this);
        extractor->setArchiveName(downloader->completeBaseName());
        extractor->setSourceFile(downloader->outputFile());
        extractor->setTargetPath(bundleDir.absolutePath());
        extractor->setAlwaysCreateDir(false);
        extractor->setClearTargetPathContents(false);

        QObject::connect(extractor, &FileExtractor::finishedChanged, this,
                         [this, downloader, extractor] {
            downloader->deleteLater();
            extractor->deleteLater();
            populateTextureBundleModels();
        });

        extractor->extract();
    });

    downloader->start();
    return false;
}

void ContentLibraryWidget::markTextureUpdated(const QString &textureKey)
{
    static QRegularExpression re("([^/]+)/([^/]+)/.*");
    QString category = re.match(textureKey).captured(1);
    QString subcategory = re.match(textureKey).captured(2);

    QString checksumOnServer;
    if (category == "Textures")
        checksumOnServer = m_texturesModel->removeModifiedFileEntry(textureKey);
    else if (category == "Environments")
        checksumOnServer = m_environmentsModel->removeModifiedFileEntry(textureKey);

    QJsonObject metaDataObj;
    QFile jsonFile(m_bundlePath + "/texture_bundle.json");
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        metaDataObj = QJsonDocument::fromJson(jsonFile.readAll()).object();
        jsonFile.close();
    }

    QJsonObject imageItems = metaDataObj["image_items"].toObject();

    QJsonObject oldImageItem = imageItems[textureKey].toObject();
    oldImageItem["checksum"] = checksumOnServer;
    imageItems[textureKey] = oldImageItem;

    metaDataObj["image_items"] = imageItems;

    QJsonDocument outDoc(metaDataObj);
    QByteArray data = outDoc.toJson();

    QFile outFile(m_bundlePath + "/texture_bundle.json");
    if (outFile.open(QIODeviceBase::WriteOnly | QIODeviceBase::Text)) {
        outFile.write(data);
        outFile.flush();
    }

    if (category == "Textures")
        m_texturesModel->markTextureHasNoUpdates(subcategory, textureKey);
    else if (category == "Environments")
        m_environmentsModel->markTextureHasNoUpdates(subcategory, textureKey);
}

bool ContentLibraryWidget::userBundleEnabled() const
{
    // TODO: this method is to be removed after user bundle implementation is complete
    return Core::ICore::settings()->value("QML/Designer/UseExperimentalFeatures45", false).toBool();
}

QSize ContentLibraryWidget::sizeHint() const
{
    return {420, 420};
}

QList<QToolButton *> ContentLibraryWidget::createToolBarWidgets()
{
    return {};
}

void ContentLibraryWidget::handleSearchFilterChanged(const QString &filterText)
{
    if (filterText != m_filterText) {
        m_filterText = filterText;
        updateSearch();
    }
}

QString ContentLibraryWidget::qmlSourcesPath()
{
#ifdef SHARE_QML_PATH
    if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE"))
        return QLatin1String(SHARE_QML_PATH) + "/contentLibraryQmlSource";
#endif
    return Core::ICore::resourcePath("qmldesigner/contentLibraryQmlSource").toString();
}

void ContentLibraryWidget::clearSearchFilter()
{
    QMetaObject::invokeMethod(m_quickWidget->rootObject(), "clearSearchFilter");
}

bool ContentLibraryWidget::hasQuick3DImport() const
{
    return m_hasQuick3DImport;
}

void ContentLibraryWidget::setHasQuick3DImport(bool b)
{
    if (b == m_hasQuick3DImport)
        return;

    const bool oldRequired = m_materialsModel->hasRequiredQuick3DImport();
    m_hasQuick3DImport = b;
    const bool newRequired = m_materialsModel->hasRequiredQuick3DImport();

    if (oldRequired != newRequired)
        emit m_materialsModel->hasRequiredQuick3DImportChanged();

    emit hasQuick3DImportChanged();

    m_materialsModel->updateIsEmpty();
    m_effectsModel->updateIsEmpty();
}

bool ContentLibraryWidget::hasMaterialLibrary() const
{
    return m_hasMaterialLibrary;
}

void ContentLibraryWidget::setHasMaterialLibrary(bool b)
{
    if (m_hasMaterialLibrary == b)
        return;

    m_hasMaterialLibrary = b;
    emit hasMaterialLibraryChanged();

    m_materialsModel->updateIsEmpty();
}

bool ContentLibraryWidget::hasActive3DScene() const
{
    return m_hasActive3DScene;
}

void ContentLibraryWidget::setHasActive3DScene(bool b)
{
    if (m_hasActive3DScene == b)
        return;

    m_hasActive3DScene = b;
    emit hasActive3DSceneChanged();
}

bool ContentLibraryWidget::isQt6Project() const
{
    return m_isQt6Project;
}

void ContentLibraryWidget::setIsQt6Project(bool b)
{
    if (m_isQt6Project == b)
        return;

    m_isQt6Project = b;
    emit isQt6ProjectChanged();
}

void ContentLibraryWidget::reloadQmlSource()
{
    const QString materialBrowserQmlPath = qmlSourcesPath() + "/ContentLibrary.qml";

    QTC_ASSERT(QFileInfo::exists(materialBrowserQmlPath), return);

    m_quickWidget->setSource(QUrl::fromLocalFile(materialBrowserQmlPath));
}

void ContentLibraryWidget::updateSearch()
{
    m_materialsModel->setSearchText(m_filterText);
    m_effectsModel->setSearchText(m_filterText);
    m_texturesModel->setSearchText(m_filterText);
    m_environmentsModel->setSearchText(m_filterText);
    m_userModel->setSearchText(m_filterText);
    m_quickWidget->update();
}

void ContentLibraryWidget::setIsDragging(bool val)
{
    if (m_isDragging != val) {
        m_isDragging = val;
        emit isDraggingChanged();
    }
}

QString ContentLibraryWidget::findTextureBundlePath()
{
    QDir texBundleDir;

    if (!qEnvironmentVariable("TEXTURE_BUNDLE_PATH").isEmpty())
        texBundleDir.setPath(qEnvironmentVariable("TEXTURE_BUNDLE_PATH"));
    else if (Utils::HostOsInfo::isMacHost())
        texBundleDir.setPath(QCoreApplication::applicationDirPath() + "/../Resources/texture_bundle");

    // search for matBundleDir from exec dir and up
    if (texBundleDir.dirName() == ".") {
        texBundleDir.setPath(QCoreApplication::applicationDirPath());
        while (!texBundleDir.cd("texture_bundle") && texBundleDir.cdUp())
            ; // do nothing

        if (texBundleDir.dirName() != "texture_bundle") // bundlePathDir not found
            return {};
    }

    return texBundleDir.path();
}

void ContentLibraryWidget::startDragEffect(QmlDesigner::ContentLibraryEffect *eff,
                                           const QPointF &mousePos)
{
    m_effectToDrag = eff;
    m_dragStartPoint = mousePos.toPoint();
    setIsDragging(true);
}

void ContentLibraryWidget::startDragMaterial(QmlDesigner::ContentLibraryMaterial *mat,
                                             const QPointF &mousePos)
{
    m_materialToDrag = mat;
    m_dragStartPoint = mousePos.toPoint();
    setIsDragging(true);
}

void ContentLibraryWidget::startDragTexture(QmlDesigner::ContentLibraryTexture *tex,
                                            const QPointF &mousePos)
{
    m_textureToDrag = tex;
    m_dragStartPoint = mousePos.toPoint();
    setIsDragging(true);
}

void ContentLibraryWidget::addImage(ContentLibraryTexture *tex)
{
    if (!tex->isDownloaded())
        return;

    emit addTextureRequested(tex->texturePath(), AddTextureMode::Image);
}

void ContentLibraryWidget::addTexture(ContentLibraryTexture *tex)
{
    if (!tex->isDownloaded())
        return;

    emit addTextureRequested(tex->texturePath(), AddTextureMode::Texture);
}

void ContentLibraryWidget::addLightProbe(ContentLibraryTexture *tex)
{
    if (!tex->isDownloaded())
        return;

    emit addTextureRequested(tex->texturePath(), AddTextureMode::LightProbe);
}

void ContentLibraryWidget::updateSceneEnvState()
{
    emit updateSceneEnvStateRequested();
}

QPointer<ContentLibraryMaterialsModel> ContentLibraryWidget::materialsModel() const
{
    return m_materialsModel;
}

QPointer<ContentLibraryTexturesModel> ContentLibraryWidget::texturesModel() const
{
    return m_texturesModel;
}

QPointer<ContentLibraryTexturesModel> ContentLibraryWidget::environmentsModel() const
{
    return m_environmentsModel;
}

QPointer<ContentLibraryEffectsModel> ContentLibraryWidget::effectsModel() const
{
    return m_effectsModel;
}

QPointer<ContentLibraryUserModel> ContentLibraryWidget::userModel() const
{
    return m_userModel;
}

} // namespace QmlDesigner