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

graphia-app / graphia / 42417955599

07 Nov 2026 08:33PM UTC coverage: 71.51% (+0.07%) from 71.441%
42417955599

push

github

timangus
CLAUDE: Suppress cppcheck's duplInheritedMember check and drop NodePositions' second mutex

11809 of 18066 branches covered (65.37%)

Branch coverage included in aggregate %.

29972 of 40361 relevant lines covered (74.26%)

591425.76 hits per line

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

88.53
/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
{
3,609 ✔
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);
3,609 ✔
88

89
    for(auto& [componentId, textVisuals_] : textVisuals)
3,609 ✔
90
    {
18 ✔
91
        for(auto& textVisual : textVisuals_)
18 ✔
92
            textVisual.updatePositions(nodePositions);
30 ✔
93
    }
18 ✔
94
}
3,609 ✔
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,604 ✔
115
        _transformedGraph(graphModel, _graph),
1,604 ✔
116
        _nodePositions(_graph),
1,604 ✔
117
        _nodeVisuals(_graph),
1,604 ✔
118
        _edgeVisuals(_graph),
1,604 ✔
119
        _mappedNodeVisuals(_graph),
1,604 ✔
120
        _mappedEdgeVisuals(_graph),
1,604 ✔
121
        _nodeNames(_graph)
1,604 ✔
122
    {
1,604 ✔
123
        _userNodeData.initialise(_graph);
1,604 ✔
124
        _userEdgeData.initialise(_graph);
1,604 ✔
125
    }
1,604 ✔
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)
43,454 ✔
173
        {}
43,454 ✔
174

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

183
    std::vector<AttributeIdentity> _previousAttributeIdentities;
184

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

190
        for(const auto& attribute : _attributes)
3,324 ✔
191
        {
43,454 ✔
192
            // cppcheck-suppress useStlAlgorithm
193
            attributeIdentities.emplace_back(
43,454 ✔
194
                attribute.first,
43,454 ✔
195
                attribute.second.valueType(),
43,454 ✔
196
                attribute.second.elementType());
43,454 ✔
197
        }
43,454 ✔
198

199
        return attributeIdentities;
3,324 ✔
200
    }
3,324 ✔
201

202
    QStringList _removedDynamicAttributeNames;
203
    QStringList _changedDynamicAttributeNames;
204

205
    void updateSharedAttributeValues(Attribute& attribute) const
206
    {
29,520 ✔
207
        if(!attribute.testFlag(AttributeFlag::FindShared))
29,520 ✔
208
            return;
25,350 ✔
209

210
        if(attribute.elementType() == ElementType::Node)
4,170 ✔
211
            attribute.updateSharedValuesForElements(_transformedGraph.nodeIds());
3,854 ✔
212
        else if(attribute.elementType() == ElementType::Edge)
316 !
213
            attribute.updateSharedValuesForElements(_transformedGraph.edgeIds());
316 ✔
214
        else if(attribute.elementType() == ElementType::Component)
×
215
            qDebug() << "updateSharedAttributeValues called on component attribute";
×
216
    }
4,170 ✔
217

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

224
    std::atomic_bool _transformRebuildRequired = false;
225
    std::atomic_bool _visualisationRebuildRequired = false;
226

227
    NodeIdSet _selectedNodeIds;
228
    NodeIdSet _foundNodeIds;
229
    NodeIdSet _highlightedNodeIds;
230
    bool _nodesMaskActive = false;
231

232
    std::mutex _pendingVisualUpdateMutex;
233
    PendingVisualUpdate _pendingVisualUpdate;
234

235
    template<typename Fn>
236
    void requestVisualUpdate(const Fn& fn)
237
    {
29,930 ✔
238
        const std::unique_lock<std::mutex> lock(_pendingVisualUpdateMutex);
29,930 ✔
239
        fn(_pendingVisualUpdate);
29,930 ✔
240
    }
29,930 ✔
241

242
    void requestFullVisualUpdate()
243
    {
29,784 ✔
244
        requestVisualUpdate([](auto& pending) { pending._full = true; });
29,784 ✔
245
    }
29,784 ✔
246

247
    std::set<AttributeChangesTracker*> _attributeChangesTrackers;
248
};
249

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

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

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

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

295
    connect(&_->_graph, &Graph::graphChanged, this, &GraphModel::onMutableGraphChanged, Qt::DirectConnection);
1,604 ✔
296

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

305
    connect(&_->_userNodeData, &UserData::vectorValuesChanged, [this](const QString& vectorName)
1,604 ✔
306
    {
8,248 ✔
307
        auto attributeName = _->_userNodeData.exposedAttributeName(vectorName);
8,248 ✔
308
        if(attributeName.isEmpty())
8,248 ✔
309
            return;
8,136 ✔
310

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

315
    connect(&_->_userEdgeData, &UserData::vectorValuesChanged, [this](const QString& vectorName)
1,604 ✔
316
    {
1,736 ✔
317
        auto attributeName = _->_userEdgeData.exposedAttributeName(vectorName);
1,736 ✔
318
        if(attributeName.isEmpty())
1,736 ✔
319
            return;
1,662 ✔
320

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

325
    connect(this, &GraphModel::attributesChanged, this, &GraphModel::onAttributesChanged, Qt::DirectConnection);
1,604 ✔
326

327
    connect(&_->_preferencesWatcher, &PreferencesWatcher::preferenceChanged,
1,604 ✔
328
        this, &GraphModel::onPreferenceChanged);
1,604 ✔
329

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

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

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

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

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

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

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

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

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

385
void GraphModel::removeDynamicAttributes()
386
{
1,662 ✔
387
    QStringList dynamicAttributeNames;
1,662 ✔
388

389
    for(const auto& attributePair : _->_attributes)
1,662 ✔
390
    {
21,586 ✔
391
        if(attributePair.second.testFlag(AttributeFlag::Dynamic))
21,586 ✔
392
            dynamicAttributeNames.append(attributePair.first);
40 ✔
393
    }
21,586 ✔
394

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

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

408
    QString newAttribute = u::findUniqueName(_->_attributes, attribute);
18,882 ✔
409

410
    if(newAttribute != attribute && !clashHint.isEmpty())
18,882 ✔
411
        newAttribute = u::findUniqueName(_->_attributes, clashHint.arg(attribute));
4 ✔
412

413
    return newAttribute;
18,882 ✔
414
}
18,882 ✔
415

416
IMutableGraph& GraphModel::mutableGraphImpl() { return mutableGraph(); }
13,926 ✔
417
const IMutableGraph& GraphModel::mutableGraphImpl() const { return mutableGraph(); }
×
418
const IGraph& GraphModel::graphImpl() const { return graph(); }
47,400 ✔
419

420

421
MutableGraph& GraphModel::mutableGraph() { return _->_graph; }
44,962 ✔
422
const MutableGraph& GraphModel::mutableGraph() const { return _->_graph; }
×
423
const Graph& GraphModel::graph() const { return _->_transformedGraph; }
1,263,604 ✔
424

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

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

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

446
float GraphModel::nodeSize() const { return _->_nodeSize; }
144 ✔
447
float GraphModel::edgeSize() const { return _->_edgeSize; }
142 ✔
448
float GraphModel::textSize() const { return _->_textSize; }
142 ✔
449

450
const ElementVisual& GraphModel::nodeVisual(NodeId nodeId) const { return _->_nodeVisuals.at(nodeId); }
356 ✔
451
const ElementVisual& GraphModel::edgeVisual(EdgeId edgeId) const { return _->_edgeVisuals.at(edgeId); }
×
452

453
void GraphModel::readVisuals(const std::function<void()>& fn) const
454
{
×
455
    const std::shared_lock<std::shared_mutex> lock(_->_visualsMutex);
×
456
    fn();
×
457
}
×
458

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

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

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

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

483
std::vector<ElementVisual> GraphModel::nodeVisuals(const std::vector<NodeId>& nodeIds) const
484
{
×
485
    std::vector<ElementVisual> visuals;
×
486
    visuals.reserve(nodeIds.size());
×
487

488
    for(auto nodeId : nodeIds)
×
489
        visuals.emplace_back(nodeVisual(nodeId)); // cppcheck-suppress useStlAlgorithm
×
490

491
    return visuals;
×
492
}
×
493

494
std::vector<ElementVisual> GraphModel::edgeVisuals(const std::vector<EdgeId>& edgeIds) const
495
{
×
496
    std::vector<ElementVisual> visuals;
×
497
    visuals.reserve(edgeIds.size());
×
498

499
    for(auto edgeId : edgeIds)
×
500
        visuals.emplace_back(edgeVisual(edgeId)); // cppcheck-suppress useStlAlgorithm
×
501

502
    return visuals;
×
503
}
×
504

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

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

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

521
    auto it = _->_textVisuals.find(componentId);
6 ✔
522
    if(it == _->_textVisuals.end())
6 !
523
        return;
×
524

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

529
NodePositions& GraphModel::nodePositions() { return _->_nodePositions; }
8,222 ✔
530
const NodePositions& GraphModel::nodePositions() const { return _->_nodePositions; }
140 ✔
531

532
const NodeArray<QString>& GraphModel::nodeNames() const { return _->_nodeNames; }
142 ✔
533
QString GraphModel::nodeName(NodeId nodeId) const { return _->_nodeNames[nodeId]; }
414,084 ✔
534
void GraphModel::setNodeName(NodeId nodeId, const QString& name)
535
{
26,234 ✔
536
    _->_nodeNames[nodeId] = name;
26,234 ✔
537
    _->requestFullVisualUpdate();
26,234 ✔
538
    scheduleVisualUpdate();
26,234 ✔
539
}
26,234 ✔
540

541
bool GraphModel::editable() const { return _plugin->editable(); }
2 ✔
542
bool GraphModel::directed() const { return _plugin->directed(); }
1,608 ✔
543

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

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

554
    if(parsed)
192 ✔
555
    {
190 ✔
556
        const auto& graphTransformConfig = p.result();
190 ✔
557

558
        const auto* factory = transformFactory(graphTransformConfig._action);
190 ✔
559

560
        if(factory == nullptr)
190 !
561
            return false;
×
562

563
        if(factory->requiresCondition() && !graphTransformConfig.hasCondition())
190 ✔
564
            return false;
2 ✔
565

566
        return factory->configIsValid(*this, graphTransformConfig);
188 ✔
567
    }
190 ✔
568

569
    return false;
2 ✔
570
}
192 ✔
571

572
QStringList GraphModel::transformsWithMissingParametersSetToDefault(const QStringList& transforms) const
573
{
1,590 ✔
574
    QStringList transformsWithDefaults;
1,590 ✔
575

576
    for(const auto& transform : transforms)
1,590 ✔
577
    {
1,140 ✔
578
        GraphTransformConfigParser graphTransformConfigParser;
1,140 ✔
579

580
        if(!graphTransformConfigParser.parse(transform))
1,140 !
581
            continue;
×
582

583
        auto graphTransformConfig = graphTransformConfigParser.result();
1,140 ✔
584

585
        const auto* factory = transformFactory(graphTransformConfig._action);
1,140 ✔
586

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

591
        factory->setMissingParametersToDefault(graphTransformConfig);
1,140 ✔
592
        transformsWithDefaults.append(graphTransformConfig.asString());
1,140 ✔
593
    }
1,140 ✔
594

595
    return transformsWithDefaults;
1,590 ✔
596
}
1,590 ✔
597

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

607
        if(!graphTransformConfigParser.parse(transform))
1,174 !
608
            continue;
×
609

610
        const auto& graphTransformConfig = graphTransformConfigParser.result();
1,174 ✔
611
        const auto& action = graphTransformConfig._action;
1,174 ✔
612

613
        if(graphTransformConfig.isFlagSet(u"disabled"_s))
1,174 !
614
            continue;
×
615

616
        const auto* factory = transformFactory(action);
1,174 ✔
617

618
        if(factory == nullptr)
1,174 !
619
            continue;
×
620
        auto graphTransform = factory->create(*this, graphTransformConfig);
1,174 ✔
621

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

634
    _->_transformedGraph.enableAutoRebuild();
1,606 ✔
635
}
1,606 ✔
636

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

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

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

653
        if(elementType == ElementType::None || attributesAvailable)
112 !
654
            stringList.append(transformName);
112 ✔
655
    }
112 ✔
656

657
    return stringList;
4 ✔
658
}
4 ✔
659

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

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

671
    for(auto& attribute : _->_attributes)
296 ✔
672
    {
3,314 ✔
673
        if(!Flags<ElementType>(elementTypes).test(attribute.second.elementType()))
3,314 ✔
674
            continue;
1,316 ✔
675

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

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

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

685
        stringList.append(attribute.first);
1,882 ✔
686
    }
1,882 ✔
687

688
    return stringList;
296 ✔
689
}
296 ✔
690

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

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

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

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

704
    return ops;
120 ✔
705
}
120 ✔
706

707
bool GraphModel::hasTransformInfo() const
708
{
996 ✔
709
    return !_->_transformInfos.empty();
996 ✔
710
}
996 ✔
711

712
const TransformInfo& GraphModel::transformInfoAtIndex(int index) const
713
{
370 ✔
714
    static const TransformInfo nullTransformInfo;
370 ✔
715

716
    if(u::contains(_->_transformInfos, index))
370 !
717
        return _->_transformInfos.at(index);
370 ✔
718

719
    return nullTransformInfo;
×
720
}
370 ✔
721

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

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

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

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

743
    return attributeNames;
6 ✔
744
}
6 ✔
745

746
ValueType GraphModel::valueTypeOfTransformAttributeName(const QString& attributeName) const
747
{
2 ✔
748
    for(const auto& [transformName, factory] : _->_application->transformFactories())
2 !
749
    {
36 ✔
750
        const auto& defaultVisualisations = factory->defaultVisualisations();
36 ✔
751

752
        for(const auto& v : defaultVisualisations)
36 ✔
753
        {
20 ✔
754
            // cppcheck-suppress useStlAlgorithm
755
            if(v._attributeName == attributeName)
20 ✔
756
                return v._attributeValueType;
2 ✔
757
        }
20 ✔
758
    }
36 ✔
759

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

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

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

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

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

780
        return true;
6 ✔
781
    }
10 ✔
782

783
    return false;
×
784
}
10 ✔
785

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

790
    _->_visualisationRebuildRequired = false;
854 ✔
791

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

797
    _->_visualisedAttributeNames.clear();
854 ✔
798
    _->_hasValidEdgeTextVisualisation = false;
854 ✔
799

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

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

807
        VisualisationConfigParser visualisationConfigParser;
400 ✔
808

809
        if(!visualisationConfigParser.parse(visualisation))
400 !
810
            continue;
×
811

812
        const auto& visualisationConfig = visualisationConfigParser.result();
400 ✔
813

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

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

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

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

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

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

838
        auto attribute = attributeValueByName(attributeName);
194 ✔
839

840
        factory->findErrors(attribute.elementType(), info);
194 ✔
841

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

848
        auto channel = factory->create(visualisationConfig);
192 ✔
849

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

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

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

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

890
            for(const auto& sharedValue : sharedValues)
128 ✔
891
            {
49,068 ✔
892
                channel->addValue(sharedValue._value);
49,068 ✔
893
                info.addStringValue(sharedValue._value);
49,068 ✔
894
            }
49,068 ✔
895
        }
128 ✔
896

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

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

907
        default:
×
908
            break;
×
909
        }
192 ✔
910

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

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

920
    nodeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
854 ✔
921
    edgeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
854 ✔
922

923
    _->requestFullVisualUpdate();
854 ✔
924
    scheduleVisualUpdate();
854 ✔
925
}
854 ✔
926

927
bool GraphModel::transformRebuildRequired() const { return _->_transformRebuildRequired; }
532 ✔
928
bool GraphModel::visualisationRebuildRequired() const { return _->_visualisationRebuildRequired; }
514 ✔
929

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

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

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

945
    return stringList;
2 ✔
946
}
2 ✔
947

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

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

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

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

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

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

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

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

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

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

983
    return descriptions;
4 ✔
984
}
6 ✔
985

986
void GraphModel::clearVisualisationInfos()
987
{
876 ✔
988
    _->_visualisationInfos.clear();
876 ✔
989
}
876 ✔
990

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

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

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

1003
    return nullVisualisationInfo;
×
1004
}
20 ✔
1005

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

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

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

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

1020
    for(auto& attribute : _->_attributes)
4,076 ✔
1021
    {
52,082 ✔
1022
        if(Flags<ElementType>(elementType).test(attribute.second.elementType()))
52,082 ✔
1023
            attributeNames.emplace_back(attribute.first);
44,462 ✔
1024
    }
52,082 ✔
1025

1026
    return attributeNames;
4,076 ✔
1027
}
4,076 ✔
1028

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

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

1039
    if(assignedName != nullptr)
18,882 ✔
1040
        *assignedName = name;
2,714 ✔
1041

1042
    Attribute& attribute = _->_attributes[name];
18,882 ✔
1043

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

1050
    for(auto* tracker : _->_attributeChangesTrackers)
18,882 ✔
1051
    {
344 ✔
1052
        tracker->assignName(requestedName, name);
344 ✔
1053

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

1060
    return attribute;
18,882 ✔
1061
}
18,882 ✔
1062

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

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

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

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

1079
const Attribute* GraphModel::attributeByName(const QString& name) const
1080
{
58,925 ✔
1081
    auto attributeName = Attribute::parseAttributeName(name);
58,925 ✔
1082

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

1089
    return &_->_attributes.at(attributeName._name);
58,921 ✔
1090
}
58,925 ✔
1091

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

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

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

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

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

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

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

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

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

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

1139
        const auto* declaredAttribute = _->_application->attributeDeclaration(attributeName, _plugin);
9,923 ✔
1140
        if(declaredAttribute != nullptr && !declaredAttribute->_displayName.isEmpty())
9,923 !
1141
            return declaredAttribute->_displayName;
192 ✔
1142

1143
        if(attribute != nullptr)
9,731 !
1144
            return attributeName;
9,731 ✔
1145

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

1150
    if(u::contains(_->_attributes, name))
11,143 ✔
1151
        return displayNameOf(name);
11,135 ✔
1152

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

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

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

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

1167
    return !attributeDisabled;
1,048 ✔
1168
}
1,048 ✔
1169

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

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

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

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

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

1191
    return attribute;
3,154 ✔
1192
}
3,266 ✔
1193

1194
void GraphModel::calculateAttributeRange(const IGraph* graph, Attribute& attribute)
1195
{
54,218 ✔
1196
    if(!attribute.testFlag(AttributeFlag::AutoRange))
54,218 ✔
1197
        return;
42,092 ✔
1198

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

1207
void GraphModel::calculateAttributeRange(Attribute& attribute)
1208
{
22,790 ✔
1209
    calculateAttributeRange(&mutableGraph(), attribute);
22,790 ✔
1210
}
22,790 ✔
1211

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

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

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

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

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

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

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

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

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

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

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

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

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

1274
    _visualUpdatesEnabled = true;
570 ✔
1275
    _->requestFullVisualUpdate();
570 ✔
1276

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

1285
static float mappedSize(float min, float max, float user, float mapped = -1.0f)
1286
{
791,084 ✔
1287
    if(mapped < 0.0f)
791,084 ✔
1288
        return user;
790,966 ✔
1289

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

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

1296
    return min + (out * (max - min));
118 ✔
1297
}
791,084 ✔
1298

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

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

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

1316
    return (isNotFound && _->_nodesMaskActive) || isNotHighlighted;
396,020 ✔
1317
}
396,020 ✔
1318

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

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

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

1335
    PendingVisualUpdate pending;
1,336 ✔
1336
    NodeIdSet previousSelectedNodeIds;
1,336 ✔
1337
    bool maskChanged = false;
1,336 ✔
1338

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

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

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

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

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

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

1370
void GraphModel::updateVisuals(bool force)
1371
{
962 ✔
1372
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
962 ✔
1373

1374
    const float userNodeSize = _->_nodeSize;
962 ✔
1375
    const float userEdgeSize = _->_edgeSize;
962 ✔
1376
    const float userTextSize = _->_textSize;
962 ✔
1377

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

1387
    auto& nodeVisuals = _->_nodeVisuals;
962 ✔
1388
    auto& edgeVisuals = _->_edgeVisuals;
962 ✔
1389

1390
    Flags<VisualChangeFlags> nodeChanges;
962 ✔
1391
    Flags<VisualChangeFlags> edgeChanges;
962 ✔
1392

1393
    bool changing = false;
962 ✔
1394
    auto beginChanging = [this, &changing]
962 ✔
1395
    {
851,822 ✔
1396
        if(changing)
851,822 ✔
1397
            return;
851,002 ✔
1398

1399
        changing = true;
820 ✔
1400
        emit visualsWillChange();
820 ✔
1401
    };
820 ✔
1402

1403
    auto setIfChanged = [&beginChanging](auto& destination, const auto& value,
962 ✔
1404
        Flags<VisualChangeFlags>& changes, VisualChangeFlags change)
962 ✔
1405
    {
5,537,588 ✔
1406
        if(destination != value) // clazy:exclude=compare-member-check
5,537,588 ✔
1407
        {
851,812 ✔
1408
            beginChanging();
851,812 ✔
1409
            destination = value;
851,812 ✔
1410
            changes.set(change);
851,812 ✔
1411
        }
851,812 ✔
1412
    };
5,537,588 ✔
1413

1414
    if(force)
962 ✔
1415
        beginChanging();
4 ✔
1416

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

1421
    for(auto edgeId : graph().edgeIds())
962 ✔
1422
    {
395,352 ✔
1423
        newEdgeStates[edgeId] = edgeVisuals[edgeId]._state;
395,352 ✔
1424
        newEdgeStates[edgeId].reset(VisualFlags::Selected, VisualFlags::Unhighlighted);
395,352 ✔
1425
    }
395,352 ✔
1426

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

1433
        setIfChanged(visual._outerColor, mapped._outerColor.isValid() ?
791,084 !
1434
            mapped._outerColor : color, changes, VisualChangeFlags::Color);
594,926 ✔
1435

1436
        setIfChanged(visual._innerColor,
791,084 ✔
1437
            !meIndicators || graph().typeOf(elementId) == MultiElementType::Not ?
791,084 !
1438
            visual._outerColor : multiColor, changes, VisualChangeFlags::Color);
791,068 ✔
1439

1440
        setIfChanged(visual._text, !mapped._text.isEmpty() ?
791,084 ✔
1441
            mapped._text : text, changes, VisualChangeFlags::Text);
790,966 ✔
1442

1443
        setIfChanged(visual._textSize, mappedTextSize(userTextSize, mapped._textSize),
791,084 ✔
1444
            changes, VisualChangeFlags::TextSize);
791,084 ✔
1445

1446
        setIfChanged(visual._textColor, mapped._textColor.isValid() ?
791,084 !
1447
            mapped._textColor : textColor, changes, VisualChangeFlags::TextColor);
791,020 ✔
1448
    };
791,084 ✔
1449

1450
    for(auto nodeId : graph().nodeIds())
962 ✔
1451
    {
395,732 ✔
1452
        auto& visual = nodeVisuals[nodeId];
395,732 ✔
1453
        const auto& mapped = _->_mappedNodeVisuals[nodeId];
395,732 ✔
1454

1455
        setElementVisual(nodeId, visual, mapped,
395,732 ✔
1456
            mappedSize(LimitConstants::minimumNodeSize(), LimitConstants::maximumNodeSize(),
395,732 ✔
1457
            nodeSize, mapped._size), nodeColor, nodeName(nodeId), nodeChanges);
395,732 ✔
1458

1459
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
395,732 ✔
1460
        auto nodeUnhighlighted = nodeIsUnhighlighted(nodeId, nodeIsSelected);
395,732 ✔
1461

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

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

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

1480
    for(auto edgeId : graph().edgeIds())
962 ✔
1481
    {
395,352 ✔
1482
        auto& visual = edgeVisuals[edgeId];
395,352 ✔
1483
        const auto& mapped = _->_mappedEdgeVisuals[edgeId];
395,352 ✔
1484

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

1491
        setElementVisual(edgeId, visual, mapped, size, edgeColor, {}, edgeChanges);
395,352 ✔
1492

1493
        setIfChanged(visual._state, newEdgeStates[edgeId], edgeChanges, VisualChangeFlags::State);
395,352 ✔
1494
    }
395,352 ✔
1495

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

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

1511
        if(previous.size() != current.size())
962 ✔
1512
            return VisualChangeFlags::State;
6 ✔
1513

1514
        auto previousComponentIds = u::keysFor(previous);
956 ✔
1515
        auto currentComponentIds = u::keysFor(current);
956 ✔
1516

1517
        if(previousComponentIds != currentComponentIds)
956 !
1518
            return VisualChangeFlags::State;
×
1519

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

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

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

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

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

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

1544
        return *change;
956 ✔
1545
    };
956 ✔
1546

1547
    const VisualChangeFlags textChange = findTextVisualsChange(_->_textVisuals, _->_newTextVisuals);
962 ✔
1548

1549
    if(textChange != VisualChangeFlags::None)
962 ✔
1550
        beginChanging();
6 ✔
1551

1552
    if(!changing)
962 ✔
1553
        return;
142 ✔
1554

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

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

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

