Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2024 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 :
23 : #include "ioc.h"
24 :
25 : #include "log.h"
26 :
27 : #ifndef NO_QT_SUPPORT
28 : #include <QQmlEngine>
29 : #include <QQmlContext>
30 : #include <QWidget>
31 :
32 189 : muse::Contextable::GetContext muse::iocCtxForQmlObject(const QObject* o)
33 : {
34 189 : return [o]() {
35 18 : const QObject* p = o;
36 18 : QQmlContext* ctx = qmlContext(p);
37 21 : while (!ctx && p->parent()) {
38 3 : p = p->parent();
39 3 : ctx = qmlContext(p);
40 : }
41 :
42 18 : IF_ASSERT_FAILED(ctx) {
43 0 : LOGW() << "QQmlContext is not set for QML Object: " << o->metaObject()->className();
44 0 : return modularity::ContextPtr();
45 : }
46 :
47 18 : return iocCtxForQmlContext(ctx);
48 189 : };
49 : }
50 :
51 18 : muse::modularity::ContextPtr muse::iocCtxForQmlContext(const QQmlContext* ctx)
52 : {
53 19 : TRACEFUNC;
54 :
55 : //! NOTE: Currently, each IoC context (window)
56 : // has its own instance of the Qml Engine,
57 : // and thus its own root Qml Context. We can use it directly.
58 18 : const QQmlContext* rootContext = ctx->engine()->rootContext();
59 :
60 18 : QmlIoCContext* qmlIoc = rootContext->contextProperty("ioc_context").value<QmlIoCContext*>();
61 18 : IF_ASSERT_FAILED(qmlIoc) {
62 0 : LOGW() << "QmlIoCContext is not set for QML Context: " << rootContext->objectName();
63 0 : return modularity::ContextPtr();
64 : }
65 :
66 18 : return qmlIoc->ctx;
67 18 : }
68 :
69 0 : muse::Contextable::GetContext muse::iocCtxForQWidget(const QWidget* w)
70 : {
71 0 : return [w]() {
72 0 : IF_ASSERT_FAILED(w) {
73 0 : return modularity::ContextPtr();
74 : }
75 :
76 0 : const QObject* obj = w;
77 0 : while (obj) {
78 0 : bool ok = false;
79 0 : int ctxId = obj->property("ioc_context").toInt(&ok);
80 0 : if (ok) {
81 0 : return std::make_shared<modularity::Context>(ctxId);
82 : }
83 0 : obj = obj->parent();
84 : }
85 :
86 0 : UNREACHABLE;
87 : return modularity::ContextPtr();
88 0 : };
89 : }
90 :
91 : #endif
|