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

graphia-app / graphia / 44197303077

17 Nov 2026 11:10PM UTC coverage: 82.227% (-0.02%) from 82.245%
44197303077

push

github

timangus
Test that the renderers of a share group get one set of element programs

13305 of 18576 branches covered (71.62%)

Branch coverage included in aggregate %.

36360 of 41824 relevant lines covered (86.94%)

501508.12 hits per line

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

89.83
/source/app/graph/graphmodel.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 "graphmodel.h"
21

22
#include "shared/loading/userelementdata.h"
23
#include "app/preferences.h"
24

25
#include "limitconstants.h"
26

27
#include "app/graph/mutablegraph.h"
28

29
#include "app/layout/nodepositions.h"
30

31
#include "app/application.h"
32

33
#include "app/ui/document.h"
34
#include "app/ui/selectionmanager.h"
35
#include "app/ui/searchmanager.h"
36

37
#include "app/transform/transformedgraph.h"
38
#include "app/transform/transforminfo.h"
39
#include "app/transform/graphtransform.h"
40
#include "app/transform/graphtransformconfigparser.h"
41

42
#include "app/ui/visualisations/visualisationchannel.h"
43

44
#include "app/ui/visualisations/visualisationconfigparser.h"
45
#include "app/ui/visualisations/visualisationbuilder.h"
46
#include "app/ui/visualisations/visualisationinfo.h"
47
#include "app/ui/visualisations/elementvisual.h"
48
#include "app/ui/visualisations/textvisual.h"
49

50
#include "shared/plugins/iplugin.h"
51

52
#include "shared/utils/container_combine.h"
53
#include "shared/utils/utils.h"
54
#include "shared/utils/pair_iterator.h"
55
#include "shared/utils/flags.h"
56
#include "shared/utils/string.h"
57
#include "shared/utils/scopetimer.h"
58

59
#include <QColor>
60
#include <QDebug>
61
#include <QList>
62
#include <QRegularExpression>
63
#include <QMetaType>
64
#include <QtGlobal>
65

66
#include <algorithm>
67
#include <atomic>
68
#include <cmath>
69
#include <cstddef>
70
#include <iterator>
71
#include <mutex>
72
#include <optional>
73
#include <set>
74
#include <shared_mutex>
75
#include <utility>
76
#include <vector>
77

78
using namespace Qt::Literals::StringLiterals;
79

80
using NodeVisuals = NodeArray<ElementVisual>;
81
using EdgeVisuals = EdgeArray<ElementVisual>;
82

83
static void updateTextVisualPositions(TextVisuals& textVisuals, const NodePositions& nodePositions)
84
{
6,296 ✔
85
    // Hold the positions still so that every text visual is placed
86
    // from the same iteration of the layout
87
    const std::unique_lock<const NodePositions> lock(nodePositions);
6,296 ✔
88

89
    for(auto& [componentId, textVisuals_] : textVisuals)
6,296 ✔
90
    {
18 ✔
91
        for(auto& textVisual : textVisuals_)
18 ✔
92
            textVisual.updatePositions(nodePositions);
30 ✔
93
    }
18 ✔
94
}
6,296 ✔
95

96
struct PendingVisualUpdate
97
{
98
    bool _full = false; // Something that every element's visual depends on has changed
99
    bool _force = false;
100

101
    std::optional<NodeIdSet> _selectedNodeIds;
102
    std::optional<bool> _nodesMaskActive;
103
    std::optional<NodeIdSet> _foundNodeIds;
104
    std::optional<NodeIdSet> _highlightedNodeIds;
105
};
106

107
class GraphModelImpl
108
{
109
    friend class GraphModel;
110
    friend class AttributeChangesTracker;
111

112
public:
113
    GraphModelImpl(GraphModel& graphModel, Application* application) :
114
        _application(application),
1,780 ✔
115
        _transformedGraph(graphModel, _graph),
1,780 ✔
116
        _nodePositions(_graph),
1,780 ✔
117
        _nodeVisuals(_graph),
1,780 ✔
118
        _edgeVisuals(_graph),
1,780 ✔
119
        _mappedNodeVisuals(_graph),
1,780 ✔
120
        _mappedEdgeVisuals(_graph),
1,780 ✔
121
        _nodeNames(_graph)
1,780 ✔
122
    {
1,780 ✔
123
        _userNodeData.initialise(_graph);
1,780 ✔
124
        _userEdgeData.initialise(_graph);
1,780 ✔
125
    }
1,780 ✔
126

127
private:
128
    Application* _application;
129

130
    MutableGraph _graph;
131
    TransformedGraph _transformedGraph;
132
    TransformInfosMap _transformInfos;
133
    NodePositions _nodePositions;
134

135
    std::atomic<float> _nodeSize = u::pref(u"visuals/defaultNormalNodeSize"_s).toFloat();
136
    std::atomic<float> _edgeSize = u::pref(u"visuals/defaultNormalEdgeSize"_s).toFloat();
137
    std::atomic<float> _textSize = LimitConstants::defaultTextSize();
138

139
    NodeVisuals _nodeVisuals;
140
    EdgeVisuals _edgeVisuals;
141

142
    // Held exclusively while anything writes to the visuals, and shared by plugins that read
143
    // them, and by the renderer as it starts; after that it relies on the scene update being
144
    // disabled instead
145
    mutable std::shared_mutex _visualsMutex;
146
    NodeVisuals _mappedNodeVisuals;
147
    EdgeVisuals _mappedEdgeVisuals;
148
    QStringList _visualisedAttributeNames;
149
    VisualisationInfosMap _visualisationInfos;
150

151
    TextVisuals _newTextVisuals;
152
    TextVisuals _textVisuals;
153
    mutable std::mutex _textVisualsMutex;
154

155
    NodeArray<QString> _nodeNames;
156

157
    UserNodeData _userNodeData;
158
    UserEdgeData _userEdgeData;
159

160
    PreferencesWatcher _preferencesWatcher;
161

162
    std::map<QString, Attribute> _attributes;
163

164
    struct AttributeIdentity
165
    {
166
        QString _name;
167
        ValueType _valueType;
168
        ElementType _elementType;
169

170
        AttributeIdentity(const QString& name,
171
            ValueType valueType, ElementType elementType) :
172
            _name(name), _valueType(valueType), _elementType(elementType)
47,106 ✔
173
        {}
47,106 ✔
174

175
        bool operator==(const AttributeIdentity& other) const
176
        {
357,082 ✔
177
            return _name == other._name &&
357,082 ✔
178
                _valueType == other._valueType &&
357,082 !
179
                _elementType == other._elementType;
357,082 !
180
        }
357,082 ✔
181
    };
182

183
    std::vector<AttributeIdentity> _previousAttributeIdentities;
184

185
    auto currentAttributeIdentities() const
186
    {
3,716 ✔
187
        std::vector<AttributeIdentity> attributeIdentities;
3,716 ✔
188
        attributeIdentities.reserve(_attributes.size());
3,716 ✔
189

190
        std::ranges::transform(_attributes, std::back_inserter(attributeIdentities), [](const auto& attribute)
3,716 ✔
191
        {
47,106 ✔
192
            return AttributeIdentity(attribute.first,
47,106 ✔
193
                attribute.second.valueType(),
47,106 ✔
194
                attribute.second.elementType());
47,106 ✔
195
        });
47,106 ✔
196

197
        return attributeIdentities;
3,716 ✔
198
    }
3,716 ✔
199

200
    QStringList _removedDynamicAttributeNames;
201
    QStringList _changedDynamicAttributeNames;
202

203
    void updateSharedAttributeValues(Attribute& attribute) const
204
    {
32,238 ✔
205
        if(!attribute.testFlag(AttributeFlag::FindShared))
32,238 ✔
206
            return;
27,766 ✔
207

208
        if(attribute.elementType() == ElementType::Node)
4,472 ✔
209
            attribute.updateSharedValuesForElements(_transformedGraph.nodeIds());
4,148 ✔
210
        else if(attribute.elementType() == ElementType::Edge)
324 !
211
            attribute.updateSharedValuesForElements(_transformedGraph.edgeIds());
324 ✔
212
        else if(attribute.elementType() == ElementType::Component)
×
213
            qDebug() << "updateSharedAttributeValues called on component attribute";
×
214
    }
4,472 ✔
215

216
    // Slightly hacky state variable that tracks whether or not a edge text
217
    // visualisation is present. This is required so that we can show a warning
218
    // to the user, if they have edge text enabled, but do not have a
219
    // corresponding visualisation
220
    bool _hasValidEdgeTextVisualisation = false;
221

222
    std::atomic_bool _transformRebuildRequired = false;
223
    std::atomic_bool _visualisationRebuildRequired = false;
224

225
    NodeIdSet _selectedNodeIds;
226
    NodeIdSet _foundNodeIds;
227
    NodeIdSet _highlightedNodeIds;
228
    bool _nodesMaskActive = false;
229

230
    std::mutex _pendingVisualUpdateMutex;
231
    PendingVisualUpdate _pendingVisualUpdate;
232

233
    template<typename Fn>
234
    void requestVisualUpdate(const Fn& fn)
235
    {
31,910 ✔
236
        const std::unique_lock<std::mutex> lock(_pendingVisualUpdateMutex);
31,910 ✔
237
        fn(_pendingVisualUpdate);
31,910 ✔
238
    }
31,910 ✔
239

240
    void requestFullVisualUpdate()
241
    {
31,710 ✔
242
        requestVisualUpdate([](auto& pending) { pending._full = true; });
31,710 ✔
243
    }
31,710 ✔
244

245
    std::set<AttributeChangesTracker*> _attributeChangesTrackers;
246
};
247

248
namespace
249
{
250
AttributeDeclaration nodeDegreeAttribute()              { return {._name = u"NodeDegree"_s,                 ._displayName = QObject::tr("Node Degree")}; }
1,896 ✔
251
AttributeDeclaration nodeInDegreeAttribute()            { return {._name = u"NodeInDegree"_s,               ._displayName = QObject::tr("Node In Degree")}; }
1,498 ✔
252
AttributeDeclaration nodeOutDegreeAttribute()           { return {._name = u"NodeOutDegree"_s,              ._displayName = QObject::tr("Node Out Degree")}; }
1,498 ✔
253
AttributeDeclaration nodeMultiplicityAttribute()        { return {._name = u"NodeMultiplicity"_s,           ._displayName = QObject::tr("Node Multiplicity")}; }
1,896 ✔
254
AttributeDeclaration edgeMultiplicityAttribute()        { return {._name = u"EdgeMultiplicity"_s,           ._displayName = QObject::tr("Edge Multiplicity")}; }
1,896 ✔
255
AttributeDeclaration componentSizeAttribute()           { return {._name = u"ComponentSize"_s,              ._displayName = QObject::tr("Component Size")}; }
1,896 ✔
256
AttributeDeclaration nodeComponentIdentifierAttribute() { return {._name = u"NodeComponentIdentifier"_s,    ._displayName = QObject::tr("Node Component Identifier")}; }
1,896 ✔
257
AttributeDeclaration edgeComponentIdentifierAttribute() { return {._name = u"EdgeComponentIdentifier"_s,    ._displayName = QObject::tr("Edge Component Identifier")}; }
1,896 ✔
258
} // namespace
259