1566
// When the selection changes, only update the selection visuals
1567
void GraphModel::updateSelectionVisuals(const NodeIdSet& previousSelectedNodeIds)
1568
{
98 ✔
1569
    std::vector<NodeId> changedNodeIds;
98 ✔
1570

1571
    for(auto nodeId : _->_selectedNodeIds)
98 ✔
1572
    {
216 ✔
1573
        if(!u::contains(previousSelectedNodeIds, nodeId))
216 ✔
1574
            changedNodeIds.emplace_back(nodeId); // cppcheck-suppress useStlAlgorithm
178 ✔
1575
    }
216 ✔
1576

1577
    for(auto nodeId : previousSelectedNodeIds)
98 ✔
1578
    {
148 ✔
1579
        if(!u::contains(_->_selectedNodeIds, nodeId))
148 ✔
1580
            changedNodeIds.emplace_back(nodeId); // cppcheck-suppress useStlAlgorithm
110 ✔
1581
    }
148 ✔
1582

1583
    if(changedNodeIds.empty())
98 ✔
1584
        return;
4 ✔
1585

1586
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
94 ✔
1587

1588
    emit visualsWillChange();
94 ✔
1589

1590
    Flags<VisualChangeFlags> nodeChange;
94 ✔
1591
    Flags<VisualChangeFlags> edgeChange;
94 ✔
1592

1593
    for(auto nodeId : changedNodeIds)
94 ✔
1594
    {
288 ✔
1595
        auto& nodeVisual = _->_nodeVisuals[nodeId];
288 ✔
1596
        const auto previousState = nodeVisual._state;
288 ✔
1597

1598
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
288 ✔
1599

1600
        nodeVisual._state.setState(VisualFlags::Selected, nodeIsSelected);
288 ✔
1601
        nodeVisual._state.setState(VisualFlags::Unhighlighted,
288 ✔
1602
            nodeIsUnhighlighted(nodeId, nodeIsSelected));
288 ✔
1603

1604
        if(nodeVisual._state != previousState) // clazy:exclude=compare-member-check
288 !
1605
            nodeChange.set(VisualChangeFlags::State);
288 ✔
1606
    }
288 ✔
1607

1608
    for(auto nodeId : changedNodeIds)
94 ✔
1609
    {
288 ✔
1610
        for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
288 ✔
1611
        {
446 ✔
1612
            auto& edgeVisual = _->_edgeVisuals[edgeId];
446 ✔
1613
            const auto previousState = edgeVisual._state;
446 ✔
1614

1615
            // An edge is selected or unhighlighted if either of the nodes it joins is;
1616
            // those are precisely the nodes whose edgeIdsForNodeId contains it
1617
            const auto& edge = graph().edgeById(edgeId);
446 ✔
1618
            const auto sourceState = _->_nodeVisuals[edge.sourceId()]._state;
446 ✔
1619
            const auto targetState = _->_nodeVisuals[edge.targetId()]._state;
446 ✔
1620

1621
            edgeVisual._state.setState(VisualFlags::Selected,
446 ✔
1622
                sourceState.test(VisualFlags::Selected) ||
446 ✔
1623
                targetState.test(VisualFlags::Selected));
446 ✔
1624

1625
            edgeVisual._state.setState(VisualFlags::Unhighlighted,
446 ✔
1626
                sourceState.test(VisualFlags::Unhighlighted) ||
446 ✔
1627
                targetState.test(VisualFlags::Unhighlighted));
446 ✔
1628

1629
            if(edgeVisual._state != previousState) // clazy:exclude=compare-member-check
446 ✔
1630
                edgeChange.set(VisualChangeFlags::State);
266 ✔
1631
        }
446 ✔
1632
    }
288 ✔
1633

1634
    visualsLock.unlock();
94 ✔
1635
    emit visualsChanged(*nodeChange, *edgeChange, VisualChangeFlags::None);
94 ✔
1636
}
94 ✔
1637

1638
void GraphModel::onSelectionChanged(const SelectionManager* selectionManager)
1639
{
112 ✔
1640
    auto selectedNodeIds = selectionManager->selectedNodes();
112 ✔
1641
    auto nodesMaskActive = selectionManager->nodesMaskActive();
112 ✔
1642

1643
    _->requestVisualUpdate([&selectedNodeIds, nodesMaskActive](auto& pending)
112 ✔
1644
    {
112 ✔
1645
        pending._selectedNodeIds = std::move(selectedNodeIds);
112 ✔
1646
        pending._nodesMaskActive = nodesMaskActive;
112 ✔
1647
    });
112 ✔
1648

1649
    scheduleVisualUpdate();
112 ✔
1650
}
112 ✔
1651

1652
void GraphModel::onFoundNodeIdsChanged(const SearchManager* searchManager)
1653
{
24 ✔
1654
    auto foundNodeIds = searchManager->foundNodeIds();
24 ✔
1655

1656
    _->requestVisualUpdate([&foundNodeIds](auto& pending)
24 ✔
1657
    {
24 ✔
1658
        pending._foundNodeIds = std::move(foundNodeIds);
24 ✔
1659
        pending._full = true;
24 ✔
1660
    });
24 ✔
1661

1662
    scheduleVisualUpdate();
24 ✔
1663
}
24 ✔
1664

