Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
3524 lines (3319 loc) · 163 KB
/
Copy pathmain.cpp
File metadata and controls
3524 lines (3319 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TreeFern — a cladogram editor that live-edits a JSON file (Qt 6).
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License, version 3, as published by the
// Free Software Foundation. It is distributed WITHOUT ANY WARRANTY; see the
// LICENSE file for details.
//
// Architecture
// * Model owns the Node tree and its file: every commit() is written
// atomically, and the file is watched so external edits are reloaded.
// * Layout gives every node a frame *relative to its parent* (origin offset +
// complex scale/rotation). Children are ordered lightest -> heaviest, so the
// heaviest clade is always the last (rightmost / clockwise) branch.
// * Canvas anchors the camera to one node's on-screen frame and re-anchors to
// a child or the parent while zooming; all other frames are derived from it,
// so coordinates stay in pixel range and zoom depth is effectively unlimited.
//
// File format: {"root": id, "nodes": [{id, parent?, name, info, collapsed, color?, images?}, …]}
// color is an optional "#rrggbb" that the clade's subtree inherits; images are
// optional pictures for the notes, as PNG or JPEG data URLs.
#include <QSvgGenerator>
#include <QtWidgets>
#include <algorithm>
#include <cmath>
#include <complex>
#include <functional>
#include <memory>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
#ifdef Q_OS_UNIX
#include <sys/resource.h>
#include <unistd.h>
#endif
// ------------------------------------------------------------- config ---
constexpr double PI = 3.14159265358979323846, DEG = PI / 180;
constexpr double DEFAULT_SPREAD = 120 * DEG, DEFAULT_SHRINK = 0.68;
constexpr double ZOOM_STEP = 1.15, FAST_ZOOM_STEP = 2.0;
constexpr int ANIM_MS = 380; // relayout animation; camera flights take twice as long
constexpr int MAX_LABELS = 400, MAX_RECENT = 10, MAX_SEARCH = 200;
constexpr int CONFIRM_DELETE_OVER = 30; // ask before deleting more clades than this
// pictures in the notes
constexpr int IMAGE_MAX_SIDE = 1200; // px; larger pictures are scaled down
constexpr int IMAGE_QUALITY = 85; // JPEG quality
constexpr double PIC_AREA = 1.5; // the picture viewer's area, as a multiple of the edit box's
constexpr qsizetype MAX_UNDO_PICTURE_BYTES = qsizetype(256) << 20; // picture data the undo history may hold
// export
constexpr int MAX_EXPORT_SIDE = 16384; // px
constexpr double MAX_EXPORT_PIXELS = 40e6; // about 160 MB of image memory
constexpr int MAX_SVG_CLADES = 20000; // larger SVGs bring most viewers to a halt
constexpr int SLOW_EXPORT_CLADES = 50000;
// labels
constexpr double LABEL_GAP = 2; // min spacing between label boxes
constexpr int MAX_WRAP_LINES = 6; // most lines a label may wrap onto
// disks style (nested discs)
constexpr double POLY_MARGIN = 0.96; // usable fraction of a parent's radius
constexpr double POLY_GAP = 0.94; // fraction of its wedge a child fills (both styles)
constexpr double POLY_ONLY_CHILD = 0.78; // radius of a single child
constexpr double POLY_EXP = 0.68; // wedge share = weight^POLY_EXP (both styles)
// standard style
constexpr double STD_WIDTH = 0.09; // branch width, in units of the frame it leaves
// Labels inside nodes: every node is a disc of this radius, in its own units
// (1 = its outgoing branch), with its name fitted inside. Tune here; above
// about 0.5 a node meets its daughters.
constexpr double INSIDE_NODE = 0.3;
constexpr double INSIDE_MIN_FONT = 8, INSIDE_MAX_FONT = 400; // px
constexpr double INSIDE_FILL = 0.88; // fraction of a node's radius its label may reach
constexpr double STD_FAN_STEP = 15 * DEG; // extra fan angle per child beyond two
constexpr double STD_MAX_FAN = 300 * DEG; // fan cap (unless the spread itself is wider)
constexpr double STD_CURVE = 0.1; // how far a branch keeps its parent's heading
constexpr double STD_WEIGHT_EXP = 0.35; // light sisters are scaled by (w / w_max)^this
constexpr double DEFAULT_CURL = 0.35; // -1..1, fraction of the safe fan rotation
constexpr double STD_BACK_GAP = 25 * DEG; // keep wedges this far from the incoming stem
constexpr double STD_CLEARANCE = 0.2; // 3+ forks: min distance between sibling subtrees, in fork units
// rectangular and circular cladograms
constexpr double CLADO_NODE = 0.3; // node footprint, in tip spacings
constexpr double CLADO_MIN_STEP = 1.5; // min distance between levels, in tip spacings
constexpr double RECT_ASPECT = 0.6; // rectangular: aim for width = this * height
constexpr double CLADO_LINE = 1.6; // branch width, px
constexpr double CLADO_TIP_R = 2.5, CLADO_NODE_R = 2;
constexpr double CLADO_TIP_FONT = 0.78; // tip label height, as a fraction of the tip spacing on screen
constexpr int CLADO_MIN_FONT = 7, CLADO_MAX_FONT = 15;
constexpr double CLADO_FOCUS_MIN = 24; // focusing a clade: at least this many px between tips
constexpr double CLADO_MARGIN = 300; // px: keep subtrees this far off screen for their labels
constexpr double CHAR_EM = 0.55; // average character width, for sizing label room before measuring
constexpr size_t MAX_CLADE_TRIES = 3000; // clades tried for a label per frame, biggest first
constexpr double CLADO_MIN_BRANCH = 12; // px: shorter branches get no clade label
// camera
constexpr double MIN_PX = 0.6; // disks: cull subtrees smaller than this on screen
constexpr double FIT_MARGIN = 120; // px left free around a fitted tree
constexpr double CAM_MAX_SCALE = 1e9; // max anchor scale in px (zooming into a gap)
constexpr double CAM_MIN_ROOT_PX = 20; // min on-screen size of the whole tree
constexpr double CAM_MAX_UP = 1e9; // stop walking up past this scale (precision)
using C = std::complex<double>;
static QPointF qpt(C c) { return {c.real(), c.imag()}; }
static C cpx(QPointF p) { return {p.x(), p.y()}; }
static QString newId() { return QUuid::createUuid().toString(QUuid::Id128).left(10); }
static QString now() { return QTime::currentTime().toString("HH:mm:ss"); }
// -------------------------------------------------------------- theme ---
struct Theme {
bool dark;
QColor bg, fg, dim, accent, cut, labelBg, labelBgHover, link;
double sat, val; // saturation / value of the depth colours
};
static Theme makeTheme(bool dark) {
if (dark)
return {true, {14, 17, 26}, {225, 230, 240}, {130, 140, 160}, {255, 200, 80}, {255, 90, 90},
{20, 24, 36, 190}, {28, 34, 50, 240}, {170, 200, 255}, 0.55, 0.95};
return {false, {246, 247, 250}, {28, 32, 42}, {105, 113, 130}, {200, 120, 0}, {215, 45, 45},
{255, 255, 255, 205}, {255, 255, 255, 245}, {40, 90, 190}, 0.70, 0.72};
}
static Theme T = makeTheme(true);
static QString colorCss(const QColor& c) { return "color:" + c.name(); }
// Plain text as HTML, its web addresses made links: anything after http:// or
// https://, anything starting www., and bare names like abc.xyz when they end
// in a common web suffix (so "e.g." or "life.json" stay text; email addresses
// too). Trailing punctuation stays outside a link, so a sentence can end with
// one; a closing bracket stays in when the link opened it, as in Wikipedia's.
static QString linkified(const QString& text, const QColor& link) {
static const QRegularExpression url("(?:https?://|www\\.)[^\\s<>\"]+"
"|(?<![@\\w.-])(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:com|org|net|edu|gov|mil|int|info|biz|io|co|ai|app|dev|xyz|me|tv|ly|site|online|tech|wiki|blog|news|museum|science|bio|eco|earth|club|page|uk|us|ca|au|nz|ie|de|fr|es|it|nl|be|at|ch|se|no|fi|dk|is|pl|cz|pt|gr|ru|ua|eu|jp|cn|kr|in|br|mx|ar|za)(?![\\w-])(?:[/?#][^\\s<>\"]*)?",
QRegularExpression::CaseInsensitiveOption);
QString out;
qsizetype at = 0;
for (auto it = url.globalMatch(text); it.hasNext();) {
const auto m = it.next();
QString u = m.captured();
for (;;) {
const QChar last = u.back();
const int k = QString(")]}").indexOf(last);
if (k >= 0 ? u.count(QString("([{")[k]) < u.count(last) : QString(".,;:!?'\"").contains(last)) u.chop(1);
else break;
}
const bool scheme = u.startsWith("http://", Qt::CaseInsensitive) || u.startsWith("https://", Qt::CaseInsensitive);
const QString href = scheme ? u : "https://" + u;
out += text.mid(at, m.capturedStart() - at).toHtmlEscaped();
out += QString("<a href=\"%1\" style=\"color:%2\">%3</a>").arg(href.toHtmlEscaped(), link.name(), u.toHtmlEscaped());
at = m.capturedStart() + u.size();
}
out += text.mid(at).toHtmlEscaped();
return "<div style=\"white-space:pre-wrap\">" + out + "</div>";
}
static QColor depthColor(int d, double bright = 1.0) {
return QColor::fromHsvF(((200 + d * 37) % 360) / 360.0, T.sat, std::min(1.0, T.val * bright));
}
static void applyPalette(const Theme& t) {
const auto pick = [&](QColor d, QColor l) { return t.dark ? d : l; };
const QColor window = pick({26, 31, 46}, {234, 236, 242});
QPalette pal = qApp->style()->standardPalette();
for (auto [role, c] : std::initializer_list<std::pair<QPalette::ColorRole, QColor>>{
{QPalette::Window, window}, {QPalette::ToolTipBase, window},
{QPalette::WindowText, t.fg}, {QPalette::Text, t.fg}, {QPalette::ButtonText, t.fg},
{QPalette::ToolTipText, t.fg}, {QPalette::PlaceholderText, t.dim},
{QPalette::Base, pick({16, 19, 30}, {255, 255, 255})},
{QPalette::AlternateBase, pick({22, 26, 40}, {244, 245, 248})},
{QPalette::Button, pick({45, 54, 78}, {218, 222, 231})},
{QPalette::Highlight, pick({58, 92, 160}, {80, 120, 200})},
{QPalette::HighlightedText, Qt::white}})
pal.setColor(role, c);
for (auto role : {QPalette::WindowText, QPalette::Text, QPalette::ButtonText})
pal.setColor(QPalette::Disabled, role, t.dim);
qApp->setPalette(pal);
}
// --------------------------------------------------------- data model ---
struct Node {
QString id, name, info;
bool collapsed = false;
QString color; // "#rrggbb" or empty: inherit
QStringList images; // pictures for the notes, as data URLs
std::vector<std::unique_ptr<Node>> kids;
Node* parent = nullptr;
static std::unique_ptr<Node> make(const QString& name, const QString& info = {}) {
return std::unique_ptr<Node>(new Node{newId(), name, info});
}
Node* addChild(std::unique_ptr<Node> c) {
c->parent = this;
return kids.emplace_back(std::move(c)).get();
}
int countDesc() const {
int n = 0;
for (auto& k : kids) n += 1 + k->countDesc();
return n;
}
int depth() const {
int d = 0;
for (auto p = parent; p; p = p->parent) ++d;
return d;
}
bool contains(const Node* n) const { // n is this node or one of its descendants
for (; n; n = n->parent)
if (n == this) return true;
return false;
}
template <class F> void walk(F&& f) { // pre-order over this subtree
f(this);
for (auto& k : kids) k->walk(f);
}
};
struct Seed { QString name, info; std::vector<Seed> kids; };
static std::unique_ptr<Node> grow(const Seed& s) {
auto n = Node::make(s.name, s.info);
for (const Seed& k : s.kids) n->addChild(grow(k));
return n;
}
static std::unique_ptr<Node> sampleTree() {
return grow({"Reptiles",
"Reptiles are an important clade of land animal, sister to modern mammals. Prior to the "
"K-Pg Boundary Event 65 million years ago, the clade had significantly more diversity.", {
{"Archelosauria",
"This is the least diverse of the two basal clades of reptile, and was discovered through "
"molecular evidence from genome sequencing, challenging the traditional belief that turtles "
"were more closely-related to snakes than to birds. Subsequent anatomical studies have "
"identified the presence of a sagittal crest on the supraoccipital bone and a lack of the "
"entepicondylar foramen on the humerus as diagnostic of this clade.", {
{"Turtles",
"Turtles are a clade of reptile distinguished by a bony composite shell over their bodies. "
"As with all reptiles, turtles descend from swimming, underwater vertebrates - but in the "
"case of modern surviving turtles, their ancestors actually went back into the water, and "
"the modern land-dwelling turtles emerged again. "},
{"Archosauria",
"The clade which contains modern birds and crocodilians - along with all extinct dinosaurs "
"and pterosaurs. Diagnostic of this clade are the fenestrae behind the eyes, as well as the "
"unique four-chambered heart design.", {
{"Crocodilians",
"A clade of large, predatory, semi-aquatic reptiles. These large species are covered in "
"bony armor-plates and have long, flat tails and webbed feet.", {
{"Alligatoridae",
"A clade distinct for its broad snout, hidden lower teeth, and freshwater environment.", {
{"Alligators", "Distinct for their bony septum and cold-temperature tolerance."},
{"Caimans", "A clade unique for the bony ridge between the eyes and needle-like nose."}}},
{"Crocodiles",
"The clade of crocodilian most amenable to salt water thanks to specialized exchange "
"glands as well as an interlocking and exposed fourth-tooth."}}},
{"Dinosaurs",
"The clade containing the modern birds, and also containing the most famous extinct "
"animals in the world thanks to books, television, and movies. Unique features of this "
"clade include an open hip socket and fused vertebrae in the lower back to accommodate an "
"upright posture.", {
{"Birds",
"The only living clade of flying reptiles, birds possess a characteristic wing with an "
"elongated upper arm - even in flightless species. They also lack the tails of other "
"theropods."}}}}}}},
{"Lepidosaurs", "The most diverse clade of reptiles, containing the tuatara, and all lizards.", {
{"Lizards (Squamata)",
"The most diverse clade of lepidosaur, featuring a common \"lizard-like\" body plan and its "
"derivatives. Unique for their paired hemipenes in male reproduction, as well as skull "
"kinesis and skin shedding.", {
{"Snakes",
"Snakes are a legless clade of lizard. They possess a highly mobile, kinetic skull; they "
"lack movable eyelids; and, they accommodate their paired organs sequentially in their "
"long, slender bodies."}}},
{"Tuatara",
"The sole surviving species of the ancient clade Rhynchocephalia, unique for their "
"possession of the ancestral form of the diapsid skull, keeping intact both the upper and "
"lower temporal bars."}}}}});
}
// Owns the tree and its backing file. Mutations go through commit(), which
// reindexes, saves, and emits treeChanged(). Functions returning QString
// return an error message, or an empty string on success.
class Model : public QObject {
Q_OBJECT
public:
QString path, status;
Model() {
auto onChange = [this] { QTimer::singleShot(150, this, &Model::checkExternal); };
connect(&watcher_, &QFileSystemWatcher::fileChanged, this, onChange);
connect(&watcher_, &QFileSystemWatcher::directoryChanged, this, onChange);
}
bool isOpen() const { return root_ != nullptr; }
Node* root() const { return root_.get(); }
Node* find(const QString& id) const { return id.isEmpty() ? nullptr : index_.value(id); }
QString open(const QString& p) { // on failure the current tree stays open
QString err;
auto tree = parseFile(p, err);
if (!tree) return err;
setTree(p, std::move(tree));
status = "Opened " + path;
emit treeChanged();
return {};
}
QString create(const QString& p, std::unique_ptr<Node> tree) { // overwrites p
setTree(p, std::move(tree));
return saveAndNotify();
}
QString saveAs(const QString& p) { // editing continues in the new file
if (!root_) return "Nothing to save";
setPath(p);
return saveAndNotify();
}
QString removeSubtree(Node* n) {
if (!n->parent) return "Cannot delete the root clade";
detach(n);
commit();
return {};
}
QString moveSubtree(Node* n, Node* target) { // graft n (with descendants) under target
if (!n->parent) return "Cannot move the root clade";
if (n->contains(target)) return "Cannot paste a clade into itself or its descendants";
target->addChild(detach(n));
target->collapsed = false;
commit();
return {};
}
void commit() {
undo_.push_back(std::exchange(current_, snapshot()));
redo_.clear();
// Every snapshot copies the pictures, so the history also has a size budget.
auto bytes = [this] { qsizetype b = 0; for (const Snapshot& s : undo_) b += s.bytes; return b; };
while (undo_.size() > 200 || (undo_.size() > 1 && bytes() > MAX_UNDO_PICTURE_BYTES)) undo_.erase(undo_.begin());
reindex();
save();
emit treeChanged();
}
QString undo() { return step(undo_, redo_, "Undone"); }
QString redo() { return step(redo_, undo_, "Redone"); }
signals:
void treeChanged();
void statusChanged();
private:
std::unique_ptr<Node> root_;
QHash<QString, Node*> index_;
QDateTime lastMtime_;
QFileSystemWatcher watcher_;
// Undo history: whole-tree snapshots. current_ is the tree as of the last commit.
struct Snapshot { QJsonObject json; qsizetype bytes = 0; }; // bytes: the picture data it holds
Snapshot current_;
std::vector<Snapshot> undo_, redo_;
Snapshot snapshot() const { return {toJson(root_.get()), pictureBytes(root_.get())}; }
static qsizetype pictureBytes(const Node* n) {
qsizetype b = 0;
for (const QString& s : n->images) b += s.size();
for (auto& k : n->kids) b += pictureBytes(k.get());
return b;
}
void resetHistory() {
current_ = snapshot();
undo_.clear();
redo_.clear();
}
QString step(std::vector<Snapshot>& from, std::vector<Snapshot>& to, const char* done) {
if (from.empty()) return QString("Nothing to %1").arg(&from == &undo_ ? "undo" : "redo");
QString err;
auto tree = fromJson(from.back().json, err);
if (!tree) return err;
to.push_back(std::exchange(current_, from.back()));
from.pop_back();
root_ = std::move(tree);
reindex();
save();
status = QString("%1 (%2)").arg(done, status);
emit treeChanged();
return {};
}
// Watch the file and its directory (the latter catches delete + recreate).
void setPath(const QString& p) {
path = QFileInfo(p).absoluteFilePath();
for (const QStringList& old : {watcher_.files(), watcher_.directories()})
if (!old.isEmpty()) watcher_.removePaths(old);
if (QFile::exists(path)) watcher_.addPath(path);
watcher_.addPath(QFileInfo(path).absolutePath());
}
void setTree(const QString& p, std::unique_ptr<Node> tree) {
setPath(p);
root_ = std::move(tree);
reindex();
resetHistory();
lastMtime_ = QFileInfo(path).lastModified();
}
void reindex() {
index_.clear();
if (root_) root_->walk([this](Node* n) { index_[n->id] = n; });
}
static QStringList readImages(const QJsonValue& v) {
static const QRegularExpression re("^data:image/(png|jpeg);base64,[A-Za-z0-9+/]+=*$");
QStringList out;
for (const auto& x : v.toArray())
if (const QString s = x.toString(); re.match(s).hasMatch()) out << s;
return out;
}
static QString readColor(const QString& c) {
static const QRegularExpression re("^#[0-9a-fA-F]{6}$");
return re.match(c).hasMatch() ? c.toLower() : QString();
}
static std::unique_ptr<Node> detach(Node* n) {
auto& v = n->parent->kids;
auto it = std::find_if(v.begin(), v.end(), [n](auto& p) { return p.get() == n; });
std::unique_ptr<Node> up = std::move(*it);
v.erase(it);
up->parent = nullptr;
return up;
}
// Flat format: {"root": id, "nodes": [{id, parent?, name, info, collapsed}, …]}.
// Children keep file order. Repairs: duplicate/missing ids get fresh ones;
// nodes whose parent is missing, or that sit on a parent cycle, are dropped.
static std::unique_ptr<Node> fromJson(const QJsonObject& top, QString& err) {
struct Rec { std::unique_ptr<Node> n; QString parent; };
std::vector<Rec> recs;
QHash<QString, size_t> byId;
for (const auto& v : top.value("nodes").toArray()) {
if (!v.isObject()) continue;
const QJsonObject o = v.toObject();
QString id = o.value("id").toString();
if (id.isEmpty() || byId.contains(id)) id = newId();
byId[id] = recs.size();
recs.push_back({std::unique_ptr<Node>(new Node{id, o.value("name").toString("Unnamed"),
o.value("info").toString(),
o.value("collapsed").toBool(false),
readColor(o.value("color").toString()),
readImages(o.value("images"))}),
o.value("parent").toString()});
}
const QString rootId = top.value("root").toString();
if (!byId.contains(rootId)) {
err = "JSON error: missing or unknown \"root\"";
return nullptr;
}
const size_t rootIdx = byId[rootId];
// Keep only nodes whose parent chain reaches the root (iterative: no cycles, no recursion).
std::vector<char> state(recs.size(), 0); // 0 unknown, 1 visiting, 2 ok, 3 bad
state[rootIdx] = 2;
for (size_t i = 0; i < recs.size(); ++i) {
std::vector<size_t> chain;
size_t j = i;
while (state[j] == 0) {
state[j] = 1;
chain.push_back(j);
const auto it = byId.constFind(recs[j].parent);
if (it == byId.cend()) { state[j] = 3; break; }
j = *it;
}
const char verdict = state[j] == 2 ? 2 : 3; // reached root, or hit missing/cycle/bad
for (size_t c : chain) state[c] = verdict;
}
// Link in file order. Raw pointers are taken first because addChild moves ownership.
std::vector<Node*> raw(recs.size());
for (size_t i = 0; i < recs.size(); ++i) raw[i] = recs[i].n.get();
std::unique_ptr<Node> root = std::move(recs[rootIdx].n);
for (size_t i = 0; i < recs.size(); ++i)
if (i != rootIdx && state[i] == 2) raw[byId[recs[i].parent]]->addChild(std::move(recs[i].n));
return root; // dropped records are freed with `recs`
}
static QJsonObject toJson(const Node* root) {
QJsonArray nodes;
std::vector<const Node*> stack{root};
while (!stack.empty()) { // pre-order; siblings keep their order
const Node* n = stack.back();
stack.pop_back();
QJsonObject o{{"id", n->id}, {"name", n->name}, {"info", n->info}, {"collapsed", n->collapsed}};
if (n->parent) o["parent"] = n->parent->id;
if (!n->color.isEmpty()) o["color"] = n->color;
if (!n->images.isEmpty()) o["images"] = QJsonArray::fromStringList(n->images);
nodes.append(o);
for (auto it = n->kids.rbegin(); it != n->kids.rend(); ++it) stack.push_back(it->get());
}
return {{"root", root->id}, {"nodes", nodes}};
}
static std::unique_ptr<Node> parseFile(const QString& p, QString& err) {
QFile f(p);
if (!f.open(QIODevice::ReadOnly)) {
err = "Cannot open " + p + ": " + f.errorString();
return nullptr;
}
QJsonParseError pe;
const auto doc = QJsonDocument::fromJson(f.readAll(), &pe);
if (pe.error != QJsonParseError::NoError)
err = QString("JSON error in %1 (offset %2): %3").arg(p).arg(pe.offset).arg(pe.errorString());
else if (!doc.isObject())
err = "JSON error in " + p + ": top level must be an object";
else {
auto tree = fromJson(doc.object(), err);
if (!tree) err = err.replace("JSON error", "JSON error in " + p);
return tree;
}
return nullptr;
}
bool save() {
if (!root_ || path.isEmpty()) return false;
const QJsonObject json = toJson(root_.get());
QSaveFile f(path); // atomic write-and-rename
if (!f.open(QIODevice::WriteOnly) || f.write(QJsonDocument(json).toJson()) < 0 || !f.commit()) {
status = "Cannot write " + path;
return false;
}
lastMtime_ = QFileInfo(path).lastModified();
if (!watcher_.files().contains(path)) watcher_.addPath(path); // the rename drops the watch
status = "Saved " + now();
return true;
}
QString saveAndNotify() {
if (!save()) return "Cannot write " + path;
emit treeChanged();
return {};
}
// Reload if the file's mtime differs from our last write; keep the old tree on parse errors.
void checkExternal() {
if (path.isEmpty()) return;
if (QFile::exists(path) && !watcher_.files().contains(path)) watcher_.addPath(path);
const QDateTime m = QFileInfo(path).lastModified();
if (!m.isValid() || m == lastMtime_) return;
lastMtime_ = m;
QString err;
if (auto tree = parseFile(path, err)) {
root_ = std::move(tree);
reindex();
resetHistory();
status = "Reloaded external change " + now();
emit treeChanged();
} else {
status = err + " (kept old tree)";
emit statusChanged();
}
}
};
// ------------------------------------------------------------- frames ---
// A node's frame relative to its parent's: origin o and complex scale+rotation
// z (both in parent units). dir = the direction the node grows in, in its own
// frame.
struct Local { C o{0, 0}; C z{1, 0}; double dir = -PI / 2; };
// A frame on screen: local point q maps to pixel o + z*q.
struct Frame { C o{0, 0}; C z{1, 0}; };
static Frame compose(const Frame& f, const Local& l) { return {f.o + f.z * l.o, f.z * l.z}; }
static Frame uncompose(const Frame& f, const Local& l) {
const C pz = f.z / l.z;
return {f.o - pz * l.o, pz};
}
static bool finiteFrame(const Frame& f) {
for (double v : {f.o.real(), f.o.imag(), f.z.real(), f.z.imag()})
if (!std::isfinite(v)) return false;
return std::abs(f.z) > 0;
}
static double lerpAngle(double a, double b, double t) { return a + std::remainder(b - a, 2 * PI) * t; }
// Rotate along the shorter arc; magnitude linearly, or geometrically for camera zoom.
static C lerpZ(C a, C b, double t, bool geometric = false) {
const double ma = std::abs(a), mb = std::abs(b);
return std::polar(geometric ? ma * std::pow(mb / ma, t) : ma + (mb - ma) * t,
lerpAngle(std::arg(a), std::arg(b), t));
}
static Local lerp(const Local& a, const Local& b, double t) {
return {a.o + (b.o - a.o) * t, lerpZ(a.z, b.z, t), lerpAngle(a.dir, b.dir, t)};
}
// ------------------------------------------------------------- layout ---
struct Layout {
enum Style { Standard, Disks, Rectangular, Circular };
Style style = Standard;
double spread = DEFAULT_SPREAD; // standard: fan angle of a fork
double shrink = DEFAULT_SHRINK; // standard: branch length ratio
double curl = DEFAULT_CURL; // standard: how far lopsided forks turn toward the heavy side
QHash<const Node*, Local> loc; // parent-relative frames (root: relative to the view)
QHash<const Node*, double> ext; // subtree radius around the node's origin, own units
QRectF bbox; // whole tree, in view units
// cladograms: tips sit at x = tipX (rectangular) or radius tipR around the
// root (circular), tipSpacing apart; maxTipChars sizes the room for their labels
double tipX = 0, tipR = 0, tipSpacing = 1;
int maxTipChars = 0;
QHash<const Node*, double> reach; // cladograms: length of the across part of the branch into a node, where its label goes
static QString styleName(Style s) {
return s == Standard ? "Standard" : s == Disks ? "Disks" : s == Rectangular ? "Rectangular" : "Circular";
}
static bool isClado(Style s) { return s == Rectangular || s == Circular; }
static bool hidesKids(const Node* n) { return n->collapsed || n->kids.empty(); }
int count() const { return int(loc.size()); }
double extent(const Node* n) const { return ext.value(n, 1.0); }
int weight(const Node* n) const { return size_.value(n, 1); } // clade size, ignoring collapse
double own(const Node* n) const { // radius of the node's own footprint, own units
return style == Disks ? 1.0 : isClado(style) ? CLADO_NODE : INSIDE_NODE;
}
void compute(const Node* root) {
loc.clear();
ext.clear();
reach.clear();
size_.clear();
leaves_.clear();
bbox = {};
if (!root) return;
weigh(root);
if (style == Standard) {
loc[root] = Local{C(0, 0), C(0, -1), 0}; // grows upwards
standard(root);
} else if (isClado(style)) {
cladogram(root);
} else {
loc[root] = Local{};
disks(root);
}
extents(root);
bounds(root);
}
// Display order: lightest first, heaviest last; ties broken by visible leaves.
std::vector<const Node*> ordered(const Node* n) const {
std::vector<const Node*> v;
for (auto& k : n->kids) v.push_back(k.get());
std::stable_sort(v.begin(), v.end(), [this](const Node* a, const Node* b) {
return std::pair(size_.value(a), leaves_.value(a)) < std::pair(size_.value(b), leaves_.value(b));
});
return v;
}
private:
QHash<const Node*, int> size_; // node + all descendants (ignores collapse)
QHash<const Node*, int> leaves_; // visible leaves (respects collapse)
void weigh(const Node* n) {
int s = 1, l = 0;
for (auto& k : n->kids) {
weigh(k.get());
s += size_[k.get()];
l += leaves_[k.get()];
}
size_[n] = s;
leaves_[n] = hidesKids(n) ? 1 : l;
}
double extents(const Node* n) {
double e = own(n);
if (!hidesKids(n))
for (auto& k : n->kids) {
const Local L = loc.value(k.get());
e = std::max(e, std::abs(L.o) + std::abs(L.z) * extents(k.get()));
}
return ext[n] = e;
}
void bounds(const Node* root) {
double x0 = 1e300, y0 = 1e300, x1 = -1e300, y1 = -1e300;
auto add = [&](C c, double r) {
x0 = std::min(x0, c.real() - r); x1 = std::max(x1, c.real() + r);
y0 = std::min(y0, c.imag() - r); y1 = std::max(y1, c.imag() + r);
};
std::function<void(const Node*, const Frame&)> rec = [&](const Node* n, const Frame& f) {
add(f.o, std::abs(f.z) * own(n));
if (!hidesKids(n))
for (auto& k : n->kids) rec(k.get(), compose(f, loc.value(k.get())));
};
const Local L = loc.value(root);
if (style == Standard) add(L.o - L.z, 0); // the trunk below the root
rec(root, Frame{L.o, L.z});
bbox = QRectF(QPointF(x0, y0), QPointF(x1, y1));
}
// Angle of each child's wedge: proportional to weight^POLY_EXP, summing to `total`.
std::vector<double> wedges(const std::vector<const Node*>& kids, double total) const {
std::vector<double> th;
double sum = 0;
for (const Node* k : kids) sum += th.emplace_back(std::pow(weight(k), POLY_EXP));
for (double& t : th) t *= total / sum;
return th;
}
// A subtree as seen by its parent: its bounding circle (centre c on its own
// x axis, radius R) and the pieces covering it (its node disc plus each
// child's bounding circle), all in its own frame.
struct Hull { double c, R; std::vector<std::pair<C, double>> pieces; };
// Angular range, relative to the child's axis and seen from the parent's
// fork, covered by a child placed at distance 1 with scale s, every piece
// grown by `pad` (parent units). Returns a full turn if a piece reaches the
// fork or the range is too wide to pack.
static std::pair<double, double> angularSpan(const std::vector<std::pair<C, double>>& pieces, double s, double pad) {
double lo = 1e300, hi = -1e300;
for (const auto& [p, r] : pieces) {
const C q = 1.0 + s * p;
const double d = std::abs(q), rr = s * r + pad;
if (rr >= d * 0.999) return {-PI, PI};
const double a = std::arg(q), h = std::asin(rr / d);
lo = std::min(lo, a - h);
hi = std::max(hi, a + h);
}
if (hi - lo >= PI) return {-PI, PI};
return {lo, hi};
}
// Disks: children sit on a ring inside the parent disc, clockwise from 12
// o'clock. Each is the largest disc inscribed in its wedge (wedges capped
// at a half-turn), so siblings can never overlap.
void disks(const Node* n) {
if (hidesKids(n)) return;
const auto kids = ordered(n);
if (kids.size() == 1) { // sit low, leaving room for the parent's label
const double r = POLY_MARGIN * POLY_ONLY_CHILD;
loc[kids[0]] = Local{C(0, POLY_MARGIN - r), C(r, 0), PI / 2};
return disks(kids[0]);
}
std::vector<double> th = wedges(kids, 2 * PI);
const size_t big = std::max_element(th.begin(), th.end()) - th.begin();
if (th[big] > PI) { // only one wedge can exceed a half-turn: cap it, rescale the rest
const double rest = 2 * PI - th[big];
for (size_t i = 0; i < th.size(); ++i) th[i] = i == big ? PI : th[i] * PI / rest;
}
const double rho = POLY_MARGIN / (1 + std::sin(th[big] / 2)); // biggest touches the rim
double a = -PI / 2;
for (size_t i = 0; i < kids.size(); ++i) {
const double mid = a + th[i] / 2;
loc[kids[i]] = Local{std::polar(rho, mid), C(rho * std::sin(th[i] / 2) * POLY_GAP, 0), mid};
disks(kids[i]);
a += th[i];
}
}
// Smallest circle centred on the real axis that encloses all the circles
// (the radius is convex in the centre, so ternary search).
static std::pair<double, double> enclose(const std::vector<std::pair<C, double>>& cs) {
double lo = 1e300, hi = -1e300;
for (auto& [p, r] : cs) { lo = std::min(lo, p.real() - r); hi = std::max(hi, p.real() + r); }
auto f = [&](double x) {
double m = 0;
for (auto& [p, r] : cs) m = std::max(m, std::abs(p - C(x, 0)) + r);
return m;
};
for (int it = 0; it < 60; ++it) {
const double a = lo + (hi - lo) / 3, b = hi - (hi - lo) / 3;
if (f(a) < f(b)) hi = b; else lo = a;
}
const double x = (lo + hi) / 2;
return {x, f(x)};
}
// Cladograms as drawn in papers. Tips are evenly spaced, one tip spacing
// apart, in display order (so the tree is ladderised) and aligned: a node
// sits as many levels in from the tips as its tallest subtree is deep, and
// halfway between its first and last daughters. Rectangular: tips in a
// column on the right. Circular: tips on a circle round the root, from 12
// o'clock clockwise. Every frame has unit scale and no rotation, so the
// tree is drawn in one coordinate system and frames are just offsets.
void cladogram(const Node* root) {
QHash<const Node*, double> pos;
QHash<const Node*, int> height;
int tips = 0, chars = 0;
std::function<void(const Node*)> visit = [&](const Node* n) {
if (hidesKids(n)) {
height[n] = 0;
pos[n] = tips++;
chars = std::max(chars, int(n->name.size()) + (n->collapsed ? 8 : 0));
return;
}
const auto kids = ordered(n);
int h = 0;
for (const Node* k : kids) {
visit(k);
h = std::max(h, height[k] + 1);
}
height[n] = h;
pos[n] = (pos[kids.front()] + pos[kids.back()]) / 2;
};
visit(root);
const int H = height[root];
maxTipChars = std::min(chars, 40);
QHash<const Node*, C> at;
if (style == Rectangular) {
const double step = H ? std::max(CLADO_MIN_STEP, RECT_ASPECT * tips / H) : 1;
tipX = H * step;
tipSpacing = 1;
for (auto it = pos.cbegin(); it != pos.cend(); ++it) at[it.key()] = C((H - height[it.key()]) * step, *it);
} else {
tipR = std::max(CLADO_MIN_STEP * H, tips / (2 * PI));
tipSpacing = 2 * PI * tipR / std::max(tips, 1);
const double step = H ? tipR / H : 0;
for (auto it = pos.cbegin(); it != pos.cend(); ++it)
at[it.key()] = std::polar((H - height[it.key()]) * step, -PI / 2 + *it * 2 * PI / std::max(tips, 1));
}
for (auto it = at.cbegin(); it != at.cend(); ++it) {
const Node* n = it.key();
if (!n->parent) {
loc[n] = Local{*it, C(1, 0), 0};
continue;
}
const C q = at.value(n->parent);
loc[n] = Local{*it - q, C(1, 0), 0};
reach[n] = style == Rectangular ? it->real() - q.real() : std::abs(*it) - std::abs(q);
}
}
// Standard: a node's frame has its origin at its fork, +x along its growth
// direction, and unit = its outgoing branch length. All children leave the
// fork together. Two-child forks split the fan by weight and inscribe each
// child's bounding circle in its wedge. Forks of 3+ children are packed by
// the angular range each child covers when grown by half the clearance (see
// angularSpan): neighbours abut, so sibling subtrees stay a clearance apart;
// slack becomes even gaps, and if the fan is too tight
// every child shrinks by a common factor. Returns the bounding circle and pieces.
Hull standard(const Node* n) {
const double ownR = own(n);
if (hidesKids(n)) return {0, ownR, {{C(0, 0), ownR}}};
const auto kids = ordered(n);
const size_t m = kids.size();
// Children's hulls don't depend on where they are placed, so compute them first.
std::vector<Hull> sub(m);
for (size_t i = 0; i < m; ++i) sub[i] = standard(kids[i]);
std::vector<std::pair<C, double>> circles{{C(0, 0), ownR}};
auto placeAt = [&](size_t i, double mid, double s) {
const C u = std::polar(1.0, mid);
loc[kids[i]] = Local{u, u * s, 0};
circles.push_back({u * (1 + s * sub[i].c), s * sub[i].R});
};
auto place = [&](size_t i, double mid, double halfWedge, double want) {
const double c = sub[i].c, R = sub[i].R;
const double sb = std::sin(std::min(halfWedge, PI / 2)) * POLY_GAP;
placeAt(i, mid, R > c * sb ? std::min(want, sb / (R - c * sb)) : want); // inscribed in the wedge
};
// Rigidly rotating the fan keeps the children disjoint and the enclose()
// circle valid; it only has to stay clear of the incoming stem at angle pi.
auto shiftFor = [&](double fan, double imbalance) {
const double room = std::max(0.0, PI - fan / 2 - STD_BACK_GAP);
return std::clamp(curl, -1.0, 1.0) * imbalance * room;
};
if (m == 1) {
place(0, shiftFor(PI, 1.0), PI / 2, std::sqrt(shrink));
} else {
const double fan = std::min(std::max(spread, STD_MAX_FAN), spread + (m - 2) * STD_FAN_STEP);
const double wmax = weight(kids.back());
std::vector<double> want(m);
double rest = 0;
for (size_t i = 0; i < m; ++i) {
want[i] = i == m - 1 ? std::sqrt(shrink) // main stem
: shrink * std::pow(weight(kids[i]) / wmax, STD_WEIGHT_EXP);
if (i + 1 < m) rest += weight(kids[i]);
}
const double imbalance = std::max(0.0, (wmax - rest) / (wmax + rest)); // 0 = balanced fork
double a = -fan / 2 + shiftFor(fan, imbalance);
if (m == 2) { // bifurcation: unchanged
const std::vector<double> th = wedges(kids, fan);
for (size_t i = 0; i < m; ++i) {
place(i, a + th[i] / 2, th[i] / 2, want[i]);
a += th[i];
}
} else {
// Half the clearance around every child; a fork too crowded to give even
// its leaves that much (each takes 2·asin(pad)) gets proportionally less.
const double pad = std::min(STD_CLEARANCE / 2, std::sin(0.9 * fan / (2.0 * double(m))));
std::vector<std::pair<double, double>> sp(m);
auto total = [&](double k) { // fan used when every child is scaled by k
double t = 0;
for (size_t i = 0; i < m; ++i) {
sp[i] = angularSpan(sub[i].pieces, k * want[i], pad);
t += sp[i].second - sp[i].first;
}
return t;
};
double k = 1;
if (total(1) > fan) {
double lo = 1e-3, hi = 1;
for (int it = 0; it < 40; ++it) {
const double mk = (lo + hi) / 2;
(total(mk) <= fan ? lo : hi) = mk;
}
k = lo;
}
const double used = total(k); // also leaves sp[] for this k
const double gap = std::max(0.0, fan - used) / double(m - 1);
for (size_t i = 0; i < m; ++i) {
placeAt(i, a - sp[i].first, k * want[i]); // this child's range starts at a
a += sp[i].second - sp[i].first + gap;
}
}
}
const auto [x, r] = enclose(circles);
return {x, r, std::move(circles)};
}
};
// ---------------------------------------------------- drawing helpers ---
// Liang–Barsky: clip segment a-b to r; false if it lies fully outside.
static bool clipLine(const QRectF& r, QPointF& a, QPointF& b) {
double t0 = 0, t1 = 1, dx = b.x() - a.x(), dy = b.y() - a.y();
const double p[4] = {-dx, dx, -dy, dy};
const double q[4] = {a.x() - r.left(), r.right() - a.x(), a.y() - r.top(), r.bottom() - a.y()};
for (int i = 0; i < 4; ++i) {
if (p[i] == 0) {
if (q[i] < 0) return false;
continue;
}
const double t = q[i] / p[i];
if (p[i] < 0) { if (t > t1) return false; t0 = std::max(t0, t); }
else { if (t < t0) return false; t1 = std::min(t1, t); }
}
const QPointF o = a, d(dx, dy);
a = o + d * t0;
b = o + d * t1;
return true;
}
static double segDist(QPointF p, QPointF a, QPointF b) {
const QPointF d = b - a;
const double l2 = QPointF::dotProduct(d, d);
const double t = l2 > 0 ? std::clamp(QPointF::dotProduct(p - a, d) / l2, 0.0, 1.0) : 0.0;
return QLineF(p, a + d * t).length();
}
// Tapered quadratic branch a -> b (control point c), widths wa -> wb.
// Returns the sampled centre line (for hit tests and label obstacles).
static std::vector<QPointF> drawTaper(QPainter& p, QPointF a, QPointF c, QPointF b, double wa, double wb,
const QColor& col, const QRectF& view) {
constexpr int N = 12;
std::vector<QPointF> mid(N + 1);
QPolygonF left, right;
for (int i = 0; i <= N; ++i) {
const double t = double(i) / N, u = 1 - t;
mid[i] = a * (u * u) + c * (2 * u * t) + b * (t * t);
QPointF tan = (c - a) * (2 * u) + (b - c) * (2 * t);
double len = std::hypot(tan.x(), tan.y());
if (len < 1e-9) { tan = b - a; len = std::max(1e-9, std::hypot(tan.x(), tan.y())); }
const QPointF nrm = QPointF(-tan.y(), tan.x()) / len * ((wa + (wb - wa) * t) / 2);
left << mid[i] + nrm;
right.prepend(mid[i] - nrm);
}
QPolygonF poly = left + right;
const QRectF br = poly.boundingRect();
if (br.width() > 1e5 || br.height() > 1e5) poly = poly.intersected(QPolygonF(view)); // keep Qt's rasteriser sane
p.setPen(Qt::NoPen);
p.setBrush(col);
p.drawPolygon(poly);
return mid;
}
// Ways to lay out a label: for each line count k = 1..MAX_WRAP_LINES, the split
// that minimises the widest line (exact linear-partition DP). An option is kept
// only if it is narrower than every option with fewer lines. Never truncates.
static std::vector<QStringList> wrapOptions(const QStringList& words, const QFontMetricsF& fm) {
const int n = words.size();
std::vector<double> pre(n + 1, 0);
for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] + fm.horizontalAdvance(words[i]);
const double sp = fm.horizontalAdvance(' ');
auto W = [&](int a, int b) { return pre[b] - pre[a] + (b - a - 1) * sp; };
const int K = std::min(n, MAX_WRAP_LINES);
constexpr double INF = 1e300;
// best[k][j]: smallest possible widest line when words [0, j) fill k lines; cut = start of the last line
std::vector<std::vector<double>> best(K + 1, std::vector<double>(n + 1, INF));
std::vector<std::vector<int>> cut(K + 1, std::vector<int>(n + 1, 0));
best[0][0] = 0;
for (int k = 1; k <= K; ++k)
for (int j = k; j <= n; ++j)
for (int i = k - 1; i < j; ++i)
if (const double m = std::max(best[k - 1][i], W(i, j)); m < best[k][j]) {
best[k][j] = m;
cut[k][j] = i;
}
std::vector<QStringList> out;
double prevW = INF;
for (int k = 1; k <= K; ++k) {
if (!(best[k][n] < prevW - 0.5)) continue; // must be visibly narrower
QStringList lines;
for (int kk = k, j = n; kk > 0; j = cut[kk][j], --kk)
lines.prepend(words.mid(cut[kk][j], j - cut[kk][j]).join(' '));
out.push_back(lines);
prevW = best[k][n];
}
return out;
}
// Points along the arc of radius r round c from angle a0 to a1 (the shorter
// way), limited to the angles at which the view can be seen from c, so a huge
// arc on a zoomed-in tree is still drawn smoothly where it shows.
static QPolygonF arcPoints(C c, double r, double a0, double a1, const QRectF& view) {