260
AttributeDeclarations GraphModel::attributeDeclarations()
261
{
116 ✔
262
    return
116 ✔
263
    {
116 ✔
264
        nodeDegreeAttribute(),
116 ✔
265
        nodeInDegreeAttribute(),
116 ✔
266
        nodeOutDegreeAttribute(),
116 ✔
267
        nodeMultiplicityAttribute(),
116 ✔
268
        edgeMultiplicityAttribute(),
116 ✔
269
        componentSizeAttribute(),
116 ✔
270
        nodeComponentIdentifierAttribute(),
116 ✔
271
        edgeComponentIdentifierAttribute()
116 ✔
272
    };
116 ✔
273
}
116 ✔
274

275
GraphModel::GraphModel(Application* application, IPlugin* plugin) :
276
    _(std::make_unique<GraphModelImpl>(*this, application)),
1,780 ✔
277
    _graphTransformsAreChanging(false),
1,780 ✔
278
    _plugin(plugin)
1,780 ✔
279
{
1,780 ✔
280
    qRegisterMetaType<VisualChangeFlags>("VisualChangeFlags");
1,780 ✔
281

282
    connect(&_->_transformedGraph, &Graph::nodeRemoved, [this](const Graph*, NodeId nodeId)
1,780 ✔
283
    {
1,780 ✔
284
        const std::unique_lock<std::shared_mutex> lock(_->_visualsMutex);
196 ✔
285
        _->_nodeVisuals[nodeId]._state = VisualFlags::None;
196 ✔
286
    });
196 ✔
287
    connect(&_->_transformedGraph, &Graph::edgeRemoved, [this](const Graph*, EdgeId edgeId)
1,780 ✔
288
    {
1,780 ✔
289
        const std::unique_lock<std::shared_mutex> lock(_->_visualsMutex);
290 ✔
290
        _->_edgeVisuals[edgeId]._state = VisualFlags::None;
290 ✔
291
    });
290 ✔
292

293
    connect(&_->_graph, &Graph::graphChanged, this, &GraphModel::onMutableGraphChanged, Qt::DirectConnection);
1,780 ✔
294

295
    connect(&_->_transformedGraph, &Graph::graphWillChange, this, &GraphModel::onTransformedGraphWillChange, Qt::DirectConnection);
1,780 ✔
296
    connect(&_->_transformedGraph, &Graph::graphChanged, this, &GraphModel::onTransformedGraphChanged, Qt::DirectConnection);
1,780 ✔
297
    connect(&_->_transformedGraph, &TransformedGraph::attributeValuesChanged,
1,780 ✔
298
    [this](const QStringList& attributeNames)
1,780 ✔
299
    {
1,780 ✔
300
        _->_changedDynamicAttributeNames = attributeNames;
10 ✔
301
    });
10 ✔
302

303
    connect(&_->_userNodeData, &UserData::vectorValuesChanged, [this](const QString& vectorName)
1,780 ✔
304
    {
8,642 ✔
305
        auto attributeName = _->_userNodeData.exposedAttributeName(vectorName);
8,642 ✔
306
        if(attributeName.isEmpty())
8,642 ✔
307
            return;
8,530 ✔
308

309
        for(auto* tracker : _->_attributeChangesTrackers)
112 ✔
310
            tracker->change(attributeName);
112 ✔
311
    });
112 ✔
312

313
    connect(&_->_userEdgeData, &UserData::vectorValuesChanged, [this](const QString& vectorName)
1,780 ✔
314
    {
1,784 ✔
315
        auto attributeName = _->_userEdgeData.exposedAttributeName(vectorName);
1,784 ✔
316
        if(attributeName.isEmpty())
1,784 ✔
317
            return;
1,710 ✔
318

319
        for(auto* tracker : _->_attributeChangesTrackers)
74 ✔
320
            tracker->change(attributeName);
74 ✔
321
    });
74 ✔
322

323
    connect(this, &GraphModel::attributesChanged, this, &GraphModel::onAttributesChanged, Qt::DirectConnection);
1,780 ✔
324

325
    connect(&_->_preferencesWatcher, &PreferencesWatcher::preferenceChanged,
1,780 ✔
326
        this, &GraphModel::onPreferenceChanged);
1,780 ✔
327

328
    GraphModel::createAttribute(nodeDegreeAttribute())
1,780 ✔
329
        .setIntValueFn([this](NodeId nodeId) { return _->_transformedGraph.nodeById(nodeId).degree(); })
3,732 ✔
330
        .intRange().setMin(0)
1,780 ✔
331
        .setDescription(tr("A node's degree is its number of incident edges."));
1,780 ✔
332

333
    if(directed())
1,780 ✔
334
    {
1,382 ✔
335
        GraphModel::createAttribute(nodeInDegreeAttribute())
1,382 ✔
336
            .setIntValueFn([this](NodeId nodeId) { return _->_transformedGraph.nodeById(nodeId).inDegree(); })
2,072 ✔
337
            .intRange().setMin(0)
1,382 ✔
338
            .setDescription(tr("A node's in degree is its number of inbound edges."));
1,382 ✔
339

340
        GraphModel::createAttribute(nodeOutDegreeAttribute())
1,382 ✔
341
            .setIntValueFn([this](NodeId nodeId) { return _->_transformedGraph.nodeById(nodeId).outDegree(); })
2,072 ✔
342
            .intRange().setMin(0)
1,382 ✔
343
            .setDescription(tr("A node's out degree is its number of outbound edges."));
1,382 ✔
344
    }
1,382 ✔
345

346
    GraphModel::createAttribute(nodeMultiplicityAttribute())
1,780 ✔
347
        .setIntValueFn([this](NodeId nodeId) { return _->_transformedGraph.multiplicityOf(nodeId); })
3,664 ✔
348
        .intRange().setMin(0)
1,780 ✔
349
        .setDescription(tr("A node's multiplicity is how many nodes it represents."));
1,780 ✔
350

351
    GraphModel::createAttribute(edgeMultiplicityAttribute())
1,780 ✔
352
        .setIntValueFn([this](EdgeId edgeId) { return _->_transformedGraph.multiplicityOf(edgeId); })
1,780 ✔
353
        .intRange().setMin(0)
1,780 ✔
354
        .setDescription(tr("An edge's multiplicity is how many edges it represents."));
1,780 ✔
355

356
    GraphModel::createAttribute(componentSizeAttribute())
1,780 ✔
357
        .setIntValueFn([](const IGraphComponent& component) { return static_cast<int>(component.numNodes()); })
1,780 ✔
358
        .intRange().setMin(1)
1,780 ✔
359
        .setDescription(tr("Component Size refers to the number of nodes the component contains."));
1,780 ✔
360

361
    GraphModel::createAttribute(nodeComponentIdentifierAttribute())
1,780 ✔
362
        .setStringValueFn([this](NodeId nodeId)
1,780 ✔
363
        {
3,678 ✔
364
            return u"Component %1"_s.arg(static_cast<int>(_->_transformedGraph.componentIdOfNode(nodeId) + 1));
3,678 ✔
365
        })
3,678 ✔
366
        .setDisplayValueFns(Attribute::numberedDisplayValueFns(u"Component "_s, tr("Component %1")))
1,780 ✔
367
        .setDescription(tr("A node's component identifier indicates which component it is part of."))
1,780 ✔
368
        .setFlag(AttributeFlag::DisableDuringTransform);
1,780 ✔
369

370
    GraphModel::createAttribute(edgeComponentIdentifierAttribute())
1,780 ✔
371
        .setStringValueFn([this](EdgeId edgeId)
1,780 ✔
372
        {
1,780 ✔
373
            return u"Component %1"_s.arg(static_cast<int>(_->_transformedGraph.componentIdOfEdge(edgeId) + 1));
680 ✔
374
        })
680 ✔
375
        .setDisplayValueFns(Attribute::numberedDisplayValueFns(u"Component "_s, tr("Component %1")))
1,780 ✔
376
        .setDescription(tr("An edge's component identifier indicates which component it is part of."))
1,780 ✔
377
        .setFlag(AttributeFlag::DisableDuringTransform);
1,780 ✔
378
}
1,780 ✔
379

380
// Only here so that we can have a unique_ptr to GraphModelImpl
381
GraphModel::~GraphModel() = default;
1,780 ✔
382

383
void GraphModel::removeDynamicAttributes()
384
{
1,858 ✔
385
    QStringList dynamicAttributeNames;
1,858 ✔
386

387
    for(const auto& attributePair : _->_attributes)
1,858 ✔
388
    {
23,330 ✔
389
        if(attributePair.second.testFlag(AttributeFlag::Dynamic))
23,330 ✔
390
            dynamicAttributeNames.append(attributePair.first);
40 ✔
391
    }
23,330 ✔
392

393
    for(const auto& attributeName : dynamicAttributeNames)
1,858 ✔
394
    {
40 ✔
395
        _->_removedDynamicAttributeNames.append(attributeName);
40 ✔
396
        _->_attributes.erase(attributeName);
40 ✔
397
    }
40 ✔
398
}
1,858 ✔
399

400
QString GraphModel::normalisedAttributeName(QString attribute, const QString& clashHint) const
401
{
20,586 ✔
402
    // Dots in attribute names are disallowed as they conflict with
403
    // the dot syntax for parameterised attributes
404
    attribute.replace('.', '_');
20,586 ✔
405

406
    QString newAttribute = u::findUniqueName(_->_attributes, attribute);
20,586 ✔
407

408
    if(newAttribute != attribute && !clashHint.isEmpty())
20,586 ✔
409
        newAttribute = u::findUniqueName(_->_attributes, clashHint.arg(attribute));
4 ✔
410

411
    return newAttribute;
20,586 ✔
412
}
20,586 ✔
413

414
IMutableGraph& GraphModel::mutableGraphImpl() { return mutableGraph(); }
14,462 ✔
415
const IMutableGraph& GraphModel::mutableGraphImpl() const { return mutableGraph(); }
×
416
const IGraph& GraphModel::graphImpl() const { return graph(); }
50,440 ✔
417

418

419
MutableGraph& GraphModel::mutableGraph() { return _->_graph; }
48,698 ✔
420
const MutableGraph& GraphModel::mutableGraph() const { return _->_graph; }
×
421
const Graph& GraphModel::graph() const { return _->_transformedGraph; }
680,104 ✔
422

423
void GraphModel::setNodeSize(float nodeSize)
424
{
158 ✔
425
    _->_nodeSize = nodeSize;
158 ✔
426
    _->requestFullVisualUpdate();
158 ✔
427
    scheduleVisualUpdate();
158 ✔
428
}
158 ✔
429

430
void GraphModel::setEdgeSize(float edgeSize)
431
{
152 ✔
432
    _->_edgeSize = edgeSize;
152 ✔
433
    _->requestFullVisualUpdate();
152 ✔
434
    scheduleVisualUpdate();
152 ✔
435
}
152 ✔
436

437
void GraphModel::setTextSize(float textSize)
438
{
156 ✔
439
    _->_textSize = textSize;
156 ✔
440
    _->requestFullVisualUpdate();
156 ✔
441
    scheduleVisualUpdate();
156 ✔
442
}
156 ✔
443

444
float GraphModel::nodeSize() const { return _->_nodeSize; }
146 ✔
445
float GraphModel::edgeSize() const { return _->_edgeSize; }
142 ✔
446
float GraphModel::textSize() const { return _->_textSize; }
142 ✔
447

448
const ElementVisual& GraphModel::nodeVisual(NodeId nodeId) const { return _->_nodeVisuals.at(nodeId); }
13,943 ✔
449
const ElementVisual& GraphModel::edgeVisual(EdgeId edgeId) const { return _->_edgeVisuals.at(edgeId); }
2,916 ✔
450