1665
void GraphModel::onPreferenceChanged(const QString& name, const QVariant&)
1666
{
22 ✔
1667
    if(!name.startsWith(u"visuals"_s))
22 ✔
1668
        return;
18 ✔
1669

1670
    const bool force = name.endsWith(u"backgroundColor"_s) ||
4 !
1671
        name.endsWith(u"showNodeText"_s) ||
4 !
1672
        name.endsWith(u"showEdgeText"_s) ||
4 !
1673
        name.endsWith(u"showEdges"_s) ||
4 !
1674
        name.endsWith(u"edgeVisualType"_s) ||
4 !
1675
        name.endsWith(u"highlightColor"_s) ||
4 !
1676
        name.endsWith(u"textFont"_s) ||
4 !
1677
        name.endsWith(u"textSize"_s) ||
4 !
1678
        name.endsWith(u"textAlignment"_s);
4 !
1679

1680
    _->requestVisualUpdate([force](auto& pending)
4 ✔
1681
    {
4 ✔
1682
        pending._full = true;
4 ✔
1683
        pending._force = pending._force || force;
4 !
1684
    });
4 ✔
1685

1686
    scheduleVisualUpdate();
4 ✔
1687
}
4 ✔
1688

1689
void GraphModel::onLayoutChanged()
1690
{
2,789 ✔
1691
    // This occurs on the layout thread
1692
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
2,789 ✔
1693
    updateTextVisualPositions(_->_textVisuals, _->_nodePositions);
2,789 ✔
1694
}
2,789 ✔
1695

1696
void GraphModel::onMutableGraphChanged(const Graph* graph)
1697
{
1,658 ✔
1698
    calculateAttributeRanges(graph, _->_attributes);
1,658 ✔
1699
}
1,658 ✔
1700

1701
void GraphModel::onTransformedGraphWillChange(const Graph*)
1702
{
1,662 ✔
1703
    // The graph may gain elements that have never been through a full visual
1704
    // update, so whatever next asks for an update must get a full one
1705
    _->requestFullVisualUpdate();
1,662 ✔
1706

1707
    // Rebuilding applies the transforms to the attribute values as they now are
1708
    _->_transformRebuildRequired = false;
1,662 ✔
1709

1710
    // Store previous attributes for comparison
1711
    _->_previousAttributeIdentities = _->currentAttributeIdentities();
1,662 ✔
1712

1713
    removeDynamicAttributes();
1,662 ✔
1714

1715
    _graphTransformsAreChanging = true;
1,662 ✔
1716
}
1,662 ✔
1717

1718
void GraphModel::onTransformedGraphChanged(const Graph*, bool changeOccurred)
1719
{
1,662 ✔
1720
    _->_removedDynamicAttributeNames.clear();
1,662 ✔
1721

1722
    auto attributeIdentities = _->currentAttributeIdentities();
1,662 ✔
1723

1724
    // Compare with previous attributes
1725
    auto removedAttributeIdentities = u::setDifference(_->_previousAttributeIdentities, attributeIdentities);
1,662 ✔
1726
    auto addedAttributeIdentities = u::setDifference(attributeIdentities, _->_previousAttributeIdentities);
1,662 ✔
1727

1728
    QStringList removedAttributeNames;
1,662 ✔
1729
    QStringList addedAttributeNames;
1,662 ✔
1730

1731
    auto identityToName = [](const auto& identity) { return identity._name; };
1,662 ✔
1732

1733
    std::ranges::transform(removedAttributeIdentities,
1,662 ✔
1734
        std::back_inserter(removedAttributeNames), identityToName);
1,662 ✔
1735
    std::ranges::transform(addedAttributeIdentities,
1,662 ✔
1736
        std::back_inserter(addedAttributeNames), identityToName);
1,662 ✔
1737

1738
    QStringList changedAttributeNames(std::move(_->_changedDynamicAttributeNames));
1,662 ✔
1739

1740
    changedAttributeNames.erase(std::ranges::remove_if(changedAttributeNames,
1,662 ✔
1741
    [&removedAttributeNames, &addedAttributeNames](const auto& dynamicAttributeName)
1,662 ✔
1742
    {
1,662 ✔
1743
        return u::contains(removedAttributeNames, dynamicAttributeName) ||
10 !
1744
            u::contains(addedAttributeNames, dynamicAttributeName);
10 !
1745
    }).begin(), changedAttributeNames.end());
10 ✔
1746

1747
    // When the graph changes, every attribute's range and shared values also potentially change
1748
    for(auto& [name, attribute] : _->_attributes)
1,662 ✔
1749
    {
21,868 ✔
1750
        // These ones will be taken care of in onAttributesChanged, below...
1751
        if(u::contains(addedAttributeNames, name) || u::contains(changedAttributeNames, name))
21,868 ✔
1752
            continue;
304 ✔
1753

1754
        calculateAttributeRange(attribute);
21,564 ✔
1755
        _->updateSharedAttributeValues(attribute);
21,564 ✔
1756
    }
21,564 ✔
1757

1758
    emit attributesChanged(addedAttributeNames, removedAttributeNames,
1,662 ✔
1759
        changedAttributeNames, changeOccurred);
1,662 ✔
1760

1761
    _graphTransformsAreChanging = false;
1,662 ✔
1762
}
1,662 ✔
1763

1764
// This will also be called when the transformed graph changes, even if there are no actual attribute changes
1765
void GraphModel::onAttributesChanged(const QStringList& addedNames, const QStringList& removedNames,
1766
    const QStringList& changedValuesNames, bool graphChangeOccurred)
