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

graphia-app / graphia / 42724698251

09 Nov 2026 10:47PM UTC coverage: 71.88% (+0.5%) from 71.427%
42724698251

push

github

timangus
Add Leiden clustering

11927 of 18208 branches covered (65.5%)

Branch coverage included in aggregate %.

486 of 497 new or added lines in 3 files covered. (97.79%)

699 existing lines in 55 files now uncovered.

30522 of 40847 relevant lines covered (74.72%)

740302.21 hits per line

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

88.7
/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,656 ✔
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,656 ✔
88

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

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

183
    std::vector<AttributeIdentity> _previousAttributeIdentities;
184

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

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

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

200
    QStringList _removedDynamicAttributeNames;
201
    QStringList _changedDynamicAttributeNames;
202

203
    void updateSharedAttributeValues(Attribute& attribute) const
204
    {
30,474 ✔
205
        if(!attribute.testFlag(AttributeFlag::FindShared))
30,474 ✔
206
            return;
26,198 ✔
207

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

411
    return newAttribute;
19,776 ✔
412
}
19,776 ✔
413

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

418

419
MutableGraph& GraphModel::mutableGraph() { return _->_graph; }
46,142 ✔
UNCOV
420
const MutableGraph& GraphModel::mutableGraph() const { return _->_graph; }
×
421
const Graph& GraphModel::graph() const { return _->_transformedGraph; }
1,203,634 ✔
422

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

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

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

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

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

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

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

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

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

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

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

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

488
    return visuals;
×
UNCOV
489
}
×
490

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

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

498
    return visuals;
×
499
}
×
500

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

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

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

517
    auto it = _->_textVisuals.find(componentId);
6 ✔
518
    if(it == _->_textVisuals.end())
6 !
UNCOV
519
        return;
×
520

521
    for(const auto& textVisual : it->second)
6 ✔
522
        fn(textVisual);
6 ✔
523
}
6 ✔
524

525
NodePositions& GraphModel::nodePositions() { return _->_nodePositions; }
8,336 ✔
526
const NodePositions& GraphModel::nodePositions() const { return _->_nodePositions; }
140 ✔
527

528
const NodeArray<QString>& GraphModel::nodeNames() const { return _->_nodeNames; }
142 ✔
529
QString GraphModel::nodeName(NodeId nodeId) const { return _->_nodeNames[nodeId]; }
394,468 ✔
530
void GraphModel::setNodeName(NodeId nodeId, const QString& name)
531
{
27,460 ✔
532
    _->_nodeNames[nodeId] = name;
27,460 ✔
533
    _->requestFullVisualUpdate();
27,460 ✔
534
    scheduleVisualUpdate();
27,460 ✔
535
}
27,460 ✔
536

537
bool GraphModel::editable() const { return _plugin->editable(); }
2 ✔
538
bool GraphModel::directed() const { return _plugin->directed(); }
1,694 ✔
539

540
QString GraphModel::pluginName() const { return _plugin->name(); }
112 ✔
541
QString GraphModel::pluginDisplayName() const { return _plugin->displayName(); }
112 ✔
542
int GraphModel::pluginDataVersion() const { return _plugin->dataVersion(); }
112 ✔
UNCOV
543
QString GraphModel::pluginQmlModule() const { return _plugin->qmlModule(); }
×
544

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

550
    if(parsed)
192 ✔
551
    {
190 ✔
552
        const auto& graphTransformConfig = p.result();
190 ✔
553

554
        const auto* factory = transformFactory(graphTransformConfig._action);
190 ✔
555

556
        if(factory == nullptr)
190 !
UNCOV
557
            return false;
×
558

559
        if(factory->requiresCondition() && !graphTransformConfig.hasCondition())
190 ✔
560
            return false;
2 ✔
561

562
        return factory->configIsValid(*this, graphTransformConfig);
188 ✔
563
    }
190 ✔
564

565
    return false;
2 ✔
566
}
192 ✔
567

568
QStringList GraphModel::transformsWithMissingParametersSetToDefault(const QStringList& transforms) const
569
{
1,680 ✔
570
    QStringList transformsWithDefaults;
1,680 ✔
571

572
    for(const auto& transform : transforms)
1,680 ✔
573
    {
1,226 ✔
574
        GraphTransformConfigParser graphTransformConfigParser;
1,226 ✔
575

576
        if(!graphTransformConfigParser.parse(transform))
1,226 !
UNCOV
577
            continue;
×
578

579
        auto graphTransformConfig = graphTransformConfigParser.result();
1,226 ✔
580

581
        const auto* factory = transformFactory(graphTransformConfig._action);
1,226 ✔
582

583
        // This can happen if the file has transforms that the app doesn't
584
        if(factory == nullptr)
1,226 !
UNCOV
585
            continue;
×
586

587
        factory->setMissingParametersToDefault(graphTransformConfig);
1,226 ✔
588
        transformsWithDefaults.append(graphTransformConfig.asString());
1,226 ✔
589
    }
1,226 ✔
590

591
    return transformsWithDefaults;
1,680 ✔
592
}
1,680 ✔
593

594
void GraphModel::buildTransforms(const QStringList& transforms, Progressable* progressable)
595
{
1,696 ✔
596
    _->_transformedGraph.clearTransforms();
1,696 ✔
597
    _->_transformInfos.clear();
1,696 ✔
598
    for(int index = 0; index < transforms.size(); index++)
2,956 ✔
599
    {
1,260 ✔
600
        const auto& transform = transforms.at(index);
1,260 ✔
601
        GraphTransformConfigParser graphTransformConfigParser;
1,260 ✔
602

603
        if(!graphTransformConfigParser.parse(transform))
1,260 !
UNCOV
604
            continue;
×
605

606
        const auto& graphTransformConfig = graphTransformConfigParser.result();
1,260 ✔
607
        const auto& action = graphTransformConfig._action;
1,260 ✔
608

609
        if(graphTransformConfig.isFlagSet(u"disabled"_s))
1,260 !
UNCOV
610
            continue;
×
611

612
        const auto* factory = transformFactory(action);
1,260 ✔
613

614
        if(factory == nullptr)
1,260 !
UNCOV
615
            continue;
×
616
        auto graphTransform = factory->create(*this, graphTransformConfig);
1,260 ✔
617

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

630
    _->_transformedGraph.enableAutoRebuild();
1,696 ✔
631
}
1,696 ✔
632

633
void GraphModel::cancelTransformBuild()
634
{
8 ✔
635
    _->_transformedGraph.cancelRebuild();
8 ✔
636
}
8 ✔
637

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

644
    for(const auto& [transformName, factory] : transformFactories)
4 ✔
645
    {
120 ✔
646
        auto elementType = factory->elementType();
120 ✔
647
        const bool attributesAvailable = !availableAttributeNames(elementType, ValueType::All).isEmpty();
120 ✔
648

649
        if(elementType == ElementType::None || attributesAvailable)
120 !
650
            stringList.append(transformName);
120 ✔
651
    }
120 ✔
652

653
    return stringList;
4 ✔
654
}
4 ✔
655

656
const GraphTransformFactory* GraphModel::transformFactory(const QString& transformName) const
657
{
2,792 ✔
658
    return _->_application->transformFactory(transformName);
2,792 ✔
659
}
2,792 ✔
660

661
QStringList GraphModel::availableAttributeNames(ElementType elementTypes,
662
    ValueType valueTypes, AttributeFlag skipFlags,
663
    const QStringList& skipAttributeNames) const
664
{
304 ✔
665
    QStringList stringList;
304 ✔
666

667
    for(auto& attribute : _->_attributes)
304 ✔
668
    {
3,402 ✔
669
        if(!Flags<ElementType>(elementTypes).test(attribute.second.elementType()))
3,402 ✔
670
            continue;
1,404 ✔
671

672
        if(!Flags<ValueType>(valueTypes).test(attribute.second.valueType()))
1,998 ✔
673
            continue;
114 ✔
674

675
        if(attribute.second.testFlag(skipFlags))
1,884 ✔
676
            continue;
2 ✔
677

678
        if(skipAttributeNames.contains(attribute.first))
1,882 !
UNCOV
679
            continue;
×
680

681
        stringList.append(attribute.first);
1,882 ✔
682
    }
1,882 ✔
683

684
    return stringList;
304 ✔
685
}
304 ✔
686