451
void GraphModel::readVisuals(const std::function<void()>& fn) const
452
{
90 ✔
453
    const std::shared_lock<std::shared_mutex> lock(_->_visualsMutex);
90 ✔
454
    fn();
90 ✔
455
}
90 ✔
456

457
void GraphModel::readNodeVisuals(const std::vector<NodeId>& nodeIds,
458
    const std::function<void(NodeId, const IElementVisual&)>& fn) const
459
{
324 ✔
460
    const std::shared_lock<std::shared_mutex> lock(_->_visualsMutex);
324 ✔
461

462
    for(auto nodeId : nodeIds)
324 ✔
463
    {
1,658 ✔
464
        if(!nodeId.isNull())
1,658 ✔
465
            fn(nodeId, _->_nodeVisuals.at(nodeId));
1,654 ✔
466
    }
1,658 ✔
467
}
324 ✔
468

469
void GraphModel::readEdgeVisuals(const std::vector<EdgeId>& edgeIds,
470
    const std::function<void(EdgeId, const IElementVisual&)>& fn) const
471
{
×
472
    const std::shared_lock<std::shared_mutex> lock(_->_visualsMutex);
×
473

474
    for(auto edgeId : edgeIds)
×
475
    {
×
476
        if(!edgeId.isNull())
×
477
            fn(edgeId, _->_edgeVisuals.at(edgeId));
×
478
    }
×
479
}
×
480

481
std::vector<ElementVisual> GraphModel::nodeVisuals(const std::vector<NodeId>& nodeIds) const
482
{
506 ✔
483
    std::vector<ElementVisual> visuals;
506 ✔
484
    visuals.reserve(nodeIds.size());
506 ✔
485

486
    std::ranges::transform(nodeIds, std::back_inserter(visuals), [this](NodeId nodeId) { return nodeVisual(nodeId); });
1,218 ✔
487

488
    return visuals;
506 ✔
489
}
506 ✔
490

491
std::vector<ElementVisual> GraphModel::edgeVisuals(const std::vector<EdgeId>& edgeIds) const
492
{
×
493
    std::vector<ElementVisual> visuals;
×
494
    visuals.reserve(edgeIds.size());
×
495

496
    std::ranges::transform(edgeIds, std::back_inserter(visuals), [this](EdgeId edgeId) { return edgeVisual(edgeId); });
×
497

498
    return visuals;
×
499
}
×
500

501
bool GraphModel::hasTextVisuals() const
502
{
×
503
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
×
504
    return !_->_textVisuals.empty();
×
505
}
×
506

507
void GraphModel::forEachTextVisual(const std::function<void(const TextVisual&)>& fn) const
508
{
96 ✔
509
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
96 ✔
510

511
    for(const auto& [componentId, textVisuals] : _->_textVisuals)
96 ✔
512
    {
18 ✔
513
        for(const auto& textVisual : textVisuals)
18 ✔
514
            fn(textVisual);
30 ✔
515
    }
18 ✔
516
}
96 ✔
517

518
void GraphModel::forEachTextVisual(ComponentId componentId,
519
    const std::function<void(const TextVisual&)>& fn) const
520
{
2,710 ✔
521
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
2,710 ✔
522

523
    auto it = _->_textVisuals.find(componentId);
2,710 ✔
524
    if(it == _->_textVisuals.end())
2,710 ✔
525
        return;
2,704 ✔
526

527
    for(const auto& textVisual : it->second)
6 ✔
528
        fn(textVisual);
6 ✔
529
}
6 ✔
530

531
NodePositions& GraphModel::nodePositions() { return _->_nodePositions; }
15,820 ✔
532
const NodePositions& GraphModel::nodePositions() const { return _->_nodePositions; }
952 ✔
533

534
const NodeArray<QString>& GraphModel::nodeNames() const { return _->_nodeNames; }
174 ✔
535
QString GraphModel::nodeName(NodeId nodeId) const { return _->_nodeNames[nodeId]; }
216,054 ✔
536
void GraphModel::setNodeName(NodeId nodeId, const QString& name)
537
{
27,774 ✔
538
    _->_nodeNames[nodeId] = name;
27,774 ✔
539
    _->requestFullVisualUpdate();
27,774 ✔
540
    scheduleVisualUpdate();
27,774 ✔
541
}
27,774 ✔
542

543
bool GraphModel::editable() const { return _plugin->editable(); }
2 ✔
544
bool GraphModel::directed() const { return _plugin->directed(); }
3,209 ✔
545

546
QString GraphModel::pluginName() const { return _plugin->name(); }
112 ✔
547
QString GraphModel::pluginDisplayName() const { return _plugin->displayName(); }
112 ✔
548
int GraphModel::pluginDataVersion() const { return _plugin->dataVersion(); }
112 ✔
549
QString GraphModel::pluginQmlModule() const { return _plugin->qmlModule(); }
×
550

551
bool GraphModel::graphTransformIsValid(const QString& transform) const
552
{
216 ✔
553
    GraphTransformConfigParser p;
216 ✔
554
    const bool parsed = p.parse(transform, "warnOnFailure"_no);
216 ✔
555

556
    if(parsed)
216 ✔
557
    {
214 ✔
558
        const auto& graphTransformConfig = p.result();
214 ✔
559

560
        const auto* factory = transformFactory(graphTransformConfig._action);
214 ✔
561

562
        if(factory == nullptr)
214 !
563
            return false;
×
564

565
        if(factory->requiresCondition() && !graphTransformConfig.hasCondition())
214 ✔
566
            return false;
2 ✔
567

568
        return factory->configIsValid(*this, graphTransformConfig);
212 ✔
569
    }
214 ✔
570

571
    return false;
2 ✔
572
}
216 ✔
573

574
QStringList GraphModel::transformsWithMissingParametersSetToDefault(const QStringList& transforms) const
575
{
1,874 ✔
576
    QStringList transformsWithDefaults;
1,874 ✔
577

578
    for(const auto& transform : transforms)
1,874 ✔
579
    {
1,238 ✔
580
        GraphTransformConfigParser graphTransformConfigParser;
1,238 ✔
581

582
        if(!graphTransformConfigParser.parse(transform))
1,238 !
583
            continue;
×
584

585
        auto graphTransformConfig = graphTransformConfigParser.result();
1,238 ✔
586

587
        const auto* factory = transformFactory(graphTransformConfig._action);
1,238 ✔
588

589
        // This can happen if the file has transforms that the app doesn't
590
        if(factory == nullptr)
1,238 !
591
            continue;
×
592

593
        factory->setMissingParametersToDefault(graphTransformConfig);
1,238 ✔
594
        transformsWithDefaults.append(graphTransformConfig.asString());
1,238 ✔
595
    }
1,238 ✔
596

597
    return transformsWithDefaults;
1,874 ✔
598
}
1,874 ✔
599

600
void GraphModel::buildTransforms(const QStringList& transforms, Progressable* progressable)
601
{
1,802 ✔
602
    _->_transformedGraph.clearTransforms();
1,802 ✔
603
    _->_transformInfos.clear();
1,802 ✔
604
    for(int index = 0; index < transforms.size(); index++)
3,074 ✔
605
    {
1,272 ✔
606
        const auto& transform = transforms.at(index);
1,272 ✔
607
        GraphTransformConfigParser graphTransformConfigParser;
1,272 ✔
608

609
        if(!graphTransformConfigParser.parse(transform))
1,272 !
610
            continue;
×
611

612
        const auto& graphTransformConfig = graphTransformConfigParser.result();
1,272 ✔
613
        const auto& action = graphTransformConfig._action;
1,272 ✔
614

615
        if(graphTransformConfig.isFlagSet(u"disabled"_s))
1,272 !
616
            continue;
×
617

618
        const auto* factory = transformFactory(action);
1,272 ✔
619

620
        if(factory == nullptr)
1,272 !
621
            continue;
×
622
        auto graphTransform = factory->create(*this, graphTransformConfig);
1,272 ✔
623

624
        Q_ASSERT(graphTransform != nullptr);
1,272 !
625
        if(graphTransform != nullptr)
1,272 !
626
        {
1,272 ✔
627
            graphTransform->setIndex(index);
1,272 ✔
628
            graphTransform->setConfig(graphTransformConfig);
1,272 ✔
629
            graphTransform->setRepeating(graphTransformConfig.isFlagSet(u"repeating"_s));
1,272 ✔
630
            graphTransform->setInfo(&_->_transformInfos[index]);
1,272 ✔
631
            graphTransform->setProgressable(progressable);
1,272 ✔
632
            _->_transformedGraph.addTransform(std::move(graphTransform));
1,272 ✔
633
        }
1,272 ✔
634
    }
1,272 ✔
635

636
    _->_transformedGraph.enableAutoRebuild();
1,802 ✔
637
}
1,802 ✔
638

639
void GraphModel::cancelTransformBuild()
640
{
8 ✔
641
    _->_transformedGraph.cancelRebuild();
8 ✔
642
}
8 ✔
643

644
QStringList GraphModel::availableTransformNames() const
645
{
4 ✔
646
    QStringList stringList;
4 ✔
647
    const auto& transformFactories = _->_application->transformFactories();
4 ✔
648
    stringList.reserve(static_cast<int>(transformFactories.size()));
4 ✔
649

650
    for(const auto& [transformName, factory] : transformFactories)
4 ✔
651
    {
120 ✔
652
        auto elementType = factory->elementType();
120 ✔
653
        const bool attributesAvailable = !availableAttributeNames(elementType, ValueType::All).isEmpty();
120 ✔
654

655
        if(elementType == ElementType::None || attributesAvailable)
120 !
656
            stringList.append(transformName);
120 ✔
657
    }
120 ✔
658

659
    return stringList;
4 ✔
660
}
4 ✔
661

662
const GraphTransformFactory* GraphModel::transformFactory(const QString& transformName) const
663
{
2,840 ✔
664
    return _->_application->transformFactory(transformName);
2,840 ✔
665
}
2,840 ✔
666

667
QStringList GraphModel::availableAttributeNames(ElementType elementTypes,
668
    ValueType valueTypes, AttributeFlag skipFlags,
669
    const QStringList& skipAttributeNames) const
670
{
304 ✔
671
    QStringList stringList;
304 ✔
672

673
    for(auto& attribute : _->_attributes)
304 ✔
674
    {
3,402 ✔
675
        if(!Flags<ElementType>(elementTypes).test(attribute.second.elementType()))
3,402 ✔
676
            continue;
1,404 ✔
677

678
        if(!Flags<ValueType>(valueTypes).test(attribute.second.valueType()))
1,998 ✔
679
            continue;
114 ✔
680

681
        if(attribute.second.testFlag(skipFlags))
1,884 ✔
682
            continue;
2 ✔
683

684
        if(skipAttributeNames.contains(attribute.first))
1,882 !
685
            continue;
×
686

687
        stringList.append(attribute.first);
1,882 ✔
688
    }
1,882 ✔
689

690
    return stringList;
304 ✔
691
}
304 ✔
692

693
QStringList GraphModel::avaliableConditionFnOps(const QString& attributeName) const
694
{
120 ✔
695
    QStringList ops;
120 ✔
696

697
    if(attributeName.isEmpty() || !u::contains(_->_attributes, attributeName))
120 !
698
        return ops;
×
699

700
    const auto& attribute = _->_attributes.at(attributeName);
120 ✔
701
    ops.append(GraphTransformConfigParser::ops(attribute.valueType()));
120 ✔
702

703
    if(attribute.hasMissingValues())
120 ✔
704
        ops.append(GraphTransformConfigParser::opToString(ConditionFnOp::Unary::HasValue));
52 ✔
705

706
    return ops;
120 ✔
707
}
120 ✔
708

