diff --git a/CHANGES b/CHANGES index a05f0a611..422c5d1a3 100644 --- a/CHANGES +++ b/CHANGES @@ -27,6 +27,7 @@ Unreleased * Report failed debugger attaches, server startup errors and Windows injection failures right away instead of timing out * Don't time out in in-process mode when remote access is disabled * Fix process names with spaces or parentheses in the attach dialog + * Show QtQuick windows that use Vulkan, Metal or Direct3D in the remote view, including decorations (Qt 6.6 or newer) Version 3.4.1 ------------- diff --git a/CMakeLists.txt b/CMakeLists.txt index 3c40ab0bd..d0725bf5f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -506,6 +506,8 @@ if(Qt6Gui_VERSION VERSION_GREATER_EQUAL "6.10.0") find_package(Qt6WidgetsPrivate REQUIRED NO_MODULE) find_package(Qt6QmlPrivate NO_MODULE) find_package(Qt6QuickPrivate NO_MODULE) + find_package(Qt6QuickWidgetsPrivate NO_MODULE) + find_package(Qt6GuiPrivate NO_MODULE) endif() # these need to included after the last Qt-related find_package() call diff --git a/common/protocol.cpp b/common/protocol.cpp index 9a1ed0bc2..5cf87a2cc 100644 --- a/common/protocol.cpp +++ b/common/protocol.cpp @@ -39,7 +39,7 @@ QModelIndex toQModelIndex(const QAbstractItemModel *model, const Protocol::Model qint32 version() { - return 38; + return 39; } qint32 broadcastFormatVersion() diff --git a/common/remoteviewframe.cpp b/common/remoteviewframe.cpp index 7dede0dd1..6b79d6617 100644 --- a/common/remoteviewframe.cpp +++ b/common/remoteviewframe.cpp @@ -68,9 +68,19 @@ void RemoteViewFrame::setImage(const QImage &image, const QTransform &transform) m_image.setTransform(transform); } +void RemoteViewFrame::setGraphicsApi(const int value) +{ + m_graphicsApi = value; +} + +int RemoteViewFrame::graphicsApi() const +{ + return m_graphicsApi; +} + QDataStream &operator<<(QDataStream &stream, const RemoteViewFrame &frame) { - stream << frame.m_image << frame.data << frame.m_viewRect << frame.m_sceneRect; + stream << frame.m_image << frame.data << frame.m_viewRect << frame.m_sceneRect << frame.m_graphicsApi; return stream; } @@ -80,6 +90,7 @@ QDataStream &operator>>(QDataStream &stream, RemoteViewFrame &frame) stream >> frame.data; stream >> frame.m_viewRect; stream >> frame.m_sceneRect; + stream >> frame.m_graphicsApi; return stream; } } diff --git a/common/remoteviewframe.h b/common/remoteviewframe.h index 6313d6a64..1143fb935 100644 --- a/common/remoteviewframe.h +++ b/common/remoteviewframe.h @@ -46,6 +46,9 @@ class GAMMARAY_COMMON_EXPORT RemoteViewFrame void setImage(const QImage &image); void setImage(const QImage &image, const QTransform &transform); + void setGraphicsApi(int value); + int graphicsApi() const; + /// tool specific frame data QVariant data; @@ -55,6 +58,7 @@ class GAMMARAY_COMMON_EXPORT RemoteViewFrame TransferImage m_image; QRectF m_viewRect; QRectF m_sceneRect; + int m_graphicsApi = 0; // QSGRendererInterface::GraphicsApi, only set and used by the QtQuick preview. 0 is Unknown. }; } diff --git a/plugins/quickinspector/CMakeLists.txt b/plugins/quickinspector/CMakeLists.txt index 990f2cce9..e5e864488 100644 --- a/plugins/quickinspector/CMakeLists.txt +++ b/plugins/quickinspector/CMakeLists.txt @@ -79,12 +79,30 @@ if(NOT GAMMARAY_CLIENT_ONLY_BUILD) ) endif() + # Only needed for the RHI screen grabber for >=6.6 + if(Qt6Core_VERSION VERSION_GREATER_EQUAL "6.6.0") + find_package(Qt${QT_VERSION_MAJOR}ShaderTools REQUIRED) + qt_add_shaders( + gammaray_quickinspector + "gammaray_quickinspector_shaders" + PRECOMPILE + PREFIX + "/gammaray_quickinspector_shaders/" + FILES + "shaders/rhi_inspector_decorations.vert" + "shaders/rhi_inspector_decorations.frag" + ) + endif() + target_link_libraries( gammaray_quickinspector gammaray_quickinspector_shared gammaray_core Qt::Quick Qt::QuickPrivate + Qt::QuickWidgets + Qt::QuickWidgetsPrivate + Qt::GuiPrivate gammaray_kitemmodels ) diff --git a/plugins/quickinspector/quickinspector.cpp b/plugins/quickinspector/quickinspector.cpp index 38fb0d86d..e3b5f5aa6 100644 --- a/plugins/quickinspector/quickinspector.cpp +++ b/plugins/quickinspector/quickinspector.cpp @@ -292,7 +292,7 @@ void RenderModeRequest::apply() if (connection) disconnect(connection); - if (window && window->rendererInterface()->graphicsApi() != QSGRendererInterface::OpenGL) + if (window && window->rendererInterface()->graphicsApi() == QSGRendererInterface::Software) return; if (window) { @@ -574,6 +574,10 @@ void QuickInspector::sendRenderedScene(const GammaRay::GrabbedFrame &grabbedFram frame.data = QVariant::fromValue(grabbedFrame.itemsGeometry); else if (!grabbedFrame.itemsGeometry.isEmpty()) frame.data = QVariant::fromValue(grabbedFrame.itemsGeometry.at(0)); + // Not m_window->rendererInterface(): this also runs for the empty frame sent from + // AbstractScreenGrabber::eventFilter() while ~QWindow hides the window, when the QQuickWindow + // part is already destroyed. + frame.setGraphicsApi(grabbedFrame.graphicsApi); m_remoteView->sendFrame(frame); } @@ -612,10 +616,10 @@ void QuickInspector::checkFeatures() return; } - if (m_window->rendererInterface()->graphicsApi() == QSGRendererInterface::OpenGL) - f = AllCustomRenderModes; - else if (m_window->rendererInterface()->graphicsApi() == QSGRendererInterface::Software) + if (m_window->rendererInterface()->graphicsApi() == QSGRendererInterface::Software) f = AnalyzePainting; + else + f = AllCustomRenderModes; emit features(f); } diff --git a/plugins/quickinspector/quickscenepreviewwidget.cpp b/plugins/quickinspector/quickscenepreviewwidget.cpp index a189a9b59..aa33ad647 100644 --- a/plugins/quickinspector/quickscenepreviewwidget.cpp +++ b/plugins/quickinspector/quickscenepreviewwidget.cpp @@ -20,6 +20,10 @@ #include #include +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) +#include +#endif + using namespace GammaRay; static const qint32 QuickScenePreviewWidgetStateVersion = 4; @@ -152,6 +156,14 @@ void QuickScenePreviewWidget::resizeEvent(QResizeEvent *e) void QuickScenePreviewWidget::renderDecoration(QPainter *p, double zoom) const { +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) + // We want to skip rendering decorations in the client, if we draw it on RHI targets and this rendering backend cannot discern between the two. + const auto graphicsApi = static_cast(frame().graphicsApi()); + if (QSGRendererInterface::isApiRhiBased(graphicsApi) && m_control->serverSideDecorationsEnabled()) { + return; + } +#endif + // Scaling and translations on QuickItemGeometry will be done on demand if (frame().data.userType() == qMetaTypeId()) { diff --git a/plugins/quickinspector/quickscreengrabber.cpp b/plugins/quickinspector/quickscreengrabber.cpp index dfbc27e3f..7250509cc 100644 --- a/plugins/quickinspector/quickscreengrabber.cpp +++ b/plugins/quickinspector/quickscreengrabber.cpp @@ -37,9 +37,16 @@ #include #include +#include #include #include +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) +#include +#include + +#endif + namespace GammaRay { class QQuickItemPropertyCache @@ -222,13 +229,20 @@ bool ItemOrLayoutFacade::isLayout() const std::unique_ptr AbstractScreenGrabber::get(QQuickWindow *window) { +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) + const auto graphicApi = graphicsApiFor(window); + if (QSGRendererInterface::isApiRhiBased(static_cast(graphicApi))) { + return std::make_unique(window); + } +#endif + switch (graphicsApiFor(window)) { #ifndef QT_NO_OPENGL case RenderInfo::OpenGL: - return std::unique_ptr(new OpenGLScreenGrabber(window)); + return std::make_unique(window); #endif case RenderInfo::Software: - return std::unique_ptr(new SoftwareScreenGrabber(window)); + return std::make_unique(window); default: return std::unique_ptr(new UnsupportedScreenGrabber(window)); } @@ -252,8 +266,11 @@ AbstractScreenGrabber::AbstractScreenGrabber(QQuickWindow *window) placeOn(ItemOrLayoutFacade()); // Install an event filter to pick up on expose events - if (m_window) + if (m_window) { + // A window's graphics API doesn't change, and a grabber is created per window. + m_grabbedFrame.graphicsApi = graphicsApiFor(m_window); m_window->installEventFilter(this); + } } GammaRay::AbstractScreenGrabber::~AbstractScreenGrabber() @@ -862,3 +879,490 @@ void UnsupportedScreenGrabber::updateOverlay() { // Intentionally dummied out because this grabber doesn't do anything useful } + +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) +struct RhiScreenGrabber::ReadbackState +{ + QMutex mutex; + RhiScreenGrabber *grabber = nullptr; // reset when the grabber is destroyed + bool pending = false; // QRhi holds a pointer to result + QRhiReadbackResult result; +}; + +RhiScreenGrabber::RhiScreenGrabber(QQuickWindow *window) + : AbstractScreenGrabber(window) +{ + // Force DirectConnection else Auto lead to Queued which is not good. + // In the order QQuickWindow emits these signals. + connect(m_window.data(), &QQuickWindow::afterSynchronizing, this, &RhiScreenGrabber::windowAfterSynchronizing, Qt::DirectConnection); + connect(m_window.data(), &QQuickWindow::beforeRendering, this, &RhiScreenGrabber::windowBeforeRendering, Qt::DirectConnection); + connect(m_window.data(), &QQuickWindow::afterRenderPassRecording, this, &RhiScreenGrabber::windowAfterRenderPassRecording, Qt::DirectConnection); + connect(m_window.data(), &QQuickWindow::afterRendering, this, &RhiScreenGrabber::windowAfterRendering, Qt::DirectConnection); + connect(m_window.data(), &QQuickWindow::sceneGraphInvalidated, this, &RhiScreenGrabber::invalidateRhiResources, Qt::DirectConnection); + + m_readback = new ReadbackState; + m_readback->grabber = this; + m_readback->result.completed = [state = m_readback] { + QMutexLocker locker(&state->mutex); + state->pending = false; + if (!state->grabber) { + // The grabber was destroyed while QRhi still had this readback queued and left the + // state to us. QRhi may be running this very callback object, so free it later. + locker.unlock(); + QMetaObject::invokeMethod(qApp, [state] { delete state; }, Qt::QueuedConnection); + return; + } + state->grabber->readbackCompleted(state->result); + }; +} + +RhiScreenGrabber::~RhiScreenGrabber() +{ + // Stop the render thread from calling into us, and wait for a call that is in progress. + if (m_window) + disconnect(m_window.data(), nullptr, this, nullptr); + // Same lock order as windowAfterRendering(): m_mutex, then the readback mutex. + QMutexLocker locker(&m_mutex); + + bool readbackPending = false; + { + QMutexLocker readbackLocker(&m_readback->mutex); + m_readback->grabber = nullptr; + readbackPending = m_readback->pending; + } + // Otherwise QRhi still references it, and its completion callback deletes it. + if (!readbackPending) + delete m_readback; + + const std::array resources = { m_pipeline, m_srb, m_texture, m_sampler, m_vertexBuffer }; + if (m_window && std::any_of(resources.begin(), resources.end(), [](QRhiResource *r) { return r != nullptr; })) { + // The resources belong to the render thread, release them there. If the window is not + // exposed the job is dropped and they are left to the QRhi. + m_window->scheduleRenderJob(QRunnable::create([resources] { + for (auto *resource : resources) { + if (resource) + resource->deleteLater(); + } + }), + QQuickWindow::NoStage); + } +} + +void RhiScreenGrabber::readbackCompleted(const QRhiReadbackResult &result) +{ + const auto rhi = m_window->rhi(); + + const QImage::Format imageFormat = [&result] { + // Can't handle all the possible formats, but any missing ones will be displayed to the user so they can file a bugreport. + switch (result.format) { + case QRhiTexture::BGRA8: + return QImage::Format_ARGB32_Premultiplied; + case QRhiTexture::RGBA8: + return QImage::Format_RGBA8888_Premultiplied; + case QRhiTexture::RGB10A2: + return QImage::Format_A2BGR30_Premultiplied; + case QRhiTexture::RGBA16F: + return QImage::Format_RGBA16FPx4; + default: + return QImage::Format_Invalid; + } + }(); + + if (imageFormat != QImage::Format_Invalid) { + // QRhi reuses result.data for the next readback (resized/overwritten in place), but the image + // outlives this callback (queued to the GUI thread, kept by the remote view). Keep a shared + // reference to the current buffer alive for as long as the image exists; QRhi then detaches. + auto *bytes = new QByteArray(result.data); + m_grabbedFrame.image = QImage( + reinterpret_cast(bytes->constData()), + result.pixelSize.width(), + result.pixelSize.height(), + imageFormat, + [](void *p) { delete static_cast(p); }, + bytes); + m_grabbedFrame.image.setDevicePixelRatio(m_renderInfo.dpr); + + m_grabbedFrame.transform.reset(); + if (rhi->isYUpInFramebuffer()) { + m_grabbedFrame.transform.scale(1.0, -1.0); + m_grabbedFrame.transform.translate(0, -result.pixelSize.height() / m_renderInfo.dpr); + } + } else { + m_grabbedFrame.image = QImage(m_window->size() * m_window->effectiveDevicePixelRatio(), QImage::Format_ARGB32); + m_grabbedFrame.image.fill(Qt::black); + m_grabbedFrame.image.setDevicePixelRatio(m_window->effectiveDevicePixelRatio()); + + QPainter p(&m_grabbedFrame.image); + p.setRenderHint(QPainter::TextAntialiasing); + QColor gray(Qt::black); + gray.setAlpha(200); + p.fillRect(QRect(QPoint {}, m_window->size()), gray); + p.setPen(Qt::white); + auto font = qApp->font(); + font.setPointSize(font.pointSize() + 1); + p.setFont(font); + QString txt = QLatin1String("RHI texture format %1 is not supported yet").arg(VariantHandler::displayString(result.format)); + p.drawText(QRect { QPoint(0, 0), m_window->size() }, Qt::AlignCenter | Qt::TextWordWrap, txt); + } + emit sceneGrabbed(m_grabbedFrame); +} + +void RhiScreenGrabber::requestGrabWindow(const QRectF &userViewport) +{ + setGrabbingMode(true, userViewport); +} + +void RhiScreenGrabber::drawDecorations() +{ + // Intentionally dummied out because we don't use this function. +} + +void RhiScreenGrabber::setGrabbingMode(bool isGrabbing, const QRectF &userViewport) +{ + QMutexLocker locker(&m_mutex); + + if (m_isGrabbing == isGrabbing) + return; + + m_isGrabbing = isGrabbing; + m_userViewport = userViewport; + + emit grabberReadyChanged(!m_isGrabbing); + + if (m_isGrabbing) + updateOverlay(); +} + +void RhiScreenGrabber::windowAfterSynchronizing() +{ + // We are in the rendering thread at this point + // And the gui thread is locked + + gatherRenderInfo(); +} + +namespace { +// position, texture coordinates. The top row of an uploaded QImage is at v = 0 on all backends, +// while NDC y = -1 is the top only where Y points down in NDC (Vulkan). +constexpr std::array s_decorationQuad = { + -1.0f, -1.0f, 0.0f, 0.0f, + 1.0f, -1.0f, 1.0f, 0.0f, + -1.0f, 1.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f +}; + +std::array decorationQuad(QRhi *rhi) +{ + auto quad = s_decorationQuad; + if (rhi->isYUpInNDC()) { + for (std::size_t v = 3; v < quad.size(); v += 4) + quad[v] = 1.0f - quad[v]; + } + return quad; +} +} + +void RhiScreenGrabber::windowBeforeRendering() +{ + Q_ASSERT(m_window != nullptr); + + // We are in the rendering thread at this point + // And the gui thread is NOT locked + + QMutexLocker locker(&m_mutex); + + QRhi *rhi = m_window->rhi(); + if (!rhi) + return; + + if (!m_pipeline && !m_pipelineFailed) { + // A window driven by a QQuickRenderControl may not have its render target yet; retry next frame. + QRhiRenderTarget *rt = currentRenderTarget(); + QRhiRenderPassDescriptor *rpDesc = rt ? rt->renderPassDescriptor() : nullptr; + if (!rpDesc) + return; + + const auto getShader = [](const QString &fileName) -> QShader { + QFile file(fileName); + if (file.open(QIODevice::ReadOnly)) + return QShader::fromSerialized(file.readAll()); + + return {}; + }; + + QShader vertexShader = getShader(":/gammaray_quickinspector_shaders/shaders/rhi_inspector_decorations.vert.qsb"); + if (!vertexShader.isValid()) + qFatal("Could not load vertex shader"); + QShader fragmentShader = getShader(":/gammaray_quickinspector_shaders/shaders/rhi_inspector_decorations.frag.qsb"); + if (!fragmentShader.isValid()) + qFatal("Could not load fragment shader"); + + m_sampler = rhi->newSampler( + QRhiSampler::Nearest, + QRhiSampler::Nearest, + QRhiSampler::None, + QRhiSampler::Repeat, + QRhiSampler::Repeat, + QRhiSampler::Repeat); + m_sampler->create(); + + // A full screen quad. Not generated from gl_VertexIndex in the shader, GLSL 120 and + // GLSL ES 100 (OpenGL 2.1 and OpenGL ES 2 contexts) don't have gl_VertexID. + m_vertexBuffer = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(s_decorationQuad)); + m_vertexBuffer->create(); + + m_pipeline = rhi->newGraphicsPipeline(); + m_pipeline->setTopology(QRhiGraphicsPipeline::TriangleStrip); + + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings({ { 4 * sizeof(float) } }); + inputLayout.setAttributes({ { 0, 0, QRhiVertexInputAttribute::Float2, 0 }, + { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) } }); + m_pipeline->setVertexInputLayout(inputLayout); + + recreateDecorationTexture(); + + QRhiGraphicsPipeline::TargetBlend blend; + blend.enable = true; + m_pipeline->setTargetBlends({ blend }); + + m_pipeline->setShaderStages({ { QRhiShaderStage::Vertex, vertexShader }, + { QRhiShaderStage::Fragment, fragmentShader } }); + + m_pipeline->setShaderResourceBindings(m_srb); + m_pipeline->setRenderPassDescriptor(rpDesc); + m_pipeline->setSampleCount(rt->sampleCount()); + if (!m_pipeline->create()) { + // Don't retry every frame. Grabbing still works, only the decorations are missing. + qWarning() << "GammaRay: failed to create the QRhi pipeline for drawing decorations with" << rhi->backendName() + << rhi->driverInfo().deviceName; + releaseRhiResources(); + m_pipelineFailed = true; + return; + } + } else if (m_pipeline) { + // Follow window size changes. QRhi resources must only be touched on the render thread, + // so this is done here rather than from updateOverlay() (GUI thread). + recreateDecorationTexture(); + } + + if (m_decorationsEnabled && m_pipeline) { + QRhiCommandBuffer *cb = nextCommandBuffer(); + if (!cb) + return; + QRhiResourceUpdateBatch *resourceUpdates = rhi->nextResourceUpdateBatch(); + if (!resourceUpdates) + return; + + // Paint at device pixels like the OpenGL grabber, so decorations stay sharp on high-DPI screens. + QImage decorations(decorationPixelSize(), QImage::Format_ARGB32_Premultiplied); + decorations.setDevicePixelRatio(m_renderInfo.dpr); + decorations.fill(Qt::transparent); + + QPainter p(&decorations); + doDrawDecorations(p); + p.end(); + + resourceUpdates->uploadTexture(m_texture, decorations); + if (!m_vertexBufferUploaded) { + const auto quad = decorationQuad(rhi); + resourceUpdates->uploadStaticBuffer(m_vertexBuffer, quad.data()); + m_vertexBufferUploaded = true; + } + cb->resourceUpdate(resourceUpdates); + } +} + +void RhiScreenGrabber::windowAfterRenderPassRecording() +{ + Q_ASSERT(m_window != nullptr); + + // We are in the rendering thread at this point + // And the gui thread is NOT locked + + QMutexLocker locker(&m_mutex); + + // m_decorationsEnabled may have been switched on since windowBeforeRendering(), then nothing is uploaded yet. + if (m_decorationsEnabled && m_pipeline && m_vertexBufferUploaded) { + QRhiCommandBuffer *cb = nextCommandBuffer(); + if (!cb) + return; + + const QRhiRenderTarget *rt = currentRenderTarget(); + const QSize outputPixelSize = rt ? rt->pixelSize() : QSize(); + if (outputPixelSize.isEmpty()) + return; + + cb->setViewport({ 0.0f, 0.0f, static_cast(outputPixelSize.width()), static_cast(outputPixelSize.height()) }); + + cb->setGraphicsPipeline(m_pipeline); + cb->setShaderResources(); + const QRhiCommandBuffer::VertexInput vertexInput(m_vertexBuffer, 0); + cb->setVertexInput(0, 1, &vertexInput); + cb->draw(4); + } +} + +void RhiScreenGrabber::windowAfterRendering() +{ + Q_ASSERT(m_window != nullptr); + + QMutexLocker locker(&m_mutex); + + // We are in the rendering thread at this point + // And the gui thread is NOT locked + + QRhi *rhi = m_window->rhi(); + if (m_isGrabbing && rhi) { + QRhiResourceUpdateBatch *resourceUpdates = rhi->nextResourceUpdateBatch(); + bool readbackQueued = false; + if (resourceUpdates) { + if (m_window->swapChain()) { + // Read from the swapchain's back-buffer. + constexpr QRhiReadbackDescription readbackDesc; + resourceUpdates->readBackTexture(readbackDesc, &m_readback->result); + readbackQueued = true; + } else if (QRhiTexture *texture = redirectTexture()) { + // Read from the texture a QQuickRenderControl user (e.g. QQuickWidget) renders into. + const QRhiReadbackDescription readbackDesc(texture); + resourceUpdates->readBackTexture(readbackDesc, &m_readback->result); + readbackQueued = true; + } + } + + const auto cb = nextCommandBuffer(); + if (cb) { + if (readbackQueued) { + QMutexLocker readbackLocker(&m_readback->mutex); + m_readback->pending = true; + } + cb->resourceUpdate(resourceUpdates); + if (readbackQueued) { + // Wait for the readback, like QQuickWindow::grabWindow(). Backends like Vulkan + // otherwise complete it only a few frames later, which never come in a static + // scene. It also keeps the frame ahead of grabberReadyChanged(), so the next grab + // can't queue a second readback into the same result. + rhi->finish(); + } + } else if (resourceUpdates) { + resourceUpdates->release(); + } + } + + if (m_isGrabbing) { + locker.unlock(); + setGrabbingMode(false, QRectF()); + } else { + emit sceneChanged(); + } +} + +QRhiCommandBuffer *RhiScreenGrabber::nextCommandBuffer() const +{ + Q_ASSERT(m_window != nullptr); + + QRhiSwapChain *swapChain = m_window->swapChain(); + if (swapChain) + return swapChain->currentFrameCommandBuffer(); + + const auto rc = QQuickWindowPrivate::get(m_window)->renderControl; + if (rc) + return rc->commandBuffer(); + + return nullptr; +} + +QRhiRenderTarget *RhiScreenGrabber::currentRenderTarget() const +{ + Q_ASSERT(m_window != nullptr); + + if (QRhiSwapChain *swapChain = m_window->swapChain()) + return swapChain->currentFrameRenderTarget(); + + // Set by QQuickRenderControl users, including QQuickWidget. + return static_cast(m_window->rendererInterface()->getResource(m_window, QSGRendererInterface::RhiRedirectRenderTarget)); +} + +QRhiTexture *RhiScreenGrabber::redirectTexture() const +{ + Q_ASSERT(m_window != nullptr); + + auto *rt = static_cast(m_window->rendererInterface()->getResource(m_window, QSGRendererInterface::RhiRedirectRenderTarget)); + if (!rt || rt->resourceType() != QRhiResource::TextureRenderTarget) + return nullptr; + + const QRhiTextureRenderTargetDescription desc = static_cast(rt)->description(); + if (desc.colorAttachmentCount() == 0) + return nullptr; + + // With MSAA the content ends up in the resolve texture; a multisample texture or + // renderbuffer cannot be read back. + const QRhiColorAttachment *attachment = desc.colorAttachmentAt(0); + QRhiTexture *texture = attachment->resolveTexture() ? attachment->resolveTexture() : attachment->texture(); + if (!texture || texture->sampleCount() > 1) + return nullptr; + + // QRhi can only read back textures created with UsedAsTransferSource (QQuickWidget sets it). + if (!texture->flags().testFlag(QRhiTexture::UsedAsTransferSource)) + return nullptr; + return texture; +} + +QSize RhiScreenGrabber::decorationPixelSize() const +{ + return m_renderInfo.windowSize * m_renderInfo.dpr; +} + +void RhiScreenGrabber::recreateDecorationTexture() +{ + const auto rhi = m_window->rhi(); + if (!rhi) + return; + + const QSize pixelSize = decorationPixelSize(); + if (m_texture && m_texture->pixelSize() == pixelSize) + return; + + // Frames in flight may still use the old ones. + if (m_srb) + m_srb->deleteLater(); + if (m_texture) + m_texture->deleteLater(); + + m_texture = rhi->newTexture(QRhiTexture::BGRA8, pixelSize); + m_texture->create(); + + m_srb = rhi->newShaderResourceBindings(); + m_srb->setBindings({ QRhiShaderResourceBinding::sampledTexture( + 0, + QRhiShaderResourceBinding::FragmentStage, + m_texture, + m_sampler) }); + m_srb->create(); + + m_pipeline->setShaderResourceBindings(m_srb); +} + +void RhiScreenGrabber::invalidateRhiResources() +{ + // Emitted on the render thread while the QRhi still exists. + // Recreate these (and retry a failed pipeline) when RHI is available again. + QMutexLocker locker(&m_mutex); + releaseRhiResources(); + m_pipelineFailed = false; +} + +void RhiScreenGrabber::releaseRhiResources() +{ + for (QRhiResource *resource : std::initializer_list { m_pipeline, m_srb, m_texture, m_sampler, m_vertexBuffer }) { + if (resource) + resource->deleteLater(); + } + m_texture = nullptr; + m_srb = nullptr; + m_pipeline = nullptr; + m_sampler = nullptr; + m_vertexBuffer = nullptr; + m_vertexBufferUploaded = false; +} +#endif diff --git a/plugins/quickinspector/quickscreengrabber.h b/plugins/quickinspector/quickscreengrabber.h index c1e2fab26..0974dbbd8 100644 --- a/plugins/quickinspector/quickscreengrabber.h +++ b/plugins/quickinspector/quickscreengrabber.h @@ -25,6 +25,14 @@ QT_BEGIN_NAMESPACE class QQuickWindow; +class QRhiBuffer; +class QRhiCommandBuffer; +class QRhiGraphicsPipeline; +class QRhiRenderTarget; +class QRhiSampler; +class QRhiShaderResourceBindings; +class QRhiTexture; +struct QRhiReadbackResult; #ifndef QT_NO_OPENGL class QOpenGLPaintDevice; #endif @@ -92,6 +100,9 @@ class GrabbedFrame QTransform transform; QRectF itemsGeometryRect; QVector itemsGeometry; + /// QSGRendererInterface::GraphicsApi of the window. Carried here so receivers don't have to + /// query the window, which may be half destroyed when the last (empty) frame is sent. + int graphicsApi = 0; }; /** @@ -257,6 +268,75 @@ class UnsupportedScreenGrabber : public AbstractScreenGrabber QPointF m_lastItemPosition; }; +#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0) +/** + * @brief Screen grabber that uses QRhi instead of a specific graphics interface. + */ +class RhiScreenGrabber : public AbstractScreenGrabber +{ + Q_OBJECT +public: + explicit RhiScreenGrabber(QQuickWindow *window); + ~RhiScreenGrabber() override; + + void requestGrabWindow(const QRectF &userViewport) override; + +protected: + void drawDecorations() override; + +private: + void setGrabbingMode(bool isGrabbingMode, const QRectF &userViewport); + // In the order QQuickWindow emits the signals they are connected to. + void windowAfterSynchronizing(); + void windowBeforeRendering(); + void windowAfterRenderPassRecording(); + void windowAfterRendering(); + /** + * @brief Takes care of grabbing the next command buffer, either from the swapchain or the render control. + * + * @note The returned value may be null in some rare circumstances. + */ + QRhiCommandBuffer *nextCommandBuffer() const; + /** + * @brief The texture behind the render target set through QQuickRenderControl (QQuickWidget + * included), if it can be read back. Null otherwise. + */ + QRhiTexture *redirectTexture() const; + /** + * @brief The render target the window renders into this frame: the swapchain's, or the one + * set through QQuickRenderControl (QQuickWidget included). May be null. + */ + QRhiRenderTarget *currentRenderTarget() const; + /** + * @brief Re-creates the off-screen decoration texture as needed. + */ + void recreateDecorationTexture(); + /// Size of the decoration texture: the window size in device pixels. + QSize decorationPixelSize() const; + void invalidateRhiResources(); + /// Releases the pipeline, SRB, texture and sampler. Render thread only, m_mutex held. + void releaseRhiResources(); + void readbackCompleted(const QRhiReadbackResult &result); + + /** + * Readback target handed to QRhi. QRhi may still hold it and call its completion + * callback after this grabber is gone, so it is owned separately (see the destructor). + */ + struct ReadbackState; + + bool m_isGrabbing = false; + ReadbackState *m_readback = nullptr; + QMutex m_mutex; + QRhiGraphicsPipeline *m_pipeline = nullptr; + QRhiShaderResourceBindings *m_srb = nullptr; + QRhiTexture *m_texture = nullptr; + QRhiSampler *m_sampler = nullptr; + QRhiBuffer *m_vertexBuffer = nullptr; + bool m_vertexBufferUploaded = false; + bool m_pipelineFailed = false; +}; +#endif + } Q_DECLARE_METATYPE(GammaRay::GrabbedFrame) diff --git a/plugins/quickinspector/shaders/rhi_inspector_decorations.frag b/plugins/quickinspector/shaders/rhi_inspector_decorations.frag new file mode 100644 index 000000000..d94a8a914 --- /dev/null +++ b/plugins/quickinspector/shaders/rhi_inspector_decorations.frag @@ -0,0 +1,11 @@ +#version 440 + +layout(location = 0) in vec2 textureCoordinates; +layout(location = 0) out vec4 fragColor; + +layout(binding = 0) uniform sampler2D tex; + +void main() +{ + fragColor = texture(tex, textureCoordinates); +} diff --git a/plugins/quickinspector/shaders/rhi_inspector_decorations.vert b/plugins/quickinspector/shaders/rhi_inspector_decorations.vert new file mode 100644 index 000000000..380e32187 --- /dev/null +++ b/plugins/quickinspector/shaders/rhi_inspector_decorations.vert @@ -0,0 +1,12 @@ +#version 440 + +layout(location = 0) in vec2 position; +layout(location = 1) in vec2 texCoord; + +layout(location = 0) out vec2 textureCoordinates; + +void main() +{ + textureCoordinates = texCoord; + gl_Position = vec4(position, 0.0, 1.0); +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index dae7a9cb3..ec9d95238 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -561,6 +561,25 @@ if(NOT GAMMARAY_CLIENT_ONLY_BUILD) ) endif() + # The QRhi screen grabber. Needs a GPU; the tests skip themselves when Qt Quick doesn't use QRhi, + # e.g. with QT_QUICK_BACKEND=software as on the Linux CI. + if(Qt6Core_VERSION VERSION_GREATER_EQUAL "6.6.0" AND TARGET Qt::QuickWidgets) + gammaray_add_quick_test(quickrhigrabbertest quickrhigrabbertest.cpp quickinspectortest.qrc) + target_link_libraries( + quickrhigrabbertest + gammaray_core + gammaray_quickinspector_shared + Qt::Quick + Qt::QuickWidgets + Qt::GuiPrivate + ) + # the default backend is OpenGL on Linux, also run with Vulkan + if(UNIX AND NOT APPLE) + add_test(NAME quickrhigrabbertest-vulkan COMMAND quickrhigrabbertest) + set_tests_properties(quickrhigrabbertest-vulkan PROPERTIES ENVIRONMENT "QSG_RHI_BACKEND=vulkan") + endif() + endif() + gammaray_add_test( quickscenegraphmodeltest quickscenegraphmodeltest.cpp diff --git a/tests/basequicktest.h b/tests/basequicktest.h index 016df0521..19faedda1 100644 --- a/tests/basequicktest.h +++ b/tests/basequicktest.h @@ -93,6 +93,13 @@ protected slots: { return m_view.get(); } + + /// Destroys the view in the middle of a test, e.g. to test what happens while it is in use. + void destroyView() + { + m_exposed = false; + m_view.reset(); + } }; #endif // BASEQUICKTEST_H diff --git a/tests/quickrhigrabbertest.cpp b/tests/quickrhigrabbertest.cpp new file mode 100644 index 000000000..12d3603c4 --- /dev/null +++ b/tests/quickrhigrabbertest.cpp @@ -0,0 +1,431 @@ +/* + quickrhigrabbertest.cpp + + This file is part of GammaRay, the Qt application inspection and manipulation tool. + + SPDX-FileCopyrightText: 2026 Klarälvdalens Datakonsult AB, a KDAB Group company + + SPDX-License-Identifier: GPL-2.0-or-later + + Contact KDAB at for commercial licensing options. +*/ + +// Tests the QtQuick remote view with the QRhi based screen grabber (RhiScreenGrabber). +// This needs a GPU: every test skips itself when the window is not rendered through QRhi, +// e.g. with QT_QUICK_BACKEND=software as on the Linux CI. + +#include "basequicktest.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// QVulkanInstance is only defined when vulkan.h is available when building the application, +// a Vulkan enabled Qt alone is not enough +#if QT_CONFIG(vulkan) && __has_include() +#include +#define HAVE_QVULKANINSTANCE +#endif +#include + +#include + +using namespace GammaRay; + +namespace { +const char *const s_qmlFile = "qrc:/manual/rotationinvariant.qml"; // four coloured quadrants + +bool isRhiBased(QSGRendererInterface::GraphicsApi api) +{ + return QSGRendererInterface::isApiRhiBased(api); +} + +bool isRhiBased(QQuickWindow *window) +{ + return isRhiBased(window->rendererInterface()->graphicsApi()); +} + +/// The frame as the client displays it. +QImage displayedImage(const RemoteViewFrame &frame) +{ + return frame.image().transformed(frame.transform()); +} + +/// Checks the colours of rotationinvariant.qml near the four corners of @p image. +/// Sampling relative to the image size works for any device pixel ratio. +bool hasQuadrants(const QImage &image) +{ + if (image.isNull()) + return false; + const int r = image.width() - 3; + const int b = image.height() - 3; + return QColor(image.pixel(2, 2)) == QColor(255, 0, 0) + && QColor(image.pixel(r, 2)) == QColor(0, 255, 0) + && QColor(image.pixel(2, b)) == QColor(0, 0, 255) + && QColor(image.pixel(r, b)) == QColor(255, 255, 0); +} +/// The decorations of the selected top left quadrant cover all of it, and only it: they are +/// neither mirrored nor scaled. +bool decorationsOnTopLeftQuadrant(const QImage &plain, const QImage &decorated) +{ + const int w = plain.width(); + const int h = plain.height(); + for (const QPoint &p : { QPoint(w / 8, h / 8), QPoint(3 * w / 8, h / 8), QPoint(w / 8, 3 * h / 8), QPoint(3 * w / 8, 3 * h / 8) }) { + if (plain.pixel(p) == decorated.pixel(p)) { + qWarning() << "not decorated inside the selected item at" << p; + return false; + } + } + for (const QPoint &p : { QPoint(3 * w / 4, h / 4), QPoint(w / 4, 3 * h / 4), QPoint(3 * w / 4, 3 * h / 4) }) { + if (plain.pixel(p) != decorated.pixel(p)) { + qWarning() << "decorated outside the selected item at" << p; + return false; + } + } + return true; +} +} + +class QuickRhiGrabberTest : public BaseQuickTest +{ + Q_OBJECT + +private: + RemoteViewInterface *m_remoteView = nullptr; + QuickInspectorInterface *m_inspector = nullptr; + + /** + * Keeps rendering (@p render) and acknowledging received frames, as the client would, until a + * frame for which @p accept returns true arrives. Returns an invalid frame on timeout. + * Rendering continues while waiting because QRhi may only complete a readback in a later frame. + */ + RemoteViewFrame waitForFrame(const std::function &render, + const std::function &accept) + { + QSignalSpy frameSpy(m_remoteView, &RemoteViewInterface::frameUpdated); + QElapsedTimer timer; + timer.start(); + while (timer.elapsed() < 5000) { + m_remoteView->clientViewUpdated(); + render(); + QTest::qWait(20); + for (const auto &args : std::as_const(frameSpy)) { + const auto frame = args.at(0).value(); + if (frame.isValid() && accept(frame)) + return frame; + } + frameSpy.clear(); + } + return {}; + } + + RemoteViewFrame waitForViewFrame(const std::function &accept) + { + return waitForFrame([this] { view()->update(); }, accept); + } + + /// Shows rotationinvariant.qml, or skips the test when that doesn't use QRhi. + bool showRhiView() + { + // Size the content to the view rather than the other way around: Windows doesn't make a + // window as small as the 100x100 QML file, the corners would then show the window background. + view()->setResizeMode(QQuickView::SizeRootObjectToView); + view()->resize(200, 150); + if (!showSource(QString::fromLatin1(s_qmlFile))) + return false; + if (!isViewExposed() || !isRhiBased(view())) + return false; + Probe::instance()->selectObject(view()); + m_remoteView->setViewActive(true); + return true; + } + +private slots: + void initTestCase() + { + // In release builds of Qt, QRhi only reports unreleased resources with this set. + qputenv("QT_RHI_LEAK_CHECK", "1"); + } + + void init() override + { + BaseQuickTest::init(); + QTest::failOnWarning(QRegularExpression(QStringLiteral("unreleased resources"))); + QTest::failOnWarning(QRegularExpression(QStringLiteral("failed to create the QRhi pipeline"))); + + m_remoteView = ObjectBroker::object(QStringLiteral("com.kdab.GammaRay.QuickRemoteView")); + QVERIFY(m_remoteView); + m_inspector = ObjectBroker::object(); + QVERIFY(m_inspector); + m_inspector->setServerSideDecorationsEnabled(false); + } + + void cleanup() override + { + if (m_remoteView) + m_remoteView->setViewActive(false); + BaseQuickTest::cleanup(); + } + + // Swapchain readback, orientation, and the graphics API sent with the frame. + void testQuickView() + { + if (!showRhiView()) + QSKIP("The view is not exposed or not rendered through QRhi"); + + const auto frame = waitForViewFrame([](const RemoteViewFrame &) { return true; }); + QVERIFY(frame.isValid()); + QCOMPARE(frame.graphicsApi(), static_cast(view()->rendererInterface()->graphicsApi())); + + const QImage image = displayedImage(frame); + QCOMPARE(image.size(), view()->size() * view()->devicePixelRatio()); + QVERIFY(hasQuadrants(image)); + } + + // The decoration texture is recreated on the render thread and the frame follows the new size. + void testResize() + { + if (!showRhiView()) + QSKIP("The view is not exposed or not rendered through QRhi"); + QVERIFY(waitForViewFrame([](const RemoteViewFrame &) { return true; }).isValid()); + + view()->resize(160, 120); + const QSize expected = QSize(160, 120) * view()->devicePixelRatio(); + const auto frame = waitForViewFrame([&](const RemoteViewFrame &f) { + return displayedImage(f).size() == expected; + }); + QVERIFY(frame.isValid()); + QVERIFY(hasQuadrants(displayedImage(frame))); + } + + // A single change in an otherwise static scene must still reach the client. Backends like + // Vulkan complete readbacks only a few frames later, which never come without further changes. + void testStaticScene() + { + if (!showRhiView()) + QSKIP("The view is not exposed or not rendered through QRhi"); + QVERIFY(waitForViewFrame([](const RemoteViewFrame &) { return true; }).isValid()); + + auto rootItem = view()->rootObject(); + QVERIFY(rootItem); + QVERIFY(!rootItem->childItems().isEmpty()); + QSignalSpy frameSpy(m_remoteView, &RemoteViewInterface::frameUpdated); + rootItem->childItems().first()->setVisible(false); // the red top left quadrant + + // Acknowledge frames like the client, but don't render: no update() calls. + bool redGone = false; + QElapsedTimer timer; + timer.start(); + while (!redGone && timer.elapsed() < 3000) { + m_remoteView->clientViewUpdated(); + QTest::qWait(20); + for (const auto &args : std::as_const(frameSpy)) { + const QImage image = displayedImage(args.at(0).value()); + redGone = redGone || (!image.isNull() && QColor(image.pixel(2, 2)) != QColor(255, 0, 0)); + } + frameSpy.clear(); + } + QVERIFY2(redGone, "the change was not grabbed"); + } + + // With server side decorations the RHI grabber draws them into the frame; they go away again + // when disabled. + void testDecorations_data() + { + QTest::addColumn("samples"); + QTest::newRow("single sample") << 1; + // The decoration pipeline must match the sample count of the render target. + QTest::newRow("multisampled") << 4; + } + + void testDecorations() + { + QFETCH(int, samples); + if (samples > 1) { + QSurfaceFormat format = view()->format(); + format.setSamples(samples); + view()->setFormat(format); + } + if (!showRhiView()) + QSKIP("The view is not exposed or not rendered through QRhi"); + if (samples > 1 && (!view()->swapChain() || view()->swapChain()->sampleCount() < 2)) + QSKIP("No multisampled swapchain"); + + const QImage plain = displayedImage(waitForViewFrame([](const RemoteViewFrame &) { return true; })); + QVERIFY(!plain.isNull()); + + auto rootItem = view()->rootObject(); + QVERIFY(rootItem); + QVERIFY(!rootItem->childItems().isEmpty()); + Probe::instance()->selectObject(rootItem->childItems().first()); + m_inspector->setServerSideDecorationsEnabled(true); + + const auto decorated = waitForViewFrame([&](const RemoteViewFrame &f) { + const QImage image = displayedImage(f); + return image.size() == plain.size() && image != plain; + }); + QVERIFY2(decorated.isValid(), "no frame with decorations"); + QVERIFY(decorationsOnTopLeftQuadrant(plain, displayedImage(decorated))); + + m_inspector->setServerSideDecorationsEnabled(false); + const auto plainAgain = waitForViewFrame([&](const RemoteViewFrame &f) { + return displayedImage(f) == plain; + }); + QVERIFY2(plainAgain.isValid(), "decorations were not removed"); + } + + // A QQuickWidget has no swapchain; the frame is read back from the texture it renders into. + void testQuickWidget() + { + QQuickWidget widget; + widget.setResizeMode(QQuickWidget::SizeRootObjectToView); + widget.setSource(QUrl(QString::fromLatin1(s_qmlFile))); + widget.resize(120, 90); + widget.show(); + if (!QTest::qWaitForWindowExposed(&widget)) + QSKIP("The widget is not exposed"); + QQuickWindow *window = widget.quickWindow(); + if (!isRhiBased(window)) + QSKIP("The QQuickWidget is not rendered through QRhi"); + + Probe::instance()->selectObject(window); + m_remoteView->setViewActive(true); + + const QSize expected = QSize(120, 90) * widget.devicePixelRatioF(); + const auto frame = waitForFrame([window] { window->update(); }, [&](const RemoteViewFrame &f) { return displayedImage(f).size() == expected; }); + QVERIFY2(frame.isValid(), "no frame from the QQuickWidget"); + QVERIFY(hasQuadrants(displayedImage(frame))); + } + + // A window driven by a custom QQuickRenderControl that renders into its own texture. + void testRenderControl() + { + if (!isRhiBased(QQuickWindow::graphicsApi())) + QSKIP("Qt Quick does not use QRhi"); + +#ifdef HAVE_QVULKANINSTANCE + QVulkanInstance vulkanInstance; // must outlive the window +#endif + QQuickRenderControl renderControl; + QQuickWindow window(&renderControl); + if (QQuickWindow::graphicsApi() == QSGRendererInterface::Vulkan) { +#ifdef HAVE_QVULKANINSTANCE + vulkanInstance.setExtensions(QQuickGraphicsConfiguration::preferredInstanceExtensions()); + if (!vulkanInstance.create()) + QSKIP("Cannot create a Vulkan instance"); + window.setVulkanInstance(&vulkanInstance); +#else + QSKIP("Qt is built without Vulkan or vulkan.h is missing"); +#endif + } + + QQmlEngine engine; + QQmlComponent component(&engine, QUrl(QString::fromLatin1(s_qmlFile))); + std::unique_ptr rootItem(qobject_cast(component.create())); + QVERIFY(rootItem); + const QSize size(100, 100); + window.contentItem()->setSize(size); + window.setGeometry(0, 0, size.width(), size.height()); + rootItem->setParentItem(window.contentItem()); + + if (!renderControl.initialize()) + QSKIP("QQuickRenderControl::initialize() failed"); + QRhi *rhi = renderControl.rhi(); + QVERIFY(rhi); + + // Destroyed before the window and the render control (reverse declaration order). + const qreal dpr = window.effectiveDevicePixelRatio(); + const QSize pixelSize = size * dpr; + std::unique_ptr texture(rhi->newTexture(QRhiTexture::RGBA8, pixelSize, 1, + QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource)); + QVERIFY(texture->create()); + std::unique_ptr depthStencil(rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, pixelSize)); + QVERIFY(depthStencil->create()); + QRhiTextureRenderTargetDescription description { QRhiColorAttachment(texture.get()) }; + description.setDepthStencilBuffer(depthStencil.get()); + std::unique_ptr renderTarget(rhi->newTextureRenderTarget(description)); + std::unique_ptr renderPass(renderTarget->newCompatibleRenderPassDescriptor()); + renderTarget->setRenderPassDescriptor(renderPass.get()); + QVERIFY(renderTarget->create()); + + auto quickRenderTarget = QQuickRenderTarget::fromRhiRenderTarget(renderTarget.get()); + quickRenderTarget.setDevicePixelRatio(dpr); + window.setRenderTarget(quickRenderTarget); + + auto renderFrame = [&] { + renderControl.polishItems(); + renderControl.beginFrame(); + renderControl.sync(); + renderControl.render(); + renderControl.endFrame(); + }; + renderFrame(); + + Probe::instance()->selectObject(&window); + m_remoteView->setViewActive(true); + + const auto frame = waitForFrame(renderFrame, [&](const RemoteViewFrame &f) { + return displayedImage(f).size() == pixelSize; + }); + QVERIFY2(frame.isValid(), "no frame from the render control window"); + QVERIFY(hasQuadrants(displayedImage(frame))); + + // Let the inspector drop the window before it goes away. + m_remoteView->setViewActive(false); + rootItem.reset(); + } + + // Destroying the window right after a grab was rendered must not crash or leak RHI resources + // (leaks fail through failOnWarning). + void testDestroyWhileGrabbing() + { + if (!showRhiView()) + QSKIP("The view is not exposed or not rendered through QRhi"); + QVERIFY(waitForViewFrame([](const RemoteViewFrame &) { return true; }).isValid()); + + auto server = qobject_cast(m_remoteView); + QVERIFY(server); + bool grabRequested = false; + int swappedSinceRequest = 0; + QObject context; + connect(server, &RemoteViewServer::requestUpdate, &context, [&] { grabRequested = true; }); + connect(view(), &QQuickWindow::frameSwapped, &context, [&] { + if (grabRequested) + ++swappedSinceRequest; + }); + + // A grab may already be in flight from waitForViewFrame(), its request then came before we + // listened. Keep acknowledging frames and rendering until a new grab is requested. + QElapsedTimer timer; + timer.start(); + while (!grabRequested && timer.elapsed() < 5000) { + m_remoteView->clientViewUpdated(); + view()->update(); + QTest::qWait(20); + } + QVERIFY(grabRequested); + QTRY_VERIFY(swappedSinceRequest > 0); // the frame with the readback in it + + destroyView(); + QTest::qWait(200); + } +}; + +QTEST_MAIN(QuickRhiGrabberTest) + +#include "quickrhigrabbertest.moc"