687
QStringList GraphModel::avaliableConditionFnOps(const QString& attributeName) const
688
{
120 ✔
689
    QStringList ops;
120 ✔
690

691
    if(attributeName.isEmpty() || !u::contains(_->_attributes, attributeName))
120 !
UNCOV
692
        return ops;
×
693

694
    const auto& attribute = _->_attributes.at(attributeName);
120 ✔
695
    ops.append(GraphTransformConfigParser::ops(attribute.valueType()));
120 ✔
696

697
    if(attribute.hasMissingValues())
120 ✔
698
        ops.append(GraphTransformConfigParser::opToString(ConditionFnOp::Unary::HasValue));
52 ✔
699

700
    return ops;
120 ✔
701
}
120 ✔
702

703
bool GraphModel::hasTransformInfo() const
704
{
1,086 ✔
705
    return !_->_transformInfos.empty();
1,086 ✔
706
}
1,086 ✔
707

708
const TransformInfo& GraphModel::transformInfoAtIndex(int index) const
709
{
456 ✔
710
    static const TransformInfo nullTransformInfo;
456 ✔
711

712
    if(u::contains(_->_transformInfos, index))
456 !
713
        return _->_transformInfos.at(index);
456 ✔
714

UNCOV
715
    return nullTransformInfo;
×
716
}
456 ✔
717

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

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

728
std::vector<QString> GraphModel::addedOrChangedAttributeNamesAtTransformIndexOrLater(int firstIndex) const
729
{
6 ✔
730
    std::vector<QString> attributeNames;
6 ✔
731

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

739
    return attributeNames;
6 ✔
740
}
6 ✔
741

742
ValueType GraphModel::valueTypeOfTransformAttributeName(const QString& attributeName) const
743
{
2 ✔
744
    for(const auto& [transformName, factory] : _->_application->transformFactories())
2 !
745
    {
38 ✔
746
        const auto& defaultVisualisations = factory->defaultVisualisations();
38 ✔
747
        auto v = std::ranges::find(defaultVisualisations, attributeName, &DefaultVisualisation::_attributeName);
38 ✔
748

749
        if(v != defaultVisualisations.end())
38 ✔
750
            return v->_attributeValueType;
2 ✔
751
    }
38 ✔
752

UNCOV
753
    return ValueType::Unknown;
×
754
}
2 ✔
755

756
bool GraphModel::opIsUnary(const QString& op)
UNCOV
757
{
×
758
    return GraphTransformConfigParser::opIsUnary(op);
×
UNCOV
759
}
×
760

761
bool GraphModel::visualisationIsValid(const QString& visualisation) const
762
{
10 ✔
763
    VisualisationConfigParser p;
10 ✔
764
    const bool parsed = p.parse(visualisation, "warnOnFailure"_no);
10 ✔
765

766
    if(parsed)
10 !
767
    {
10 ✔
768
        const auto& visualisationConfig = p.result();
10 ✔
769

770
        if(_->_application->visualisationChannelFactory(visualisationConfig._channelName) == nullptr)
10 ✔
771
            return false;
4 ✔
772

773
        return true;
6 ✔
774
    }
10 ✔
775

UNCOV
776
    return false;
×
777
}
10 ✔
778

779
void GraphModel::buildVisualisations(const QStringList& visualisations)
780
{
844 ✔
781
    SCOPE_TIMER_MULTISAMPLES(50)
844 ✔
782

783
    _->_visualisationRebuildRequired = false;
844 ✔
784

785
    _->_mappedNodeVisuals.resetElements();
844 ✔
786
    _->_mappedEdgeVisuals.resetElements();
844 ✔
787
    _->_newTextVisuals.clear();
844 ✔
788
    clearVisualisationInfos();
844 ✔
789

790
    _->_visualisedAttributeNames.clear();
844 ✔
791
    _->_hasValidEdgeTextVisualisation = false;
844 ✔
792

793
    VisualisationsBuilder<NodeId> nodeVisualisationsBuilder(graph(), _->_mappedNodeVisuals);
844 ✔
794
    VisualisationsBuilder<EdgeId> edgeVisualisationsBuilder(graph(), _->_mappedEdgeVisuals);
844 ✔
795

796
    for(int index = 0; index < visualisations.size(); index++)
1,229 ✔
797
    {
385 ✔
798
        const auto& visualisation = visualisations.at(index);
385 ✔
799

800
        VisualisationConfigParser visualisationConfigParser;
385 ✔
801

802
        if(!visualisationConfigParser.parse(visualisation))
385 !
UNCOV
803
            continue;
×
804

805
        const auto& visualisationConfig = visualisationConfigParser.result();
385 ✔
806

807
        if(visualisationConfig.isFlagSet(u"disabled"_s))
385 ✔
808
            continue;
2 ✔
809

810
        const auto& attributeName = visualisationConfig._attributeName;
383 ✔
811
        const auto& channelName = visualisationConfig._channelName;
383 ✔
812
        auto& info = _->_visualisationInfos[index];
383 ✔
813

814
        // Track referenced attribute names, even if the attributes in question don't exist
815
        _->_visualisedAttributeNames.append(attributeName);
383 ✔
816

817
        if(!attributeExists(attributeName))
383 ✔
818
        {
6 ✔
819
            info.addAlert(AlertType::Error, tr("Attribute '%1' doesn't exist").arg(attributeName));
6 ✔
820
            continue;
6 ✔
821
        }
6 ✔
822

823
        const auto* factory = _->_application->visualisationChannelFactory(channelName);
377 ✔
824

825
        if(factory == nullptr)
377 ✔
826
        {
188 ✔
827
            info.addAlert(AlertType::Error, tr("Visualisation channel '%1' doesn't exist").arg(channelName));
188 ✔
828
            continue;
188 ✔
829
        }
188 ✔
830

831
        auto attribute = attributeValueByName(attributeName);
189 ✔
832

833
        factory->findErrors(attribute.elementType(), info);
189 ✔
834

835
        if(!factory->supports(attribute.valueType()))
189 ✔
836
        {
2 ✔
837
            info.addAlert(AlertType::Error, tr("Visualisation doesn't support attribute type"));
2 ✔
838
            continue;
2 ✔
839
        }
2 ✔
840

841
        auto channel = factory->create(visualisationConfig);
187 ✔
842

843
        if(attribute.elementType() == ElementType::Edge && channelName == u"Text"_s)
187 !
844
            _->_hasValidEdgeTextVisualisation = true;
6 ✔
845

846
        if(attribute.valueType() == ValueType::String)
187 ✔
847
        {
123 ✔
848
            auto sharedValues = attribute.sharedValues();
123 ✔
849
            if(sharedValues.empty())
123 ✔
850
            {
109 ✔
851
                if(attribute.elementType() == ElementType::Node)
109 !
852
                    sharedValues = attribute.findSharedValuesForElements(graph().nodeIds());
109 ✔
UNCOV
853
                else if(attribute.elementType() == ElementType::Edge)
×
UNCOV
854
                    sharedValues = attribute.findSharedValuesForElements(graph().edgeIds());
×
855
            }
109 ✔
856

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

879
                    return a._count > b._count;
4 ✔
880
                });
8 ✔
881
            }
2 ✔
882

883
            for(const auto& sharedValue : sharedValues)
123 ✔
884
            {
46,568 ✔
885
                channel->addValue(sharedValue._value);
46,568 ✔
886
                info.addStringValue(sharedValue._value);
46,568 ✔
887
            }
46,568 ✔
888
        }