709
bool GraphModel::hasTransformInfo() const
710
{
1,086 ✔
711
    return !_->_transformInfos.empty();
1,086 ✔
712
}
1,086 ✔
713

714
const TransformInfo& GraphModel::transformInfoAtIndex(int index) const
715
{
456 ✔
716
    static const TransformInfo nullTransformInfo;
456 ✔
717

718
    if(u::contains(_->_transformInfos, index))
456 !
719
        return _->_transformInfos.at(index);
456 ✔
720

721
    return nullTransformInfo;
×
722
}
456 ✔
723

724
std::map<QString, QString> GraphModel::assignedAttributeNamesAtTransformIndex(int index) const
725
{
22 ✔
726
    return _->_transformedGraph.assignedAttributeNamesAtTransformIndex(index);
22 ✔
727
}
22 ✔
728

729
std::vector<QString> GraphModel::addedOrChangedAttributeNamesAtTransformIndex(int index) const
730
{
6 ✔
731
    return u::valuesFor(assignedAttributeNamesAtTransformIndex(index));
6 ✔
732
}
6 ✔
733

734
std::vector<QString> GraphModel::addedOrChangedAttributeNamesAtTransformIndexOrLater(int firstIndex) const
735
{
6 ✔
736
    std::vector<QString> attributeNames;
6 ✔
737

738
    for(int index = firstIndex; index < static_cast<int>(_->_transformedGraph.numTransforms()); index++)
12 ✔
739
    {
6 ✔
740
        auto addedOrChangedAttributeNames = addedOrChangedAttributeNamesAtTransformIndex(index);
6 ✔
741
        attributeNames.insert(attributeNames.end(),
6 ✔
742
            addedOrChangedAttributeNames.begin(), addedOrChangedAttributeNames.end());
6 ✔
743
    }
6 ✔
744

745
    return attributeNames;
6 ✔
746
}
6 ✔
747

748
ValueType GraphModel::valueTypeOfTransformAttributeName(const QString& attributeName) const
749
{
2 ✔
750
    for(const auto& [transformName, factory] : _->_application->transformFactories())
2 !
751
    {
38 ✔
752
        const auto& defaultVisualisations = factory->defaultVisualisations();
38 ✔
753
        auto v = std::ranges::find(defaultVisualisations, attributeName, &DefaultVisualisation::_attributeName);
38 ✔
754

755
        if(v != defaultVisualisations.end())
38 ✔
756
            return v->_attributeValueType;
2 ✔
757
    }
38 ✔
758

759
    return ValueType::Unknown;
×
760
}
2 ✔
761

762
bool GraphModel::opIsUnary(const QString& op)
763
{
×
764
    return GraphTransformConfigParser::opIsUnary(op);
×
765
}
×
766

767
bool GraphModel::visualisationIsValid(const QString& visualisation) const
768
{
10 ✔
769
    VisualisationConfigParser p;
10 ✔
770
    const bool parsed = p.parse(visualisation, "warnOnFailure"_no);
10 ✔
771

772
    if(parsed)
10 !
773
    {
10 ✔
774
        const auto& visualisationConfig = p.result();
10 ✔
775

776
        if(_->_application->visualisationChannelFactory(visualisationConfig._channelName) == nullptr)
10 ✔
777
            return false;
4 ✔
778

779
        return true;
6 ✔
780
    }
10 ✔
781

782
    return false;
×
783
}
10 ✔
784

785
void GraphModel::buildVisualisations(const QStringList& visualisations)
786
{
952 ✔
787
    SCOPE_TIMER_MULTISAMPLES(50)
952 ✔
788

789
    _->_visualisationRebuildRequired = false;
952 ✔
790

791
    _->_mappedNodeVisuals.resetElements();
952 ✔
792
    _->_mappedEdgeVisuals.resetElements();
952 ✔
793
    _->_newTextVisuals.clear();
952 ✔
794
    clearVisualisationInfos();
952 ✔
795

796
    _->_visualisedAttributeNames.clear();
952 ✔
797
    _->_hasValidEdgeTextVisualisation = false;
952 ✔
798

799
    VisualisationsBuilder<NodeId> nodeVisualisationsBuilder(graph(), _->_mappedNodeVisuals);
952 ✔
800
    VisualisationsBuilder<EdgeId> edgeVisualisationsBuilder(graph(), _->_mappedEdgeVisuals);
952 ✔
801

802
    for(int index = 0; index < visualisations.size(); index++)
1,308 ✔
803
    {
356 ✔
804
        const auto& visualisation = visualisations.at(index);
356 ✔
805

806
        VisualisationConfigParser visualisationConfigParser;
356 ✔
807

808
        if(!visualisationConfigParser.parse(visualisation))
356 !
809
            continue;
×
810

811
        const auto& visualisationConfig = visualisationConfigParser.result();
356 ✔
812

813
        if(visualisationConfig.isFlagSet(u"disabled"_s))
356 ✔
814
            continue;
2 ✔
815

816
        const auto& attributeName = visualisationConfig._attributeName;
354 ✔
817
        const auto& channelName = visualisationConfig._channelName;
354 ✔
818
        auto& info = _->_visualisationInfos[index];
354 ✔
819

820
        // Track referenced attribute names, even if the attributes in question don't exist
821
        _->_visualisedAttributeNames.append(attributeName);
354 ✔
822

823
        if(!attributeExists(attributeName))
354 ✔
824
        {
6 ✔
825
            info.addAlert(AlertType::Error, tr("Attribute '%1' doesn't exist").arg(attributeName));
6 ✔
826
            continue;
6 ✔
827
        }
6 ✔
828

829
        const auto* factory = _->_application->visualisationChannelFactory(channelName);
348 ✔
830

831
        if(factory == nullptr)
348 ✔
832
        {
98 ✔
833
            info.addAlert(AlertType::Error, tr("Visualisation channel '%1' doesn't exist").arg(channelName));
98 ✔
834
            continue;
98 ✔
835
        }
98 ✔
836

837
        auto attribute = attributeValueByName(attributeName);
250 ✔
838

839
        factory->findErrors(attribute.elementType(), info);
250 ✔
840

841
        if(!factory->supports(attribute.valueType()))
250 ✔
842
        {
2 ✔
843
            info.addAlert(AlertType::Error, tr("Visualisation doesn't support attribute type"));
2 ✔
844
            continue;
2 ✔
845
        }
2 ✔
846

847
        auto channel = factory->create(visualisationConfig);
248 ✔
848

849
        if(attribute.elementType() == ElementType::Edge && channelName == u"Text"_s)
248 !
850
            _->_hasValidEdgeTextVisualisation = true;
6 ✔
851

852
        if(attribute.valueType() == ValueType::String)
248 ✔
853
        {
184 ✔
854
            auto sharedValues = attribute.sharedValues();
184 ✔
855
            if(sharedValues.empty())
184 ✔
856
            {
170 ✔
857
                if(attribute.elementType() == ElementType::Node)
170 !
858
                    sharedValues = attribute.findSharedValuesForElements(graph().nodeIds());
170 ✔
859
                else if(attribute.elementType() == ElementType::Edge)
×
860
                    sharedValues = attribute.findSharedValuesForElements(graph().edgeIds());
×
861
            }
170 ✔
862

863
            if(!visualisationConfig.isFlagSet(u"assignByQuantity"_s))
184 ✔
864
            {
182 ✔
865
                // Sort in natural order so that e.g. "Thing 1" is always
866
                // assigned a visualisation before "Thing 2"
867
                std::ranges::sort(sharedValues,
182 ✔
868
                [](const auto& a, const auto& b)
182 ✔
869
                {
219,986 ✔
870
                    return u::numericCompare(a._value, b._value) < 0;
219,986 ✔
871
                });
219,986 ✔
872
            }
182 ✔
873
            else
2 ✔
874
            {
2 ✔
875
                // Shared values should already be sorted at this point,
876
                // but resort anyway as in that case it'll be cheap and
877
                // if it's not sorted (for whatever reason), we need it
878
                // to be sorted
879
                std::ranges::sort(sharedValues,
2 ✔
880
                [](const auto& a, const auto& b)
2 ✔
881
                {
8 ✔
882
                    if(a._count == b._count)
8 ✔
883
                        return u::numericCompare(a._value, b._value) < 0;
4 ✔
884

885
                    return a._count > b._count;
4 ✔
886
                });
8 ✔
887
            }
2 ✔
888

889
            for(const auto& sharedValue : sharedValues)
184 ✔
890
            {
24,426 ✔
891
                channel->addValue(sharedValue._value);
24,426 ✔
892
                info.addStringValue(sharedValue._value);
24,426 ✔
893
            }
24,426 ✔
894
        }
184 ✔
895

896
        switch(attribute.elementType())
248 ✔
897
        {
248 ✔
898
        case ElementType::Node:
242 ✔
899
            nodeVisualisationsBuilder.build(attribute, *factory, *channel, visualisationConfig, index, info);
242 ✔
900
            break;
242 ✔
901

902
        case ElementType::Edge:
6 ✔
903
            edgeVisualisationsBuilder.build(attribute, *factory, *channel, visualisationConfig, index, info);
6 ✔
904
            break;
6 ✔
905

906
        default:
×
907
            break;
×
908
        }
248 ✔
909

910
        auto textVisuals = channel->textVisuals(attributeName, *this, _->_transformedGraph);
248 ✔
911

912
        for(const auto& [componentId, textVisual] : textVisuals)
248 ✔
913
        {
18 ✔
914
            auto& existingTextVisuals = _->_newTextVisuals[componentId];
18 ✔
915
            existingTextVisuals.insert(existingTextVisuals.end(), textVisual.begin(), textVisual.end());
18 ✔
916
        }
18 ✔
917
    }
248 ✔
918

919
    nodeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
952 ✔
920
    edgeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
952 ✔
921

922
    _->requestFullVisualUpdate();
952 ✔
923
    scheduleVisualUpdate();
952 ✔
924
}
952 ✔
925

926
bool GraphModel::transformRebuildRequired() const { return _->_transformRebuildRequired; }
810 ✔
927
bool GraphModel::visualisationRebuildRequired() const { return _->_visualisationRebuildRequired; }
792 ✔
928

929
bool GraphModel::hasValidEdgeTextVisualisation() const
930
{
2 ✔
931
    return _->_hasValidEdgeTextVisualisation;
2 ✔
932
}
2 ✔
933

934
QStringList GraphModel::availableVisualisationChannelNames(ElementType elementType, ValueType valueType) const
935
{
2 ✔
936
    QStringList stringList;
2 ✔
937

938
    for(const auto& [channelName, factory] : _->_application->visualisationChannelFactories())
2 ✔
939
    {
12 ✔
940
        if(factory->appliesTo(elementType) && factory->supports(valueType))
12 !
941
            stringList.append(channelName);
10 ✔
942
    }
12 ✔
943

944
    return stringList;
2 ✔
945
}
2 ✔
946

947
bool GraphModel::visualisationChannelAllowsMapping(const QString& channelName) const
948
{
16 ✔
949
    if(channelName.isEmpty())
16 ✔
950
        return false;
2 ✔
951

952
    const auto* factory = _->_application->visualisationChannelFactory(channelName);
14 ✔
953

954
    if(factory == nullptr)
14 ✔
955
        return false;
2 ✔
956

957
    return factory->allowsMapping();
12 ✔
958
}
14 ✔
959

