• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

graphia-app / graphia / 43746057935

15 Nov 2026 06:15PM UTC coverage: 82.168% (+1.2%) from 80.934%
43746057935

push

github

timangus
CLAUDE: Add tests of mouse interaction with the graph display

13289 of 18562 branches covered (71.59%)

Branch coverage included in aggregate %.

36268 of 41750 relevant lines covered (86.87%)

408826.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.61
/source/app/rendering/graphrenderer.cpp
1
/* Copyright © 2013-2025 Tim Angus
2
 * Copyright © 2013-2025 Tom Freeman
3
 *
4
 * This file is part of Graphia.
5
 *
6
 * Graphia is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * Graphia is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with Graphia.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
#include "graphrenderer.h"
21

22
#include "graphcomponentscene.h"
23
#include "graphoverviewscene.h"
24

25
#include "app/layout/nodepositions.h"
26

27
#include "shared/utils/container.h"
28
#include "shared/utils/doasyncthen.h"
29

30
#include "app/graph/graph.h"
31
#include "shared/graph/igraphcomponent.h"
32
#include "app/maths/boundingsphere.h"
33
#include "app/graph/graphmodel.h"
34

35
#include "app/ui/graphcomponentinteractor.h"
36
#include "app/ui/graphoverviewinteractor.h"
37
#include "app/ui/selectionmanager.h"
38
#include "app/ui/visualisations/elementvisual.h"
39
#include "app/ui/visualisations/textvisual.h"
40
#include "app/ui/qml/Graphia/graphdisplay.h"
41

42
#include "shadertools.h"
43
#include "screenshotrenderer.h"
44

45
#include <QCoreApplication>
46
#include <QDebug>
47
#include <QOpenGLFramebufferObjectFormat>
48
#include <QQuickOpenGLUtils>
49
#include <QOpenGLDebugLogger>
50
#include <QQuickWindow>
51
#include <QNativeGestureEvent>
52
#include <QTextLayout>
53
#include <QBuffer>
54
#include <QFutureWatcher>
55
#include <QMouseEvent>
56
#include <QOpenGLFramebufferObject>
57
#include <QWheelEvent>
58
#include <QtGlobal>
59

60
#include <algorithm>
61
#include <array>
62
#include <chrono>
63
#include <functional>
64
#include <limits>
65
#include <utility>
66

67
using namespace Qt::Literals::StringLiterals;
68

69
template<typename Target>
70
void initialiseFromGraph(const Graph* graph, Target& target)
71
{
270 ✔
72
    for(auto componentId : graph->componentIds())
270 ✔
73
        target.onComponentAdded(graph, componentId, false);
384 ✔
74

75
    target.onGraphChanged(graph, true);
270 ✔
76
}
270 ✔
77

78
GraphRenderer::GraphRenderer(GraphModel* graphModel, CommandManager* commandManager, SelectionManager* selectionManager) :
79
    _graphModel(graphModel),
90 ✔
80
    _selectionManager(selectionManager),
90 ✔
81
    _componentRenderers(_graphModel->graph()),
90 ✔
82
    _graphOverviewScene(new GraphOverviewScene(commandManager, this)),
90 ✔
83
    _graphComponentScene(new GraphComponentScene(this)),
90 ✔
84
    _graphOverviewInteractor(new GraphOverviewInteractor(_graphModel, _graphOverviewScene, commandManager, _selectionManager, this)),
90 ✔
85
    _graphComponentInteractor(new GraphComponentInteractor(_graphModel, _graphComponentScene, commandManager, _selectionManager, this)),
90 ✔
86
    _hiddenNodes(_graphModel->graph()),
90 ✔
87
    _hiddenEdges(_graphModel->graph()),
90 ✔
88
    _layoutChanged(true),
90 ✔
89
    _performanceCounter(std::chrono::seconds(1))
90 ✔
90
{
90 ✔
91
    ShaderTools::loadShaderProgram(_debugLinesShader, u":/shaders/debuglines.vert"_s, u":/shaders/debuglines.frag"_s);
90 ✔
92

93
    _glyphMap = std::make_unique<GlyphMap>(u::pref(u"visuals/textFont"_s).toString());
90 ✔
94

95
    const auto* graph = &_graphModel->graph();
90 ✔
96

97
    connect(graph, &Graph::nodeAdded, this, &GraphRenderer::onNodeAdded, Qt::DirectConnection);
90 ✔
98
    connect(graph, &Graph::edgeAdded, this, &GraphRenderer::onEdgeAdded, Qt::DirectConnection);
90 ✔
99
    connect(graph, &Graph::nodeAddedToComponent, this, &GraphRenderer::onNodeAddedToComponent, Qt::DirectConnection);
90 ✔
100
    connect(graph, &Graph::edgeAddedToComponent, this, &GraphRenderer::onEdgeAddedToComponent, Qt::DirectConnection);
90 ✔
101
    connect(graph, &Graph::nodeMovedBetweenComponents, this, &GraphRenderer::onNodeMovedBetweenComponents, Qt::DirectConnection);
90 ✔
102
    connect(graph, &Graph::edgeMovedBetweenComponents, this, &GraphRenderer::onEdgeMovedBetweenComponents, Qt::DirectConnection);
90 ✔
103

104
    connect(graph, &Graph::graphWillChange, this, &GraphRenderer::onGraphWillChange, Qt::DirectConnection);
90 ✔
105
    connect(graph, &Graph::graphChanged, this, &GraphRenderer::onGraphChanged, Qt::DirectConnection);
90 ✔
106
    connect(graph, &Graph::componentAdded, this, &GraphRenderer::onComponentAdded, Qt::DirectConnection);
90 ✔
107

108
    connect(&_transition, &Transition::started, this, &GraphRenderer::rendererStartedTransition, Qt::DirectConnection);
90 ✔
109
    connect(&_transition, &Transition::finished, this, &GraphRenderer::rendererFinishedTransition, Qt::DirectConnection);
90 ✔
110

111
    connect(graph, &Graph::componentWillBeRemoved, this, &GraphRenderer::onComponentWillBeRemoved, Qt::DirectConnection);
90 ✔
112

113
    _screenshotRenderer = std::make_unique<ScreenshotRenderer>();
90 ✔
114
    connect(_screenshotRenderer.get(), &ScreenshotRenderer::screenshotComplete, this, &GraphRenderer::screenshotComplete);
90 ✔
115
    connect(_screenshotRenderer.get(), &ScreenshotRenderer::previewComplete, this, &GraphRenderer::previewComplete);
90 ✔
116

117
    connect(&_preferencesWatcher, &PreferencesWatcher::preferenceChanged,
90 ✔
118
        this, &GraphRenderer::onPreferenceChanged, Qt::DirectConnection);
90 ✔
119

120
    connect(_graphModel, &GraphModel::visualsWillChange, [this]
90 ✔
121
    {
132 ✔
122
        _visualsChanging = true;
132 ✔
123
        disableSceneUpdate();
132 ✔
124
    });
132 ✔
125

126
    connect(_graphModel, &GraphModel::visualsChanged, [this](
90 ✔
127
        VisualChangeFlags nodeChange, VisualChangeFlags edgeChange, VisualChangeFlags textChange)
90 ✔
128
    {
132 ✔
129
        auto textChanged = [](VisualChangeFlags change)
132 ✔
130
        {
264 ✔
131
            return Flags<VisualChangeFlags>(change).test(VisualChangeFlags::Text);
264 ✔
132
        };
264 ✔
133

134
        // Changing the font forces a visual update, and it is here that the glyphs are
135
        // rebuilt in the new font, since updateText reads every element's text, and so
136
        // must not happen alongside another visual update
137
        _glyphMap->setFontName(u::pref(u"visuals/textFont"_s).toString());
132 ✔
138

139
        if(textChanged(nodeChange) || textChanged(edgeChange) ||
132 !
140
            textChange != VisualChangeFlags::None || _glyphMap->updateRequired())
132 !
141
        {
×
142
            updateText();
×
143
        }
×
144

145
        executeOnRendererThread([this]
132 ✔
146
        {
132 ✔
147
            updateGPUData(When::Later);
132 ✔
148
            update(); // QQuickFramebufferObject::Renderer::update
132 ✔
149
        }, u"GraphRenderer::visualsChanged"_s);
132 ✔
150

151
        if(_visualsChanging.exchange(false))
132 !
152
            enableSceneUpdate();
132 ✔
153
    });
132 ✔
154

155
    _performanceCounter.setReportFn([this](float ticksPerSecond)
90 ✔
156
    {
166 ✔
157
        emit fpsChanged(ticksPerSecond);
166 ✔
158
    });
166 ✔
159

160
    u::doAsync([this, graph]
90 ✔
161
    {
90 ✔
162
        const std::unique_lock<std::mutex> lock(_initialisationMutex);
90 ✔
163

164
        // This reads the visuals, so it keeps visual updates out; not with the scene update
165
        // lock, as the frame takes that too, and it would wait here for the whole of this
166
        _graphModel->readVisuals([this, graph]
90 ✔
167
        {
90 ✔
168
            initialiseFromGraph(graph, *this);
90 ✔
169
            initialiseFromGraph(graph, *_graphOverviewScene);
90 ✔
170
            initialiseFromGraph(graph, *_graphComponentScene);
90 ✔
171

172
            // If the graph is a single component or empty, use component mode by default
173
            if(graph->numComponents() <= 1)
90 ✔
174
                switchToComponentMode("doTransition"_no);
60 ✔
175
            else
30 ✔
176
                switchToOverviewMode("doTransition"_no);
30 ✔
177

178
            updateText();
90 ✔
179
        });
90 ✔
180

181
        // Wait for the layout to have iterated at least once, so that what is
182
        // first displayed is a (partially) laid out graph, rather than every node
183
        // drawn on top of itself
184
        _layoutInitialised.wait(false);
90 ✔
185

186
    }).then([this]
90 ✔
187
    {
90 ✔
188
        emit initialised();
90 ✔
189

190
        // The initial state is disabled, so this has no complement disableSceneUpdate call
191
        enableSceneUpdate();
90 ✔
192
        update();
90 ✔
193
    });
90 ✔
194
}
90 ✔
195

196
GraphRenderer::~GraphRenderer()
197
{
90 ✔
198
    _layoutInitialised = true;
90 ✔
199
    _layoutInitialised.notify_all();
90 ✔
200

201
    const std::unique_lock<std::mutex> lock(_initialisationMutex);
90 ✔
202

203
    // Force event processing in case the above .then(...) is still to run (due to a slow init)
204
    QCoreApplication::processEvents();
90 ✔
205

206
    _FBOcomplete = false;
90 ✔
207
}
90 ✔
208

209
void GraphRenderer::createGPUGlyphData(const QString& text, const QColor& textColor, const TextAlignment& textAlignment,
210
                                    float textScale, float elementSize, const TextAnchor& anchor,
211
                                    int componentIndex, GPUGraphData* gpuGraphData)
212
{
477 ✔
213
    Q_ASSERT(gpuGraphData != nullptr);
477 !
214

215
    auto& textLayout = _textLayoutResults._layouts[text];
477 ✔
216
    Q_ASSERT(textLayout._initialised);
477 !
217

218
    const auto verticalCentre = -textLayout._xHeight * textScale * 0.5f;
477 ✔
219
    const auto top = elementSize;
477 ✔
220
    const auto bottom = (-elementSize) - (textLayout._xHeight * textScale);
477 ✔
221

222
    const auto horizontalCentre = -textLayout._width * textScale * 0.5f;
477 ✔
223
    const auto right = elementSize;
477 ✔
224
    const auto left = (-elementSize) - (textLayout._width * textScale);
477 ✔
225

226
    std::array<float, 2> baseOffset{{0.0f, 0.0f}};
477 ✔
227
    switch(textAlignment)
477 ✔
228
    {
477 ✔
229
    default:
×
230
    case TextAlignment::Right:  baseOffset = {{right,            verticalCentre}}; break;
477 !
231
    case TextAlignment::Left:   baseOffset = {{left,             verticalCentre}}; break;
×
232
    case TextAlignment::Centre: baseOffset = {{horizontalCentre, verticalCentre}}; break;
×
233
    case TextAlignment::Top:    baseOffset = {{horizontalCentre, top           }}; break;
×
234
    case TextAlignment::Bottom: baseOffset = {{horizontalCentre, bottom        }}; break;
×
235
    }
477 ✔
236

237
    for(const auto& glyph : textLayout._glyphs)
477 ✔
238
    {
477 ✔
239
        GPUGraphData::GlyphData glyphData;
477 ✔
240

241
        auto textureGlyph = _textLayoutResults._glyphs[glyph._index];
477 ✔
242

243
        glyphData._component = componentIndex;
477 ✔
244

245
        glyphData._glyphOffset[0] = baseOffset[0] + (static_cast<float>(glyph._advance) * textScale);
477 ✔
246
        glyphData._glyphOffset[1] = baseOffset[1] - ((textureGlyph._height + textureGlyph._ascent) * textScale);
477 ✔
247
        glyphData._glyphSize[0] = textureGlyph._width;
477 ✔
248
        glyphData._glyphSize[1] = textureGlyph._height;
477 ✔
249
        glyphData._glyphScale = textScale;
477 ✔
250
        glyphData._textHeight = textLayout._xHeight * textScale;
477 ✔
251

252
        glyphData._textureCoord[0] = textureGlyph._u;
477 ✔
253
        glyphData._textureCoord[1] = textureGlyph._v;
477 ✔
254
        glyphData._textureLayer = textureGlyph._layer;
477 ✔
255

256
        glyphData._anchorNodes[0] = static_cast<int>(anchor._nodeIds[0]);
477 ✔
257
        glyphData._anchorNodes[1] = static_cast<int>(anchor._nodeIds[1]);
477 ✔
258

259
        glyphData._basePosition[0] = anchor._position.x();
477 ✔
260
        glyphData._basePosition[1] = anchor._position.y();
477 ✔
261
        glyphData._basePosition[2] = anchor._position.z();
477 ✔
262

263
        glyphData._color[0] = textColor.redF();
477 ✔
264
        glyphData._color[1] = textColor.greenF();
477 ✔
265
        glyphData._color[2] = textColor.blueF();
477 ✔
266

267
        gpuGraphData->addGlyph(glyphData);
477 ✔
268
    }
477 ✔
269
}
477 ✔
270

271
void GraphRenderer::updateGPUNodePositions()
272
{
1,203 ✔
273
    auto& nodePositions = _graphModel->nodePositions();
1,203 ✔
274
    const std::unique_lock<NodePositions> nodePositionsLock(nodePositions);
1,203 ✔
275

276
    nodeGeometry().setPositions(_graphModel->graph().nodeIds(), nodePositions);
1,203 ✔
277
}
1,203 ✔
278

279
void GraphRenderer::updateGPUNodeSizes()
280
{
1,203 ✔
281
    auto& geometry = nodeGeometry();
1,203 ✔
282

283
    for(auto nodeId : _graphModel->graph().nodeIds())
1,203 ✔
284
        geometry.setSize(nodeId, _graphModel->nodeVisual(nodeId)._size);
5,276 ✔
285
}
1,203 ✔
286

287
void GraphRenderer::updateGPUDataIfRequired()
288
{
6,090 ✔
289
    const auto update = std::exchange(_pendingGPUDataUpdate, GPUDataUpdate::None);
6,090 ✔
290

291
    if(update == GPUDataUpdate::None)
6,090 ✔
292
        return;
4,887 ✔
293

294
    // Everything else follows the nodes, except shared text, which is placed
295
    // where it is created
296
    if(update == GPUDataUpdate::NodePositions && !_graphModel->hasTextVisuals())
1,203 !
297
    {
×
298
        updateGPUNodePositions();
×
299
        uploadNodeGeometry();
×
300
        return;
×
301
    }
×
302

303
    const std::unique_lock<std::recursive_mutex> glyphMapLock(_glyphMap->mutex());
1,203 ✔
304

305
    int componentIndex = 0;
1,203 ✔
306

307
    resetGPUGraphData();
1,203 ✔
308

309
    updateGPUNodePositions();
1,203 ✔
310
    updateGPUNodeSizes();
1,203 ✔
311

312
    const float textScale = u::pref(u"visuals/textSize"_s).toFloat();
1,203 ✔
313
    auto textAlignment = normaliseQmlEnum<TextAlignment>(u::pref(u"visuals/textAlignment"_s).toInt());
1,203 ✔
314
    auto showNodeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showNodeText"_s).toInt());
1,203 ✔
315
    auto showEdgeText = normaliseQmlEnum<TextState>(u::pref(u"visuals/showEdgeText"_s).toInt());
1,203 ✔
316
    auto edgeVisualType = normaliseQmlEnum<EdgeVisualType>(u::pref(u"visuals/edgeVisualType"_s).toInt());
1,203 ✔
317

318
    // Ignore the setting if the graph is undirected
319
    if(!_graphModel->directed())
1,203 !
320
        edgeVisualType = EdgeVisualType::Cylinder;
×
321

322
    class Layer
1,203 ✔
323
    {
1,203 ✔
324
    public:
1,203 ✔
325
        explicit Layer(std::function<GPUGraphData*()> claimFn) :
1,203 ✔
326
            _claimFn(std::move(claimFn))
6,738 ✔
327
        {}
6,738 ✔
328

329
        GPUGraphData* get()
1,203 ✔
330
        {
7,499 ✔
331
            if(_layer == nullptr)
7,499 ✔
332
                _layer = _claimFn();
2,707 ✔
333

334
            return _layer;
7,499 ✔
335
        }
7,499 ✔
336

337
    private:
1,203 ✔
338
        std::function<GPUGraphData*()> _claimFn;
1,203 ✔
339
        GPUGraphData* _layer = nullptr;
1,203 ✔
340
    };
1,203 ✔
341

342
    for(const auto& componentRendererRef : _componentRenderers)
1,203 ✔
343
    {
2,673 ✔
344
        const GraphComponentRenderer* componentRenderer = componentRendererRef;
2,673 ✔
345
        if(!componentRenderer->visible())
2,673 ✔
346
            continue;
427 ✔
347

348
        const float UnhighlightedAlpha = 0.22f;
2,246 ✔
349
        const float componentAlpha = componentRenderer->alpha();
2,246 ✔
350

351
        Layer highlightedLayer([this, componentAlpha]
2,246 ✔
352
            { return gpuGraphDataForAlpha(componentAlpha, 1.0f); });
2,246 ✔
353
        Layer unhighlightedLayer([this, componentAlpha, UnhighlightedAlpha]
2,246 ✔
354
            { return gpuGraphDataForAlpha(componentAlpha, UnhighlightedAlpha); });
2,246 ✔
355
        Layer textLayer([this, componentAlpha]
2,246 ✔
356
            { return gpuGraphDataForOverlay(componentAlpha); });
2,246 ✔
357

358
        auto layerFor = [&](const ElementVisual& visual)
2,246 ✔
359
        {
7,022 ✔
360
            return visual._state.test(VisualFlags::Unhighlighted) ?
7,022 !
361
                unhighlightedLayer.get() : highlightedLayer.get();
7,022 ✔
362
        };
7,022 ✔
363

364
        for(auto nodeId : componentRenderer->nodeIds())
2,246 ✔
365
        {
4,634 ✔
366
            if(_hiddenNodes.get(nodeId))
4,634 !
367
                continue;
×
368

369
            const auto& nodeVisual = _graphModel->nodeVisual(nodeId);
4,634 ✔
370

371
            // Create and add NodeData
372
            GPUGraphData::NodeData nodeData;
4,634 ✔
373
            nodeData._nodeIndex = static_cast<int>(nodeId);
4,634 ✔
374
            nodeData._component = componentIndex;
4,634 ✔
375
            nodeData._outerColor = GPUGraphData::colorFrom(nodeVisual._outerColor);
4,634 ✔
376
            nodeData._innerColor = GPUGraphData::colorFrom(nodeVisual._innerColor);
4,634 ✔
377
            nodeData._selected = nodeVisual._state.test(VisualFlags::Selected) ? 1.0f : 0.0f;
4,634 ✔
378

379
            auto* gpuGraphData = layerFor(nodeVisual);
4,634 ✔
380

381
            if(gpuGraphData != nullptr)
4,634 !
382
            {
4,634 ✔
383
                gpuGraphData->addNode(nodeData, nodeVisual._size);
4,634 ✔
384

385
                if(nodeData._selected != 0.0f)
4,634 ✔
386
                    gpuGraphData->_elementsSelected = true;
473 ✔
387

388
                if(nodeVisual._text.isEmpty())
4,634 !
389
                    continue;
×
390

391
                if(showNodeText == TextState::Off || nodeVisual._state.test(VisualFlags::Unhighlighted))
4,634 !
392
                    continue;
48 ✔
393

394
                if(showNodeText == TextState::Selected && !nodeVisual._state.test(VisualFlags::Selected))
4,586 ✔
395
                    continue;
4,109 ✔
396

397
                if(showNodeText == TextState::Focused && componentRenderer->focusNodeId() != nodeId)
477 !
398
                    continue;
×
399

400
                createGPUGlyphData(nodeVisual._text,
477 ✔
401
                    nodeVisual._textColor, textAlignment,
477 ✔
402
                    textScale * nodeVisual._textSize,
477 ✔
403
                    nodeVisual._size, TextAnchor(nodeId), componentIndex,
477 ✔
404
                    textLayer.get());
477 ✔
405
            }
477 ✔
406
        }
4,634 ✔
407

408
        for(const auto& edge : componentRenderer->edges())
2,246 ✔
409
        {
2,388 ✔
410
            if(_hiddenEdges.get(edge->id()) || _hiddenNodes.get(edge->sourceId()) || _hiddenNodes.get(edge->targetId()))
2,388 !
411
                continue;
×
412

413
            const auto& edgeVisual = _graphModel->edgeVisual(edge->id());
2,388 ✔
414

415
            GPUGraphData::EdgeData edgeData;
2,388 ✔
416
            edgeData._sourceIndex = static_cast<int>(edge->sourceId());
2,388 ✔
417
            edgeData._targetIndex = static_cast<int>(edge->targetId());
2,388 ✔
418
            edgeData._edgeType = static_cast<int>(edgeVisualType);
2,388 ✔
419
            edgeData._component = componentIndex;
2,388 ✔
420
            edgeData._size = edgeVisual._size;
2,388 ✔
421
            edgeData._outerColor = GPUGraphData::colorFrom(edgeVisual._outerColor);
2,388 ✔
422
            edgeData._innerColor = GPUGraphData::colorFrom(edgeVisual._innerColor);
2,388 ✔
423
            edgeData._selected = 0.0f;
2,388 ✔
424

425
            auto* gpuGraphData = layerFor(edgeVisual);
2,388 ✔
426

427
            if(gpuGraphData != nullptr)
2,388 !
428
            {
2,388 ✔
429
                gpuGraphData->addEdge(edgeData);
2,388 ✔
430

431
                if(edgeData._selected != 0.0f)
2,388 !
432
                    gpuGraphData->_elementsSelected = true;
×
433

434
                if(edgeVisual._text.isEmpty())
2,388 !
435
                    continue;
2,388 ✔
436

437
                if(showEdgeText == TextState::Off || edgeVisual._state.test(VisualFlags::Unhighlighted))
×
438
                    continue;
×
439

440
                if(showEdgeText == TextState::Selected && !edgeVisual._state.test(VisualFlags::Selected))
×
441
                    continue;
×
442

443
                createGPUGlyphData(edgeVisual._text,
×
444
                    edgeVisual._textColor, textAlignment,
×
445
                    textScale * edgeVisual._textSize,
×
446
                    edgeVisual._size, TextAnchor(edge->sourceId(), edge->targetId()), componentIndex,
×
447
                    textLayer.get());
×
448
            }
×
449
        }
2,388 ✔
450

451
        _graphModel->forEachTextVisual(componentRenderer->componentId(),
2,246 ✔
452
        [&](const TextVisual& textVisual)
2,246 ✔
453
        {
2,246 ✔
454
            createGPUGlyphData(textVisual._text,
×
455
                textVisual._color, textAlignment,
×
456
                textScale * textVisual._size,
×
457
                textVisual._radius, TextAnchor(textVisual._centre), componentIndex,
×
458
                textLayer.get());
×
459
        });
×
460

461
        componentIndex++;
2,246 ✔
462
    }
2,246 ✔
463

464
    uploadNodeGeometry();
1,203 ✔
465
    uploadGPUGraphData();
1,203 ✔
466
}
1,203 ✔
467

468
void GraphRenderer::updateGPUData(GraphRenderer::When when, GPUDataUpdate update)
469
{
2,262 ✔
470
    _pendingGPUDataUpdate = std::max(_pendingGPUDataUpdate, update);
2,262 ✔
471

472
    if(when == When::Now)
2,262 !
473
        updateGPUDataIfRequired();
×
474
}
2,262 ✔
475

476
void GraphRenderer::onPreviewRequested(int width, int height, bool fillSize)
477
{
×
478
    makeContextCurrent();
×
479
    _screenshotRenderer->requestPreview(*this, width, height, fillSize);
×
480
}
×
481

482
void GraphRenderer::onScreenshotRequested(int width, int height, const QString& path, int dpi, bool fillSize)
483
{
8 ✔
484
    makeContextCurrent();
8 ✔
485
    _screenshotRenderer->requestScreenshot(*this, width, height, path, dpi, fillSize);
8 ✔
486
}
8 ✔
487

488
void GraphRenderer::updateComponentGPUData()
489
{
6,090 ✔
490
    //FIXME this doesn't necessarily need to be entirely regenerated and rebuffered
491
    // every frame, so it makes sense to do partial updates as and when required.
492
    // OTOH, it's probably not ever going to be masses of data, so maybe we should
493
    // just suck it up; need to get a profiler on it and see how long we're spending
494
    // here transfering the buffer, when there are lots of components
495
    resetGPUComponentData();
6,090 ✔
496

497
    for(const auto& componentRendererRef : _componentRenderers)
6,090 ✔
498
    {
11,604 ✔
499
        GraphComponentRenderer* componentRenderer = componentRendererRef;
11,604 ✔
500
        if(componentRenderer == nullptr)
11,604 !
501
        {
×
502
            qWarning() << "null component renderer";
×
503
            continue;
×
504
        }
×
505

506
        if(!componentRenderer->visible())
11,604 ✔
507
            continue;
1,943 ✔
508

509
        appendGPUComponentData(componentRenderer->modelViewMatrix(),
9,661 ✔
510
            componentRenderer->projectionMatrix(),
9,661 ✔
511
            componentRenderer->camera()->distance(),
9,661 ✔
512
            componentRenderer->lightScale(),
9,661 ✔
513
            componentRenderer->maxDistanceFromFocus());
9,661 ✔
514
    }
9,661 ✔
515

516
    uploadGPUComponentData();
6,090 ✔
517
}
6,090 ✔
518

519
// The selection rectangle is drawn into the gathered picture, so moving it restarts gathering
520
void GraphRenderer::setSelectionRect(const QRect& selectionRect)
521
{
44 ✔
522
    if(selectionRect == _selectionRect)
44 !
523
        return;
×
524

525
    _selectionRect = selectionRect;
44 ✔
526
    restartGathering();
44 ✔
527
}
44 ✔
528

529
void GraphRenderer::setScene(Scene* scene)
530
{
112 ✔
531
    if(_scene != nullptr)
112 ✔
532
    {
22 ✔
533
        _scene->setVisible(false);
22 ✔
534
        _scene->onHide();
22 ✔
535
    }
22 ✔
536

537
    _scene = scene;
112 ✔
538

539
    _scene->setViewportSize(width(), height());
112 ✔
540

541
    _scene->setProjection(_projection);
112 ✔
542
    _scene->setVisible(true);
112 ✔
543
    _scene->onShow();
112 ✔
544
}
112 ✔
545

546
GraphRenderer::Mode GraphRenderer::mode() const
547
{
5,388 ✔
548
    return _mode;
5,388 ✔
549
}
5,388 ✔
550

551
void GraphRenderer::setMode(Mode mode)
552
{
112 ✔
553
    if(mode != _mode)
112 ✔
554
    {
82 ✔
555
        _mode = mode;
82 ✔
556
        emit modeChanged();
82 ✔
557
    }
82 ✔
558
}
112 ✔
559

560
Projection GraphRenderer::projection() const
561
{
132 ✔
562
    return _projection;
132 ✔
563
}
132 ✔
564

565
void GraphRenderer::setProjection(Projection projection)
566
{
894 ✔
567
    if(projection != _projection)
894 ✔
568
    {
8 ✔
569
        _projection = projection;
8 ✔
570

571
        if(_scene != nullptr)
8 !
572
            _scene->setProjection(projection);
8 ✔
573
    }
8 ✔
574
}
894 ✔
575

576
void GraphRenderer::resetTime()
577
{
627 ✔
578
    _time.start();
627 ✔
579
    _lastTime = 0.0f;
627 ✔
580
}
627 ✔
581

582
float GraphRenderer::secondsElapsed()
583
{
6,090 ✔
584
    const float time = static_cast<float>(_time.elapsed()) / 1000.0f;
6,090 ✔
585
    const float dTime = time - _lastTime;
6,090 ✔
586
    _lastTime = time;
6,090 ✔
587

588
    return dTime;
6,090 ✔
589
}
6,090 ✔
590

591
bool GraphRenderer::transitionActive() const
592
{
6,285 ✔
593
    return _transition.active() || _scene->transitionActive();
6,285 ✔
594
}
6,285 ✔
595

596
void GraphRenderer::moveFocusToNode(NodeId nodeId, float radius)
597
{
12 ✔
598
    if(mode() == Mode::Component)
12 ✔
599
    {
10 ✔
600
        if(!_graphComponentScene->focusedOnNodeAtRadius(nodeId, radius))
10 !
601
            rendererStartedTransition();
10 ✔
602

603
        executeOnRendererThread([this, nodeId, radius]
10 ✔
604
        {
10 ✔
605
            _graphComponentScene->moveFocusToNode(nodeId, radius);
10 ✔
606
        }, u"GraphRenderer::moveFocusToNode"_s);
10 ✔
607
    }
10 ✔
608
    else if(mode() == Mode::Overview)
2 !
609
    {
2 ✔
610
        // To focus on a node, we need to be in component mode
611
        auto componentId = _graphModel->graph().componentIdOfNode(nodeId);
2 ✔
612
        switchToComponentMode("doTransition"_yes, componentId, nodeId, radius);
2 ✔
613
    }
2 ✔
614
}
12 ✔
615

616
void GraphRenderer::moveFocusToComponent(ComponentId componentId)
617
{
12 ✔
618
    if(mode() == Mode::Component)
12 !
619
    {
12 ✔
620
        if(componentId != _graphComponentScene->componentId())
12 !
621
            rendererStartedTransition();
12 ✔
622

623
        _graphComponentScene->setComponentId(componentId, "doTransition"_yes);
12 ✔
624
    }
12 ✔
625
}
12 ✔
626

627
void GraphRenderer::moveFocusToComponents(const std::vector<ComponentId>& componentIds)
628
{
2 ✔
629
    if(mode() == Mode::Overview)
2 !
630
        _graphOverviewScene->zoomTo(componentIds);
2 ✔
631
}
2 ✔
632

633
void GraphRenderer::rendererStartedTransition()
634
{
226 ✔
635
    if(!_transitionPotentiallyInProgress)
226 ✔
636
    {
163 ✔
637
        _transitionPotentiallyInProgress = true;
163 ✔
638

639
        emit transitionStarted();
163 ✔
640
        resetTime();
163 ✔
641
    }
163 ✔
642
}
226 ✔
643

644
void GraphRenderer::rendererFinishedTransition()
645
{
195 ✔
646
    if(transitionActive())
195 ✔
647
        return;
9 ✔
648

649
    // A queued task may start the next transition of a chain
650
    if(_preUpdateExecutor.hasTasks())
186 ✔
651
    {
23 ✔
652
        _transitionFinishAwaitsTasks = true;
23 ✔
653
        update(); // QQuickFramebufferObject::Renderer::update
23 ✔
654
        return;
23 ✔
655
    }
23 ✔
656

657
    // The transition may have been initiated by changes that
658
    // require the GPU data to be updated, so ensure this is done
659
    updateGPUData(When::Later);
163 ✔
660

661
    _transitionPotentiallyInProgress = false;
163 ✔
662
    emit transitionFinished();
163 ✔
663
}
163 ✔
664

665
void GraphRenderer::sceneFinishedTransition()
666
{
44 ✔
667
    clearHiddenElements();
44 ✔
668
    updateGPUData(When::Later);
44 ✔
669
}
44 ✔
670

671
void GraphRenderer::executeOnRendererThread(DeferredExecutor::TaskFn task, const QString& description)
672
{
1,413 ✔
673
    _preUpdateExecutor.enqueue(std::move(task), description);
1,413 ✔
674
    emit taskAddedToExecutor();
1,413 ✔
675
}
1,413 ✔
676

677
// Stop the renderer thread executing any tasks until...
678
void GraphRenderer::pauseRendererThreadExecution()
679
{
16 ✔
680
    _preUpdateExecutor.pause();
16 ✔
681
}
16 ✔
682

683
// ...this is called
684
void GraphRenderer::resumeRendererThreadExecution()
685
{
212 ✔
686
    _preUpdateExecutor.resume();
212 ✔
687
}
212 ✔
688

689
bool GraphRenderer::visible() const
690
{
106 ✔
691
    return _graphOverviewScene->visible() || _graphComponentScene->visible();
106 ✔
692
}
106 ✔
693

694
void GraphRenderer::onNodeAdded(const Graph*, NodeId nodeId)
695
{
4 ✔
696
    _hiddenNodes.set(nodeId, true);
4 ✔
697
}
4 ✔
698

699
void GraphRenderer::onEdgeAdded(const Graph*, EdgeId edgeId)
700
{
8 ✔
701
    _hiddenEdges.set(edgeId, true);
8 ✔
702
}
8 ✔
703

704
void GraphRenderer::onNodeAddedToComponent(const Graph*, NodeId nodeId, ComponentId)
705
{
4 ✔
706
    _hiddenNodes.set(nodeId, true);
4 ✔
707
}
4 ✔
708

709
void GraphRenderer::onEdgeAddedToComponent(const Graph*, EdgeId edgeId, ComponentId)
710
{
8 ✔
711
    _hiddenEdges.set(edgeId, true);
8 ✔
712
}
8 ✔
713

714
void GraphRenderer::onNodeMovedBetweenComponents(const Graph*, NodeId nodeId, ComponentId, ComponentId)
715
{
×
716
    _hiddenNodes.set(nodeId, true);
×
717
}
×
718

719
void GraphRenderer::onEdgeMovedBetweenComponents(const Graph*, EdgeId edgeId, ComponentId, ComponentId)
720
{
×
721
    _hiddenEdges.set(edgeId, true);
×
722
}
×
723

724
void GraphRenderer::finishTransitionToOverviewMode(NamedBool<"doTransition"> doTransition,
725
    const std::vector<ComponentId>& focusComponentIds)
726
{
36 ✔
727
    // If component mode has a queued transition nodeId, cancel the switch to overview
728
    if(_graphComponentScene->performQueuedTransition())
36 !
729
        return;
×
730

731
    setMode(GraphRenderer::Mode::Overview);
36 ✔
732
    setScene(_graphOverviewScene);
36 ✔
733
    setInteractor(_graphOverviewInteractor);
36 ✔
734

735
    _graphOverviewScene->resetView("doTransition"_no);
36 ✔
736

737
    if(doTransition)
36 ✔
738
    {
6 ✔
739
        // When we first change to overview mode we want all
740
        // the renderers to be in their reset state
741
        for(auto componentId : _graphModel->graph().componentIds())
6 ✔
742
        {
14 ✔
743
            auto* renderer = componentRendererForId(componentId);
14 ✔
744
            renderer->resetView();
14 ✔
745
        }
14 ✔
746

747
        _graphOverviewScene->startTransitionFromComponentMode(
6 ✔
748
            _graphComponentScene->componentId(), focusComponentIds);
6 ✔
749
    }
6 ✔
750

751
    updateGPUData(When::Later);
36 ✔
752
}
36 ✔
753

754
void GraphRenderer::finishTransitionToOverviewModeOnRendererThread(NamedBool<"doTransition"> doTransition,
755
    const std::vector<ComponentId>& focusComponentIds)
756
{
6 ✔
757
    executeOnRendererThread([this, doTransition, focusComponentIds]
6 ✔
758
    {
6 ✔
759
        finishTransitionToOverviewMode(doTransition, focusComponentIds);
6 ✔
760
    }, u"GraphRenderer::finishTransitionToOverviewMode"_s);
6 ✔
761
}
6 ✔
762

763
void GraphRenderer::finishTransitionToComponentMode(NamedBool<"doTransition"> doTransition)
764
{
76 ✔
765
    setMode(GraphRenderer::Mode::Component);
76 ✔
766
    setScene(_graphComponentScene);
76 ✔
767
    setInteractor(_graphComponentInteractor);
76 ✔
768

769
    if(doTransition)
76 ✔
770
    {
12 ✔
771
        // Go back to where we were before
772
        _graphComponentScene->startTransition().then([this] { _graphComponentScene->performQueuedTransition(); });
12 ✔
773
        _graphComponentScene->restoreViewData();
12 ✔
774
    }
12 ✔
775

776
    updateGPUData(When::Later);
76 ✔
777
}
76 ✔
778

779
void GraphRenderer::finishTransitionToComponentModeOnRendererThread(NamedBool<"doTransition"> doTransition)
780
{
16 ✔
781
    executeOnRendererThread([this, doTransition]
16 ✔
782
    {
16 ✔
783
        finishTransitionToComponentMode(doTransition);
16 ✔
784
    }, u"GraphRenderer::finishTransitionToComponentMode"_s);
16 ✔
785
}
16 ✔
786

787
void GraphRenderer::switchToOverviewMode(NamedBool<"doTransition"> doTransition, const std::vector<ComponentId>& focusComponentIds)
788
{
36 ✔
789
    // Refuse to switch to overview mode if there is nothing to display
790
    if(_graphModel->graph().numComponents() <= 1)
36 !
791
        return;
×
792

793
    doTransition = doTransition && mode() != GraphRenderer::Mode::Overview &&
36 !
794
        _graphComponentScene->componentRenderer() != nullptr;
36 !
795

796
    if(doTransition)
36 ✔
797
        rendererStartedTransition();
6 ✔
798

799
    executeOnRendererThread([this, doTransition, focusComponentIds]
36 ✔
800
    {
36 ✔
801
        // So that we can return to the current view parameters later
802
        _graphComponentScene->saveViewData();
36 ✔
803

804
        if(doTransition)
36 ✔
805
        {
6 ✔
806
            _graphComponentScene->clearQueuedTransition();;
6 ✔
807

808
            auto doPostViewResetTransition = [this, focusComponentIds]
6 ✔
809
            {
6 ✔
810
                sceneFinishedTransition();
2 ✔
811
                _transition.willBeImmediatelyReused();
2 ✔
812
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
2 ✔
813
            };
2 ✔
814

815
            if(!_graphComponentScene->viewIsReset())
6 ✔
816
            {
2 ✔
817
                _graphComponentScene->startTransition().then(doPostViewResetTransition);
2 ✔
818
                _graphComponentScene->resetView("doTransition"_no);
2 ✔
819
            }
2 ✔
820
            else if(_graphComponentScene->transitionActive())
4 !
821
            {
×
822
                // The view reset transition is still in progress but our ultimate
823
                // target has (potentially) changed
824
                _transition.alternativeThen(doPostViewResetTransition);
×
825
            }
×
826
            else
4 ✔
827
                finishTransitionToOverviewModeOnRendererThread("doTransition"_yes, focusComponentIds);
4 ✔
828
        }
6 ✔
829
        else
30 ✔
830
            finishTransitionToOverviewMode("doTransition"_no, focusComponentIds);
30 ✔
831

832
    }, u"GraphRenderer::switchToOverviewMode"_s);
36 ✔
833
}
36 ✔
834

835
void GraphRenderer::switchToComponentMode(NamedBool<"doTransition"> doTransition, ComponentId componentId, NodeId nodeId, float radius)
836
{
76 ✔
837
    doTransition = doTransition && mode() != GraphRenderer::Mode::Component;
76 !
838

839
    if(doTransition)
76 ✔
840
        rendererStartedTransition();
16 ✔
841

842
    executeOnRendererThread([this, componentId, nodeId, radius, doTransition]
76 ✔
843
    {
76 ✔
844
        _graphComponentScene->setComponentId(componentId);
76 ✔
845

846
        if(doTransition)
76 ✔
847
        {
16 ✔
848
            _graphOverviewScene->startTransitionToComponentMode(_graphComponentScene->componentId()).then(
16 ✔
849
            [this, componentId, nodeId, radius]
16 ✔
850
            {
16 ✔
851
                if(!nodeId.isNull())
16 ✔
852
                {
12 ✔
853
                    Q_ASSERT(_graphModel->graph().componentIdOfNode(nodeId) == componentId);
12 !
854
                    componentRendererForId(componentId)->moveSavedFocusToNode(nodeId, radius);
12 ✔
855
                }
12 ✔
856

857
                if(!_graphComponentScene->savedViewIsReset())
16 ✔
858
                {
12 ✔
859
                    _transition.willBeImmediatelyReused();
12 ✔
860
                    finishTransitionToComponentModeOnRendererThread("doTransition"_yes);
12 ✔
861
                }
12 ✔
862
                else
4 ✔
863
                    finishTransitionToComponentModeOnRendererThread("doTransition"_no);
4 ✔
864
            });
16 ✔
865
        }
16 ✔
866
        else
60 ✔
867
            finishTransitionToComponentMode("doTransition"_no);
60 ✔
868

869
    }, u"GraphRenderer::switchToComponentMode"_s);
76 ✔
870
}
76 ✔
871

872
void GraphRenderer::onGraphWillChange(const Graph* graph)
873
{
16 ✔
874
    pauseRendererThreadExecution();
16 ✔
875

876
    // Hide any graph elements that are merged; they aren't displayed normally,
877
    // but during scene transitions they may become unmerged, and we don't want
878
    // to show them until the scene transition is over
879
    for(const NodeId nodeId : graph->nodeIds())
16 ✔
880
    {
52 ✔
881
        if(graph->typeOf(nodeId) == MultiElementType::Tail)
52 !
882
            _hiddenNodes.set(nodeId, true);
×
883
    }
52 ✔
884

885
    for(const EdgeId edgeId : graph->edgeIds())
16 ✔
886
    {
24 ✔
887
        if(graph->typeOf(edgeId) == MultiElementType::Tail)
24 !
888
            _hiddenEdges.set(edgeId, true);
×
889
    }
24 ✔
890
}
16 ✔
891

892
void GraphRenderer::onGraphChanged(const Graph* graph, bool changed)
893
{
106 ✔
894
    if(!changed)
106 !
895
        return;
×
896

897
    _numComponents = graph->numComponents();
106 ✔
898

899
    // We may not, in fact, subsequently actually start a transition here, but we
900
    // speculatively pretend we do so that if a command is currently in progress
901
    // there is some overlap between it and the renderer transition. This ensures
902
    // that Document::busy() returns true for the duration of the transaction.
903
    if(visible())
106 ✔
904
        rendererStartedTransition();
16 ✔
905

906
    executeOnRendererThread([this]
106 ✔
907
    {
106 ✔
908
        for(const ComponentId componentId : _graphModel->graph().componentIds())
106 ✔
909
        {
152 ✔
910
            componentRendererForId(componentId)->initialise(_graphModel, componentId,
152 ✔
911
                                                            _selectionManager, this);
152 ✔
912
        }
152 ✔
913
        updateGPUData(When::Later);
106 ✔
914
    }, u"GraphRenderer::onGraphChanged update"_s);
106 ✔
915
}
106 ✔
916

917
void GraphRenderer::onComponentAdded(const Graph*, ComponentId componentId, bool)
918
{
132 ✔
919
    Q_ASSERT(!componentId.isNull());
132 !
920

921
    // If the component is entirely new, we shouldn't be hiding any of it
922
    const auto* component = _graphModel->graph().componentById(componentId);
132 ✔
923
    for(const NodeId nodeId : component->nodeIds())
132 ✔
924
        _hiddenNodes.set(nodeId, false);
318 ✔
925
    for(const EdgeId edgeId : component->edgeIds())
132 ✔
926
        _hiddenEdges.set(edgeId, false);
186 ✔
927

928
    executeOnRendererThread([this, componentId]
132 ✔
929
    {
132 ✔
930
        componentRendererForId(componentId)->initialise(_graphModel, componentId,
132 ✔
931
                                                        _selectionManager, this);
132 ✔
932
    }, u"GraphRenderer::onComponentAdded"_s);
132 ✔
933
}
132 ✔
934

935
void GraphRenderer::onComponentWillBeRemoved(const Graph*, ComponentId componentId, bool)
936
{
8 ✔
937
    executeOnRendererThread([this, componentId]
8 ✔
938
    {
8 ✔
939
        componentRendererForId(componentId)->cleanup();
8 ✔
940
    }, u"GraphRenderer::onComponentWillBeRemoved (cleanup) component %1"_s.arg(static_cast<int>(componentId)));
8 ✔
941
}
8 ✔
942

943
void GraphRenderer::onPreferenceChanged(const QString& key, const QVariant&)
944
{
6 ✔
945
    if(key == u"visuals/backgroundColor"_s || key == u"visuals/enableAntialiasing"_s ||
6 !
946
        key == u"visuals/improveStaticImages"_s || key == u"visuals/ambientOcclusion"_s ||
6 !
947
        key.startsWith(u"debug/"_s))
6 !
948
    {
×
949
        update();
×
950
    }
×
951
}
6 ✔
952

953
void GraphRenderer::onCommandsStarted()
954
{
242 ✔
955
    disableSceneUpdate();
242 ✔
956
}
242 ✔
957

958
void GraphRenderer::onCommandsFinished()
959
{
242 ✔
960
    enableSceneUpdate();
242 ✔
961
    update();
242 ✔
962
}
242 ✔
963

964
void GraphRenderer::onLayoutInitialised()
965
{
90 ✔
966
    _layoutInitialised = true;
90 ✔
967
    _layoutInitialised.notify_one();
90 ✔
968
}
90 ✔
969

970
void GraphRenderer::onLayoutChanged()
971
{
942 ✔
972
    _layoutChanged = true;
942 ✔
973
}
942 ✔
974

975
void GraphRenderer::onComponentAlphaChanged(ComponentId)
976
{
1,223 ✔
977
    updateGPUData(When::Later);
1,223 ✔
978
}
1,223 ✔
979

980
void GraphRenderer::onComponentCleanup(ComponentId)
981
{
8 ✔
982
    updateGPUData(When::Later);
8 ✔
983
}
8 ✔
984

985
void GraphRenderer::onVisibilityChanged()
986
{
294 ✔
987
    updateGPUData(When::Later);
294 ✔
988
}
294 ✔
989

990
GLuint GraphRenderer::sdfTexture() const
991
{
1,018 ✔
992
    return _sdfTexture.front();
1,018 ✔
993
}
1,018 ✔
994

995
QSize GraphRenderer::sdfTextureSize() const
996
{
8 ✔
997
    return _sdfTextureSize;
8 ✔
998
}
8 ✔
999

1000
void GraphRenderer::updateText()
1001
{
90 ✔
1002
    const std::unique_lock<std::recursive_mutex> lock(_glyphMap->mutex());
90 ✔
1003

1004
    for(auto nodeId : _graphModel->graph().nodeIds())
90 ✔
1005
        _glyphMap->addText(_graphModel->nodeVisual(nodeId)._text);
314 ✔
1006

1007
    for(auto edgeId : _graphModel->graph().edgeIds())
90 ✔
1008
        _glyphMap->addText(_graphModel->edgeVisual(edgeId)._text);
186 ✔
1009

1010
    _graphModel->forEachTextVisual([this](const TextVisual& textVisual)
90 ✔
1011
    {
90 ✔
1012
        _glyphMap->addText(textVisual._text);
×
1013
    });
×
1014

1015
    if(_glyphMap->updateRequired())
90 !
1016
    {
90 ✔
1017
        _glyphMap->update();
90 ✔
1018

1019
        executeOnRendererThread([this]
90 ✔
1020
        {
90 ✔
1021
            _sdfTextureSize = renderSdfTexture(*_glyphMap, _sdfTexture.back());
90 ✔
1022
            _sdfTexture.swap();
90 ✔
1023
            _textLayoutResults = _glyphMap->results();
90 ✔
1024

1025
            updateGPUData(When::Later);
90 ✔
1026
            update(); // QQuickFramebufferObject::Renderer::update
90 ✔
1027
        }, u"GraphRenderer::updateText"_s);
90 ✔
1028
    }
90 ✔
1029
}
90 ✔
1030

1031
void GraphRenderer::resetView()
1032
{
90 ✔
1033
    if(_scene != nullptr)
90 !
1034
        _scene->resetView();
90 ✔
1035
}
90 ✔
1036

1037
bool GraphRenderer::viewIsReset() const
1038
{
894 ✔
1039
    if(_scene != nullptr)
894 ✔
1040
        return _scene->viewIsReset();
714 ✔
1041

1042
    return true;
180 ✔
1043
}
894 ✔
1044

1045
void GraphRenderer::processEventQueue()
1046
{
6,090 ✔
1047
    while(!_eventQueue.empty())
6,394 ✔
1048
    {
304 ✔
1049
        auto e = std::move(_eventQueue.front());
304 ✔
1050
        _eventQueue.pop();
304 ✔
1051

1052
        // You might expect mouse button events to be delivered as QMouseEvents,
1053
        // and for the most part they are, except when a touchscreen device is
1054
        // used to generate them, specifically a touchscreen laptop. Under this
1055
        // regime, we seem to only get QSinglePointEvents. This is a base for
1056
        // QMouseEvent, so we get the same information we need for both cases.
1057
        auto* singlePointEvent = dynamic_cast<QSinglePointEvent*>(e.get());
304 ✔
1058
        auto* wheelEvent = dynamic_cast<QWheelEvent*>(e.get());
304 ✔
1059
        auto* nativeEvent = dynamic_cast<QNativeGestureEvent*>(e.get());
304 ✔
1060

1061
        switch(e->type())
304 ✔
1062
        {
304 ✔
1063
        case QEvent::Type::MouseButtonPress:
68 ✔
1064
            Q_ASSERT(singlePointEvent != nullptr);
68 !
1065
            _interactor->mousePressEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
68 ✔
1066
                singlePointEvent->modifiers(), singlePointEvent->button());
68 ✔
1067

1068
            break;
68 ✔
1069

1070
        case QEvent::Type::MouseButtonRelease:
68 ✔
1071
            Q_ASSERT(singlePointEvent != nullptr);
68 !
1072
            _interactor->mouseReleaseEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
68 ✔
1073
                singlePointEvent->modifiers(), singlePointEvent->button());
68 ✔
1074

1075
            break;
68 ✔
1076

1077
        case QEvent::Type::MouseMove:
100 ✔
1078
            Q_ASSERT(singlePointEvent != nullptr);
100 !
1079
            _interactor->mouseMoveEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
100 ✔
1080
                singlePointEvent->modifiers(), singlePointEvent->button());
100 ✔
1081

1082
            break;
100 ✔
1083

1084
        case QEvent::Type::MouseButtonDblClick:
20 ✔
1085
            Q_ASSERT(singlePointEvent != nullptr);
20 !
1086
            _interactor->mouseDoubleClickEvent(singlePointEvent->position().toPoint() * _devicePixelRatio,
20 ✔
1087
                singlePointEvent->modifiers(), singlePointEvent->button());
20 ✔
1088

1089
            break;
20 ✔
1090

1091
        case QEvent::Type::Wheel:
44 ✔
1092
            Q_ASSERT(wheelEvent != nullptr);
44 !
1093
            switch(wheelEvent->deviceType())
44 ✔
1094
            {
44 ✔
1095
            case QInputDevice::DeviceType::Mouse:
4 ✔
1096
                _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
4 ✔
1097
                    wheelEvent->angleDelta().y());
4 ✔
1098
                break;
4 ✔
1099

1100
            case QInputDevice::DeviceType::TouchScreen:
×
1101
            case QInputDevice::DeviceType::TouchPad:
40 ✔
1102
            {
40 ✔
1103
                if(u::pref(u"misc/panGestureZooms"_s).toBool())
40 !
1104
                {
×
1105
                    _interactor->wheelEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
×
1106
                        wheelEvent->angleDelta().y());
×
1107
                }
×
1108
                else
40 ✔
1109
                {
40 ✔
1110
                    _interactor->panGestureEvent(wheelEvent->position().toPoint() * _devicePixelRatio,
40 ✔
1111
                        -wheelEvent->pixelDelta() * _devicePixelRatio);
40 ✔
1112
                }
40 ✔
1113

1114
                break;
40 ✔
1115
            }
×
1116

1117
            default: break;
×
1118
            }
44 ✔
1119

1120
            break;
44 ✔
1121

1122
        case QEvent::Type::NativeGesture:
44 ✔
1123
            Q_ASSERT(nativeEvent != nullptr);
4 !
1124
            if(nativeEvent->gestureType() == Qt::ZoomNativeGesture)
4 !
1125
            {
4 ✔
1126
                _interactor->zoomGestureEvent(
4 ✔
1127
                    nativeEvent->position().toPoint() * _devicePixelRatio,
4 ✔
1128
                    static_cast<float>(nativeEvent->value()));
4 ✔
1129
            }
4 ✔
1130

1131
            break;
4 ✔
1132

1133
        default: break;
×
1134
        }
304 ✔
1135
    }
304 ✔
1136
}
6,090 ✔
1137

1138
void GraphRenderer::updateScene()
1139
{
6,465 ✔
1140
    ifSceneUpdateEnabled([this]
6,465 ✔
1141
    {
6,465 ✔
1142
        _preUpdateExecutor.execute();
6,176 ✔
1143

1144
        if(std::exchange(_transitionFinishAwaitsTasks, false))
6,176 ✔
1145
            rendererFinishedTransition();
23 ✔
1146
    });
6,176 ✔
1147

1148
    if(_scene == nullptr)
6,465 ✔
1149
        return;
180 ✔
1150

1151
    if(_resized)
6,285 ✔
1152
    {
90 ✔
1153
        _scene->setViewportSize(width(), height());
90 ✔
1154
        _resized = false;
90 ✔
1155
    }
90 ✔
1156

1157
    ifSceneUpdateEnabled([this]
6,285 ✔
1158
    {
6,285 ✔
1159
        processEventQueue();
6,090 ✔
1160

1161
        // _synchronousLayoutChanged can only ever be (atomically) true in this scope
1162
        _synchronousLayoutChanged = _layoutChanged.exchange(false);
6,090 ✔
1163

1164
        // If there is a transition active then we'll need another
1165
        // frame once we're finished with this one
1166
        if(transitionActive())
6,090 ✔
1167
            update(); // QQuickFramebufferObject::Renderer::update
5,549 ✔
1168

1169
        const float dTime = secondsElapsed();
6,090 ✔
1170
        _transition.update(dTime);
6,090 ✔
1171
        _scene->update(dTime);
6,090 ✔
1172

1173
        if(layoutChanged())
6,090 ✔
1174
            updateGPUData(When::Later, GPUDataUpdate::NodePositions);
90 ✔
1175

1176
        updateGPUDataIfRequired();
6,090 ✔
1177
        updateComponentGPUData();
6,090 ✔
1178

1179
        _synchronousLayoutChanged = false;
6,090 ✔
1180
    });
6,090 ✔
1181

1182
    if(!_FBOcomplete)
6,285 !
1183
    {
×
1184
        qWarning() << "Attempting to render without a complete FBO";
×
1185
        return;
×
1186
    }
×
1187
}
6,285 ✔
1188

1189
GraphRenderer::Mode GraphRenderer::bestFocusParameters(GraphDisplay* graphDisplay,
1190
    ComponentIdSet& componentIds, NodeId& focusNodeId, float& radius) const
1191
{
894 ✔
1192
    radius = 0.0f;
894 ✔
1193
    focusNodeId = {};
894 ✔
1194

1195
    auto nodeIds = graphDisplay->desiredFocusNodeIds();
894 ✔
1196

1197
    // Tail nodes aren't visible, so they can't be focused
1198
    std::erase_if(nodeIds, [this](auto nodeId)
894 ✔
1199
    {
894 ✔
1200
        return _graphModel->graph().typeOf(nodeId) == MultiElementType::Tail;
20 ✔
1201
    });
20 ✔
1202

1203
    if(nodeIds.empty())
894 ✔
1204
        return mode();
878 ✔
1205

1206
    if(nodeIds.size() == 1)
16 ✔
1207
    {
12 ✔
1208
        radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
12 ✔
1209
        focusNodeId = nodeIds.front();
12 ✔
1210
        return Mode::Component;
12 ✔
1211
    }
12 ✔
1212

1213
    for(auto nodeId : nodeIds)
4 ✔
1214
        componentIds.insert(_graphModel->graph().componentIdOfNode(nodeId));
8 ✔
1215

1216
    if(componentIds.size() > 1)
4 !
1217
    {
4 ✔
1218
        // We want to focus on multiple nodes, but they span multiple components
1219
        if(mode() == Mode::Component && u::pref(u"misc/stayInComponentMode"_s).toBool())
4 !
1220
        {
×
1221
            // Prune the nodeIds we consider for focus down to only those in the focused component
1222
            auto focusedComponentId = _graphComponentScene->componentId();
×
1223

1224
            std::erase_if(nodeIds, [this, focusedComponentId](auto nodeId)
×
1225
            {
×
1226
                return _graphModel->graph().componentIdOfNode(nodeId) != focusedComponentId;
×
1227
            });
×
1228
        }
×
1229
        else
4 ✔
1230
            return Mode::Overview;
4 ✔
1231
    }
4 ✔
1232

1233
    // None of the nodes are in the currently focused component
1234
    if(nodeIds.empty())
×
1235
        return Mode::Overview;
×
1236

1237
    // If the request is for more than 1 node, then find their barycentre and
1238
    // pick the closest node to where ever this happens to be
1239
    std::vector<QVector3D> points;
×
1240
    points.reserve(nodeIds.size());
×
1241
    for(auto nodeId : nodeIds)
×
1242
    {
×
1243
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1244
        points.push_back(nodePosition);
×
1245
    }
×
1246

1247
    const BoundingSphere boundingSphere(points);
×
1248
    const QVector3D centre = boundingSphere.centre();
×
1249
    float minDistance = std::numeric_limits<float>::max();
×
1250
    NodeId closestToCentreNodeId;
×
1251
    for(auto nodeId : nodeIds)
×
1252
    {
×
1253
        auto nodePosition = _graphModel->nodePositions().get(nodeId);
×
1254
        const float distance = (centre - nodePosition).length();
×
1255

1256
        if(distance < minDistance)
×
1257
        {
×
1258
            minDistance = distance;
×
1259
            closestToCentreNodeId = nodeId;
×
1260
        }
×
1261
    }
×
1262

1263
    radius = GraphComponentRenderer::maxNodeDistanceFromPoint(*_graphModel,
×
1264
        _graphModel->nodePositions().get(closestToCentreNodeId), nodeIds);
×
1265
    focusNodeId = closestToCentreNodeId;
×
1266

1267
    return mode();
×
1268
}
×
1269

1270
QOpenGLFramebufferObject* GraphRenderer::createFramebufferObject(const QSize& size)
1271
{
90 ✔
1272
    // Piggy back our FBO resize on to Qt's
1273
    _FBOcomplete = resize(size.width(), size.height());
90 ✔
1274
    _resized = true;
90 ✔
1275

1276
    return new QOpenGLFramebufferObject(size);
90 ✔
1277
}
90 ✔
1278

1279
void GraphRenderer::render()
1280
{
6,465 ✔
1281
    if(!_FBOcomplete)
6,465 !
1282
    {
×
1283
        qWarning() << "Attempting to render incomplete FBO";
×
1284
        return;
×
1285
    }
×
1286

1287
    // Read each frame, so that changing them takes effect at once
1288
    const bool antialiasing = u::pref(u"visuals/enableAntialiasing"_s).toBool();
6,465 ✔
1289
    setAntialiasing(antialiasing);
6,465 ✔
1290
    // The selection rectangle is drawn into each frame, so nothing is gathered under it
1291
    setGatherWhenStill(antialiasing && u::pref(u"visuals/improveStaticImages"_s).toBool() && _selectionRect.isNull());
6,465 !
1292
    setAmbientOcclusionMode(normaliseQmlEnum<AmbientOcclusionMode>(u::pref(u"visuals/ambientOcclusion"_s).toInt()));
6,465 ✔
1293
    setDetailLevels({
6,465 ✔
1294
        ._tracedNodes = u::pref(u"debug/tracedNodes"_s).toBool(),
6,465 ✔
1295
        ._splattedNodes = u::pref(u"debug/splattedNodes"_s).toBool(),
6,465 ✔
1296
        ._tracedEdges = u::pref(u"debug/tracedEdges"_s).toBool(),
6,465 ✔
1297
        ._approximateTracedEdges = u::pref(u"debug/approximateTracedEdges"_s).toBool(),
6,465 ✔
1298
        ._splattedEdges = u::pref(u"debug/splattedEdges"_s).toBool(),
6,465 ✔
1299
        ._fastSplattedEdges = u::pref(u"debug/fastSplattedEdges"_s).toBool(),
6,465 ✔
1300
    });
6,465 ✔
1301

1302
    updateScene();
6,465 ✔
1303

1304
    QQuickOpenGLUtils::resetOpenGLState();
6,465 ✔
1305
    glViewport(0, 0, width(), height());
6,465 ✔
1306

1307
    auto renderFrame = [this]
6,465 ✔
1308
    {
6,465 ✔
1309
        renderGraph();
6,465 ✔
1310
        render2D(_selectionRect);
6,465 ✔
1311
        compositeInto(framebufferObject()->handle());
6,465 ✔
1312
    };
6,465 ✔
1313

1314
    if(nextFrameIsSample())
6,465 !
1315
    {
×
1316
        // Gather several frames at once
1317
        // cppcheck-suppress knownConditionTrueFalse
1318
        for(int i = 0; i < 4 && nextFrameIsSample(); i++)
×
1319
            renderFrame();
×
1320
    }
×
1321
    else
6,465 ✔
1322
        renderFrame();
6,465 ✔
1323

1324
    // Nothing asks for a frame once the image is static, so force an update if necessary
1325
    if(gathering() || handingOver())
6,465 !
1326
        update(); // QQuickFramebufferObject::Renderer::update
×
1327

1328
    QQuickOpenGLUtils::resetOpenGLState();
6,465 ✔
1329

1330
    _performanceCounter.tick();
6,465 ✔
1331
}
6,465 ✔
1332

1333
void GraphRenderer::synchronize(QQuickFramebufferObject* item)
1334
{
894 ✔
1335
    _devicePixelRatio = item->window()->devicePixelRatio();
894 ✔
1336
    setOutlineScale(static_cast<float>(_devicePixelRatio));
894 ✔
1337

1338
    auto* graphDisplay = qobject_cast<GraphDisplay*>(item);
894 ✔
1339

1340
    if(graphDisplay->viewResetPending())
894 ✔
1341
        resetView();
90 ✔
1342

1343
    if(graphDisplay->overviewModeSwitchPending())
894 !
1344
        switchToOverviewMode();
×
1345

1346
    setProjection(graphDisplay->projection());
894 ✔
1347
    setShading(graphDisplay->projection() == Projection::TwoDee ?
894 ✔
1348
        graphDisplay->shading2D() : graphDisplay->shading3D());
882 ✔
1349

1350
    ComponentIdSet componentIds;
894 ✔
1351
    NodeId focusNodeId;
894 ✔
1352
    float radius = GraphComponentRenderer::COMFORTABLE_ZOOM_RADIUS;
894 ✔
1353
    auto targetMode = bestFocusParameters(graphDisplay, componentIds, focusNodeId, radius);
894 ✔
1354
    const ComponentId focusComponentId = graphDisplay->desiredFocusComponentId();
894 ✔
1355

1356
    if(mode() == Mode::Component && targetMode == Mode::Overview)
894 ✔
1357
        switchToOverviewMode("doTransition"_yes, u::vectorFrom(componentIds));
2 ✔
1358
    else if(!focusNodeId.isNull())
892 ✔
1359
        moveFocusToNode(focusNodeId, radius);
12 ✔
1360
    else if(!focusComponentId.isNull())
880 ✔
1361
    {
12 ✔
1362
        if(mode() == Mode::Overview)
12 !
1363
            switchToComponentMode("doTransition"_yes, focusComponentId);
×
1364
        else
12 ✔
1365
            moveFocusToComponent(focusComponentId);
12 ✔
1366
    }
12 ✔
1367
    else if(mode() == Mode::Overview && !componentIds.empty())
868 ✔
1368
        moveFocusToComponents(u::vectorFrom(componentIds));
2 ✔
1369

1370
    ifSceneUpdateEnabled([this, &graphDisplay]
894 ✔
1371
    {
894 ✔
1372
        auto& newEvents = graphDisplay->events();
614 ✔
1373
        while(!newEvents.empty())
918 ✔
1374
        {
304 ✔
1375
            _eventQueue.push(std::move(newEvents.front()));
304 ✔
1376
            newEvents.pop();
304 ✔
1377
        }
304 ✔
1378
    });
614 ✔
1379

1380
    // Tell the QuickItem what we're doing
1381
    graphDisplay->setViewIsReset(viewIsReset());
894 ✔
1382
    graphDisplay->setCanEnterOverviewMode(mode() != Mode::Overview && _numComponents > 1);
894 ✔
1383
    graphDisplay->setInOverviewMode(mode() == Mode::Overview);
894 ✔
1384

1385
    const ComponentId focusedComponentId = mode() != Mode::Overview ? _graphComponentScene->componentId() : ComponentId();
894 ✔
1386
    graphDisplay->setFocusedComponentId(focusedComponentId);
894 ✔
1387

1388
    emit synchronizeComplete();
894 ✔
1389
}
894 ✔
1390

1391
GraphComponentRenderer* GraphRenderer::componentRendererForId(ComponentId componentId) const
1392
{
40,699 ✔
1393
    if(componentId.isNull())
40,699 ✔
1394
        return nullptr;
2,989 ✔
1395

1396
    GraphComponentRenderer* renderer = _componentRenderers.at(componentId);
37,710 ✔
1397
    Q_ASSERT(renderer != nullptr);
37,710 !
1398
    return renderer;
37,710 ✔
1399
}
40,699 ✔
1400

1401
void GraphRenderer::enableSceneUpdate()
1402
{
464 ✔
1403
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
464 ✔
1404
    Q_ASSERT(_sceneUpdateDisabled > 0);
464 !
1405
    _sceneUpdateDisabled--;
464 ✔
1406
    resetTime();
464 ✔
1407
}
464 ✔
1408

1409
void GraphRenderer::disableSceneUpdate()
1410
{
374 ✔
1411
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
374 ✔
1412
    _sceneUpdateDisabled++;
374 ✔
1413
}
374 ✔
1414

1415
void GraphRenderer::ifSceneUpdateEnabled(const std::function<void()>& f) const
1416
{
13,644 ✔
1417
    const std::unique_lock<std::recursive_mutex> lock(_sceneUpdateMutex);
13,644 ✔
1418
    if(_sceneUpdateDisabled == 0)
13,644 ✔
1419
        f();
12,880 ✔
1420
}
13,644 ✔
1421

1422
void GraphRenderer::clearHiddenElements()
1423
{
44 ✔
1424
    _hiddenNodes.resetElements();
44 ✔
1425
    _hiddenEdges.resetElements();
44 ✔
1426
}
44 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc