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

graphia-app / graphia / 42082325281

05 Nov 2026 06:13PM UTC coverage: 71.439% (+0.08%) from 71.364%
42082325281

push

github

timangus
Use QCustomPlot's split sources from its repository

11786 of 18050 branches covered (65.3%)

Branch coverage included in aggregate %.

30011 of 40457 relevant lines covered (74.18%)

300661.03 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
{
4,636 ✔
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);
4,636 ✔
88

89
    for(auto& [componentId, textVisuals_] : textVisuals)
4,636 ✔
90
    {
18 ✔
91
        for(auto& textVisual : textVisuals_)
18 ✔
92
            textVisual.updatePositions(nodePositions);
30 ✔
93
    }
18 ✔
94
}
4,636 ✔
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
            attributeIdentities.emplace_back(
43,454 ✔
193
                attribute.first,
43,454 ✔
194
                attribute.second.valueType(),
43,454 ✔
195
                attribute.second.elementType());
43,454 ✔
196
        }
43,454 ✔
197

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

201
    QStringList _removedDynamicAttributeNames;
202
    QStringList _changedDynamicAttributeNames;
203

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

419

420
MutableGraph& GraphModel::mutableGraph() { return _->_graph; }
44,962 ✔
421
const MutableGraph& GraphModel::mutableGraph() const { return _->_graph; }
×
422
const Graph& GraphModel::graph() const { return _->_transformedGraph; }
639,134 ✔
423

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

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

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

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

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

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

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

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

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

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

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

487
    for(auto nodeId : nodeIds)
×
488
        visuals.emplace_back(nodeVisual(nodeId));
×
489

490
    return visuals;
×
491
}
×
492

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

498
    for(auto edgeId : edgeIds)
×
499
        visuals.emplace_back(edgeVisual(edgeId));
×
500

501
    return visuals;
×
502
}
×
503

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

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

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

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

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

528
NodePositions& GraphModel::nodePositions() { return _->_nodePositions; }
10,484 ✔
529
const NodePositions& GraphModel::nodePositions() const { return _->_nodePositions; }
140 ✔
530

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

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

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

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

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

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

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

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

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

568
    return false;
2 ✔
569
}
192 ✔
570

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

656
    return stringList;
4 ✔
657
}
4 ✔
658

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

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

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

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

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

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

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

687
    return stringList;
296 ✔
688
}
296 ✔
689

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

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

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

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

703
    return ops;
120 ✔
704
}
120 ✔
705

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

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

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

718
    return nullTransformInfo;
×
719
}
370 ✔
720

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

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

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

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

742
    return attributeNames;
6 ✔
743
}
6 ✔
744

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

751
        for(const auto& v : defaultVisualisations)
36 ✔
752
        {
20 ✔
753
            if(v._attributeName == attributeName)
20 ✔
754
                return v._attributeValueType;
2 ✔
755
        }
20 ✔
756
    }
36 ✔
757

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

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

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

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

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

778
        return true;
6 ✔
779
    }
10 ✔
780

781
    return false;
×
782
}
10 ✔
783

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

788
    _->_visualisationRebuildRequired = false;
750 ✔
789

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

795
    _->_visualisedAttributeNames.clear();
750 ✔
796
    _->_hasValidEdgeTextVisualisation = false;
750 ✔
797

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

801
    for(int index = 0; index < visualisations.size(); index++)
994 ✔
802
    {
244 ✔
803
        const auto& visualisation = visualisations.at(index);
244 ✔
804

805
        VisualisationConfigParser visualisationConfigParser;
244 ✔
806

807
        if(!visualisationConfigParser.parse(visualisation))
244 !
808
            continue;
×
809

810
        const auto& visualisationConfig = visualisationConfigParser.result();
244 ✔
811

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

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

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

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

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

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

836
        auto attribute = attributeValueByName(attributeName);
142 ✔
837

838
        factory->findErrors(attribute.elementType(), info);
142 ✔
839

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

846
        auto channel = factory->create(visualisationConfig);
140 ✔
847

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

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

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

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

888
            for(const auto& sharedValue : sharedValues)
76 ✔
889
            {
23,068 ✔
890
                channel->addValue(sharedValue._value);
23,068 ✔
891
                info.addStringValue(sharedValue._value);
23,068 ✔
892
            }
23,068 ✔
893
        }
76 ✔
894

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

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

905
        default:
×
906
            break;
×
907
        }
140 ✔
908

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

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

918
    nodeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
750 ✔
919
    edgeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
750 ✔
920

921
    _->requestFullVisualUpdate();
750 ✔
922
    scheduleVisualUpdate();
750 ✔
923
}
750 ✔
924

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

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

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

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

943
    return stringList;
2 ✔
944
}
2 ✔
945

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

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

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

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

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

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

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

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

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

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

981
    return descriptions;
4 ✔
982
}
6 ✔
983

984
void GraphModel::clearVisualisationInfos()
985
{
772 ✔
986
    _->_visualisationInfos.clear();
772 ✔
987
}
772 ✔
988

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

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

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

1001
    return nullVisualisationInfo;
×
1002
}
20 ✔
1003

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

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

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

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

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

1024
    return attributeNames;
4,076 ✔
1025
}
4,076 ✔
1026

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

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

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

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

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

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

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

1058
    return attribute;
18,882 ✔
1059
}
18,882 ✔
1060

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

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

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

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

1077
const Attribute* GraphModel::attributeByName(const QString& name) const
1078
{
58,916 ✔
1079
    auto attributeName = Attribute::parseAttributeName(name);
58,916 ✔
1080

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

1087
    return &_->_attributes.at(attributeName._name);
58,912 ✔
1088
}
58,916 ✔
1089

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

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

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

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

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

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

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

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

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

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

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

1141
        if(attribute != nullptr)
9,722 !
1142
            return attributeName;
9,722 ✔
1143

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

1148
    if(u::contains(_->_attributes, name))
11,134 ✔
1149
        return displayNameOf(name);
11,126 ✔
1150

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

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

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

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

1165
    return !attributeDisabled;
1,048 ✔
1166
}
1,048 ✔
1167

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

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

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

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

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

1189
    return attribute;
3,102 ✔
1190
}
3,214 ✔
1191

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1272
    _visualUpdatesEnabled = true;
570 ✔
1273
    _->requestFullVisualUpdate();
570 ✔
1274

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

1283
static float mappedSize(float min, float max, float user, float mapped = -1.0f)
1284
{
375,188 ✔
1285
    if(mapped < 0.0f)
375,188 ✔
1286
        return user;
375,070 ✔
1287

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

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

1294
    return min + (out * (max - min));
118 ✔
1295
}
375,188 ✔
1296

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

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

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

1314
    return (isNotFound && _->_nodesMaskActive) || isNotHighlighted;
188,020 ✔
1315
}
188,020 ✔
1316

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

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

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

1333
    PendingVisualUpdate pending;
1,232 ✔
1334
    NodeIdSet previousSelectedNodeIds;
1,232 ✔
1335
    bool maskChanged = false;
1,232 ✔
1336

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

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

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

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

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

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

1368
void GraphModel::updateVisuals(bool force)
1369
{
858 ✔
1370
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
858 ✔
1371

1372
    const float userNodeSize = _->_nodeSize;
858 ✔
1373
    const float userEdgeSize = _->_edgeSize;
858 ✔
1374
    const float userTextSize = _->_textSize;
858 ✔
1375

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

1385
    auto& nodeVisuals = _->_nodeVisuals;
858 ✔
1386
    auto& edgeVisuals = _->_edgeVisuals;
858 ✔
1387

1388
    Flags<VisualChangeFlags> nodeChanges;
858 ✔
1389
    Flags<VisualChangeFlags> edgeChanges;
858 ✔
1390

1391
    bool changing = false;
858 ✔
1392
    auto beginChanging = [this, &changing]
858 ✔
1393
    {
435,822 ✔
1394
        if(changing)
435,822 ✔
1395
            return;
435,106 ✔
1396

1397
        changing = true;
716 ✔
1398
        emit visualsWillChange();
716 ✔
1399
    };
716 ✔
1400

1401
    auto setIfChanged = [&beginChanging](auto& destination, const auto& value,
858 ✔
1402
        Flags<VisualChangeFlags>& changes, VisualChangeFlags change)
858 ✔
1403
    {
2,626,316 ✔
1404
        if(destination != value) // clazy:exclude=compare-member-check
2,626,316 ✔
1405
        {
435,812 ✔
1406
            beginChanging();
435,812 ✔
1407
            destination = value;
435,812 ✔
1408
            changes.set(change);
435,812 ✔
1409
        }
435,812 ✔
1410
    };
2,626,316 ✔
1411

1412
    if(force)
858 ✔
1413
        beginChanging();
4 ✔
1414

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

1419
    for(auto edgeId : graph().edgeIds())
858 ✔
1420
    {
187,456 ✔
1421
        newEdgeStates[edgeId] = edgeVisuals[edgeId]._state;
187,456 ✔
1422
        newEdgeStates[edgeId].reset(VisualFlags::Selected, VisualFlags::Unhighlighted);
187,456 ✔
1423
    }
187,456 ✔
1424

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

1431
        setIfChanged(visual._outerColor, mapped._outerColor.isValid() ?
375,188 !
1432
            mapped._outerColor : color, changes, VisualChangeFlags::Color);
283,030 ✔
1433

1434
        setIfChanged(visual._innerColor,
375,188 ✔
1435
            !meIndicators || graph().typeOf(elementId) == MultiElementType::Not ?
375,188 !
1436
            visual._outerColor : multiColor, changes, VisualChangeFlags::Color);
375,172 ✔
1437

1438
        setIfChanged(visual._text, !mapped._text.isEmpty() ?
375,188 ✔
1439
            mapped._text : text, changes, VisualChangeFlags::Text);
375,070 ✔
1440

1441
        setIfChanged(visual._textSize, mappedTextSize(userTextSize, mapped._textSize),
375,188 ✔
1442
            changes, VisualChangeFlags::TextSize);
375,188 ✔
1443

1444
        setIfChanged(visual._textColor, mapped._textColor.isValid() ?
375,188 !
1445
            mapped._textColor : textColor, changes, VisualChangeFlags::TextColor);
375,124 ✔
1446
    };
375,188 ✔
1447

1448
    for(auto nodeId : graph().nodeIds())
858 ✔
1449
    {
187,732 ✔
1450
        auto& visual = nodeVisuals[nodeId];
187,732 ✔
1451
        const auto& mapped = _->_mappedNodeVisuals[nodeId];
187,732 ✔
1452

1453
        setElementVisual(nodeId, visual, mapped,
187,732 ✔
1454
            mappedSize(LimitConstants::minimumNodeSize(), LimitConstants::maximumNodeSize(),
187,732 ✔
1455
            nodeSize, mapped._size), nodeColor, nodeName(nodeId), nodeChanges);
187,732 ✔
1456

1457
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
187,732 ✔
1458
        auto nodeUnhighlighted = nodeIsUnhighlighted(nodeId, nodeIsSelected);
187,732 ✔
1459

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

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

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

1478
    for(auto edgeId : graph().edgeIds())
858 ✔
1479
    {
187,456 ✔
1480
        auto& visual = edgeVisuals[edgeId];
187,456 ✔
1481
        const auto& mapped = _->_mappedEdgeVisuals[edgeId];
187,456 ✔
1482

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

1489
        setElementVisual(edgeId, visual, mapped, size, edgeColor, {}, edgeChanges);
187,456 ✔
1490

1491
        setIfChanged(visual._state, newEdgeStates[edgeId], edgeChanges, VisualChangeFlags::State);
187,456 ✔
1492
    }
187,456 ✔
1493

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

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

1509
        if(previous.size() != current.size())
858 ✔
1510
            return VisualChangeFlags::State;
6 ✔
1511

1512
        auto previousComponentIds = u::keysFor(previous);
852 ✔
1513
        auto currentComponentIds = u::keysFor(current);
852 ✔
1514

1515
        if(previousComponentIds != currentComponentIds)
852 !
1516
            return VisualChangeFlags::State;
×
1517

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

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

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

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

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

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

1542
        return *change;
852 ✔
1543
    };
852 ✔
1544

1545
    const VisualChangeFlags textChange = findTextVisualsChange(_->_textVisuals, _->_newTextVisuals);
858 ✔
1546

1547
    if(textChange != VisualChangeFlags::None)
858 ✔
1548
        beginChanging();
6 ✔
1549

1550
    if(!changing)
858 ✔
1551
        return;
142 ✔
1552

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

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

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

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

1569
    for(auto nodeId : _->_selectedNodeIds)
98 ✔
1570
    {
216 ✔
1571
        if(!u::contains(previousSelectedNodeIds, nodeId))
216 ✔
1572
            changedNodeIds.emplace_back(nodeId);
178 ✔
1573
    }
216 ✔
1574

1575
    for(auto nodeId : previousSelectedNodeIds)
98 ✔
1576
    {
148 ✔
1577
        if(!u::contains(_->_selectedNodeIds, nodeId))
148 ✔
1578
            changedNodeIds.emplace_back(nodeId);
110 ✔
1579
    }
148 ✔
1580

1581
    if(changedNodeIds.empty())
98 ✔
1582
        return;
4 ✔
1583

1584
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
94 ✔
1585

1586
    emit visualsWillChange();
94 ✔
1587

1588
    Flags<VisualChangeFlags> nodeChange;
94 ✔
1589
    Flags<VisualChangeFlags> edgeChange;
94 ✔
1590

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

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

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

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

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

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

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

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

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

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

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

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

1647
    scheduleVisualUpdate();
112 ✔
1648
}
112 ✔
1649

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

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

1660
    scheduleVisualUpdate();
24 ✔
1661
}
24 ✔
1662

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

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

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

1684
    scheduleVisualUpdate();
4 ✔
1685
}
4 ✔
1686

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

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

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

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

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

1711
    removeDynamicAttributes();
1,662 ✔
1712

1713
    _graphTransformsAreChanging = true;
1,662 ✔
1714
}
1,662 ✔
1715

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

1720
    auto attributeIdentities = _->currentAttributeIdentities();
1,662 ✔
1721

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

1726
    QStringList removedAttributeNames;
1,662 ✔
1727
    QStringList addedAttributeNames;
1,662 ✔
1728

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

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

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

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

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

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

1756
    emit attributesChanged(addedAttributeNames, removedAttributeNames,
1,662 ✔
1757
        changedAttributeNames, changeOccurred);
1,662 ✔
1758

1759
    _graphTransformsAreChanging = false;
1,662 ✔
1760
}
1,662 ✔
1761

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

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

1777
        calculateAttributeRange(attribute);
424 ✔
1778
        _->updateSharedAttributeValues(attribute);
424 ✔
1779
    }
424 ✔
1780

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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