123 ✔
889

890
        switch(attribute.elementType())
187 ✔
891
        {
187 ✔
892
        case ElementType::Node:
181 ✔
893
            nodeVisualisationsBuilder.build(attribute, *factory, *channel, visualisationConfig, index, info);
181 ✔
894
            break;
181 ✔
895

896
        case ElementType::Edge:
6 ✔
897
            edgeVisualisationsBuilder.build(attribute, *factory, *channel, visualisationConfig, index, info);
6 ✔
898
            break;
6 ✔
899

UNCOV
900
        default:
×
UNCOV
901
            break;
×
902
        }
187 ✔
903

904
        auto textVisuals = channel->textVisuals(attributeName, *this, _->_transformedGraph);
187 ✔
905

906
        for(const auto& [componentId, textVisual] : textVisuals)
187 ✔
907
        {
18 ✔
908
            auto& existingTextVisuals = _->_newTextVisuals[componentId];
18 ✔
909
            existingTextVisuals.insert(existingTextVisuals.end(), textVisual.begin(), textVisual.end());
18 ✔
910
        }
18 ✔
911
    }
187 ✔
912

913
    nodeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
844 ✔
914
    edgeVisualisationsBuilder.findOverrideAlerts(_->_visualisationInfos);
844 ✔
915

916
    _->requestFullVisualUpdate();
844 ✔
917
    scheduleVisualUpdate();
844 ✔
918
}
844 ✔
919

920
bool GraphModel::transformRebuildRequired() const { return _->_transformRebuildRequired; }
532 ✔
921
bool GraphModel::visualisationRebuildRequired() const { return _->_visualisationRebuildRequired; }
514 ✔
922

923
bool GraphModel::hasValidEdgeTextVisualisation() const
924
{
2 ✔
925
    return _->_hasValidEdgeTextVisualisation;
2 ✔
926
}
2 ✔
927

928
QStringList GraphModel::availableVisualisationChannelNames(ElementType elementType, ValueType valueType) const
929
{
2 ✔
930
    QStringList stringList;
2 ✔
931

932
    for(const auto& [channelName, factory] : _->_application->visualisationChannelFactories())
2 ✔
933
    {
12 ✔
934
        if(factory->appliesTo(elementType) && factory->supports(valueType))
12 !
935
            stringList.append(channelName);
10 ✔
936
    }
12 ✔
937

938
    return stringList;
2 ✔
939
}
2 ✔
940

941
bool GraphModel::visualisationChannelAllowsMapping(const QString& channelName) const
942
{
16 ✔
943
    if(channelName.isEmpty())
16 ✔
944
        return false;
2 ✔
945

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

948
    if(factory == nullptr)
14 ✔
949
        return false;
2 ✔
950

951
    return factory->allowsMapping();
12 ✔
952
}
14 ✔
953

954
QStringList GraphModel::visualisationDescription(const QString& attributeName, const QStringList& channelNames) const
955
{
8 ✔
956
    QStringList descriptions;
8 ✔
957

958
    if(!attributeExists(attributeName))
8 ✔
959
        return descriptions;
2 ✔
960

961
    for(const auto& channelName : channelNames)
6 ✔
962
    {
20 ✔
963
        const auto* factory = _->_application->visualisationChannelFactory(channelName);
20 ✔
964

965
        if(factory == nullptr)
20 ✔
966
            return descriptions;
2 ✔
967

968
        auto attribute = attributeValueByName(attributeName);
18 ✔
969

970
        if(!factory->supports(attribute.valueType()))
18 ✔
971
            descriptions.append(tr("This visualisation channel is not supported for the attribute type."));
4 ✔
972
        else
14 ✔
973
            descriptions.append(factory->description(attribute.elementType(), attribute.valueType()));
14 ✔
974
    }
18 ✔
975

976
    return descriptions;
4 ✔
977
}
6 ✔
978

979
void GraphModel::clearVisualisationInfos()
980
{
866 ✔
981
    _->_visualisationInfos.clear();
866 ✔
982
}
866 ✔
983

984
bool GraphModel::hasVisualisationInfo() const
985
{
2 ✔
986
    return !_->_visualisationInfos.empty();
2 ✔
987
}
2 ✔
988

989
const VisualisationInfo& GraphModel::visualisationInfoAtIndex(int index) const
990
{
20 ✔
991
    static const VisualisationInfo nullVisualisationInfo;
20 ✔
992

993
    if(u::contains(_->_visualisationInfos, index))
20 !
994
        return _->_visualisationInfos.at(index);
20 ✔
995

UNCOV
996
    return nullVisualisationInfo;
×
997
}
20 ✔
998

999
QVariantMap GraphModel::visualisationDefaultParameters(ValueType valueType, const QString& channelName) const
1000
{
10 ✔
1001
    const auto* factory = _->_application->visualisationChannelFactory(channelName);
10 ✔
1002

1003
    if(factory == nullptr)
10 !
UNCOV
1004
        return {};
×
1005

1006
    return factory->defaultParameters(valueType);
10 ✔
1007
}
10 ✔
1008

1009
std::vector<QString> GraphModel::attributeNames(ElementType elementType) const
1010
{
4,174 ✔
1011
    std::vector<QString> attributeNames;
4,174 ✔
1012

1013
    for(auto& attribute : _->_attributes)
4,174 ✔
1014
    {
52,936 ✔
1015
        if(Flags<ElementType>(elementType).test(attribute.second.elementType()))
52,936 ✔
1016
            attributeNames.emplace_back(attribute.first);
45,316 ✔
1017
    }
52,936 ✔
1018

1019
    return attributeNames;
4,174 ✔
1020
}
4,174 ✔
1021

1022
Attribute& GraphModel::createAttribute(const AttributeDeclaration& declaration)
1023
{
16,136 ✔
1024
    return GraphModel::createAttribute(declaration._name).setDisplayName(declaration._displayName);
16,136 ✔
1025
}
16,136 ✔
1026

1027
Attribute& GraphModel::createAttribute(QString name, QString* assignedName, QString clashHint)
1028
{
19,776 ✔
1029
    const QString requestedName = name;
19,776 ✔
1030
    name = normalisedAttributeName(name, clashHint);
19,776 ✔
1031

1032
    if(assignedName != nullptr)
19,776 ✔
1033
        *assignedName = name;
2,742 ✔
1034

1035
    Attribute& attribute = _->_attributes[name];
19,776 ✔
1036

1037
    // If we're creating an attribute during the graph transform, it's
1038
    // a dynamically created attribute rather than a persistent one,
1039
    // so mark it as such
1040
    if(_graphTransformsAreChanging)
19,776 ✔
1041
        attribute.setFlag(AttributeFlag::Dynamic);
468 ✔
1042

1043
    for(auto* tracker : _->_attributeChangesTrackers)
19,776 ✔
1044
    {
508 ✔
1045
        tracker->assignName(requestedName, name);
508 ✔
1046

1047
        if(_graphTransformsAreChanging && _->_removedDynamicAttributeNames.contains(name))
508 ✔
1048
            tracker->change(name);
4 ✔
1049
        else
504 ✔
1050
            tracker->add(name);
504 ✔
1051
    }
508 ✔
1052

1053
    return attribute;
19,776 ✔
1054
}
19,776 ✔
1055

1056
void GraphModel::addAttributes(const std::map<QString, Attribute>& attributes)
1057
{
26 ✔
1058
    _->_attributes.insert(attributes.begin(), attributes.end());
26 ✔
1059
}
26 ✔
1060

1061
void GraphModel::removeAttribute(const QString& name)
1062
{
44 ✔
1063
    if(!u::contains(_->_attributes, name))
44 !
UNCOV
1064
        return;
×
1065

1066
    _->_attributes.erase(name);
44 ✔
1067

1068
    for(auto* tracker : _->_attributeChangesTrackers)
44 ✔
1069
        tracker->remove(name);
44 ✔
1070
}
44 ✔
1071

