| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "qmlcomponentfactory.h" |
| 5 | |
| 6 | #include "qmlcomponentregistry.h" |
| 7 | #include "qmlitem.h" |
| 8 | #include <QQmlApplicationEngine> |
| 9 | #include <QQmlEngine> |
| 10 | #include <QQuickItem> |
| 11 | #include <QString> |
| 12 | #include <utility> |
| 13 | |
| 14 | QMLComponentFactory::QMLComponentFactory( |
| 15 | std::unique_ptr<IQMLComponentRegistry> &&qmlComponentRegistry) noexcept |
| 16 | : qmlComponentRegistry_(std::move(qmlComponentRegistry)) |
| 17 | { |
| 18 | } |
| 19 | |
| 20 | void QMLComponentFactory::registerQMLTypes() const |
| 21 | { |
| 22 | auto const &qmlTypeRegisterers = qmlComponentRegistry_->qmlTypeRegisterers(); |
| 23 | for (auto const &qmlTypeRegisterer : qmlTypeRegisterers) |
| 24 | qmlTypeRegisterer(); |
| 25 | } |
| 26 | |
| 27 | QMLItem *QMLComponentFactory::createQMLItem(std::string const &itemID, |
| 28 | QQuickItem *parent, |
| 29 | QQmlApplicationEngine &qmlEngine) const |
| 30 | { |
| 31 | auto &qmlItemProviders = qmlComponentRegistry_->qmlItemProviders(); |
| 32 | auto const providerIt = qmlItemProviders.find(itemID); |
| 33 | if (providerIt != qmlItemProviders.cend()) { |
| 34 | auto item = providerIt->second(qmlEngine); |
| 35 | QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership); |
| 36 | |
| 37 | auto parentName = parent->objectName(); |
| 38 | if (!parentName.contains(QMLItem::ParentObjectSuffix.data())) |
| 39 | parentName.append(QMLItem::ParentObjectSuffix.data()); |
| 40 | |
| 41 | parentItem(item, parent, parentName.toStdString()); |
| 42 | |
| 43 | return item; |
| 44 | } |
| 45 | |
| 46 | return nullptr; |
| 47 | } |
| 48 | |
| 49 | QQuickItem * |
| 50 | QMLComponentFactory::createQuickItem(std::string const &itemID, |
| 51 | QQuickItem *parent, |
| 52 | std::string const &parentObjectName) const |
| 53 | { |
| 54 | auto quickItemProviders = qmlComponentRegistry_->quickItemProviders(); |
| 55 | auto providerIt = quickItemProviders.find(itemID); |
| 56 | if (providerIt != quickItemProviders.cend()) { |
| 57 | auto item = providerIt->second(); |
| 58 | QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership); |
| 59 | parentItem(item, parent, parentObjectName); |
| 60 | |
| 61 | return item; |
| 62 | } |
| 63 | |
| 64 | return nullptr; |
| 65 | } |
| 66 | |
| 67 | void QMLComponentFactory::parentItem(QQuickItem *item, QQuickItem *parent, |
| 68 | std::string_view parentObjectName) const |
| 69 | { |
| 70 | QQuickItem *parentItem = parent; |
| 71 | if (parent->objectName() != parentObjectName.data()) { |
| 72 | parentItem = parent->findChild<QQuickItem *>(parentObjectName.data()); |
| 73 | if (parentItem == nullptr) |
| 74 | parentItem = parent; |
| 75 | } |
| 76 | item->setParentItem(parentItem); |
| 77 | item->setParent(parentItem); |
| 78 | } |