aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/components/collectioneditor/collectionview.cpp
blob: 0c9a2eed94dc0cb6103ce417d2bf29a4b090e829 (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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "collectionview.h"

#include "collectiondatatypemodel.h"
#include "collectiondetailsmodel.h"
#include "collectioneditorconstants.h"
#include "collectioneditorutils.h"
#include "collectionlistmodel.h"
#include "collectionwidget.h"
#include "datastoremodelnode.h"
#include "designmodecontext.h"
#include "nodeabstractproperty.h"
#include "nodemetainfo.h"
#include "nodeproperty.h"
#include "qmldesignerplugin.h"
#include "variantproperty.h"

#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectmanager.h>
#include <qmljs/qmljsmodelmanagerinterface.h>

#include <coreplugin/icore.h>
#include <utils/algorithm.h>
#include <utils/qtcassert.h>

#include <QTimer>

namespace {

bool isStudioCollectionModel(const QmlDesigner::ModelNode &node)
{
    return node.metaInfo().isQtQuickStudioUtilsJsonListModel();
}

inline bool isProjectImport(const QmlDesigner::Import &import)
{
    ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectManager::startupProject();
    return currentProject && import.toString() == currentProject->displayName();
}

inline void setVariantPropertyValue(const QmlDesigner::ModelNode &node,
                                    const QmlDesigner::PropertyName &propertyName,
                                    const QVariant &value)
{
    QmlDesigner::VariantProperty property = node.variantProperty(propertyName);
    property.setValue(value);
}

inline void setBindingPropertyExpression(const QmlDesigner::ModelNode &node,
                                         const QmlDesigner::PropertyName &propertyName,
                                         const QString &expression)
{
    QmlDesigner::BindingProperty property = node.bindingProperty(propertyName);
    property.setExpression(expression);
}

} // namespace

namespace QmlDesigner {

CollectionView::CollectionView(ExternalDependenciesInterface &externalDependencies)
    : AbstractView(externalDependencies)
    , m_dataStore(std::make_unique<DataStoreModelNode>())

{
}

CollectionView::~CollectionView() = default;

bool CollectionView::hasWidget() const
{
    return true;
}

QmlDesigner::WidgetInfo CollectionView::widgetInfo()
{
    if (!m_widget) {
        m_widget = Utils::makeUniqueObjectPtr<CollectionWidget>(this);
        m_widget->setMinimumSize(m_widget->minimumSizeHint());
        connect(ProjectExplorer::ProjectManager::instance(),
                &ProjectExplorer::ProjectManager::startupProjectChanged, m_widget.get(), [&] {
            resetDataStoreNode();
            m_widget->collectionDetailsModel()->removeAllCollections();
        });

        auto collectionEditorContext = new Internal::CollectionEditorContext(m_widget.get());
        Core::ICore::addContextObject(collectionEditorContext);
        CollectionListModel *listModel = m_widget->listModel().data();

        connect(listModel,
                &CollectionListModel::selectedCollectionNameChanged,
                this,
                [this](const QString &collection) {
                    m_widget->collectionDetailsModel()->loadCollection(dataStoreNode(), collection);
                });

        connect(listModel, &CollectionListModel::isEmptyChanged, this, [this](bool isEmpty) {
            if (isEmpty)
                m_widget->collectionDetailsModel()->loadCollection({}, {});
        });

        connect(listModel, &CollectionListModel::modelReset, this, [this] {
            CollectionListModel *listModel = m_widget->listModel().data();
            if (listModel->sourceNode() == dataStoreNode())
                m_dataStore->setCollectionNames(listModel->collections());
        });

        connect(listModel,
                &CollectionListModel::collectionAdded,
                this,
                [this](const QString &collectionName) { m_dataStore->addCollection(collectionName); });

        connect(listModel,
                &CollectionListModel::collectionNameChanged,
                this,
                [this](const QString &oldName, const QString &newName) {
                    m_dataStore->renameCollection(oldName, newName);
                    m_widget->collectionDetailsModel()->renameCollection(dataStoreNode(),
                                                                         oldName,
                                                                         newName);
                });

        connect(listModel,
                &CollectionListModel::collectionsRemoved,
                this,
                [this](const QStringList &collectionNames) {
                    m_dataStore->removeCollections(collectionNames);
                    for (const QString &collectionName : collectionNames) {
                        m_widget->collectionDetailsModel()->removeCollection(dataStoreNode(),
                                                                             collectionName);
                    }
                });
    }

    return createWidgetInfo(m_widget.get(),
                            "CollectionEditor",
                            WidgetInfo::LeftPane,
                            0,
                            tr("Model Editor [beta]"),
                            tr("Model Editor view"));
}

void CollectionView::modelAttached(Model *model)
{
    AbstractView::modelAttached(model);
    m_widget->setProjectImportExists(Utils::anyOf(model->imports(), isProjectImport));
    resetDataStoreNode();
}

void CollectionView::modelAboutToBeDetached([[maybe_unused]] Model *model)
{
    unloadDataStore();
    m_widget->setProjectImportExists(false);
}

void CollectionView::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
                                          [[maybe_unused]] const QList<ModelNode> &lastSelectedNodeList)
{
    if (!m_widget)
        return;

    QList<ModelNode> selectedCollectionNodes = Utils::filtered(selectedNodeList,
                                                               &isStudioCollectionModel);

    bool singleNonCollectionNodeSelected = selectedNodeList.size() == 1
                                           && selectedCollectionNodes.isEmpty();

    bool singleSelectedHasModelProperty = false;
    if (singleNonCollectionNodeSelected) {
        const ModelNode selectedNode = selectedNodeList.first();
        singleSelectedHasModelProperty = CollectionEditorUtils::canAcceptCollectionAsModel(
            selectedNode);
    }

    m_widget->setTargetNodeSelected(singleSelectedHasModelProperty);
}

void CollectionView::importsChanged(const Imports &addedImports, const Imports &removedImports)
{
    if (Utils::anyOf(addedImports, isProjectImport)) {
        m_widget->setProjectImportExists(true);
        resetDataStoreNode();
    } else if (Utils::anyOf(removedImports, isProjectImport)) {
        m_widget->setProjectImportExists(false);
        unloadDataStore();
    }
}

void CollectionView::customNotification(const AbstractView *,
                                        const QString &identifier,
                                        const QList<ModelNode> &nodeList,
                                        const QList<QVariant> &data)
{
    if (!m_widget)
        return;

    if (identifier == QLatin1String("item_library_created_by_drop") && !nodeList.isEmpty())
        onItemLibraryNodeCreated(nodeList.first());
    else if (identifier == QLatin1String("open_collection_by_id") && !data.isEmpty())
        m_widget->openCollection(collectionNameFromDataStoreChildren(data.first().toByteArray()));
    else if (identifier == "delete_selected_collection")
        m_widget->deleteSelectedCollection();
}

void CollectionView::addResource(const QUrl &url, const QString &name)
{
    executeInTransaction(Q_FUNC_INFO, [this, &url, &name]() {
        ensureStudioModelImport();
        QString sourceAddress;
        if (url.isLocalFile()) {
            Utils::FilePath fp = QmlDesignerPlugin::instance()->currentDesignDocument()->fileName().parentDir();
            sourceAddress = Utils::FilePath::calcRelativePath(url.toLocalFile(),
                                                              fp.absoluteFilePath().toString());
        } else {
            sourceAddress = url.toString();
        }
#ifdef QDS_USE_PROJECTSTORAGE
        ModelNode resourceNode = createModelNode("JsonListModel");
#else
        const NodeMetaInfo resourceMetaInfo = jsonCollectionMetaInfo();
        ModelNode resourceNode = createModelNode(resourceMetaInfo.typeName(),
                                                 resourceMetaInfo.majorVersion(),
                                                 resourceMetaInfo.minorVersion());
#endif
        VariantProperty sourceProperty = resourceNode.variantProperty(
            CollectionEditorConstants::SOURCEFILE_PROPERTY);
        VariantProperty nameProperty = resourceNode.variantProperty("objectName");
        sourceProperty.setValue(sourceAddress);
        nameProperty.setValue(name);
        resourceNode.setIdWithoutRefactoring(model()->generateIdFromName(name, "model"));
        rootModelNode().defaultNodeAbstractProperty().reparentHere(resourceNode);
    });
}

void CollectionView::addProjectImport()
{
    if (!m_widget)
        return;

    ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectManager::startupProject();
    if (!currentProject)
        return;

    executeInTransaction(__FUNCTION__, [&] {
        Import import = Import::createLibraryImport(currentProject->displayName());
        if (!model()->hasImport(import, true, true))
            model()->changeImports({import}, {});
    });
}

void CollectionView::assignCollectionToNode(const QString &collectionName, const ModelNode &node)
{
    if (!m_widget)
        return;

    using DataType = CollectionDetails::DataType;
    executeInTransaction("CollectionView::assignCollectionToNode", [&]() {
        m_dataStore->assignCollectionToNode(
            this,
            node,
            collectionName,
            [&](const QString &collectionName, const QString &columnName) -> bool {
                const CollectionReference reference{dataStoreNode(), collectionName};
                return m_widget->collectionDetailsModel()->collectionHasColumn(reference, columnName);
            },
            [&](const QString &collectionName) -> QString {
                const CollectionReference reference{dataStoreNode(), collectionName};
                return m_widget->collectionDetailsModel()->getFirstColumnName(reference);
            });

        // Create and assign a delegate to the list view item
        if (node.metaInfo().isQtQuickListView()) {
            CollectionDetails collection = m_widget->collectionDetailsModel()->upToDateConstCollection(
                {dataStoreNode(), collectionName});

            ModelNode rowItem(createModelNode("QtQuick.Row"));
            ::setVariantPropertyValue(rowItem, "spacing", 5);

            const int columnsCount = collection.columns();
            for (int column = 0; column < columnsCount; ++column) {
                const DataType dataType = collection.typeAt(column);
                const QString columnName = collection.propertyAt(column);
                ModelNode cellItem;
                if (dataType == DataType::Color) {
                    cellItem = createModelNode("QtQuick.Rectangle");
                    ::setBindingPropertyExpression(cellItem, "color", columnName);
                    ::setVariantPropertyValue(cellItem, "height", 20);
                } else {
                    cellItem = createModelNode("QtQuick.Text");
                    ::setBindingPropertyExpression(cellItem, "text", columnName);
                }
                ::setVariantPropertyValue(cellItem, "width", 100);
                rowItem.defaultNodeAbstractProperty().reparentHere(cellItem);
            }

            NodeProperty delegateProperty = node.nodeProperty("delegate");
            // Remove the old model node if is available
            if (delegateProperty.modelNode())
                delegateProperty.modelNode().destroy();

            delegateProperty.setModelNode(rowItem);
        }
    });
}

void CollectionView::assignCollectionToSelectedNode(const QString &collectionName)
{
    QTC_ASSERT(dataStoreNode() && hasSingleSelectedModelNode(), return);
    assignCollectionToNode(collectionName, singleSelectedModelNode());
}

void CollectionView::addNewCollection(const QString &collectionName, const QJsonObject &localCollection)
{
    if (!m_widget)
        return;

    addTask(QSharedPointer<CollectionTask>(
        new AddCollectionTask(this, m_widget->listModel(), localCollection, collectionName)));
}

void CollectionView::openCollection(const QString &collectionName)
{
    if (!m_widget)
        return;

    m_widget->openCollection(collectionName);
}

void CollectionView::registerDeclarativeType()
{
    CollectionDetails::registerDeclarativeType();
    CollectionDataTypeModel::registerDeclarativeType();
}

void CollectionView::resetDataStoreNode()
{
    if (!m_widget)
        return;

    m_dataStore->reloadModel();

    ModelNode dataStore = dataStoreNode();
    m_widget->setDataStoreExists(dataStore.isValid());
    if (!dataStore || m_widget->listModel()->sourceNode() == dataStore)
        return;

    bool dataStoreSingletonFound = m_dataStoreTypeFound;
    if (!dataStoreSingletonFound && rewriterView() && rewriterView()->isAttached()) {
        const QList<QmlTypeData> types = rewriterView()->getQMLTypes();
        for (const QmlTypeData &cppTypeData : types) {
            if (cppTypeData.isSingleton && cppTypeData.typeName == "DataStore") {
                dataStoreSingletonFound = true;
                break;
            }
        }
        if (!dataStoreSingletonFound && !m_rewriterAmended) {
            rewriterView()->forceAmend();
            m_rewriterAmended = true;
        }
    }

    if (dataStoreSingletonFound) {
        m_widget->listModel()->setDataStoreNode(dataStore);
        m_dataStoreTypeFound = true;

        while (!m_delayedTasks.isEmpty())
            m_delayedTasks.takeFirst()->process();
    } else if (++m_reloadCounter < 50) {
        QTimer::singleShot(200, this, &CollectionView::resetDataStoreNode);
    } else {
        QTC_ASSERT(false, m_delayedTasks.clear());
    }
}

ModelNode CollectionView::dataStoreNode() const
{
    return m_dataStore->modelNode();
}

void CollectionView::ensureDataStoreExists()
{
    bool filesJustCreated = false;
    bool filesExist = CollectionEditorUtils::ensureDataStoreExists(filesJustCreated);
    if (filesExist && filesJustCreated) {
        // Force code model reset to notice changes to existing module
        if (auto modelManager = QmlJS::ModelManagerInterface::instance())
            modelManager->resetCodeModel();
        resetDataStoreNode();
    }
}

QString CollectionView::collectionNameFromDataStoreChildren(const PropertyName &childPropertyName) const
{
    return dataStoreNode()
        .nodeProperty(childPropertyName)
        .modelNode()
        .property(CollectionEditorConstants::JSONCHILDMODELNAME_PROPERTY)
        .toVariantProperty()
        .value()
        .toString();
}

NodeMetaInfo CollectionView::jsonCollectionMetaInfo() const
{
    return model()->metaInfo(CollectionEditorConstants::JSONCOLLECTIONMODEL_TYPENAME);
}

void CollectionView::unloadDataStore()
{
    m_reloadCounter = 0;
    m_rewriterAmended = false;
    m_dataStoreTypeFound = false;
    QTC_ASSERT(m_delayedTasks.isEmpty(), m_delayedTasks.clear());
    if (m_widget) {
        m_widget->setDataStoreExists(dataStoreNode().isValid());
        m_widget->listModel()->setDataStoreNode();
    }
}

void CollectionView::ensureStudioModelImport()
{
    executeInTransaction(__FUNCTION__, [&] {
        Import import = Import::createLibraryImport(CollectionEditorConstants::COLLECTIONMODEL_IMPORT);
        try {
            if (!model()->hasImport(import, true, true))
                model()->changeImports({import}, {});
        } catch (const Exception &) {
            QTC_ASSERT(false, return);
        }
    });
}

void CollectionView::onItemLibraryNodeCreated(const ModelNode &node)
{
    if (!m_widget)
        return;

    if (node.metaInfo().isQtQuickListView()) {
        addTask(QSharedPointer<CollectionTask>(
            new DropListViewTask(this, m_widget->listModel(), node)));
    }
}

void CollectionView::addTask(QSharedPointer<CollectionTask> task)
{
    ensureDataStoreExists();
    if (m_dataStoreTypeFound)
        task->process();
    else if (dataStoreNode())
        m_delayedTasks << task;
}

CollectionTask::CollectionTask(CollectionView *view, CollectionListModel *listModel)
    : m_collectionView(view)
    , m_listModel(listModel)
{}

DropListViewTask::DropListViewTask(CollectionView *view,
                                   CollectionListModel *listModel,
                                   const ModelNode &node)
    : CollectionTask(view, listModel)
    , m_node(node)
{}

void DropListViewTask::process()
{
    AbstractView *view = m_node.view();
    if (!m_node || !m_collectionView || !m_listModel || !view)
        return;

    const QString newCollectionName = m_listModel->getUniqueCollectionName("ListModel");
    m_listModel->addCollection(newCollectionName, CollectionEditorUtils::defaultColorCollection());
    m_collectionView->openCollection(newCollectionName);
    m_collectionView->assignCollectionToNode(newCollectionName, m_node);
}

AddCollectionTask::AddCollectionTask(CollectionView *view,
                                     CollectionListModel *listModel,
                                     const QJsonObject &localJsonObject,
                                     const QString &collectionName)
    : CollectionTask(view, listModel)
    , m_localJsonObject(localJsonObject)
    , m_name(collectionName)
{}

void AddCollectionTask::process()
{
    if (!m_listModel)
        return;

    const QString newCollectionName = m_listModel->collectionExists(m_name)
                                          ? m_listModel->getUniqueCollectionName(m_name)
                                          : m_name;

    m_listModel->addCollection(newCollectionName, m_localJsonObject);
}

} // namespace QmlDesigner