1072
const Attribute* GraphModel::attributeByName(const QString& name) const
1073
{
59,010 ✔
1074
    auto attributeName = Attribute::parseAttributeName(name);
59,010 ✔
1075

1076
    if(!u::contains(_->_attributes, attributeName._name))
59,010 ✔
1077
    {
4 ✔
1078
        qDebug() << "WARNING: attribute unknown in attributeByName" << attributeName._name;
4 ✔
1079
        return nullptr;
4 ✔
1080
    }
4 ✔
1081

1082
    return &_->_attributes.at(attributeName._name);
59,006 ✔
1083
}
59,010 ✔
1084

1085
Attribute* GraphModel::attributeByName(const QString& name)
1086
{
56,932 ✔
1087
    return const_cast<Attribute*>(const_cast<const GraphModel*>(this)->attributeByName(name));
56,932 ✔
1088
}
56,932 ✔
1089

1090
bool GraphModel::attributeExists(const QString& name) const
1091
{
9,467 ✔
1092
    auto attributeName = Attribute::parseAttributeName(name);
9,467 ✔
1093
    return u::contains(_->_attributes, attributeName._name);
9,467 ✔
1094
}
9,467 ✔
1095

1096
QString GraphModel::attributeDisplayValue(const QString& name, const QString& value) const
1097
{
54 ✔
1098
    if(!attributeExists(name))
54 ✔
1099
        return value;
2 ✔
1100

1101
    const auto* attribute = attributeByName(name);
52 ✔
1102
    return attribute != nullptr ? attribute->displayValue(value) : value;
52 !
1103
}
54 ✔
1104

1105
QString GraphModel::attributeStoredValue(const QString& name, const QString& displayValue) const
1106
{
4 ✔
1107
    if(!attributeExists(name))
4 ✔
1108
        return displayValue;
2 ✔
1109

1110
    const auto* attribute = attributeByName(name);
2 ✔
1111
    return attribute != nullptr ? attribute->storedValue(displayValue) : displayValue;
2 !
1112
}
4 ✔
1113

1114
bool GraphModel::attributeIsDeclared(const QString& name) const
1115
{
2,670 ✔
1116
    return _->_application->attributeDeclaration(name, _plugin) != nullptr;
2,670 ✔
1117
}
2,670 ✔
1118

1119
QString GraphModel::attributeDisplayName(const QString& name) const
1120
{
11,336 ✔
1121
    if(name.isEmpty())
11,336 ✔
1122
        return {};
148 ✔
1123

1124
    auto displayNameOf = [this](const QString& attributeName)
11,188 ✔
1125
    {
11,188 ✔
1126
        const auto* attribute = u::contains(_->_attributes, attributeName) ?
11,188 ✔
1127
            &_->_attributes.at(attributeName) : nullptr;
11,186 ✔
1128

1129
        if(attribute != nullptr && !attribute->displayName().isEmpty())
11,188 ✔
1130
            return attribute->displayName();
1,220 ✔
1131

1132
        const auto* declaredAttribute = _->_application->attributeDeclaration(attributeName, _plugin);
9,968 ✔
1133
        if(declaredAttribute != nullptr && !declaredAttribute->_displayName.isEmpty())
9,968 !
1134
            return declaredAttribute->_displayName;
192 ✔
1135

1136
        if(attribute != nullptr)
9,776 !
1137
            return attributeName;
9,776 ✔
1138

1139
        // It doesn't exist, so there's no name to show for it
UNCOV
1140
        return QObject::tr("Unknown Attribute");
×
1141
    };
9,776 ✔
1142

1143
    if(u::contains(_->_attributes, name))
11,188 ✔
1144
        return displayNameOf(name);
11,180 ✔
1145

1146
    return Attribute::fullyQualifiedDisplayName(name, displayNameOf);
8 ✔
1147
}
11,188 ✔
1148

1149
bool GraphModel::attributeIsValid(const QString& name) const
1150
{
1,064 ✔
1151
    if(!attributeExists(name))
1,064 !
UNCOV
1152
        return false;
×
1153

1154
    auto attributeName = Attribute::parseAttributeName(name);
1,064 ✔
1155
    const auto* attribute = &_->_attributes.at(attributeName._name);
1,064 ✔
1156

1157
    const bool attributeDisabled = _graphTransformsAreChanging &&
1,064 !
1158
        attribute->testFlag(AttributeFlag::DisableDuringTransform);
1,064 !
1159

1160
    return !attributeDisabled;
1,064 ✔
1161
}
1,064 ✔
1162

1163
Attribute GraphModel::attributeValueByName(const QString& name) const
1164
{
3,541 ✔
1165
    auto attributeName = Attribute::parseAttributeName(name);
3,541 ✔
1166

1167
    if(!u::contains(_->_attributes, attributeName._name))
3,541 ✔
1168
    {
6 ✔
1169
        qDebug() << "WARNING: attribute unknown in attributeValueByName" << attributeName._name;
6 ✔
1170
        return {};
6 ✔
1171
    }
6 ✔
1172

1173
    auto attribute = _->_attributes.at(attributeName._name);
3,535 ✔
1174

1175
    if(!attributeName._parameter.isEmpty())
3,535 ✔
1176
        attribute.setParameterValue(attributeName._parameter);
16 ✔
1177

1178
    if(attributeName._type != Attribute::EdgeNodeType::None)
3,535 ✔
1179
    {
112 ✔
1180
        return Attribute::edgeNodesAttribute(_->_graph,
112 ✔
1181
            attribute, attributeName._type);
112 ✔
1182
    }
112 ✔
1183

1184
    return attribute;
3,423 ✔
1185
}
3,535 ✔
1186

1187
void GraphModel::calculateAttributeRange(const IGraph* graph, Attribute& attribute)
1188
{
56,590 ✔
1189
    if(!attribute.testFlag(AttributeFlag::AutoRange))
56,590 ✔
1190
        return;
44,334 ✔
1191

1192
    if(attribute.elementType() == ElementType::Node)
12,256 ✔
1193
        attribute.autoSetRangeForElements(graph->nodeIds());
9,938 ✔
1194
    else if(attribute.elementType() == ElementType::Edge)
2,318 !
1195
        attribute.autoSetRangeForElements(graph->edgeIds());
2,318 ✔
UNCOV
1196
    else if(attribute.elementType() == ElementType::Component)
×
UNCOV
1197
        qDebug() << "calculateAttributeRange called on component attribute";
×
1198
}
12,256 ✔
1199

1200
void GraphModel::calculateAttributeRange(Attribute& attribute)
1201
{
23,758 ✔
1202
    calculateAttributeRange(&mutableGraph(), attribute);
23,758 ✔
1203
}
23,758 ✔
1204

1205
static void calculateAttributeRanges(const Graph* graph,
1206
    std::map<QString, Attribute>& attributes)
1207
{
3,164 ✔
1208
    for(auto& attribute : make_value_wrapper(attributes)) // clazy:exclude=compare-member-check
3,164 ✔
1209
        GraphModel::calculateAttributeRange(graph, attribute);
32,832 ✔
1210
}
3,164 ✔
1211

1212
void GraphModel::initialiseAttributeRanges()
1213
{
1,420 ✔
1214
    calculateAttributeRanges(&mutableGraph(), _->_attributes);
1,420 ✔
1215
}
1,420 ✔
1216

1217
void GraphModel::initialiseSharedAttributeValues()
1218
{
514 ✔
1219
    for(auto& attribute : make_value_wrapper(_->_attributes)) // clazy:exclude=compare-member-check
514 ✔
1220
        _->updateSharedAttributeValues(attribute);
7,532 ✔
1221
}
514 ✔
1222

