Debian Codegraph @

src/GUI/QQuickDrawable.cxx

raw symbols SCIP
1 // QQuickDrawable.cxx - OSG Drawable using a QQuickRenderControl to draw
2 //
3 // Copyright (C) 2019 James Turner <[email protected]>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
19 #include "config.h"
20
21 #include <simgear/compiler.h>
22 #include <atomic>
23
24 #include <QOpenGLContext>
25
26 #include "QQuickDrawable.hxx"
27
28 #include <QQmlComponent>
29 #include <QQmlContext>
30 #include <QQmlEngine>
31 #include <QQuickRenderControl>
32
33 #include <QTimer>
34 #include <QCoreApplication>
35 #include <QOpenGLFunctions>
36 #include <QQuickItem>
37 #include <QQuickWindow>
38 #include <QSurfaceFormat>
39 #include <QThread>
40
41
42 // private Qt headers, needed to make glue work between Qt and OSG
43 // graphics window unfortunately.
44 #include <private/qopenglcontext_p.h>
45
46 #if defined(SG_MAC)
47 # include "fake_qguiapp_p.h"
48 #else
49 # include <private/qguiapplication_p.h>
50 #endif
51
52 #include <osg/GraphicsContext>
53 #include <osgGA/GUIEventAdapter>
54 #include <osgGA/GUIEventHandler>
55 #include <osgViewer/GraphicsWindow>
56 #include <osgViewer/Viewer>
57
58 #include <GUI/DialogStateController.hxx>
59 #include <GUI/FGQQWindowManager.hxx>
60 #include <GUI/FGQmlInstance.hxx>
61 #include <GUI/FGQmlPropertyNode.hxx>
62 #include <Main/fg_props.hxx>
63 #include <Main/globals.hxx>
64 #include <GUI/OSGQtAdaption.hxx>
65 #include <simgear/structure/commands.hxx>
66
67 #if defined(HAVE_PUI)
68 #include "FlightGear_pu.h"
69 #endif
70
71 using namespace osgGA;
72
73 struct QtKey {
74 QtKey(int _o, int _q, QString _s = {}) : osg(_o), qt(_q), s(_s) {}
75
76 int osg;
77 int qt;
78 QString s;
79 };
80
81 const std::initializer_list<QtKey> keymapInit = {
82 // contains all the key mappings except 0..9 and A..Z which are generated
83 // programatically
84
85 {GUIEventAdapter::KEY_Space, Qt::Key_Space, " "},
86 {GUIEventAdapter::KEY_Escape, Qt::Key_Escape, "\x1B"},
87 {GUIEventAdapter::KEY_Return, Qt::Key_Return, "\r"},
88 {GUIEventAdapter::KEY_Tab, Qt::Key_Tab, "\t"},
89 {GUIEventAdapter::KEY_BackSpace, Qt::Key_Backspace, "\x08"},
90 {GUIEventAdapter::KEY_Delete, Qt::Key_Delete, "\x7f"},
91
92 {GUIEventAdapter::KEY_Period, Qt::Key_Period, "."},
93 {GUIEventAdapter::KEY_Comma, Qt::Key_Comma, ","},
94 {GUIEventAdapter::KEY_Colon, Qt::Key_Colon, ":"},
95 {GUIEventAdapter::KEY_Quote, Qt::Key_QuoteLeft, "'"},
96 {GUIEventAdapter::KEY_Quotedbl, Qt::Key_QuoteDbl, "\""},
97 {GUIEventAdapter::KEY_Underscore, Qt::Key_Underscore, "_"},
98 {GUIEventAdapter::KEY_Plus, Qt::Key_Plus, "+"},
99 {GUIEventAdapter::KEY_Minus, Qt::Key_Minus, "-"},
100 {GUIEventAdapter::KEY_Asterisk, Qt::Key_Asterisk, "*"},
101 {GUIEventAdapter::KEY_Equals, Qt::Key_Equal, "="},
102 {GUIEventAdapter::KEY_Slash, Qt::Key_Slash, "/"},
103
104 {GUIEventAdapter::KEY_Left, Qt::Key_Left},
105 {GUIEventAdapter::KEY_Right, Qt::Key_Right},
106 {GUIEventAdapter::KEY_Up, Qt::Key_Up},
107 {GUIEventAdapter::KEY_Down, Qt::Key_Down},
108
109 {GUIEventAdapter::KEY_Shift_L, Qt::Key_Shift},
110 {GUIEventAdapter::KEY_Shift_R, Qt::Key_Shift},
111 {GUIEventAdapter::KEY_Control_L, Qt::Key_Control},
112 {GUIEventAdapter::KEY_Control_R, Qt::Key_Control},
113 {GUIEventAdapter::KEY_Meta_L, Qt::Key_Meta},
114 {GUIEventAdapter::KEY_Meta_R, Qt::Key_Meta},
115
116
117 };
118
119 std::vector<QtKey> global_keymap;
120
121 class CustomRenderControl : public QQuickRenderControl
122 {
123 public:
124 CustomRenderControl(QWindow* win)
125 : _qWindow(win)
126 {
127 // Q_ASSERT(win);
128 }
129
130 QWindow* renderWindow(QPoint* offset) override
131 {
132 if (offset) {
133 *offset = QPoint(0, 0);
134 }
135 return _qWindow;
136 }
137
138 private:
139 QWindow* _qWindow = nullptr;
140 };
141
142 class QQuickDrawablePrivate : public QObject
143 {
144 Q_OBJECT
145 public:
146 QQuickDrawablePrivate() :
147 renderControlInited(false)
148 {
149
150 }
151
152 ~QQuickDrawablePrivate()
153 {
154
155 }
156
157 CustomRenderControl* renderControl = nullptr;
158
159 QQmlComponent* qmlComponent = nullptr;
160 QQmlEngine* qmlEngine = nullptr;
161 bool syncRequired = true;
162
163 QQuickItem* rootItem = nullptr;
164
165 // this window is neither created()-ed nor shown but is needed by
166 // QQuickRenderControl for historical reasons, and gives us a place to
167 // inject events from the OSG side.
168 QQuickWindow* quickWindow = nullptr;
169
170 // window representing the OSG window, needed
171 // for making our adpoted context current
172 QWindow* foreignOSGWindow = nullptr;
173 QOpenGLContext* qtContext = nullptr;
174 osg::GraphicsContext* osgContext = nullptr;
175
176 std::atomic_int renderControlInited;
177 std::atomic_int syncPending;
178
179 void frameEvent()
180 {
181 if (syncRequired) {
182 renderControl->polishItems();
183 syncRequired = false;
184 syncPending = true;
185
186 osgContext->add(flightgear::makeGraphicsOp("Sync QQ2 Render control", [this](osg::GraphicsContext*) {
187 QOpenGLContextPrivate::setCurrentContext(qtContext);
188 renderControl->sync();
189 syncPending = false;
190 }));
191 }
192 }
193 public slots:
194 void onComponentLoaded()
195 {
196 if (qmlComponent->isError()) {
197 QList<QQmlError> errorList = qmlComponent->errors();
198 Q_FOREACH (const QQmlError& error, errorList) {
199 qWarning() << error.url() << error.line() << error;
200 }
201 return;
202 }
203
204 QObject* rootObject = qmlComponent->create();
205 if (qmlComponent->isError()) {
206 QList<QQmlError> errorList = qmlComponent->errors();
207 Q_FOREACH (const QQmlError& error, errorList) {
208 qWarning() << error.url() << error.line() << error;
209 }
210 return;
211 }
212
213 rootItem = qobject_cast<QQuickItem*>(rootObject);
214 if (!rootItem) {
215 qWarning() << Q_FUNC_INFO << "root object not a QQuickItem" << rootObject;
216 delete rootObject;
217 return;
218 }
219
220 // The root item is ready. Associate it with the window.
221 rootItem->setParentItem(quickWindow->contentItem());
222 syncRequired = true;
223 rootItem->setWidth(quickWindow->width());
224 rootItem->setHeight(quickWindow->height());
225 }
226
227 void initRenderControl()
228 {
229 qtContext = flightgear::qtContextFromOSG(osgContext);
230 renderControl->prepareThread(QThread::currentThread());
231 QOpenGLContextPrivate::setCurrentContext(qtContext);
232 QOpenGLContextPrivate::get(qtContext)->surface = foreignOSGWindow;
233 renderControl->initialize(qtContext);
234
235 renderControlInited = true;
236 }
237
238 void onSceneChanged()
239 {
240 syncRequired = true;
241 }
242
243 void onRenderRequested()
244 {
245 qWarning() << Q_FUNC_INFO;
246 }
247
248 void onWindowActiveFocusItemChanged()
249 {
250 if (quickWindow->activeFocusItem())
251 qInfo() << Q_FUNC_INFO << "Active focus item is now:" << quickWindow->activeFocusItem();
252 else
253 qInfo() << Q_FUNC_INFO << "Active focus cleared";
254 }
255 };
256
257
258 static QObject* fgqmlinstance_provider(QQmlEngine* engine, QJSEngine* scriptEngine)
259 {
260 Q_UNUSED(engine)
261 Q_UNUSED(scriptEngine)
262
263 FGQmlInstance* instance = new FGQmlInstance;
264 return instance;
265 }
266
267 static QObject* fgqq_windowManager_provider(QQmlEngine* engine, QJSEngine* scriptEngine)
268 {
269 Q_UNUSED(scriptEngine)
270
271 FGQQWindowManager* instance = new FGQQWindowManager(engine);
272 return instance;
273 }
274
275 class ReloadCommand : public SGCommandMgr::Command
276 {
277 public:
278 ReloadCommand(QQuickDrawable* qq) : _drawable(qq)
279 {
280 }
281
282 bool operator()(const SGPropertyNode* aNode, SGPropertyNode* root) override
283 {
284 SG_UNUSED(aNode);
285 SG_UNUSED(root);
286
287 QTimer::singleShot(0, [this]() {
288 std::string rootQMLPath = fgGetString("/sim/gui/qml-root-path");
289 _drawable->reload(QUrl::fromLocalFile(QString::fromStdString(rootQMLPath)));
290 });
291 return true;
292 }
293
294 private:
295 QQuickDrawable* _drawable;
296 };
297
298 class QuickEventHandler : public osgGA::GUIEventHandler
299 {
300 public:
301 QuickEventHandler(QQuickDrawablePrivate* p) : _drawable(p)
302 {
303 populateKeymap();
304 }
305
306 bool handle(const GUIEventAdapter& ea, GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) override
307 {
308 Q_UNUSED(aa);
309
310 if (ea.getHandled()) return false;
311
312 // frame event, ho hum ...
313 if (ea.getEventType() == GUIEventAdapter::FRAME) {
314 _drawable->frameEvent();
315 return false;
316 }
317
318 // Qt expects increasing downward mouse coords
319 const float fixedY = (ea.getMouseYOrientation() == GUIEventAdapter::Y_INCREASING_UPWARDS) ? ea.getWindowHeight() - ea.getY() : ea.getY();
320 const double pixelRatio = _drawable->foreignOSGWindow->devicePixelRatio();
321
322 QPointF pointInWindow{ea.getX() / pixelRatio, fixedY / pixelRatio};
323 QPointF screenPt = pointInWindow +
324 QPointF{ea.getWindowX() / pixelRatio, ea.getWindowY() / pixelRatio};
325
326 // const int scaledX = static_cast<int>(ea.getX() / static_pixelRatio);
327 // const int scaledY = static_cast<int>(fixedY / static_pixelRatio);
328
329 switch (ea.getEventType()) {
330 case (GUIEventAdapter::DRAG):
331 case (GUIEventAdapter::MOVE): {
332 QMouseEvent m(QEvent::MouseMove, pointInWindow, pointInWindow, screenPt,
333 Qt::NoButton,
334 osgButtonMaskToQt(ea), osgModifiersToQt(ea));
335 QCoreApplication::sendEvent(_drawable->quickWindow, &m);
336 return m.isAccepted();
337 }
338
339 case (GUIEventAdapter::PUSH):
340 case (GUIEventAdapter::RELEASE): {
341 const bool isUp = (ea.getEventType() == GUIEventAdapter::RELEASE);
342 QMouseEvent m(isUp ? QEvent::MouseButtonRelease : QEvent::MouseButtonPress,
343 pointInWindow, pointInWindow, screenPt,
344 osgButtonToQt(ea),
345 osgButtonMaskToQt(ea), osgModifiersToQt(ea));
346 QCoreApplication::sendEvent(_drawable->quickWindow, &m);
347
348 if (!isUp) {
349 if (m.isAccepted()) {
350 // deactivate PUI
351 auto active = puActiveWidget();
352 if (active) {
353 active->invokeDownCallback();
354 }
355 }
356
357 // on mouse downs which we don't accept, take focus back
358 // qInfo() << "Clearing QQ focus";
359 // auto focused = _drawable->quickWindow->activeFocusItem();
360 // if (focused) {
361 // focused->setFocus(false, Qt::MouseFocusReason);
362 // }
363 }
364
365 return m.isAccepted();
366 }
367
368 case (GUIEventAdapter::KEYDOWN):
369 case (GUIEventAdapter::KEYUP): {
370 if (!_drawable->quickWindow->activeFocusItem()) {
371 return false;
372 }
373
374 const bool isKeyRelease = (ea.getEventType() == GUIEventAdapter::KEYUP);
375 const auto& key = osgKeyToQt(ea.getKey());
376 QString s = key.s;
377
378 QKeyEvent k(isKeyRelease ? QEvent::KeyRelease : QEvent::KeyPress,
379 key.qt, osgModifiersToQt(ea), s);
380 QCoreApplication::sendEvent(_drawable->quickWindow, &k);
381 return k.isAccepted();
382 }
383
384 default:
385 return false;
386 }
387
388 return false;
389 }
390 private:
391 Qt::MouseButtons osgButtonMaskToQt(const osgGA::GUIEventAdapter& ea) const
392 {
393 const int mask = ea.getButtonMask();
394 Qt::MouseButtons result = Qt::NoButton;
395 if (mask & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
396 result |= Qt::LeftButton;
397
398 if (mask & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
399 result |= Qt::MiddleButton;
400
401 if (mask & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
402 result |= Qt::RightButton;
403
404 return result;
405 }
406
407 Qt::MouseButton osgButtonToQt(const osgGA::GUIEventAdapter& ea) const
408 {
409 switch (ea.getButton()) {
410 case osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON: return Qt::LeftButton;
411 case osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON: return Qt::MiddleButton;
412 case osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON: return Qt::RightButton;
413
414 default:
415 break;
416 }
417
418 return Qt::NoButton;
419 }
420
421 Qt::KeyboardModifiers osgModifiersToQt(const osgGA::GUIEventAdapter& ea) const
422 {
423 Qt::KeyboardModifiers result = Qt::NoModifier;
424 const int mask = ea.getModKeyMask();
425 if (mask & osgGA::GUIEventAdapter::MODKEY_ALT) result |= Qt::AltModifier;
426 if (mask & osgGA::GUIEventAdapter::MODKEY_CTRL) result |= Qt::ControlModifier;
427 if (mask & osgGA::GUIEventAdapter::MODKEY_META) result |= Qt::MetaModifier;
428 if (mask & osgGA::GUIEventAdapter::MODKEY_SHIFT) result |= Qt::ShiftModifier;
429 return result;
430 }
431
432 QtKey osgKeyToQt(int code) const
433 {
434 auto it = std::lower_bound(global_keymap.begin(), global_keymap.end(),
435 QtKey{code, 0, {}},
436 [](const QtKey& a, const QtKey& b) { return a.osg < b.osg; });
437 if ((it == global_keymap.end()) || (it->osg != code)) {
438 qWarning() << "no mapping defined for OSG key:" << code;
439 return {0, 0, ""};
440 }
441
442 return *it;
443 }
444
445 void populateKeymap()
446 {
447 if (!global_keymap.empty())
448 return;
449
450 // regular keymappsing for A..Z and 0..9
451 for (int i = 0; i < 10; ++i) {
452 global_keymap.emplace_back(GUIEventAdapter::KEY_0 + i, Qt::Key_0 + i, QString::number(i));
453 }
454
455 for (int i = 0; i < 26; ++i) {
456 global_keymap.emplace_back(GUIEventAdapter::KEY_A + i, Qt::Key_A + i, QChar::fromLatin1('a' + i));
457 }
458
459 for (int i = 0; i < 26; ++i) {
460 global_keymap.emplace_back('A' + i, Qt::Key_A + i, QChar::fromLatin1('A' + i));
461 }
462
463 // custom key mappsing
464 global_keymap.insert(global_keymap.end(), keymapInit);
465
466 // sort by OSG code for fast lookups
467 std::sort(global_keymap.begin(), global_keymap.end(),
468 [](const QtKey& a, const QtKey& b) { return a.osg < b.osg; });
469 }
470
471 QQuickDrawablePrivate* _drawable;
472 };
473
474 QQuickDrawable::QQuickDrawable() : d(new QQuickDrawablePrivate)
475 {
476 setUseDisplayList(false);
477 setDataVariance(Object::DYNAMIC);
478
479 osg::StateSet* stateSet = getOrCreateStateSet();
480 stateSet->setRenderBinDetails(1001, "RenderBin");
481
482 QSurfaceFormat format;
483 format.setRenderableType(QSurfaceFormat::OpenGL);
484 QSurfaceFormat::setDefaultFormat(format);
485
486 static bool doneQmlRegistration = false;
487 if (!doneQmlRegistration) {
488 doneQmlRegistration = true;
489
490 // singleton system object
491 qmlRegisterSingletonType<FGQmlInstance>("FlightGear", 1, 0, "System", fgqmlinstance_provider);
492 qmlRegisterSingletonType<FGQmlInstance>("FlightGear", 1, 0, "WindowManager", fgqq_windowManager_provider);
493
494 // QML types
495 qmlRegisterType<FGQmlPropertyNode>("FlightGear", 1, 0, "Property");
496 qmlRegisterType<DialogStateController>("FlightGear", 1, 0, "DialogStateController");
497 }
498
499 globals->get_commands()->addCommandObject("reload-quick-gui", new ReloadCommand(this));
500 }
501
502 QQuickDrawable::~QQuickDrawable()
503 {
504 delete d->qmlEngine;
505 delete d->renderControl;
506 }
507
508 void QQuickDrawable::setup(osgViewer::GraphicsWindow *gw, osgViewer::Viewer *viewer)
509 {
510 osg::GraphicsContext* gc = gw;
511
512 // none of this stuff needs the context current, so we can do it
513 // all safely on the main thread
514
515 d->foreignOSGWindow = flightgear::qtWindowFromOSG(gw);
516 // d->foreignOSGWindow->setFormat(format);
517 d->foreignOSGWindow->setSurfaceType(QSurface::OpenGLSurface);
518
519 // QWindow::requestActive would do QPA::makeKey, but on macOS this
520 // is a no-op for foreign windows. So we're going to manually set
521 // the focus window!
522 QGuiApplicationPrivate::focus_window = d->foreignOSGWindow;
523
524 d->osgContext = gc;
525 d->renderControl = new CustomRenderControl(d->foreignOSGWindow);
526 d->quickWindow = new QQuickWindow(d->renderControl);
527 d->quickWindow->setClearBeforeRendering(false);
528
529 d->qmlEngine = new QQmlEngine;
530
531 SGPath rootQMLPath = SGPath::fromUtf8(fgGetString("/sim/gui/qml-root-path"));
532 SG_LOG(SG_GENERAL, SG_INFO, "Root QML dir:" << rootQMLPath.dir());
533 d->qmlEngine->addImportPath(QString::fromStdString(rootQMLPath.dir()));
534 // d->qmlEngine->addImportPath(QStringLiteral("qrc:///"));
535
536 if (!d->qmlEngine->incubationController())
537 d->qmlEngine->setIncubationController(d->quickWindow->incubationController());
538
539 // QObject::connect(d->quickWindow, &QQuickWindow::activeFocusItemChanged,
540 // d.get(), &QQuickDrawablePrivate::onWindowActiveFocusItemChanged);
541
542 QObject::connect(d->renderControl, &QQuickRenderControl::sceneChanged,
543 d.get(), &QQuickDrawablePrivate::onSceneChanged);
544 QObject::connect(d->renderControl, &QQuickRenderControl::renderRequested,
545 d.get(), &QQuickDrawablePrivate::onRenderRequested);
546
547
548 viewer->getEventHandlers().push_front(new QuickEventHandler(d.get()));
549 }
550
551 void QQuickDrawable::drawImplementation(osg::RenderInfo& renderInfo) const
552 {
553 if (!d->renderControlInited) {
554 d->initRenderControl();
555 }
556
557 if (QOpenGLContext::currentContext() != d->qtContext) {
558 QOpenGLContextPrivate::setCurrentContext(d->qtContext);
559 }
560
561 QOpenGLFunctions* glFuncs = d->qtContext->functions();
562 // prepare any state QQ2 needs
563 d->quickWindow->resetOpenGLState();
564
565 // and reset these manually
566 glFuncs->glPixelStorei(GL_PACK_ALIGNMENT, 4);
567 glFuncs->glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
568 glFuncs->glPixelStorei(GL_PACK_ROW_LENGTH, 0);
569 glFuncs->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
570
571 d->renderControl->render();
572
573 // otherwise the PUI camera gets confused
574 d->quickWindow->resetOpenGLState();
575 }
576
577 void QQuickDrawable::reload(const QUrl& url)
578 {
579 d->qmlEngine->clearComponentCache();
580 setSource(url);
581 }
582
583 void QQuickDrawable::setSourcePath(const std::string& path)
584 {
585 setSource(QUrl::fromLocalFile(QString::fromStdString(path)));
586 }
587
588 void QQuickDrawable::setSource(const QUrl& url)
589 {
590 if (d->rootItem)
591 delete d->rootItem;
592 if (d->qmlComponent)
593 delete d->qmlComponent;
594 d->rootItem = nullptr;
595
596 d->qmlComponent = new QQmlComponent(d->qmlEngine, url);
597 if (d->qmlComponent->isLoading()) {
598 QObject::connect(d->qmlComponent, &QQmlComponent::statusChanged,
599 d.get(), &QQuickDrawablePrivate::onComponentLoaded);
600 } else {
601 d->onComponentLoaded();
602 }
603 }
604
605 void QQuickDrawable::resize(int width, int height)
606 {
607 // we need to unscale from physical pixels back to logical, otherwise we end up double-scaled.
608 const float currentPixelRatio = static_cast<float>(d->foreignOSGWindow->devicePixelRatio());
609 const int logicalWidth = static_cast<int>(width / currentPixelRatio);
610 const int logicalHeight = static_cast<int>(height / currentPixelRatio);
611
612 if (d->rootItem) {
613 d->rootItem->setWidth(logicalWidth);
614 d->rootItem->setHeight(logicalHeight);
615 }
616
617 // SG_LOG(SG_GUI, SG_INFO, "Resize:, lw=" << logicalWidth << ", lh=" << logicalHeight);
618 d->quickWindow->setGeometry(0, 0, logicalWidth, logicalHeight);
619 }
620
621 #include "QQuickDrawable.moc"