960
QStringList GraphModel::visualisationDescription(const QString& attributeName, const QStringList& channelNames) const
961
{
8 ✔
962
    QStringList descriptions;
8 ✔
963

964
    if(!attributeExists(attributeName))
8 ✔
965
        return descriptions;
2 ✔
966

967
    for(const auto& channelName : channelNames)
6 ✔
968
    {
20 ✔
969
        const auto* factory = _->_application->visualisationChannelFactory(channelName);
20 ✔
970

971
        if(factory == nullptr)
20 ✔
972
            return descriptions;
2 ✔
973

974
        auto attribute = attributeValueByName(attributeName);
18 ✔
975

976
        if(!factory->supports(attribute.valueType()))
18 ✔
977
            descriptions.append(tr("This visualisation channel is not supported for the attribute type."));
4 ✔
978
        else
14 ✔
979
            descriptions.append(factory->description(attribute.elementType(), attribute.valueType()));
14 ✔
980
    }
18 ✔
981

982
    return descriptions;
4 ✔
983
}
6 ✔
984

985
void GraphModel::clearVisualisationInfos()
986
{
1,066 ✔
987
    _->_visualisationInfos.clear();
1,066 ✔
988
}
1,066 ✔
989

990
bool GraphModel::hasVisualisationInfo() const
991
{
2 ✔
992
    return !_->_visualisationInfos.empty();
2 ✔
993
}
2 ✔
994

995
const VisualisationInfo& GraphModel::visualisationInfoAtIndex(int index) const
996
{
20 ✔
997
    static const VisualisationInfo nullVisualisationInfo;
20 ✔
998

999
    if(u::contains(_->_visualisationInfos, index))
20 !
1000
        return _->_visualisationInfos.at(index);
20 ✔
1001

1002
    return nullVisualisationInfo;
×
1003
}
20 ✔
1004

1005
QVariantMap GraphModel::visualisationDefaultParameters(ValueType valueType, const QString& channelName) const
1006
{
10 ✔
1007
    const auto* factory = _->_application->visualisationChannelFactory(channelName);
10 ✔
1008

1009
    if(factory == nullptr)
10 !
1010
        return {};
×
1011

1012
    return factory->defaultParameters(valueType);
10 ✔
1013
}
10 ✔
1014

1015
std::vector<QString> GraphModel::attributeNames(ElementType elementType) const
1016
{
4,566 ✔
1017
    std::vector<QString> attributeNames;
4,566 ✔
1018

1019
    for(auto& attribute : _->_attributes)
4,566 ✔
1020
    {
56,374 ✔
1021
        if(Flags<ElementType>(elementType).test(attribute.second.elementType()))
56,374 ✔
1022
            attributeNames.emplace_back(attribute.first);
47,896 ✔
1023
    }
56,374 ✔
1024

1025
    return attributeNames;
4,566 ✔
1026
}
4,566 ✔
1027

1028
Attribute& GraphModel::createAttribute(const AttributeDeclaration& declaration)
1029
{
16,856 ✔
1030
    return GraphModel::createAttribute(declaration._name).setDisplayName(declaration._displayName);
16,856 ✔
1031
}
16,856 ✔
1032

1033
Attribute& GraphModel::createAttribute(QString name, QString* assignedName, QString clashHint)
1034
{
20,586 ✔
1035
    const QString requestedName = name;
20,586 ✔
1036
    name = normalisedAttributeName(name, clashHint);
20,586 ✔
1037

1038
    if(assignedName != nullptr)
20,586 ✔
1039
        *assignedName = name;
2,832 ✔
1040

1041
    Attribute& attribute = _->_attributes[name];
20,586 ✔
1042

1043
    // If we're creating an attribute during the graph transform, it's
1044
    // a dynamically created attribute rather than a persistent one,
1045
    // so mark it as such
1046
    if(_graphTransformsAreChanging)
20,586 ✔
1047
        attribute.setFlag(AttributeFlag::Dynamic);
468 ✔
1048

1049
    for(auto* tracker : _->_attributeChangesTrackers)
20,586 ✔
1050
    {
508 ✔
1051
        tracker->assignName(requestedName, name);
508 ✔
1052

1053
        if(_graphTransformsAreChanging && _->_removedDynamicAttributeNames.contains(name))
508 ✔
1054
            tracker->change(name);
4 ✔
1055
        else
504 ✔
1056
            tracker->add(name);
504 ✔
1057
    }
508 ✔
1058

1059
    return attribute;
20,586 ✔
1060
}
20,586 ✔
1061

1062
void GraphModel::addAttributes(const std::map<QString, Attribute>& attributes)
1063
{
26 ✔
1064
    _->_attributes.insert(attributes.begin(), attributes.end());
26 ✔
1065
}
26 ✔
1066

1067
void GraphModel::removeAttribute(const QString& name)
1068
{
44 ✔
1069
    if(!u::contains(_->_attributes, name))
44 !
1070
        return;
×
1071

1072
    _->_attributes.erase(name);
44 ✔
1073

1074
    for(auto* tracker : _->_attributeChangesTrackers)
44 ✔
1075
        tracker->remove(name);
44 ✔
1076
}
44 ✔
1077

1078
const Attribute* GraphModel::attributeByName(const QString& name) const
1079
{
62,955 ✔
1080
    auto attributeName = Attribute::parseAttributeName(name);
62,955 ✔
1081

1082
    if(!u::contains(_->_attributes, attributeName._name))
62,955 ✔
1083
    {
4 ✔
1084
        qDebug() << "WARNING: attribute unknown in attributeByName" << attributeName._name;
4 ✔
1085
        return nullptr;
4 ✔
1086
    }
4 ✔
1087

1088
    return &_->_attributes.at(attributeName._name);
62,951 ✔
1089
}
62,955 ✔
1090

1091
Attribute* GraphModel::attributeByName(const QString& name)
1092
{
60,886 ✔
1093
    return const_cast<Attribute*>(const_cast<const GraphModel*>(this)->attributeByName(name));
60,886 ✔
1094
}
60,886 ✔
1095

1096
bool GraphModel::attributeExists(const QString& name) const
1097
{
9,633 ✔
1098
    auto attributeName = Attribute::parseAttributeName(name);
9,633 ✔
1099
    return u::contains(_->_attributes, attributeName._name);
9,633 ✔
1100
}
9,633 ✔
1101

1102
QString GraphModel::attributeDisplayValue(const QString& name, const QString& value) const
1103
{
54 ✔
1104
    if(!attributeExists(name))
54 ✔
1105
        return value;
2 ✔
1106

1107
    const auto* attribute = attributeByName(name);
52 ✔
1108
    return attribute != nullptr ? attribute->displayValue(value) : value;
52 !
1109
}
54 ✔
1110

1111
QString GraphModel::attributeStoredValue(const QString& name, const QString& displayValue) const
1112
{
4 ✔
1113
    if(!attributeExists(name))
4 ✔
1114
        return displayValue;
2 ✔
1115

1116
    const auto* attribute = attributeByName(name);
2 ✔
1117
    return attribute != nullptr ? attribute->storedValue(displayValue) : displayValue;
2 !
1118
}
4 ✔
1119

1120
bool GraphModel::attributeIsDeclared(const QString& name) const
1121
{
2,760 ✔
1122
    return _->_application->attributeDeclaration(name, _plugin) != nullptr;
2,760 ✔
1123
}
2,760 ✔
1124

1125
QString GraphModel::attributeDisplayName(const QString& name) const
1126
{
11,417 ✔
1127
    if(name.isEmpty())
11,417 ✔
1128
        return {};
148 ✔
1129

1130
    auto displayNameOf = [this](const QString& attributeName)
11,269 ✔
1131
    {
11,269 ✔
1132
        const auto* attribute = u::contains(_->_attributes, attributeName) ?
11,269 ✔
1133
            &_->_attributes.at(attributeName) : nullptr;
11,267 ✔
1134

1135
        if(attribute != nullptr && !attribute->displayName().isEmpty())
11,269 ✔
1136
            return attribute->displayName();
1,220 ✔
1137

1138
        const auto* declaredAttribute = _->_application->attributeDeclaration(attributeName, _plugin);
10,049 ✔
1139
        if(declaredAttribute != nullptr && !declaredAttribute->_displayName.isEmpty())
10,049 !
1140
            return declaredAttribute->_displayName;
282 ✔
1141

1142
        if(attribute != nullptr)
9,767 !
1143
            return attributeName;
9,767 ✔
1144

1145
        // It doesn't exist, so there's no name to show for it
1146
        return QObject::tr("Unknown Attribute");
×
1147
    };
9,767 ✔
1148

1149
    if(u::contains(_->_attributes, name))
11,269 ✔
1150
        return displayNameOf(name);
11,261 ✔
1151

1152
    return Attribute::fullyQualifiedDisplayName(name, displayNameOf);
8 ✔
1153
}
11,269 ✔
1154

1155
bool GraphModel::attributeIsValid(const QString& name) const
1156
{
1,076 ✔
1157
    if(!attributeExists(name))
1,076 !
1158
        return false;
×
1159

1160
    auto attributeName = Attribute::parseAttributeName(name);
1,076 ✔
1161
    const auto* attribute = &_->_attributes.at(attributeName._name);
1,076 ✔
1162

1163
    const bool attributeDisabled = _graphTransformsAreChanging &&
1,076 !
1164
        attribute->testFlag(AttributeFlag::DisableDuringTransform);
1,076 !
1165

1166
    return !attributeDisabled;
1,076 ✔
1167
}
1,076 ✔
1168

1169
Attribute GraphModel::attributeValueByName(const QString& name) const
1170
{
3,614 ✔
1171
    auto attributeName = Attribute::parseAttributeName(name);
3,614 ✔
1172

1173
    if(!u::contains(_->_attributes, attributeName._name))
3,614 ✔
1174
    {
6 ✔
1175
        qDebug() << "WARNING: attribute unknown in attributeValueByName" << attributeName._name;
6 ✔
1176
        return {};
6 ✔
1177
    }
6 ✔
1178

1179
    auto attribute = _->_attributes.at(attributeName._name);
3,608 ✔
1180

1181
    if(!attributeName._parameter.isEmpty())
3,608 ✔
1182
        attribute.setParameterValue(attributeName._parameter);
16 ✔
1183

1184
    if(attributeName._type != Attribute::EdgeNodeType::None)
3,608 ✔
1185
    {
112 ✔
1186
        return Attribute::edgeNodesAttribute(_->_graph,
112 ✔
1187
            attribute, attributeName._type);
112 ✔
1188
    }
112 ✔
1189

1190
    return attribute;
3,496 ✔
1191
}
3,608 ✔
1192

1193
void GraphModel::calculateAttributeRange(const IGraph* graph, Attribute& attribute)
1194
{
59,074 ✔
1195
    if(!attribute.testFlag(AttributeFlag::AutoRange))
59,074 ✔
1196
        return;
46,818 ✔
1197

1198
    if(attribute.elementType() == ElementType::Node)
12,256 ✔
1199
        attribute.autoSetRangeForElements(graph->nodeIds());
9,938 ✔
1200
    else if(attribute.elementType() == ElementType::Edge)
2,318 !
1201
        attribute.autoSetRangeForElements(graph->edgeIds());
2,318 ✔
1202
    else if(attribute.elementType() == ElementType::Component)
×
1203
        qDebug() << "calculateAttributeRange called on component attribute";
×
1204
}
12,256 ✔
1205

1206
void GraphModel::calculateAttributeRange(Attribute& attribute)
1207
{
24,712 ✔
1208
    calculateAttributeRange(&mutableGraph(), attribute);
24,712 ✔
1209
}
24,712 ✔
1210