1223
bool GraphModel::attributeNameIsValid(const QString& attributeName)
1224
{
100 ✔
1225
    if(attributeName.isEmpty())
100 ✔
1226
        return false;
6 ✔
1227

1228
    auto attributeNameRegex = QRegularExpression(IAttribute::ValidNameRegex);
94 ✔
1229
    return attributeNameRegex.match(attributeName).hasMatch();
94 ✔
1230
}
100 ✔
1231

1232
UserNodeData& GraphModel::userNodeData() { return _->_userNodeData; }
60,150 ✔
1233
UserEdgeData& GraphModel::userEdgeData() { return _->_userEdgeData; }
2,432 ✔
1234

1235
void GraphModel::clearHighlightedNodes()
UNCOV
1236
{
×
UNCOV
1237
    highlightNodes({});
×
UNCOV
1238
}
×
1239

1240
void GraphModel::highlightNodes(const NodeIdSet& nodeIds)
1241
{
6 ✔
1242
    bool requested = false;
6 ✔
1243

1244
    _->requestVisualUpdate([this, &nodeIds, &requested](auto& pending)
6 ✔
1245
    {
6 ✔
1246
        const auto& latestHighlightedNodeIds = pending._highlightedNodeIds ?
6 !
1247
            *pending._highlightedNodeIds : _->_highlightedNodeIds;
6 ✔
1248

1249
        if(latestHighlightedNodeIds.empty() && nodeIds.empty())
6 !
UNCOV
1250
            return;
×
1251

1252
        pending._highlightedNodeIds = nodeIds;
6 ✔
1253
        pending._full = true;
6 ✔
1254
        requested = true;
6 ✔
1255
    });
6 ✔
1256

1257
    if(requested)
6 !
1258
        scheduleVisualUpdate();
6 ✔
1259
}
6 ✔
1260