1767
{
1,800 ✔
1768
    for(const auto& attributeName : u::combine(addedNames, changedValuesNames))
1,800 ✔
1769
    {
424 ✔
1770
        auto& attribute = _->_attributes.at(Attribute::parseAttributeName(attributeName)._name);
424 ✔
1771

1772
        if(attribute.testFlag(AttributeFlag::Dynamic) && attribute.userDefined())
424 !
1773
        {
×
1774
            qDebug() << "WARNING: Dynamic attribute" << attributeName <<
×
1775
                "has userDefined set, this is not allowed, resetting...";
×
1776
            attribute.setUserDefined(false);
×
1777
        }
×
1778

1779
        calculateAttributeRange(attribute);
424 ✔
1780
        _->updateSharedAttributeValues(attribute);
424 ✔
1781
    }
424 ✔
1782

1783
    // Attribute changes may require a graph transform or visualisation to be rebuilt
1784
    QStringList changed;
1,800 ✔
1785
    changed << addedNames << removedNames << changedValuesNames;
1,800 ✔
1786
    u::removeDuplicates(changed);
1,800 ✔
1787

1788
    const bool transformRebuildRequired = !_graphTransformsAreChanging &&
1,800 ✔
1789
        _->_transformedGraph.onAttributeValuesChangedExternally(changed);
1,800 ✔
1790

1791
    const bool visualisationRebuildRequired = graphChangeOccurred || !u::setIntersection(
1,800 !
1792
        static_cast<const QList<QString>&>(_->_visualisedAttributeNames),
242 ✔
1793
        static_cast<const QList<QString>&>(changed)).empty();
242 ✔
1794

1795
    if(transformRebuildRequired)
1,800 ✔
1796
        _->_transformRebuildRequired = true;
6 ✔
1797

1798
    if(visualisationRebuildRequired)
1,800 ✔
1799
        _->_visualisationRebuildRequired = true;
1,558 ✔
1800

1801
    // The rebuilds happen alongside the next visual update
1802
    if(transformRebuildRequired || visualisationRebuildRequired)
1,800 ✔
1803
        scheduleVisualUpdate();
1,564 ✔
1804
}
1,800 ✔
1805

1806
AttributeChangesTracker::AttributeChangesTracker(GraphModel* graphModel,
1807
    NamedBool<"emitOnDestruct"> emitOnDestruct) :
1808
    _graphModel(graphModel), _emitOnDestruct(emitOnDestruct)
1,336 ✔
1809
{
1,336 ✔
1810
    _graphModel->_->_attributeChangesTrackers.insert(this);
1,336 ✔
1811
}
1,336 ✔
1812

1813
AttributeChangesTracker::~AttributeChangesTracker()
1814
{
1,336 ✔
1815
    if(_emitOnDestruct)
1,336 ✔
1816
        emitAttributesChanged();
172 ✔
1817

1818
    _graphModel->_->_attributeChangesTrackers.erase(this);
1,336 ✔
1819
}
1,336 ✔
1820

1821
void AttributeChangesTracker::assignName(const QString& requestedName, const QString& assignedName)
1822
{
344 ✔
1823
    _assignedNames[requestedName] = assignedName;
344 ✔
1824
}
344 ✔
1825

1826
void AttributeChangesTracker::add(const QString& name)
1827
{
340 ✔
1828
    if(u::contains(_changed, name))
340 !
1829
    {
×
1830
        qDebug() << "AttributeChangesTracker::add called on attribute marked as changed" << name;
×
1831
        _changed.remove(name);
×
1832
    }
×
1833

1834
    if(u::contains(_removed, name))
340 ✔
1835
    {
6 ✔
1836
        // If it's been removed and added, count that as changed (potentially)
1837
        _removed.remove(name);
6 ✔
1838
        _changed.insert(name);
6 ✔
1839
    }
6 ✔
1840
    else
334 ✔
1841
       _added.insert(name);
334 ✔
1842
}
340 ✔
1843

1844
void AttributeChangesTracker::remove(const QString& name)
1845
{
44 ✔
1846
    if(u::contains(_added, name))
44 !
1847
    {
×
1848
        // If it's been added and removed, count that as net zero
1849
        _added.remove(name);
×
1850
    }
×
1851
    else
44 ✔
1852
        _removed.insert(name);
44 ✔
1853
}
44 ✔
1854

1855
void AttributeChangesTracker::change(const QString& name)
1856
{
190 ✔
1857
    // Only count an attribute as changed if it's not new
1858
    if(!u::contains(_added, name))
190 !
1859
        _changed.insert(name);
190 ✔
1860
}
190 ✔
1861

1862
QStringList AttributeChangesTracker::addedOrChanged() const
1863
{
1,160 ✔
1864
    auto combined = u::combine(_added, _changed);
1,160 ✔
1865
    return {combined.begin(), combined.end()};
1,160 ✔
1866
}
1,160 ✔
1867

1868
void AttributeChangesTracker::emitAttributesChanged()
1869
{
172 ✔
1870
    if(_added.empty() && _removed.empty() && _changed.empty())
172 ✔
1871
        return;
34 ✔
1872

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