1211
static void calculateAttributeRanges(const Graph* graph,
1212
    std::map<QString, Attribute>& attributes)
1213
{
3,344 ✔
1214
    for(auto& attribute : make_value_wrapper(attributes)) // clazy:exclude=compare-member-check
3,344 ✔
1215
        GraphModel::calculateAttributeRange(graph, attribute);
34,362 ✔
1216
}
3,344 ✔
1217

1218
void GraphModel::initialiseAttributeRanges()
1219
{
1,510 ✔
1220
    calculateAttributeRanges(&mutableGraph(), _->_attributes);
1,510 ✔
1221
}
1,510 ✔
1222

1223
void GraphModel::initialiseSharedAttributeValues()
1224
{
604 ✔
1225
    for(auto& attribute : make_value_wrapper(_->_attributes)) // clazy:exclude=compare-member-check
604 ✔
1226
        _->updateSharedAttributeValues(attribute);
8,342 ✔
1227
}
604 ✔
1228

1229
bool GraphModel::attributeNameIsValid(const QString& attributeName)
1230
{
100 ✔
1231
    if(attributeName.isEmpty())
100 ✔
1232
        return false;
6 ✔
1233

1234
    auto attributeNameRegex = QRegularExpression(IAttribute::ValidNameRegex);
94 ✔
1235
    return attributeNameRegex.match(attributeName).hasMatch();
94 ✔
1236
}
100 ✔
1237

1238
UserNodeData& GraphModel::userNodeData() { return _->_userNodeData; }
60,420 ✔
1239
UserEdgeData& GraphModel::userEdgeData() { return _->_userEdgeData; }
2,612 ✔
1240

1241
void GraphModel::clearHighlightedNodes()
1242
{
×
1243
    highlightNodes({});
×
1244
}
×
1245

1246
void GraphModel::highlightNodes(const NodeIdSet& nodeIds)
1247
{
6 ✔
1248
    bool requested = false;
6 ✔
1249

1250
    _->requestVisualUpdate([this, &nodeIds, &requested](auto& pending)
6 ✔
1251
    {
6 ✔
1252
        const auto& latestHighlightedNodeIds = pending._highlightedNodeIds ?
6 !
1253
            *pending._highlightedNodeIds : _->_highlightedNodeIds;
6 ✔
1254

1255
        if(latestHighlightedNodeIds.empty() && nodeIds.empty())
6 !
1256
            return;
×
1257

1258
        pending._highlightedNodeIds = nodeIds;
6 ✔
1259
        pending._full = true;
6 ✔
1260
        requested = true;
6 ✔
1261
    });
6 ✔
1262

1263
    if(requested)
6 !
1264
        scheduleVisualUpdate();
6 ✔
1265
}
6 ✔
1266

1267
void GraphModel::enableVisualUpdates()
1268
{
660 ✔
1269
    // Loading has only just built the transforms and visualisations from scratch
1270
    _->_transformRebuildRequired = false;
660 ✔
1271
    _->_visualisationRebuildRequired = false;
660 ✔
1272

1273
    _visualUpdatesEnabled = true;
660 ✔
1274
    _->requestFullVisualUpdate();
660 ✔
1275

1276
    // This is the one update made on the main thread, and it is made here deliberately.
1277
    // Loading has finished, so there is no command to overlap, and the renderer is only
1278
    // ever created while the main thread is blocked, so it cannot appear part way through
1279
    // this update, and then read the visuals while they are being written, or see the
1280
    // end of the change without having seen its beginning
1281
    applyPendingVisualUpdates();
660 ✔
1282
}
660 ✔
1283

1284
static float mappedSize(float min, float max, float user, float mapped = -1.0f)
1285
{
392,322 ✔
1286
    if(mapped < 0.0f)
392,322 ✔
1287
        return user;
392,204 ✔
1288

1289
    // The fraction of the mapped value that contributes to the final value
1290
    const float mappedRange = 0.75f;
118 ✔
1291

1292
    auto normalised = u::normalise(min, max, user);
118 ✔
1293
    auto out = (mapped * mappedRange) + (normalised * (1.0f - mappedRange));
118 ✔
1294

1295
    return min + (out * (max - min));
118 ✔
1296
}
392,322 ✔
1297

1298
static float mappedTextSize(float user, float mapped = -1.0f)
1299
{
393,394 ✔
1300
    auto value = mapped >= 0.0f ?
393,394 ✔
1301
        ((1.0f * user) + (2.0f * mapped)) / 3.0f :
16 ✔
1302
        user;
393,394 ✔
1303

1304
    return value < 0.5f ?
393,394 ✔
1305
        u::interpolate(LimitConstants::minimumTextSize(), 1.0f, value / 0.5f) :
52 ✔
1306
        u::interpolate(1.0f, LimitConstants::maximumTextSize(), (value - 0.5f) / 0.5f);
393,394 ✔
1307
}
393,394 ✔
1308

1309
bool GraphModel::nodeIsUnhighlighted(NodeId nodeId, bool nodeIsSelected) const
1310
{
196,780 ✔
1311
    auto isNotFound = !_->_foundNodeIds.empty() && !u::contains(_->_foundNodeIds, nodeId);
196,780 ✔
1312
    auto isNotHighlighted = !_->_highlightedNodeIds.empty() && nodeIsSelected &&
196,780 !
1313
        !u::contains(_->_highlightedNodeIds, nodeId);
196,780 ✔
1314

1315
    return (isNotFound && _->_nodesMaskActive) || isNotHighlighted;
196,780 ✔
1316
}
196,780 ✔
1317

1318
void GraphModel::scheduleVisualUpdate()
1319
{
31,148 ✔
1320
    // Before visual updates are enabled requests only accumulate, and
1321
    // enabling them schedules the update that takes account of them all
1322
    if(_visualUpdatesEnabled)
31,148 ✔
1323
        emit visualUpdateRequested();
632 ✔
1324
}
31,148 ✔
1325

1326
void GraphModel::applyPendingVisualUpdates()
1327
{
1,604 ✔
1328
    if(!_visualUpdatesEnabled)
1,604 !
1329
        return;
×
1330

1331
    // Nothing locks the graph while it is read here: after loading it only ever changes
1332
    // in commands, and this only ever runs between them, or at the end of one
1333

1334
    PendingVisualUpdate pending;
1,604 ✔
1335
    NodeIdSet previousSelectedNodeIds;
1,604 ✔
1336
    bool maskChanged = false;
1,604 ✔
1337

1338
    {
1,604 ✔
1339
        const std::unique_lock<std::mutex> pendingLock(_->_pendingVisualUpdateMutex);
1,604 ✔
1340
        pending = std::exchange(_->_pendingVisualUpdate, {});
1,604 ✔
1341

1342
        if(pending._selectedNodeIds)
1,604 ✔
1343
        {
156 ✔
1344
            previousSelectedNodeIds = std::exchange(_->_selectedNodeIds,
156 ✔
1345
                std::move(*pending._selectedNodeIds));
156 ✔
1346
        }
156 ✔
1347

1348
        if(pending._nodesMaskActive)
1,604 ✔
1349
        {
156 ✔
1350
            maskChanged = std::exchange(_->_nodesMaskActive,
156 ✔
1351
                *pending._nodesMaskActive) != *pending._nodesMaskActive;
156 ✔
1352
        }
156 ✔
1353

1354
        if(pending._foundNodeIds)
1,604 ✔
1355
            _->_foundNodeIds = std::move(*pending._foundNodeIds);
24 ✔
1356

1357
        if(pending._highlightedNodeIds)
1,604 ✔
1358
            _->_highlightedNodeIds = std::move(*pending._highlightedNodeIds);
6 ✔
1359
    }
1,604 ✔
1360

1361
    // Whether a mask is in place affects the highlight state of every node, not
1362
    // just the ones whose selected state changed, so there is no shortcut here
1363
    if(pending._full || maskChanged)
1,604 ✔
1364
        updateVisuals(pending._force);
1,072 ✔
1365
    else if(pending._selectedNodeIds)
532 ✔
1366
        updateSelectionVisuals(previousSelectedNodeIds);
142 ✔
1367
}
1,604 ✔
1368