1261
void GraphModel::enableVisualUpdates()
1262
{
570 ✔
1263
    // Loading has only just built the transforms and visualisations from scratch
1264
    _->_transformRebuildRequired = false;
570 ✔
1265
    _->_visualisationRebuildRequired = false;
570 ✔
1266

1267
    _visualUpdatesEnabled = true;
570 ✔
1268
    _->requestFullVisualUpdate();
570 ✔
1269

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

1278
static float mappedSize(float min, float max, float user, float mapped = -1.0f)
1279
{
751,094 ✔
1280
    if(mapped < 0.0f)
751,094 ✔
1281
        return user;
750,976 ✔
1282

1283
    // The fraction of the mapped value that contributes to the final value
1284
    const float mappedRange = 0.75f;
118 ✔
1285

1286
    auto normalised = u::normalise(min, max, user);
118 ✔
1287
    auto out = (mapped * mappedRange) + (normalised * (1.0f - mappedRange));
118 ✔
1288

1289
    return min + (out * (max - min));
118 ✔
1290
}
751,094 ✔
1291

1292
static float mappedTextSize(float user, float mapped = -1.0f)
1293
{
752,046 ✔
1294
    auto value = mapped >= 0.0f ?
752,046 ✔
1295
        ((1.0f * user) + (2.0f * mapped)) / 3.0f :
16 ✔
1296
        user;
752,046 ✔
1297

1298
    return value < 0.5f ?
752,046 ✔
1299
        u::interpolate(LimitConstants::minimumTextSize(), 1.0f, value / 0.5f) :
52 ✔
1300
        u::interpolate(1.0f, LimitConstants::maximumTextSize(), (value - 0.5f) / 0.5f);
752,046 ✔
1301
}
752,046 ✔
1302

1303
bool GraphModel::nodeIsUnhighlighted(NodeId nodeId, bool nodeIsSelected) const
1304
{
376,020 ✔
1305
    auto isNotFound = !_->_foundNodeIds.empty() && !u::contains(_->_foundNodeIds, nodeId);
376,020 ✔
1306
    auto isNotHighlighted = !_->_highlightedNodeIds.empty() && nodeIsSelected &&
376,020 !
1307
        !u::contains(_->_highlightedNodeIds, nodeId);
376,020 ✔
1308

1309
    return (isNotFound && _->_nodesMaskActive) || isNotHighlighted;
376,020 ✔
1310
}
376,020 ✔
1311

1312
void GraphModel::scheduleVisualUpdate()
1313
{
30,564 ✔
1314
    // Before visual updates are enabled requests only accumulate, and
1315
    // enabling them schedules the update that takes account of them all
1316
    if(_visualUpdatesEnabled)
30,564 ✔
1317
        emit visualUpdateRequested();
542 ✔
1318
}
30,564 ✔
1319

1320
void GraphModel::applyPendingVisualUpdates()
1321
{
1,326 ✔
1322
    if(!_visualUpdatesEnabled)
1,326 !
UNCOV
1323
        return;
×
1324

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

1328
    PendingVisualUpdate pending;
1,326 ✔
1329
    NodeIdSet previousSelectedNodeIds;
1,326 ✔
1330
    bool maskChanged = false;
1,326 ✔
1331

1332
    {
1,326 ✔
1333
        const std::unique_lock<std::mutex> pendingLock(_->_pendingVisualUpdateMutex);
1,326 ✔
1334
        pending = std::exchange(_->_pendingVisualUpdate, {});
1,326 ✔
1335

1336
        if(pending._selectedNodeIds)
1,326 ✔
1337
        {
112 ✔
1338
            previousSelectedNodeIds = std::exchange(_->_selectedNodeIds,
112 ✔
1339
                std::move(*pending._selectedNodeIds));
112 ✔
1340
        }
112 ✔
1341

1342
        if(pending._nodesMaskActive)
1,326 ✔
1343
        {
112 ✔
1344
            maskChanged = std::exchange(_->_nodesMaskActive,
112 ✔
1345
                *pending._nodesMaskActive) != *pending._nodesMaskActive;
112 ✔
1346
        }
112 ✔
1347

1348
        if(pending._foundNodeIds)
1,326 ✔
1349
            _->_foundNodeIds = std::move(*pending._foundNodeIds);
24 ✔
1350

1351
        if(pending._highlightedNodeIds)
1,326 ✔
1352
            _->_highlightedNodeIds = std::move(*pending._highlightedNodeIds);
6 ✔
1353
    }
1,326 ✔
1354

1355
    // Whether a mask is in place affects the highlight state of every node, not
1356
    // just the ones whose selected state changed, so there is no shortcut here
1357
    if(pending._full || maskChanged)
1,326 ✔
1358
        updateVisuals(pending._force);
952 ✔
1359
    else if(pending._selectedNodeIds)
374 ✔
1360
        updateSelectionVisuals(previousSelectedNodeIds);
98 ✔
1361
}
1,326 ✔
1362

1363
void GraphModel::updateVisuals(bool force)
1364
{
952 ✔
1365
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
952 ✔
1366

1367
    const float userNodeSize = _->_nodeSize;
952 ✔
1368
    const float userEdgeSize = _->_edgeSize;
952 ✔
1369
    const float userTextSize = _->_textSize;
952 ✔
1370

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

1380
    auto& nodeVisuals = _->_nodeVisuals;
952 ✔
1381
    auto& edgeVisuals = _->_edgeVisuals;
952 ✔
1382

1383
    Flags<VisualChangeFlags> nodeChanges;
952 ✔
1384
    Flags<VisualChangeFlags> edgeChanges;
952 ✔
1385

1386
    bool changing = false;
952 ✔
1387
    auto beginChanging = [this, &changing]
952 ✔
1388
    {
811,822 ✔
1389
        if(changing)
811,822 ✔
1390
            return;
811,012 ✔
1391

1392
        changing = true;
810 ✔
1393
        emit visualsWillChange();
810 ✔
1394
    };
810 ✔
1395

1396
    auto setIfChanged = [&beginChanging](auto& destination, const auto& value,
952 ✔
1397
        Flags<VisualChangeFlags>& changes, VisualChangeFlags change)
952 ✔
1398
    {
5,257,658 ✔
1399
        if(destination != value) // clazy:exclude=compare-member-check
5,257,658 ✔
1400
        {
811,812 ✔
1401
            beginChanging();
811,812 ✔
1402
            destination = value;
811,812 ✔
1403
            changes.set(change);
811,812 ✔
1404
        }
811,812 ✔
1405
    };
5,257,658 ✔
1406

1407
    if(force)
952 ✔
1408
        beginChanging();
4 ✔
1409

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

1414
    for(auto edgeId : graph().edgeIds())
952 ✔
1415
    {
375,362 ✔
1416
        newEdgeStates[edgeId] = edgeVisuals[edgeId]._state;
375,362 ✔
1417
        newEdgeStates[edgeId].reset(VisualFlags::Selected, VisualFlags::Unhighlighted);
375,362 ✔
1418
    }
375,362 ✔
1419

1420
    auto setElementVisual = [&](auto elementId, auto& visual, const auto& mapped,
952 ✔
1421
        float size, const QColor& color, const QString& text,
952 ✔
1422
        Flags<VisualChangeFlags>& changes)
952 ✔
1423
    {
751,094 ✔
1424
        setIfChanged(visual._size, size, changes, VisualChangeFlags::Size);
751,094 ✔
1425

1426
        setIfChanged(visual._outerColor, mapped._outerColor.isValid() ?
751,094 !
1427
            mapped._outerColor : color, changes, VisualChangeFlags::Color);
564,936 ✔
1428

1429
        setIfChanged(visual._innerColor,
751,094 ✔
1430
            !meIndicators || graph().typeOf(elementId) == MultiElementType::Not ?
751,094 !
1431
            visual._outerColor : multiColor, changes, VisualChangeFlags::Color);
751,078 ✔
1432

1433
        setIfChanged(visual._text, !mapped._text.isEmpty() ?
751,094 ✔
1434
            mapped._text : text, changes, VisualChangeFlags::Text);
750,976 ✔
1435

1436
        setIfChanged(visual._textSize, mappedTextSize(userTextSize, mapped._textSize),
751,094 ✔
1437
            changes, VisualChangeFlags::TextSize);
751,094 ✔
1438

1439
        setIfChanged(visual._textColor, mapped._textColor.isValid() ?
751,094 !
1440
            mapped._textColor : textColor, changes, VisualChangeFlags::TextColor);
751,030 ✔
1441
    };
751,094 ✔
1442

1443
    for(auto nodeId : graph().nodeIds())
952 ✔
1444
    {
375,732 ✔
1445
        auto& visual = nodeVisuals[nodeId];
375,732 ✔
1446
        const auto& mapped = _->_mappedNodeVisuals[nodeId];
375,732 ✔
1447

1448
        setElementVisual(nodeId, visual, mapped,
375,732 ✔
1449
            mappedSize(LimitConstants::minimumNodeSize(), LimitConstants::maximumNodeSize(),
375,732 ✔
1450
            nodeSize, mapped._size), nodeColor, nodeName(nodeId), nodeChanges);
375,732 ✔
1451

1452
        auto nodeIsSelected = u::contains(_->_selectedNodeIds, nodeId);
375,732 ✔
1453
        auto nodeUnhighlighted = nodeIsUnhighlighted(nodeId, nodeIsSelected);
375,732 ✔
1454

1455
        auto state = visual._state;
375,732 ✔
1456
        state.setState(VisualFlags::Selected, nodeIsSelected);
375,732 ✔
1457
        state.setState(VisualFlags::Unhighlighted, nodeUnhighlighted);
375,732 ✔
1458
        setIfChanged(visual._state, state, nodeChanges, VisualChangeFlags::State);
375,732 ✔
1459

1460
        if(nodeIsSelected)
375,732 ✔
1461
        {
90 ✔
1462
            for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
90 ✔
1463
                newEdgeStates[edgeId].set(VisualFlags::Selected);
144 ✔
1464
        }
90 ✔
1465

1466
        if(nodeUnhighlighted)
375,732 ✔
1467
        {
38 ✔
1468
            for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
38 ✔
1469
                newEdgeStates[edgeId].set(VisualFlags::Unhighlighted);
56 ✔
1470
        }
38 ✔
1471
    }
375,732 ✔
1472

1473
    for(auto edgeId : graph().edgeIds())
952 ✔
1474
    {
375,362 ✔
1475
        auto& visual = edgeVisuals[edgeId];
375,362 ✔
1476
        const auto& mapped = _->_mappedEdgeVisuals[edgeId];
375,362 ✔
1477

1478
        // An edge is never drawn thicker than either of the nodes it joins
1479
        const auto& edge = graph().edgeById(edgeId);
375,362 ✔
1480
        auto size = std::min({mappedSize(LimitConstants::minimumEdgeSize(),
375,362 ✔
1481
            LimitConstants::maximumEdgeSize(), edgeSize, mapped._size),
375,362 ✔
1482
            nodeVisuals[edge.sourceId()]._size, nodeVisuals[edge.targetId()]._size});
375,362 ✔
1483

1484
        setElementVisual(edgeId, visual, mapped, size, edgeColor, {}, edgeChanges);
375,362 ✔
1485

1486
        setIfChanged(visual._state, newEdgeStates[edgeId], edgeChanges, VisualChangeFlags::State);
375,362 ✔
1487
    }
375,362 ✔
1488

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

1500
    auto findTextVisualsChange = [](const TextVisuals& previous, const TextVisuals& current)
952 ✔
1501
    {
952 ✔
1502
        Flags<VisualChangeFlags> change;
952 ✔
1503

1504
        if(previous.size() != current.size())
952 ✔
1505
            return VisualChangeFlags::State;
6 ✔
1506

1507
        auto previousComponentIds = u::keysFor(previous);
946 ✔
1508
        auto currentComponentIds = u::keysFor(current);
946 ✔
1509

1510
        if(previousComponentIds != currentComponentIds)
946 !
UNCOV
1511
            return VisualChangeFlags::State;
×
1512

1513
        for(const ComponentId componentId : previousComponentIds)
946 !
UNCOV
1514
        {
×
UNCOV
1515
            const auto& previousTextVisuals = previous.at(componentId);
×
1516
            const auto& currentTextVisuals = current.at(componentId);
×
1517

UNCOV
1518
            if(previousTextVisuals.size() != currentTextVisuals.size())
×
1519
                return VisualChangeFlags::State;
×
1520

1521
            for(size_t i = 0; i < previousTextVisuals.size(); i++)
×
UNCOV
1522
            {
×
1523
                const auto& previousTextVisual = previousTextVisuals.at(i);
×
1524
                const auto& currentTextVisual = currentTextVisuals.at(i);
×
1525

1526
                if(previousTextVisual._nodeIds != currentTextVisual._nodeIds)
×
1527
                    return VisualChangeFlags::State;
×
1528

1529
                if(previousTextVisual._color != currentTextVisual._color)
×
UNCOV
1530
                    change.set(VisualChangeFlags::TextColor);
×
1531

1532
                if(previousTextVisual._size != currentTextVisual._size)
×
UNCOV
1533
                    change.set(VisualChangeFlags::TextSize);
×
1534
            }
×
1535
        }
×
1536

1537
        return *change;
946 ✔
1538
    };
946 ✔
1539

1540
    const VisualChangeFlags textChange = findTextVisualsChange(_->_textVisuals, _->_newTextVisuals);
952 ✔
1541

1542
    if(textChange != VisualChangeFlags::None)
952 ✔
1543
        beginChanging();
6 ✔
1544

1545
    if(!changing)
952 ✔
1546
        return;
142 ✔
1547

1548
    {
810 ✔
1549
        const std::unique_lock<std::mutex> textVisualsLock(_->_textVisualsMutex);
810 ✔
1550

1551
        _->_textVisuals = _->_newTextVisuals;
810 ✔
1552
        updateTextVisualPositions(_->_textVisuals, _->_nodePositions);
810 ✔
1553
    }
810 ✔
1554

1555
    visualsLock.unlock();
810 ✔
1556
    emit visualsChanged(*nodeChanges, *edgeChanges, textChange);
810 ✔
1557
}
810 ✔
1558

1559
// When the selection changes, only update the selection visuals
1560
void GraphModel::updateSelectionVisuals(const NodeIdSet& previousSelectedNodeIds)
1561
{
98 ✔
1562
    std::vector<NodeId> changedNodeIds;
98 ✔
1563
    std::ranges::set_symmetric_difference(_->_selectedNodeIds, previousSelectedNodeIds,
98 ✔
1564
        std::back_inserter(changedNodeIds));
98 ✔
1565

1566
    if(changedNodeIds.empty())
98 ✔
1567
        return;
4 ✔
1568

1569
    std::unique_lock<std::shared_mutex> visualsLock(_->_visualsMutex);
94 ✔
1570

1571
    emit visualsWillChange();
94 ✔
1572

1573
    Flags<VisualChangeFlags> nodeChange;
94 ✔
1574
    Flags<VisualChangeFlags> edgeChange;
94 ✔
1575

1576
    for(auto nodeId : changedNodeIds)
94 ✔
1577
    {
288 ✔
1578
        auto& nodeVisual = _->_nodeVisuals[nodeId];
288 ✔
1579
        const auto previousState = nodeVisual._state;
288 ✔
1580

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

1583
        nodeVisual._state.setState(VisualFlags::Selected, nodeIsSelected);
288 ✔
1584
        nodeVisual._state.setState(VisualFlags::Unhighlighted,
288 ✔
1585
            nodeIsUnhighlighted(nodeId, nodeIsSelected));
288 ✔
1586

1587
        if(nodeVisual._state != previousState) // clazy:exclude=compare-member-check
288 !
1588
            nodeChange.set(VisualChangeFlags::State);
288 ✔
1589
    }
288 ✔
1590

1591
    for(auto nodeId : changedNodeIds)
94 ✔
1592
    {
288 ✔
1593
        for(auto edgeId : graph().edgeIdsForNodeId(nodeId))
288 ✔
1594
        {
446 ✔
1595
            auto& edgeVisual = _->_edgeVisuals[edgeId];
446 ✔
1596
            const auto previousState = edgeVisual._state;
446 ✔
1597

1598
            // An edge is selected or unhighlighted if either of the nodes it joins is;
1599
            // those are precisely the nodes whose edgeIdsForNodeId contains it
1600
            const auto& edge = graph().edgeById(edgeId);
446 ✔
1601
            const auto sourceState = _->_nodeVisuals[edge.sourceId()]._state;
446 ✔
1602
            const auto targetState = _->_nodeVisuals[edge.targetId()]._state;
446 ✔
1603

1604
            edgeVisual._state.setState(VisualFlags::Selected,
446 ✔
1605
                sourceState.test(VisualFlags::Selected) ||
446 ✔
1606
                targetState.test(VisualFlags::Selected));
446 ✔
1607

1608
            edgeVisual._state.setState(VisualFlags::Unhighlighted,
446 ✔
1609
                sourceState.test(VisualFlags::Unhighlighted) ||
446 ✔
1610
                targetState.test(VisualFlags::Unhighlighted));
446 ✔
1611

1612
            if(edgeVisual._state != previousState) // clazy:exclude=compare-member-check
446 ✔
1613
                edgeChange.set(VisualChangeFlags::State);
266 ✔
1614
        }
446 ✔
1615
    }
288 ✔
1616

1617
    visualsLock.unlock();
94 ✔
1618
    emit visualsChanged(*nodeChange, *edgeChange, VisualChangeFlags::None);
94 ✔
1619
}
94 ✔
1620

1621
void GraphModel::onSelectionChanged(const SelectionManager* selectionManager)
1622
{
112 ✔
1623
    auto selectedNodeIds = selectionManager->selectedNodes();
112 ✔
1624
    auto nodesMaskActive = selectionManager->nodesMaskActive();
112 ✔
1625

1626
    _->requestVisualUpdate([&selectedNodeIds, nodesMaskActive](auto& pending)
112 ✔
1627
    {
112 ✔
1628
        pending._selectedNodeIds = std::move(selectedNodeIds);
112 ✔
1629
        pending._nodesMaskActive = nodesMaskActive;
112 ✔
1630
    });
112 ✔
1631

1632
    scheduleVisualUpdate();
112 ✔
1633
}
112 ✔
1634

1635
void GraphModel::onFoundNodeIdsChanged(const SearchManager* searchManager)
1636
{
24 ✔
1637
    auto foundNodeIds = searchManager->foundNodeIds();
24 ✔
1638

1639
    _->requestVisualUpdate([&foundNodeIds](auto& pending)
24 ✔
1640
    {
24 ✔
1641
        pending._foundNodeIds = std::move(foundNodeIds);
24 ✔
1642
        pending._full = true;
24 ✔
1643
    });
24 ✔
1644

1645
    scheduleVisualUpdate();
24 ✔
1646
}
24 ✔
1647

1648
void GraphModel::onPreferenceChanged(const QString& name, const QVariant&)
1649
{
22 ✔
1650
    if(!name.startsWith(u"visuals"_s))
22 ✔
1651
        return;
18 ✔
1652

1653
    const bool force = name.endsWith(u"backgroundColor"_s) ||
4 !
1654
        name.endsWith(u"showNodeText"_s) ||
4 !
1655
        name.endsWith(u"showEdgeText"_s) ||
4 !
1656
        name.endsWith(u"showEdges"_s) ||
4 !
1657
        name.endsWith(u"edgeVisualType"_s) ||
4 !
1658
        name.endsWith(u"highlightColor"_s) ||
4 !
1659
        name.endsWith(u"textFont"_s) ||
4 !
1660
        name.endsWith(u"textSize"_s) ||
4 !
1661
        name.endsWith(u"textAlignment"_s);
4 !
1662

1663
    _->requestVisualUpdate([force](auto& pending)
4 ✔
1664
    {
4 ✔
1665
        pending._full = true;
4 ✔
1666
        pending._force = pending._force || force;
4 !
1667
    });
4 ✔
1668

1669
    scheduleVisualUpdate();
4 ✔
1670
}
4 ✔
1671

1672
void GraphModel::onLayoutChanged()
1673
{
2,846 ✔
1674
    // This occurs on the layout thread
1675
    const std::unique_lock<std::mutex> lock(_->_textVisualsMutex);
2,846 ✔
1676
    updateTextVisualPositions(_->_textVisuals, _->_nodePositions);
2,846 ✔
1677
}
2,846 ✔
1678

1679
void GraphModel::onMutableGraphChanged(const Graph* graph)
1680
{
1,744 ✔
1681
    calculateAttributeRanges(graph, _->_attributes);
1,744 ✔
1682
}
1,744 ✔
1683

1684
void GraphModel::onTransformedGraphWillChange(const Graph*)
1685
{
1,752 ✔
1686
    // The graph may gain elements that have never been through a full visual
1687
    // update, so whatever next asks for an update must get a full one
1688
    _->requestFullVisualUpdate();
1,752 ✔
1689

1690
    // Rebuilding applies the transforms to the attribute values as they now are
1691
    _->_transformRebuildRequired = false;
1,752 ✔
1692

1693
    // Store previous attributes for comparison
1694
    _->_previousAttributeIdentities = _->currentAttributeIdentities();
1,752 ✔
1695

1696
    removeDynamicAttributes();
1,752 ✔
1697

1698
    _graphTransformsAreChanging = true;
1,752 ✔
1699
}
1,752 ✔
1700

1701
void GraphModel::onTransformedGraphChanged(const Graph*, bool changeOccurred)
1702
{
1,752 ✔
1703
    _->_removedDynamicAttributeNames.clear();
1,752 ✔
1704

1705
    auto attributeIdentities = _->currentAttributeIdentities();
1,752 ✔
1706

1707
    // Compare with previous attributes
1708
    auto removedAttributeIdentities = u::setDifference(_->_previousAttributeIdentities, attributeIdentities);
1,752 ✔
1709
    auto addedAttributeIdentities = u::setDifference(attributeIdentities, _->_previousAttributeIdentities);
1,752 ✔
1710

1711
    QStringList removedAttributeNames;
1,752 ✔
1712
    QStringList addedAttributeNames;
1,752 ✔
1713

1714
    auto identityToName = [](const auto& identity) { return identity._name; };
1,752 ✔
1715

1716
    std::ranges::transform(removedAttributeIdentities,
1,752 ✔
1717
        std::back_inserter(removedAttributeNames), identityToName);
1,752 ✔
1718
    std::ranges::transform(addedAttributeIdentities,
1,752 ✔
1719
        std::back_inserter(addedAttributeNames), identityToName);
1,752 ✔
1720

1721
    QStringList changedAttributeNames(std::move(_->_changedDynamicAttributeNames));
1,752 ✔
1722

1723
    changedAttributeNames.erase(std::ranges::remove_if(changedAttributeNames,
1,752 ✔
1724
    [&removedAttributeNames, &addedAttributeNames](const auto& dynamicAttributeName)
1,752 ✔
1725
    {
1,752 ✔
1726
        return u::contains(removedAttributeNames, dynamicAttributeName) ||
10 !
1727
            u::contains(addedAttributeNames, dynamicAttributeName);
10 !
1728
    }).begin(), changedAttributeNames.end());
10 ✔
1729

1730
    // When the graph changes, every attribute's range and shared values also potentially change
1731
    for(auto& [name, attribute] : _->_attributes)
1,752 ✔
1732
    {
22,822 ✔
1733
        // These ones will be taken care of in onAttributesChanged, below...
1734
        if(u::contains(addedAttributeNames, name) || u::contains(changedAttributeNames, name))
22,822 ✔
1735
            continue;
468 ✔
1736

1737
        calculateAttributeRange(attribute);
22,354 ✔
1738
        _->updateSharedAttributeValues(attribute);
22,354 ✔
1739
    }
22,354 ✔
1740

1741
    emit attributesChanged(addedAttributeNames, removedAttributeNames,
1,752 ✔
1742
        changedAttributeNames, changeOccurred);
1,752 ✔
1743

1744
    _graphTransformsAreChanging = false;
1,752 ✔
1745
}
1,752 ✔
1746

1747
// This will also be called when the transformed graph changes, even if there are no actual attribute changes
1748
void GraphModel::onAttributesChanged(const QStringList& addedNames, const QStringList& removedNames,
1749
    const QStringList& changedValuesNames, bool graphChangeOccurred)
1750
{
1,890 ✔
1751
    for(const auto& attributeName : u::combine(addedNames, changedValuesNames))
1,890 ✔
1752
    {
588 ✔
1753
        auto& attribute = _->_attributes.at(Attribute::parseAttributeName(attributeName)._name);
588 ✔
1754

1755
        if(attribute.testFlag(AttributeFlag::Dynamic) && attribute.userDefined())
588 !
UNCOV
1756
        {
×
UNCOV
1757
            qDebug() << "WARNING: Dynamic attribute" << attributeName <<
×
UNCOV
1758
                "has userDefined set, this is not allowed, resetting...";
×
UNCOV
1759
            attribute.setUserDefined(false);
×
UNCOV
1760
        }
×
1761

1762
        calculateAttributeRange(attribute);
588 ✔
1763
        _->updateSharedAttributeValues(attribute);
588 ✔
1764
    }
588 ✔
1765

1766
    // Attribute changes may require a graph transform or visualisation to be rebuilt
1767
    QStringList changed;
1,890 ✔
1768
    changed << addedNames << removedNames << changedValuesNames;
1,890 ✔
1769
    u::removeDuplicates(changed);
1,890 ✔
1770

1771
    const bool transformRebuildRequired = !_graphTransformsAreChanging &&
1,890 ✔
1772
        _->_transformedGraph.onAttributeValuesChangedExternally(changed);
1,890 ✔
1773

1774
    const bool visualisationRebuildRequired = graphChangeOccurred || !u::setIntersection(
1,890 !
1775
        static_cast<const QList<QString>&>(_->_visualisedAttributeNames),
246 ✔
1776
        static_cast<const QList<QString>&>(changed)).empty();
246 ✔
1777

1778
    if(transformRebuildRequired)
1,890 ✔
1779
        _->_transformRebuildRequired = true;
6 ✔
1780

1781
    if(visualisationRebuildRequired)
1,890 ✔
1782
        _->_visualisationRebuildRequired = true;
1,644 ✔
1783

1784
    // The rebuilds happen alongside the next visual update
1785
    if(transformRebuildRequired || visualisationRebuildRequired)
1,890 ✔
1786
        scheduleVisualUpdate();
1,650 ✔
1787
}
1,890 ✔
1788

1789
AttributeChangesTracker::AttributeChangesTracker(GraphModel* graphModel,
1790
    NamedBool<"emitOnDestruct"> emitOnDestruct) :
1791
    _graphModel(graphModel), _emitOnDestruct(emitOnDestruct)
1,422 ✔
1792
{
1,422 ✔
1793
    _graphModel->_->_attributeChangesTrackers.insert(this);
1,422 ✔
1794
}
1,422 ✔
1795

1796
AttributeChangesTracker::~AttributeChangesTracker()
1797
{
1,422 ✔
1798
    if(_emitOnDestruct)
1,422 ✔
1799
        emitAttributesChanged();
172 ✔
1800

1801
    _graphModel->_->_attributeChangesTrackers.erase(this);
1,422 ✔
1802
}
1,422 ✔
1803

1804
void AttributeChangesTracker::assignName(const QString& requestedName, const QString& assignedName)
1805
{
508 ✔
1806
    _assignedNames[requestedName] = assignedName;
508 ✔
1807
}
508 ✔
1808

1809
void AttributeChangesTracker::add(const QString& name)
1810
{
504 ✔
1811
    if(u::contains(_changed, name))
504 !
UNCOV
1812
    {
×
UNCOV
1813
        qDebug() << "AttributeChangesTracker::add called on attribute marked as changed" << name;
×
UNCOV
1814
        _changed.remove(name);
×
UNCOV
1815
    }
×
1816

1817
    if(u::contains(_removed, name))
504 ✔
1818
    {
6 ✔
1819
        // If it's been removed and added, count that as changed (potentially)
1820
        _removed.remove(name);
6 ✔
1821
        _changed.insert(name);
6 ✔
1822
    }
6 ✔
1823
    else
498 ✔
1824
       _added.insert(name);
498 ✔
1825
}
504 ✔
1826

1827
void AttributeChangesTracker::remove(const QString& name)
1828
{
44 ✔
1829
    if(u::contains(_added, name))
44 !
1830
    {
×
1831
        // If it's been added and removed, count that as net zero
UNCOV
1832
        _added.remove(name);
×
UNCOV
1833
    }
×
1834
    else
44 ✔
1835
        _removed.insert(name);
44 ✔
1836
}
44 ✔
1837

1838
void AttributeChangesTracker::change(const QString& name)
1839
{
190 ✔
1840
    // Only count an attribute as changed if it's not new
1841
    if(!u::contains(_added, name))
190 !
1842
        _changed.insert(name);
190 ✔
1843
}
190 ✔
1844

1845
QStringList AttributeChangesTracker::addedOrChanged() const
1846
{
1,246 ✔
1847
    auto combined = u::combine(_added, _changed);
1,246 ✔
1848
    return {combined.begin(), combined.end()};
1,246 ✔
1849
}
1,246 ✔
1850

1851
void AttributeChangesTracker::emitAttributesChanged()
1852
{
172 ✔
1853
    if(_added.empty() && _removed.empty() && _changed.empty())
172 ✔
1854
        return;
34 ✔
1855

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