1369
void GraphModel::updateVisuals(bool force)
1370
{
1,072 ✔
1371
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
1,072 ✔
1372

1373
    const float userNodeSize = _->_nodeSize;
1,072 ✔
1374
    const float userEdgeSize = _->_edgeSize;
1,072 ✔
1375
    const float userTextSize = _->_textSize;
1,072 ✔
1376

1377
    auto nodeColor      = u::pref(u"visuals/defaultNodeColor"_s).value<QColor>();
1,072 ✔
1378
    auto edgeColor      = u::pref(u"visuals/defaultEdgeColor"_s).value<QColor>();
1,072 ✔
1379
    auto multiColor     = u::pref(u"visuals/multiElementColor"_s).value<QColor>();
1,072 ✔
1380
    auto nodeSize       = u::interpolate(LimitConstants::minimumNodeSize(), LimitConstants::maximumNodeSize(), userNodeSize);
1,072 ✔
1381
    auto edgeSize       = u::interpolate(LimitConstants::minimumEdgeSize(), LimitConstants::maximumEdgeSize(), userEdgeSize);
1,072 ✔
1382
    auto textSize       = mappedTextSize(userTextSize);
1,072 ✔
1383
    auto textColor      = Document::contrastingColorForBackground();
1,072 ✔
1384
    auto meIndicators   = u::pref(u"visuals/showMultiElementIndicators"_s).toBool();
1,072 ✔
1385

1386
    auto& nodeVisuals = _->_nodeVisuals;
1,072 ✔
1387
    auto& edgeVisuals = _->_edgeVisuals;
1,072 ✔
1388

1389
    Flags<VisualChangeFlags> nodeChanges;
1,072 ✔
1390
    Flags<VisualChangeFlags> edgeChanges;
1,072 ✔
1391

1392
    bool changing = false;
1,072 ✔
1393
    auto beginChanging = [this, &changing]
1,072 ✔
1394
    {
455,288 ✔
1395
        if(changing)
455,288 ✔
1396
            return;
454,380 ✔
1397

1398
        changing = true;
908 ✔
1399
        emit visualsWillChange();
908 ✔
1400
    };
908 ✔
1401

1402
    auto setIfChanged = [&beginChanging](auto& destination, const auto& value,
1,072 ✔
1403
        Flags<VisualChangeFlags>& changes, VisualChangeFlags change)
1,072 ✔
1404
    {
2,746,254 ✔
1405
        if(destination != value) // clazy:exclude=compare-member-check
2,746,254 ✔
1406
        {
455,274 ✔
1407
            beginChanging();
455,274 ✔
1408
            destination = value;
455,274 ✔
1409
            changes.set(change);
455,274 ✔
1410
        }
455,274 ✔
1411
    };
2,746,254 ✔
1412

1413
    if(force)
1,072 ✔
1414
        beginChanging();
8 ✔
1415

1416
    // An edge's state is accumulated from the nodes it joins, so it is staged here and
1417
    // written back once complete, rather than being cleared and rebuilt where it lives
1418
    EdgeArray<Flags<VisualFlags>> newEdgeStates(graph());
1,072 ✔
1419

1420
    for(auto edgeId : graph().edgeIds())
1,072 ✔
1421
    {
195,872 ✔
1422
        newEdgeStates[edgeId] = edgeVisuals[edgeId]._state;
195,872 ✔
1423
        newEdgeStates[edgeId].reset(VisualFlags::Selected, VisualFlags::Unhighlighted);
195,872 ✔
1424
    }
195,872 ✔
1425

1426
    auto setElementVisual = [&](auto elementId, auto& visual, const auto& mapped,
1,072 ✔
1427
        float size, const QColor& color, const QString& text,
1,072 ✔
1428
        Flags<VisualChangeFlags>& changes)
1,072 ✔
1429
    {
392,322 ✔
1430
        setIfChanged(visual._size, size, changes, VisualChangeFlags::Size);
392,322 ✔
1431

1432
        setIfChanged(visual._outerColor, mapped._outerColor.isValid() ?
392,322 !
1433
            mapped._outerColor : color, changes, VisualChangeFlags::Color);
295,778 ✔
1434

1435
        setIfChanged(visual._innerColor,
392,322 ✔
1436
            !meIndicators || graph().typeOf(elementId) == MultiElementType::Not ?
392,322 !
1437
            visual._outerColor : multiColor, changes, VisualChangeFlags::Color);
392,306 ✔
1438

1439
        setIfChanged(visual._text, !mapped._text.isEmpty() ?
392,322 ✔
1440
            mapped._text : text, changes, VisualChangeFlags::Text);
392,204 ✔
1441

1442
        setIfChanged(visual._textSize, mappedTextSize(userTextSize, mapped._textSize),
392,322 ✔
1443
            changes, VisualChangeFlags::TextSize);
392,322 ✔
1444

1445
        setIfChanged(visual._textColor, mapped._textColor.isValid() ?
392,322 !
1446
            mapped._textColor : textColor, changes, VisualChangeFlags::TextColor);
392,258 ✔
1447
    };
392,322 ✔
1448

1449
    for(auto nodeId : graph().nodeIds())
1,072 ✔
1450
    {
196,450 ✔
1451
        auto& visual = nodeVisuals[nodeId];
196,450 ✔
1452
        const auto& mapped = _->_mappedNodeVisuals[nodeId];
196,450 ✔
1453

1454
        setElementVisual(nodeId, visual, mapped,
196,450 ✔
1455
            mappedSize(LimitConstants::minimumNodeSize(), LimitConstants::maximumNodeSize(),
196,450 ✔
1456
            nodeSize, mapped._size), nodeColor, nodeName(nodeId), nodeChanges);
196,450 ✔
1457

1458
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
196,450 ✔
1459
        auto nodeUnhighlighted = nodeIsUnhighlighted(nodeId, nodeIsSelected);
196,450 ✔
1460

1461
        auto state = visual._state;
196,450 ✔
1462
        state.setState(VisualFlags::Selected, nodeIsSelected);
196,450 ✔
1463
        state.setState(VisualFlags::Unhighlighted, nodeUnhighlighted);
196,450 ✔
1464
        setIfChanged(visual._state, state, nodeChanges, VisualChangeFlags::State);
196,450 ✔
1465

1466
        if(nodeIsSelected)
196,450 ✔
1467
        {
90 ✔
1468
            for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
90 ✔
1469
                newEdgeStates[edgeId].set(VisualFlags::Selected);
144 ✔
1470
        }
90 ✔
1471

1472
        if(nodeUnhighlighted)
196,450 ✔
1473
        {
38 ✔
1474
            for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
38 ✔
1475
                newEdgeStates[edgeId].set(VisualFlags::Unhighlighted);
56 ✔
1476
        }
38 ✔
1477
    }
196,450 ✔
1478

1479
    for(auto edgeId : graph().edgeIds())
1,072 ✔
1480
    {
195,872 ✔
1481
        auto& visual = edgeVisuals[edgeId];
195,872 ✔
1482
        const auto& mapped = _->_mappedEdgeVisuals[edgeId];
195,872 ✔
1483

1484
        // An edge is never drawn thicker than either of the nodes it joins
1485
        const auto& edge = graph().edgeById(edgeId);
195,872 ✔
1486
        auto size = std::min({mappedSize(LimitConstants::minimumEdgeSize(),
195,872 ✔
1487
            LimitConstants::maximumEdgeSize(), edgeSize, mapped._size),
195,872 ✔
1488
            nodeVisuals[edge.sourceId()]._size, nodeVisuals[edge.targetId()]._size});
195,872 ✔
1489

1490
        setElementVisual(edgeId, visual, mapped, size, edgeColor, {}, edgeChanges);
195,872 ✔
1491

1492
        setIfChanged(visual._state, newEdgeStates[edgeId], edgeChanges, VisualChangeFlags::State);
195,872 ✔
1493
    }
195,872 ✔
1494

1495
    for(auto& [componentId, textVisuals] : _->_newTextVisuals)
1,072 ✔
1496
    {
18 ✔
1497
        for(auto& textVisual : textVisuals)
18 ✔
1498
        {
30 ✔
1499
            // This is a reasonable approximation for fixing the text size to something that
1500
            // is close to the average radius of the node island being annotated
1501
            textVisual._size = textSize * std::cbrt(static_cast<float>(textVisual._nodeIds.size()));
30 ✔
1502
            textVisual._color = textColor;
30 ✔
1503
        }
30 ✔
1504
    }
18 ✔
1505

1506
    auto findTextVisualsChange = [](const TextVisuals& previous, const TextVisuals& current)
1,072 ✔
1507
    {
1,072 ✔
1508
        Flags<VisualChangeFlags> change;
1,072 ✔
1509

1510
        if(previous.size() != current.size())
1,072 ✔
1511
            return VisualChangeFlags::State;
6 ✔
1512

1513
        auto previousComponentIds = u::keysFor(previous);
1,066 ✔
1514
        auto currentComponentIds = u::keysFor(current);
1,066 ✔
1515

1516
        if(previousComponentIds != currentComponentIds)
1,066 !
1517
            return VisualChangeFlags::State;
×
1518

1519
        for(const ComponentId componentId : previousComponentIds)
1,066 !
1520
        {
×
1521
            const auto& previousTextVisuals = previous.at(componentId);
×
1522
            const auto& currentTextVisuals = current.at(componentId);
×
1523

1524
            if(previousTextVisuals.size() != currentTextVisuals.size())
×
1525
                return VisualChangeFlags::State;
×
1526

1527
            for(size_t i = 0; i < previousTextVisuals.size(); i++)
×
1528
            {
×
1529
                const auto& previousTextVisual = previousTextVisuals.at(i);
×
1530
                const auto& currentTextVisual = currentTextVisuals.at(i);
×
1531

1532
                if(previousTextVisual._nodeIds != currentTextVisual._nodeIds)
×
1533
                    return VisualChangeFlags::State;
×
1534

1535
                if(previousTextVisual._color != currentTextVisual._color)
×
1536
                    change.set(VisualChangeFlags::TextColor);
×
1537

1538
                if(previousTextVisual._size != currentTextVisual._size)
×
1539
                    change.set(VisualChangeFlags::TextSize);
×
1540
            }
×
1541
        }
×
1542

1543
        return *change;
1,066 ✔
1544
    };
1,066 ✔
1545

1546
    const VisualChangeFlags textChange = findTextVisualsChange(_->_textVisuals, _->_newTextVisuals);
1,072 ✔
1547

1548
    if(textChange != VisualChangeFlags::None)
1,072 ✔
1549
        beginChanging();
6 ✔
1550

1551
    if(!changing)
1,072 ✔
1552
        return;
164 ✔
1553

1554
    {
908 ✔
1555
        const std::unique_lock<std::mutex> textVisualsLock(_->_textVisualsMutex);
908 ✔
1556

1557
        _->_textVisuals = _->_newTextVisuals;
908 ✔
1558
        updateTextVisualPositions(_->_textVisuals, _->_nodePositions);
908 ✔
1559
    }
908 ✔
1560

1561
    visualsLock.unlock();
908 ✔
1562
    emit visualsChanged(*nodeChanges, *edgeChanges, textChange);
908 ✔
1563
}
908 ✔
1564

1565
// When the selection changes, only update the selection visuals
1566
void GraphModel::updateSelectionVisuals(const NodeIdSet& previousSelectedNodeIds)
1567
{
142 ✔
1568
    std::vector<NodeId> changedNodeIds;
142 ✔
1569
    std::ranges::set_symmetric_difference(_->_selectedNodeIds, previousSelectedNodeIds,
142 ✔
1570
        std::back_inserter(changedNodeIds));
142 ✔
1571

1572
    if(changedNodeIds.empty())
142 ✔
1573
        return;
14 ✔
1574

1575
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
128 ✔
1576

1577
    emit visualsWillChange();
128 ✔
1578

1579
    Flags<VisualChangeFlags> nodeChange;
128 ✔
1580
    Flags<VisualChangeFlags> edgeChange;
128 ✔
1581

1582
    for(auto nodeId : changedNodeIds)
128 ✔
1583
    {
330 ✔
1584
        auto& nodeVisual = _->_nodeVisuals[nodeId];
330 ✔
1585
        const auto previousState = nodeVisual._state;
330 ✔
1586

1587
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
330 ✔
1588

1589
        nodeVisual._state.setState(VisualFlags::Selected, nodeIsSelected);
330 ✔
1590
        nodeVisual._state.setState(VisualFlags::Unhighlighted,
330 ✔
1591
            nodeIsUnhighlighted(nodeId, nodeIsSelected));
330 ✔
1592

1593
        if(nodeVisual._state != previousState) // clazy:exclude=compare-member-check
330 !
1594
            nodeChange.set(VisualChangeFlags::State);
330 ✔
1595
    }
330 ✔
1596

1597
    for(auto nodeId : changedNodeIds)
128 ✔
1598
    {
330 ✔
1599
        for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
330 ✔
1600
        {
498 ✔
1601
            auto& edgeVisual = _->_edgeVisuals[edgeId];
498 ✔
1602
            const auto previousState = edgeVisual._state;
498 ✔
1603

1604
            // An edge is selected or unhighlighted if either of the nodes it joins is;
1605
            // those are precisely the nodes whose edgeIdsForNodeId contains it
1606
            const auto& edge = graph().edgeById(edgeId);
498 ✔
1607
            const auto sourceState = _->_nodeVisuals[edge.sourceId()]._state;
498 ✔
1608
            const auto targetState = _->_nodeVisuals[edge.targetId()]._state;
498 ✔
1609

1610
            edgeVisual._state.setState(VisualFlags::Selected,
498 ✔
1611
                sourceState.test(VisualFlags::Selected) ||
498 ✔
1612
                targetState.test(VisualFlags::Selected));
498 ✔
1613

1614
            edgeVisual._state.setState(VisualFlags::Unhighlighted,
498 ✔
1615
                sourceState.test(VisualFlags::Unhighlighted) ||
498 ✔
1616
                targetState.test(VisualFlags::Unhighlighted));
498 ✔
1617

1618
            if(edgeVisual._state != previousState) // clazy:exclude=compare-member-check
498 ✔
1619
                edgeChange.set(VisualChangeFlags::State);
304 ✔
1620
        }
498 ✔
1621
    }
330 ✔
1622

1623
    visualsLock.unlock();
128 ✔
1624
    emit visualsChanged(*nodeChange, *edgeChange, VisualChangeFlags::None);
128 ✔
1625
}
128 ✔
1626

1627
void GraphModel::onSelectionChanged(const SelectionManager* selectionManager)
1628
{
156 ✔
1629
    auto selectedNodeIds = selectionManager->selectedNodes();
156 ✔
1630
    auto nodesMaskActive = selectionManager->nodesMaskActive();
156 ✔
1631

1632
    _->requestVisualUpdate([&selectedNodeIds, nodesMaskActive](auto& pending)
156 ✔
1633
    {
156 ✔
1634
        pending._selectedNodeIds = std::move(selectedNodeIds);
156 ✔
1635
        pending._nodesMaskActive = nodesMaskActive;
156 ✔
1636
    });
156 ✔
1637

1638
    scheduleVisualUpdate();
156 ✔
1639
}
156 ✔
1640

1641
void GraphModel::onFoundNodeIdsChanged(const SearchManager* searchManager)
1642
{
24 ✔
1643
    auto foundNodeIds = searchManager->foundNodeIds();
24 ✔
1644

1645
    _->requestVisualUpdate([&foundNodeIds](auto& pending)
24 ✔
1646
    {
24 ✔
1647
        pending._foundNodeIds = std::move(foundNodeIds);
24 ✔
1648
        pending._full = true;
24 ✔
1649
    });
24 ✔
1650

1651
    scheduleVisualUpdate();
24 ✔
1652
}
24 ✔
1653

1654
void GraphModel::onPreferenceChanged(const QString& name, const QVariant&)
1655
{
32 ✔
1656
    if(!name.startsWith(u"visuals"_s))
32 ✔
1657
        return;
18 ✔
1658

1659
    const bool force = name.endsWith(u"backgroundColor"_s) ||
14 !
1660
        name.endsWith(u"showNodeText"_s) ||
14 ✔
1661
        name.endsWith(u"showEdgeText"_s) ||
14 ✔
1662
        name.endsWith(u"showEdges"_s) ||
14 !
1663
        name.endsWith(u"edgeVisualType"_s) ||
14 !
1664
        name.endsWith(u"highlightColor"_s) ||
14 !
1665
        name.endsWith(u"textFont"_s) ||
14 !
1666
        name.endsWith(u"textSize"_s) ||
14 !
1667
        name.endsWith(u"textAlignment"_s);
14 !
1668

1669
    _->requestVisualUpdate([force](auto& pending)
14 ✔
1670
    {
14 ✔
1671
        pending._full = true;
14 ✔
1672
        pending._force = pending._force || force;
14 !
1673
    });
14 ✔
1674

1675
    scheduleVisualUpdate();
14 ✔
1676
}
14 ✔
1677

1678
void GraphModel::onLayoutChanged()
1679
{
5,388 ✔
1680
    // This occurs on the layout thread
1681
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
5,388 ✔
1682
    updateTextVisualPositions(_->_textVisuals, _->_nodePositions);
5,388 ✔
1683
}
5,388 ✔
1684

1685
void GraphModel::onMutableGraphChanged(const Graph* graph)
1686
{
1,834 ✔
1687
    calculateAttributeRanges(graph, _->_attributes);
1,834 ✔
1688
}
1,834 ✔
1689

1690
void GraphModel::onTransformedGraphWillChange(const Graph*)
1691
{
1,858 ✔
1692
    // The graph may gain elements that have never been through a full visual
1693
    // update, so whatever next asks for an update must get a full one
1694
    _->requestFullVisualUpdate();
1,858 ✔
1695

1696
    // Rebuilding applies the transforms to the attribute values as they now are
1697
    _->_transformRebuildRequired = false;
1,858 ✔
1698

1699
    // Store previous attributes for comparison
1700
    _->_previousAttributeIdentities = _->currentAttributeIdentities();
1,858 ✔
1701

1702
    removeDynamicAttributes();
1,858 ✔
1703

1704
    _graphTransformsAreChanging = true;
1,858 ✔
1705
}
1,858 ✔
1706

1707
void GraphModel::onTransformedGraphChanged(const Graph*, bool changeOccurred)
1708
{
1,858 ✔
1709
    _->_removedDynamicAttributeNames.clear();
1,858 ✔
1710

1711
    auto attributeIdentities = _->currentAttributeIdentities();
1,858 ✔
1712

1713
    // Compare with previous attributes
1714
    auto removedAttributeIdentities = u::setDifference(_->_previousAttributeIdentities, attributeIdentities);
1,858 ✔
1715
    auto addedAttributeIdentities = u::setDifference(attributeIdentities, _->_previousAttributeIdentities);
1,858 ✔
1716

1717
    QStringList removedAttributeNames;
1,858 ✔
1718
    QStringList addedAttributeNames;
1,858 ✔
1719

1720
    auto identityToName = [](const auto& identity) { return identity._name; };
1,858 ✔
1721

1722
    std::ranges::transform(removedAttributeIdentities,
1,858 ✔
1723
        std::back_inserter(removedAttributeNames), identityToName);
1,858 ✔
1724
    std::ranges::transform(addedAttributeIdentities,
1,858 ✔
1725
        std::back_inserter(addedAttributeNames), identityToName);
1,858 ✔
1726

1727
    QStringList changedAttributeNames(std::move(_->_changedDynamicAttributeNames));
1,858 ✔
1728

1729
    changedAttributeNames.erase(std::ranges::remove_if(changedAttributeNames,
1,858 ✔
1730
    [&removedAttributeNames, &addedAttributeNames](const auto& dynamicAttributeName)
1,858 ✔
1731
    {
1,858 ✔
1732
        return u::contains(removedAttributeNames, dynamicAttributeName) ||
10 !
1733
            u::contains(addedAttributeNames, dynamicAttributeName);
10 !
1734
    }).begin(), changedAttributeNames.end());
10 ✔
1735

1736
    // When the graph changes, every attribute's range and shared values also potentially change
1737
    for(auto& [name, attribute] : _->_attributes)
1,858 ✔
1738
    {
23,776 ✔
1739
        // These ones will be taken care of in onAttributesChanged, below...
1740
        if(u::contains(addedAttributeNames, name) || u::contains(changedAttributeNames, name))
23,776 ✔
1741
            continue;
468 ✔
1742

1743
        calculateAttributeRange(attribute);
23,308 ✔
1744
        _->updateSharedAttributeValues(attribute);
23,308 ✔
1745
    }
23,308 ✔
1746

1747
    emit attributesChanged(addedAttributeNames, removedAttributeNames,
1,858 ✔
1748
        changedAttributeNames, changeOccurred);
1,858 ✔
1749

1750
    _graphTransformsAreChanging = false;
1,858 ✔
1751
}
1,858 ✔
1752

1753
// This will also be called when the transformed graph changes, even if there are no actual attribute changes
1754
void GraphModel::onAttributesChanged(const QStringList& addedNames, const QStringList& removedNames,
1755
    const QStringList& changedValuesNames, bool graphChangeOccurred)
1756
{
1,996 ✔
1757
    for(const auto& attributeName : u::combine(addedNames, changedValuesNames))
1,996 ✔
1758
    {
588 ✔
1759
        auto& attribute = _->_attributes.at(Attribute::parseAttributeName(attributeName)._name);
588 ✔
1760

1761
        if(attribute.testFlag(AttributeFlag::Dynamic) && attribute.userDefined())
588 !
1762
        {
×
1763
            qDebug() << "WARNING: Dynamic attribute" << attributeName <<
×
1764
                "has userDefined set, this is not allowed, resetting...";
×
1765
            attribute.setUserDefined(false);
×
1766
        }
×
1767

1768
        calculateAttributeRange(attribute);
588 ✔
1769
        _->updateSharedAttributeValues(attribute);
588 ✔
1770
    }
588 ✔
1771

1772
    // Attribute changes may require a graph transform or visualisation to be rebuilt
1773
    QStringList changed;
1,996 ✔
1774
    changed << addedNames << removedNames << changedValuesNames;
1,996 ✔
1775
    u::removeDuplicates(changed);
1,996 ✔
1776

1777
    const bool transformRebuildRequired = !_graphTransformsAreChanging &&
1,996 ✔
1778
        _->_transformedGraph.onAttributeValuesChangedExternally(changed);
1,996 ✔
1779

1780
    const bool visualisationRebuildRequired = graphChangeOccurred || !u::setIntersection(
1,996 !
1781
        static_cast<const QList<QString>&>(_->_visualisedAttributeNames),
246 ✔
1782
        static_cast<const QList<QString>&>(changed)).empty();
246 ✔
1783

1784
    if(transformRebuildRequired)
1,996 ✔
1785
        _->_transformRebuildRequired = true;
6 ✔
1786

1787
    if(visualisationRebuildRequired)
1,996 ✔
1788
        _->_visualisationRebuildRequired = true;
1,750 ✔
1789

1790
    // The rebuilds happen alongside the next visual update
1791
    if(transformRebuildRequired || visualisationRebuildRequired)
1,996 ✔
1792
        scheduleVisualUpdate();
1,756 ✔
1793
}
1,996 ✔
1794

1795
AttributeChangesTracker::AttributeChangesTracker(GraphModel* graphModel,
1796
    NamedBool<"emitOnDestruct"> emitOnDestruct) :
1797
    _graphModel(graphModel), _emitOnDestruct(emitOnDestruct)
1,434 ✔
1798
{
1,434 ✔
1799
    _graphModel->_->_attributeChangesTrackers.insert(this);
1,434 ✔
1800
}
1,434 ✔
1801

1802
AttributeChangesTracker::~AttributeChangesTracker()
1803
{
1,434 ✔
1804
    if(_emitOnDestruct)
1,434 ✔
1805
        emitAttributesChanged();
172 ✔
1806

1807
    _graphModel->_->_attributeChangesTrackers.erase(this);
1,434 ✔
1808
}
1,434 ✔
1809

1810
void AttributeChangesTracker::assignName(const QString& requestedName, const QString& assignedName)
1811
{
508 ✔
1812
    _assignedNames[requestedName] = assignedName;
508 ✔
1813
}
508 ✔
1814

1815
void AttributeChangesTracker::add(const QString& name)
1816
{
504 ✔
1817
    if(u::contains(_changed, name))
504 !
1818
    {
×
1819
        qDebug() << "AttributeChangesTracker::add called on attribute marked as changed" << name;
×
1820
        _changed.remove(name);
×
1821
    }
×
1822

1823
    if(u::contains(_removed, name))
504 ✔
1824
    {
6 ✔
1825
        // If it's been removed and added, count that as changed (potentially)
1826
        _removed.remove(name);
6 ✔
1827
        _changed.insert(name);
6 ✔
1828
    }
6 ✔
1829
    else
498 ✔
1830
       _added.insert(name);
498 ✔
1831
}
504 ✔
1832

1833
void AttributeChangesTracker::remove(const QString& name)
1834
{
44 ✔
1835
    if(u::contains(_added, name))
44 !
1836
    {
×
1837
        // If it's been added and removed, count that as net zero
1838
        _added.remove(name);
×
1839
    }
×
1840
    else
44 ✔
1841
        _removed.insert(name);
44 ✔
1842
}
44 ✔
1843

1844
void AttributeChangesTracker::change(const QString& name)
1845
{
190 ✔
1846
    // Only count an attribute as changed if it's not new
1847
    if(!u::contains(_added, name))
190 !
1848
        _changed.insert(name);
190 ✔
1849
}
190 ✔
1850

1851
QStringList AttributeChangesTracker::addedOrChanged() const
1852
{
1,258 ✔
1853
    auto combined = u::combine(_added, _changed);
1,258 ✔
1854
    return {combined.begin(), combined.end()};
1,258 ✔
1855
}
1,258 ✔
1856

1857
void AttributeChangesTracker::emitAttributesChanged()
1858
{
172 ✔
1859
    if(_added.empty() && _removed.empty() && _changed.empty())
172 ✔
1860
        return;
34 ✔
1861

1862
    emit _graphModel->attributesChanged(added(), removed(), changed(), false);
138 ✔
1863
}
138 ✔
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