diff --git a/README.md b/README.md
index 8c0202c..1527fea 100644
--- a/README.md
+++ b/README.md
@@ -43,12 +43,11 @@ You can also [use TreeFern in your browser](https://docrountree.github.io/treefe
- **Editing**: add daughter clades, rename clades and attach free-form notes to them, collapse or expand subtrees, delete subtrees, and move a subtree to a new mother clade with cut and paste.
- **Pictures in the notes**: drag pictures onto a clade, the side panel or the Edit box. They are kept in the cladogram file, scaled to at most 1200 px.
- **Autosave and live sync**: each change is written to disk atomically, and the file is reloaded automatically if another program modifies it.
-- **Dynamic labels**: labels too small to read are hidden until you zoom in, and labels reposition themselves to avoid overlapping. Labels can be placed over or beside nodes.
- **Search and navigation**: find clades by name from the side panel, follow the trail of mother clades above the selection, and move around the tree entirely by keyboard or entirely by mouse.
- **Export**: save the current view or the whole tree as a PNG image (at 1x, 2x or 4x resolution) or a scalable SVG, optionally with a transparent background, or copy it to the clipboard.
- **Command palette**: Ctrl+K finds any command by typing part of its name.
- **Dark and light themes.**
-- **Remembered preferences**: layout, label placement, theme and recently opened files persist between sessions.
+- **Remembered preferences**: layout, theme and recently opened files persist between sessions.
## Download
@@ -179,11 +178,9 @@ Because the format is plain JSON, files can be generated or edited by scripts an
 |
-  |
| Light mode |
- Labels beside nodes |
diff --git a/main.cpp b/main.cpp
index 61ed43f..e030f89 100644
--- a/main.cpp
+++ b/main.cpp
@@ -53,19 +53,21 @@ 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_MIN_SCREEN_LEN = 35; // disks: smaller discs get no label
constexpr double LABEL_GAP = 2; // min spacing between label boxes
-constexpr double WRAP_COST = 0.12; // placement penalty per extra wrapped line
constexpr int MAX_WRAP_LINES = 6; // most lines a label may wrap onto
-constexpr double STEM_COST = 0.8; // soft penalty for covering the node's own branches
// 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_NODE = 0.05; // leaf / collapsed node radius, in its own units
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
@@ -118,6 +120,36 @@ 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<>\"]+"
+ "|(?\"]*)?",
+ 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("%3").arg(href.toHtmlEscaped(), link.name(), u.toHtmlEscaped());
+ at = m.capturedStart() + u.size();
+ }
+ out += text.mid(at).toHtmlEscaped();
+ return "" + out + "
";
+}
+
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));
}
@@ -521,7 +553,7 @@ class Model : public QObject {
// ------------------------------------------------------------- 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 (used to place beside-labels).
+// 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}; };
@@ -574,7 +606,7 @@ struct Layout {
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 : hidesKids(n) ? STD_NODE : STD_WIDTH;
+ return style == Disks ? 1.0 : isClado(style) ? CLADO_NODE : INSIDE_NODE;
}
void compute(const Node* root) {
@@ -792,13 +824,14 @@ struct Layout {
// 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) {
- if (hidesKids(n)) return {0, STD_NODE, {{C(0, 0), STD_NODE}}};
+ 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 sub(m);
for (size_t i = 0; i < m; ++i) sub[i] = standard(kids[i]);
- std::vector> circles{{C(0, 0), STD_WIDTH}};
+ std::vector> 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};
@@ -924,13 +957,6 @@ static std::vector drawTaper(QPainter& p, QPointF a, QPointF c, QPointF
return mid;
}
-// Box of size w*h whose side facing direction (ux, uy) touches (px, py).
-static QRectF anchoredRect(double w, double h, double px, double py, double ux, double uy) {
- const double l = ux > 0.35 ? px : ux < -0.35 ? px - w : px - w / 2;
- const double t = uy > 0.35 ? py : uy < -0.35 ? py - h : py - h / 2;
- return QRectF(std::round(l), std::round(t), w, h);
-}
-
// 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.
@@ -996,11 +1022,9 @@ static QPolygonF arcPoints(C c, double r, double a0, double a1, const QRectF& vi
class Canvas : public QWidget {
Q_OBJECT
public:
- enum class LabelMode { Over, Beside };
Layout lay; // target layout; what is drawn (shownLoc) animates towards it
QString selId, cutId;
- LabelMode labelMode = LabelMode::Over;
explicit Canvas(Model* m) : model(m) {
setFocusPolicy(Qt::StrongFocus);
@@ -1499,7 +1523,7 @@ class Canvas : public QWidget {
if (clado()) // branchPx: the length of the branch into it
return {n, qpt(f.o), leaf ? CLADO_TIP_R : CLADO_NODE_R, s, 0, depth,
n->parent ? s * lay.reach.value(n) : 1e300};
- const double r = disks() ? s : leaf ? std::max(3.0, s * STD_NODE) : std::max(3.5, s * STD_WIDTH * 0.65);
+ const double r = disks() ? s : std::max(3.0, s * INSIDE_NODE);
// Standard: a leaf has no outgoing branch, so its size on screen is the branch drawn to it.
double len = s;
if (!disks() && leaf && n->parent)
@@ -1615,6 +1639,7 @@ class Canvas : public QWidget {
return f ? std::optional(f->o) : std::nullopt;
}
void drawNodes(QPainter& p);
+ void drawInsideLabels(QPainter& p);
void drawLabels(QPainter& p, const std::vector& segs);
};
@@ -1696,154 +1721,74 @@ void Canvas::drawNodes(QPainter& p) {
}
}
-// Greedy placement, selection first, then well-sized clades. Each label tries
-// every wrap option at every candidate position (Over: around the node centre /
-// disc top; Beside: rings around the node), cheapest first, and takes the first
-// one that is not blocked. Hard obstacles: placed labels (+gap), other nodes,
-// and branches not incident to the node. Its own branches are a soft cost.
-// The selection is forced if nothing is free; the hovered label is drawn last.
+// Cladograms label their tips and branches; the other layouts put each name inside its node.
void Canvas::drawLabels(QPainter& p, const std::vector& segs) {
if (clado()) return drawCladoLabels(p, segs);
- const bool dk = disks(), beside = labelMode == LabelMode::Beside;
- const Node *sel = model->find(selId), *cut = model->find(cutId), *hov = model->find(hoverId);
- constexpr double padX = 5, padY = 2;
- static const double OFFS[] = {0, .45, -.45, .9, -.9, 1.4, -1.4, 2.0, -2.0, 2.5, -2.5, PI};
- const QRectF view = vrect(), inner = view.adjusted(4, 4, -4, -4);
- const QRectF nearView = view.adjusted(-120, -120, 120, 120);
-
- const auto anySeg = segFinder(segs, nearView);
-
- std::vector nodeRects, placed;
- if (!dk)
- for (const Item& v : items_)
- nodeRects.push_back(QRectF(v.s.x() - v.r - 2, v.s.y() - v.r - 2, 2 * v.r + 4, 2 * v.r + 4));
-
- auto blocked = [&](const QRectF& r, int own) {
- const Node* me = items_[own].n;
- if (me != sel && !inner.contains(r)) return true;
- const QRectF t = r.adjusted(-LABEL_GAP, -LABEL_GAP, LABEL_GAP, LABEL_GAP);
- if (std::any_of(placed.begin(), placed.end(), [&](const QRectF& q) { return q.intersects(t); })) return true;
- for (size_t i = 0; i < nodeRects.size(); ++i)
- if (int(i) != own && nodeRects[i].intersects(r)) return true;
- return anySeg(r, [me](const Seg& s) { return s.p != me && s.c != me; });
- };
- auto onOwnStem = [&](const QRectF& r, const Node* me) {
- return anySeg(r, [me](const Seg& s) { return s.p == me || s.c == me; });
- };
+ drawInsideLabels(p);
+}
- struct Lbl { QRectF box; QString text; QFont font; const Node* n; QPointF target; bool forced, leader; };
- auto makeLabel = [&](const Item& v, int own, bool force) -> std::optional {
+// Labels inside nodes: each name at the largest size that fits its disc (on
+// Disks, a clade with daughters uses the band at the top of its disc), wrapped
+// onto the lines that allow the largest; too small to read, it is left out, except for the selected or hovered clade, which gets a
+// label over its node instead.
+void Canvas::drawInsideLabels(QPainter& p) {
+ const Node *sel = model->find(selId), *cut = model->find(cutId), *hov = model->find(hoverId);
+ constexpr double REF = 100, LINE = 1.2;
+ QFont ref = font();
+ ref.setPixelSize(int(REF));
+ const QFontMetricsF rfm(ref);
+ const QRectF view = vrect();
+ std::vector small;
+ int drawn = 0;
+ for (const Item& v : items_) {
+ const bool named = v.n == sel || v.n == hov;
+ const bool band = disks() && !Layout::hidesKids(v.n);
+ const QPointF c = band ? QPointF(v.s.x(), v.s.y() - v.r * 0.8) : v.s;
+ const double rr = band ? v.r * 0.15 : v.r;
+ if (rr < INSIDE_MIN_FONT || !view.intersects(QRectF(c.x() - rr, c.y() - rr, 2 * rr, 2 * rr))) {
+ if (named) small.push_back(&v);
+ continue;
+ }
QStringList words = v.n->name.split(' ', Qt::SkipEmptyParts);
if (words.isEmpty()) words << "?";
if (v.n == cut) words[0] = "✂ " + words[0];
if (v.n->collapsed && !v.n->kids.empty()) words << QString("[+%1]").arg(v.n->countDesc());
-
+ QStringList lines;
+ double px = 0;
+ for (const QStringList& o : wrapOptions(words, rfm)) { // the text's half-diagonal within the disc
+ double w = 0;
+ for (const QString& s : o) w = std::max(w, rfm.horizontalAdvance(s));
+ const double k = std::min(INSIDE_MAX_FONT, INSIDE_FILL * rr * REF / std::hypot(w / 2, o.size() * LINE * REF / 2));
+ if (k > px) { px = k; lines = o; }
+ }
+ if (px < INSIDE_MIN_FONT) {
+ if (named) small.push_back(&v);
+ continue;
+ }
+ if (drawn++ >= MAX_LABELS * 4) break;
+ QFont f = font();
+ f.setPixelSize(int(px));
+ p.setFont(f);
+ const QColor fill = inCut(v.n) ? T.cut.darker(160) : nodeColor(v.n, v.depth, disks() ? 0.55 : 1.0);
+ p.setPen(qGray(fill.rgb()) > 140 ? QColor("#10131e") : QColor("#f4f6fb"));
+ const double lineH = int(px) * LINE, top = c.y() - (lines.size() - 1) * lineH / 2;
+ for (int i = 0; i < lines.size(); ++i)
+ p.drawText(QRectF(c.x() - rr, top + i * lineH - lineH / 2, 2 * rr, lineH), Qt::AlignCenter, lines[i]);
+ }
+ for (const Item* v : small) { // the selection and the hovered clade are always named
QFont f = font();
- f.setPixelSize(std::clamp(int(dk ? v.lenPx * 0.11 : v.lenPx * 0.14), 11, 28));
+ f.setPixelSize(13);
const QFontMetricsF fm(f);
-
- QPointF c = v.s;
- double rr = v.r;
- if (!beside) {
- if (dk && !Layout::hidesKids(v.n)) {
- c.ry() -= v.r * 0.82;
- rr = std::min(v.r * 0.1, 12.0) + 2;
- if (v.r > 200 && c.y() < 24 && v.s.y() + v.r > 80) {
- c.setY(std::clamp(24.0, v.s.y() - v.r + 24.0, v.s.y()));
- c.setX(std::clamp(c.x(), 80.0, vw() - 80.0));
- }
- }
- if (!force && !nearView.contains(c)) return std::nullopt;
- }
-
- const std::vector opts = wrapOptions(words, fm);
- struct Cand { double cost; QRectF r; int opt; bool leader; };
- std::vector cs;
- for (int k = 0; k < int(opts.size()); ++k) {
- double tw = 0;
- for (const QString& line : opts[k]) tw = std::max(tw, fm.horizontalAdvance(line));
- const double w = std::ceil(tw) + 2 * padX;
- const double h = std::ceil(fm.height() + (opts[k].size() - 1) * fm.lineSpacing()) + 2 * padY;
-
- if (beside) {
- const int maxRings = (v.lenPx > 80 || force) ? 3 : 1;
- for (int ring = 0; ring < maxRings; ++ring) {
- const double gap = v.r + 6 + ring * 22;
- for (double off : OFFS) {
- const double ux = std::cos(v.angle + off), uy = std::sin(v.angle + off);
- cs.push_back({ring + std::abs(off) * 0.25 + WRAP_COST * k,
- anchoredRect(w, h, v.s.x() + ux * gap, v.s.y() + uy * gap, ux, uy), k, ring > 0});
- }
- }
- continue;
- }
-
- if (dk && !force && v.lenPx < 140 && w > v.r * 1.85) continue;
- const double mx = w / 2 + rr - 1, my = h / 2 + rr - 1;
- const int steps = (v.lenPx > 90 || force) ? 3 : 2;
- for (int i = -steps; i <= steps; ++i)
- for (int j = -steps; j <= steps; ++j) {
- const double dx = mx * i / 2.0, dy = my * j / 2.0;
- const QRectF r(std::round(c.x() + dx - w / 2), std::round(c.y() + dy - h / 2), w, h);
- const QPointF q(std::clamp(c.x(), r.left(), r.right()), std::clamp(c.y(), r.top(), r.bottom()));
- const double dist = QLineF(q, c).length();
- if (dist <= rr || (v.lenPx > 90 && dist <= rr + 36))
- cs.push_back({std::abs(dx) / w + std::abs(dy) / h + WRAP_COST * k + (dist > rr ? 1.5 : 0),
- r, k, dist > rr + 4});
- }
- }
- if (cs.empty()) return std::nullopt;
- if (!segs.empty())
- for (Cand& cd : cs)
- if (onOwnStem(cd.r, v.n)) cd.cost += STEM_COST;
- std::stable_sort(cs.begin(), cs.end(), [](const Cand& a, const Cand& b) { return a.cost < b.cost; });
- for (const Cand& cd : cs)
- if (!blocked(cd.r, own)) return Lbl{cd.r, opts[cd.opt].join('\n'), f, v.n, c, false, cd.leader};
- if (!force) return std::nullopt;
- return Lbl{cs.front().r, opts[cs.front().opt].join('\n'), f, v.n, c, true, false};
- };
-
- const double minLen = dk ? LABEL_MIN_SCREEN_LEN : 24.0;
- std::vector cands;
- for (int i = 0; i < int(items_.size()); ++i) {
- const Item& v = items_[i];
- if (v.n == sel || v.branchPx >= minLen) cands.push_back(i);
- }
- auto priority = [&](const Item& v) {
- const bool giantOffCenter = v.lenPx > std::max(vw(), vh()) * 1.2;
- return std::make_tuple(v.n != sel, giantOffCenter, -lay.weight(v.n), v.depth, -v.lenPx);
- };
- std::sort(cands.begin(), cands.end(), [&](int a, int b) { return priority(items_[a]) < priority(items_[b]); });
-
- std::vector labels;
- bool hovShown = false;
- for (int i : cands) {
- if (int(labels.size()) >= MAX_LABELS) break;
- if (auto l = makeLabel(items_[i], i, items_[i].n == sel)) {
- placed.push_back(l->box);
- labels.push_back(*l);
- hovShown |= l->n == hov;
- }
- }
- if (hov && !hovShown) {
- const auto it = std::find_if(items_.begin(), items_.end(), [&](const Item& v) { return v.n == hov; });
- if (it != items_.end())
- if (auto l = makeLabel(*it, int(it - items_.begin()), true)) labels.push_back(*l);
- }
-
- for (const Lbl& l : labels) {
- if (l.leader) {
- p.setPen(QPen(T.dim, 1.2, Qt::DotLine));
- p.drawLine(l.target, l.box.center());
- }
- const bool isSel = l.n == sel, isHov = l.n == hov;
- p.setPen(isSel ? QPen(T.accent, 1) : isHov ? QPen(T.dim, 1) : QPen(Qt::NoPen));
- p.setBrush(isHov || l.forced ? T.labelBgHover : T.labelBg);
- p.drawRoundedRect(l.box, 5, 5);
- p.setFont(l.font);
- p.setPen(isSel ? T.accent : inCut(l.n) ? T.cut : T.fg);
- p.drawText(l.box.adjusted(padX, padY, -padX, -padY), Qt::AlignCenter, l.text);
- labelHits.push_back({l.box, l.n->id});
+ const QString name = v->n->name.isEmpty() ? "?" : v->n->name;
+ const double w = fm.horizontalAdvance(name) + 10, h = 19;
+ const QRectF b(std::round(v->s.x() - w / 2), std::round(v->s.y() - v->r - 6 - h), w, h);
+ p.setPen(QPen(v->n == sel ? T.accent : T.dim, 1));
+ p.setBrush(T.labelBgHover);
+ p.drawRoundedRect(b, 5, 5);
+ p.setFont(f);
+ p.setPen(v->n == sel ? T.accent : T.fg);
+ p.drawText(b, Qt::AlignCenter, name);
+ labelHits.push_back({b, v->n->id});
}
}
@@ -2386,6 +2331,7 @@ class InfoPanel : public QWidget {
kids->setMaximumHeight(160);
up->setFlat(true);
info->setPlaceholderText("(no info — press E, double-click the node, or click 'Edit')");
+ info->setOpenExternalLinks(true); // web addresses in the info open in the browser
empty->setWordWrap(true);
setAcceptDrops(true);
@@ -2455,7 +2401,8 @@ class InfoPanel : public QWidget {
upId = n->parent ? n->parent->id : QString();
up->setVisible(n->parent);
if (n->parent) up->setText("‹ up to " + n->parent->name);
- info->setPlainText(n->info);
+ if (n->info.isEmpty()) info->clear(); // keeps the placeholder
+ else info->setHtml(linkified(n->info, T.link));
if (n->images != shownImages)
fillThumbnails(pics, shownImages = n->images, [this](int i) { emit pictureOpened(i); }, [this](int i) { emit pictureRemoved(i); });
}
@@ -2761,12 +2708,6 @@ class MainWindow : public QMainWindow {
for (Layout::Style st : {Layout::Standard, Layout::Disks, Layout::Rectangular, Layout::Circular})
styleActs.push_back(radio(styleGroup, mk(Layout::styleName(st), {QKeySequence(QString("Ctrl+%1").arg(st + 1))},
[this, st] { setStyle(st); })));
- viewMenu->addSection("Labels");
- auto labelGroup = new QActionGroup(this);
- aLabelsOver = radio(labelGroup, mk("Labels over nodes", {}, [this] { setLabelsBeside(false); }));
- aLabelsBeside = radio(labelGroup, mk("Labels beside nodes", {}, [this] { setLabelsBeside(true); }));
- viewMenu->addAction(mk("Toggle label placement", {Qt::Key_L},
- [this] { setLabelsBeside(canvas->labelMode == Canvas::LabelMode::Over); }));
viewMenu->addSection("Theme");
viewMenu->addAction(aDark = mk("Dark mode", {QKeySequence("Ctrl+Shift+D")}, [this](bool on) { applyTheme(on); }));
aDark->setCheckable(true);
@@ -2813,7 +2754,6 @@ class MainWindow : public QMainWindow {
const int st = std::clamp(s.value("view/style", int(Layout::Standard)).toInt(), 0, int(Layout::Circular));
canvas->lay.style = Layout::Style(st);
styleActs[st]->setChecked(true);
- setLabelsBeside(s.value("view/labelsBeside", false).toBool());
applyTheme(s.value("view/dark", true).toBool());
canvas->relayout(false);
refresh();
@@ -2876,7 +2816,7 @@ class MainWindow : public QMainWindow {
QLabel* hud = new QLabel;
QMenu* recentMenu = nullptr;
QAction *aAdd, *aSister, *aEdit, *aCollapse, *aColor, *aFocus, *aDelete, *aCut, *aPaste, *aSaveAs, *aExport;
- QAction *aLabelsOver, *aLabelsBeside, *aDark, *aPalette = nullptr;
+ QAction *aDark, *aPalette = nullptr;
std::vector styleActs; // indexed by Layout::Style
Node* sel() const { return model.find(canvas->selId); }
@@ -2937,13 +2877,6 @@ class MainWindow : public QMainWindow {
updateHud();
}
- void setLabelsBeside(bool beside) {
- canvas->labelMode = beside ? Canvas::LabelMode::Beside : Canvas::LabelMode::Over;
- (beside ? aLabelsBeside : aLabelsOver)->setChecked(true);
- QSettings().setValue("view/labelsBeside", beside);
- canvas->update();
- }
-
void applyTheme(bool dark) {
T = makeTheme(dark);
applyPalette(T);
diff --git a/web/index.html b/web/index.html
index 16aa090..a71ef35 100644
--- a/web/index.html
+++ b/web/index.html
@@ -200,7 +200,7 @@ Keyboard
| F / Home | Focus on the clade / fit the whole tree |
| Ctrl+F | Search |
| 1 2 3 4 | Standard / Disks / Rectangular cladogram / Circular cladogram layout |
- | L / Shift+D | Labels over or beside nodes / dark mode |
+ | Shift+D | Dark mode |
| + - [ ] , . | Spread, shrink and curl (Standard layout) |
| Ctrl+O / Ctrl+S | Open / save a file |
| Ctrl+E | Export an image of the view or the whole tree |
diff --git a/web/js/app.js b/web/js/app.js
index 5ffc46c..06bd149 100644
--- a/web/js/app.js
+++ b/web/js/app.js
@@ -57,6 +57,39 @@ function showToast(s) {
}
// ---------------------------------------------------------------- hover notes
+// Text as nodes, its web addresses made links that open in a new tab: 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.
+const URL_RE = /(?:https?:\/\/|www\.)[^\s<>"]+|(?"]*)?/gi;
+function trimUrl(u) {
+ for (;;) {
+ const last = u.slice(-1);
+ const open = { ')': '(', ']': '[', '}': '{' }[last];
+ if (open ? u.split(open).length <= u.split(last).length - 1 : /[.,;:!?'"]/.test(last)) u = u.slice(0, -1);
+ else return u;
+ }
+}
+function linkified(text) {
+ const out = [];
+ let at = 0;
+ for (const m of text.matchAll(URL_RE)) {
+ m[0] = trimUrl(m[0]);
+ if (m.index > at) out.push(document.createTextNode(text.slice(at, m.index)));
+ const a = document.createElement('a');
+ a.href = /^https?:\/\//i.test(m[0]) ? m[0] : 'https://' + m[0];
+ a.textContent = m[0];
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
+ out.push(a);
+ at = m.index + m[0].length;
+ }
+ if (at < text.length) out.push(document.createTextNode(text.slice(at)));
+ return out;
+}
+
// A clade's info appears beside the pointer after a short rest on it.
function hover(id, x, y) {
hideTip();
@@ -186,7 +219,8 @@ function renderPanel() {
}
if (!n.kids.length) { const li = document.createElement('li'); li.textContent = '(none)'; li.style.color = 'var(--dim)'; li.style.cursor = 'default'; kids.append(li); }
const info = $('info');
- info.textContent = n.info || 'No info yet. Use Edit to add some.';
+ if (n.info) info.replaceChildren(...linkified(n.info));
+ else info.textContent = 'No info yet. Use Edit to add some.';
info.classList.toggle('none', !n.info);
const id = n.id;
renderPics($('pics'), () => doc.find(id)?.images || [], i => {
@@ -986,7 +1020,7 @@ if ('launchQueue' in window)
});
// ---------------------------------------------------------------- view settings
-const prefs = Object.assign({ style: STANDARD, beside: false, theme: matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark' },
+const prefs = Object.assign({ style: STANDARD, theme: matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark' },
store.get(PREFS_KEY) || {});
function savePrefs() { store.set(PREFS_KEY, prefs); }
@@ -1007,7 +1041,6 @@ function setStyle(st) {
savePrefs();
refresh();
}
-function setBeside(on) { prefs.beside = on; view.labelsBeside = on; view.draw(); savePrefs(); }
function tune(f) {
f(view.lay);
if (view.lay.style === STANDARD) view.relayout(true);
@@ -1054,9 +1087,6 @@ const MENUS = {
View: () => [
...STYLES.map((st, i) => ({ label: STYLE_NAMES[st] + ' layout', key: String(i + 1), checked: view.lay.style === st, run: () => setStyle(st) })),
{ sep: true },
- { label: 'Labels over nodes', checked: !view.labelsBeside, run: () => setBeside(false) },
- { label: 'Labels beside nodes', key: 'L', checked: view.labelsBeside, run: () => setBeside(true) },
- { sep: true },
{ label: 'Dark mode', key: 'Shift+D', checked: prefs.theme === 'dark', run: () => applyTheme(prefs.theme === 'dark' ? 'light' : 'dark') },
{ sep: true },
{ label: 'Fit whole tree', key: 'Home', run: () => view.fitView() },
@@ -1320,7 +1350,6 @@ addEventListener('keydown', e => {
ArrowLeft: () => navigate('left'), ArrowRight: () => navigate('right'),
Home: () => view.fitView(),
1: () => setStyle(STYLES[0]), 2: () => setStyle(STYLES[1]), 3: () => setStyle(STYLES[2]), 4: () => setStyle(STYLES[3]),
- l: () => setBeside(!view.labelsBeside),
d: e.shiftKey ? () => applyTheme(prefs.theme === 'dark' ? 'light' : 'dark') : actAdd, // D: add a daughter
'/': focusSearch, '?': () => $('helpDlg').showModal(),
'+': () => tune(l => { l.spread = Math.min(340 * DEG, l.spread + 10 * DEG); }),
@@ -1356,7 +1385,7 @@ if (CHANNEL) {
document.querySelector('.brand').after(b);
}
view.lay.style = STYLES.includes(prefs.style) ? prefs.style : STANDARD;
-view.labelsBeside = !!prefs.beside;
+delete prefs.beside, delete prefs.labels; // label settings of older versions
applyTheme(prefs.theme === 'light' ? 'light' : 'dark');
(async () => {
diff --git a/web/js/layout.js b/web/js/layout.js
index e23aada..7d36a53 100644
--- a/web/js/layout.js
+++ b/web/js/layout.js
@@ -11,8 +11,11 @@ const POLY_GAP = 0.94; // fraction of its wedge a child fills (both styl
const POLY_ONLY_CHILD = 0.78; // radius of a single child
const POLY_EXP = 0.68; // wedge share = weight^POLY_EXP (both styles)
// standard style
-export const STD_NODE = 0.05; // leaf / collapsed node radius, in its own units
export const 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.
+export const INSIDE_NODE = 0.3;
const STD_FAN_STEP = 15 * DEG; // extra fan angle per child beyond two
const STD_MAX_FAN = 300 * DEG; // fan cap (unless the spread itself is wider)
const STD_WEIGHT_EXP = 0.35; // light sisters are scaled by (w / w_max)^this
@@ -51,7 +54,7 @@ export class Layout {
count() { return this.loc.size; }
extent(n) { return this.ext.get(n) ?? 1; }
weight(n) { return this.size.get(n) ?? 1; }
- own(n) { return this.style === DISKS ? 1 : isClado(this.style) ? CLADO_NODE : hidesKids(n) ? STD_NODE : STD_WIDTH; }
+ own(n) { return this.style === DISKS ? 1 : isClado(this.style) ? CLADO_NODE : INSIDE_NODE; }
compute(root) {
this.loc.clear(); this.ext.clear(); this.size.clear(); this.leaves.clear(); this.reach.clear();
@@ -195,10 +198,11 @@ export class Layout {
// direction, and unit = its outgoing branch length. Returns the subtree's
// bounding circle (centre c on its x axis, radius R) and its pieces.
standard(n) {
- if (hidesKids(n)) return { c: 0, R: STD_NODE, pieces: [[C(0, 0), STD_NODE]] };
+ const own = this.own(n);
+ if (hidesKids(n)) return { c: 0, R: own, pieces: [[C(0, 0), own]] };
const kids = this.ordered(n), m = kids.length;
const sub = kids.map(k => this.standard(k));
- const circles = [[C(0, 0), STD_WIDTH]];
+ const circles = [[C(0, 0), own]];
const placeAt = (i, mid, s) => {
const u = polar(1, mid);
this.loc.set(kids[i], Local(u, scale(u, s), 0));
diff --git a/web/js/view.js b/web/js/view.js
index ab646e2..8aeba08 100644
--- a/web/js/view.js
+++ b/web/js/view.js
@@ -4,17 +4,16 @@ import {
PI, C, add, sub, mul, scale, abs, norm, arg, polar, remainder, clamp, Local, Frame,
compose, uncompose, finiteFrame, lerpZ, lerpLocal, easeOutCubic, easeInOutCubic,
} from './geom.js';
-import { Layout, STANDARD, DISKS, CIRC, STD_NODE, STD_WIDTH, isClado } from './layout.js';
+import { Layout, STANDARD, DISKS, CIRC, STD_WIDTH, INSIDE_NODE, isClado } from './layout.js';
import { hidesKids, depth as nodeDepth, contains, countDesc } from './model.js';
const ANIM_MS = 380; // relayout animation; camera flights take twice as long
const ZOOM_STEP = 1.15, FAST_ZOOM_STEP = 2.0;
const MAX_LABELS = 400;
-const LABEL_MIN_SCREEN_LEN = 35; // disks: smaller discs get no label
const LABEL_GAP = 2;
-const WRAP_COST = 0.12;
+const INSIDE_MIN_FONT = 8, INSIDE_MAX_FONT = 400; // px: labels inside nodes
+const INSIDE_FILL = 0.88; // fraction of a node's radius its label may reach
const MAX_WRAP_LINES = 6;
-const STEM_COST = 0.8;
const STD_CURVE = 0.1;
const MIN_PX = 0.6;
const FIT_MARGIN = 120;
@@ -83,13 +82,6 @@ const hits = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
const inside = (outer, r) => r.x0 >= outer.x0 && r.y0 >= outer.y0 && r.x1 <= outer.x1 && r.y1 <= outer.y1;
const has = (r, p) => p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1;
-// Box of size w*h whose side facing direction (ux, uy) touches (px, py).
-function anchoredRect(w, h, px, py, ux, uy) {
- const l = ux > 0.35 ? px : ux < -0.35 ? px - w : px - w / 2;
- const t = uy > 0.35 ? py : uy < -0.35 ? py - h : py - h / 2;
- return rectWH(Math.round(l), Math.round(t), w, h);
-}
-
// Finds whether a rect touches any (padded) branch piece accepted by want(),
// with a uniform grid over the pieces. Every rect a caller tests lies in
// nearView, so clamping to it loses nothing.
@@ -150,7 +142,6 @@ export class TreeView {
this.h = handlers; // {select(id), edit(id), menu(id, clientX, clientY), viewChanged()}
this.lay = new Layout();
this.theme = THEMES.dark;
- this.labelsBeside = false;
this.selId = '';
this.cutId = '';
this.hoverId = '';
@@ -516,7 +507,7 @@ export class TreeView {
if (this.clado()) // branchPx: the length of the branch into it
return { n, s: f.o, r: leaf ? CLADO_TIP_R : CLADO_NODE_R, lenPx: s, angle: 0, depth: d,
branchPx: n.parent ? s * (this.lay.reach.get(n) ?? 0) : Infinity };
- const r = this.disks() ? s : leaf ? Math.max(3, s * STD_NODE) : Math.max(3.5, s * STD_WIDTH * 0.65);
+ const r = this.disks() ? s : Math.max(3, s * INSIDE_NODE);
let len = s;
if (!this.disks() && leaf && n.parent) {
const L = this.sloc(n);
@@ -730,130 +721,69 @@ export class TreeView {
return out;
}
- // Greedy placement, selection first, then well-sized clades (see the desktop app).
+ // Cladograms label their tips and branches; the other layouts put each name inside its node.
drawLabels(segs) {
if (this.clado()) return this.drawCladoLabels(segs);
- const ctx = this.ctx, t = this.theme, dk = this.disks(), beside = this.labelsBeside;
- const sel = this.doc.find(this.selId), cutN = this.doc.find(this.cutId), hov = this.doc.find(this.hoverId);
- const padX = 5, padY = 2;
- const OFFS = [0, .45, -.45, .9, -.9, 1.4, -1.4, 2.0, -2.0, 2.5, -2.5, PI];
- const view = R(0, 0, this.width, this.height), inner = R(4, 4, this.width - 4, this.height - 4);
- const nearView = inflate(view, 120);
- const items = this.items;
+ this.drawInsideLabels();
+ }
- const anySeg = segFinder(segs, nearView);
- const nodeRects = dk ? [] : items.map(v => R(v.s.x - v.r - 2, v.s.y - v.r - 2, v.s.x + v.r + 2, v.s.y + v.r + 2));
- const placed = [];
- const blocked = (r, own) => {
- const me = items[own].n;
- if (me !== sel && !inside(inner, r)) return true;
- const tr = inflate(r, LABEL_GAP);
- if (placed.some(q => hits(q, tr))) return true;
- for (let i = 0; i < nodeRects.length; ++i) if (i !== own && hits(nodeRects[i], r)) return true;
- return anySeg(r, s => s.p !== me && s.c !== me);
- };
- const onOwnStem = (r, me) => anySeg(r, s => s.p === me || s.c === me);
+ // Labels inside nodes: each name at the largest size that fits its disc (on
+ // Disks, a clade with daughters uses the band at the top of its disc), wrapped
+ // onto the lines that allow the largest; too small to read, it is left out,
+ // except for the selected or hovered clade, which gets a label over its node instead.
- const makeLabel = (v, own, force) => {
+ drawInsideLabels() {
+ const ctx = this.ctx, t = this.theme;
+ const sel = this.doc.find(this.selId), cutN = this.doc.find(this.cutId), hov = this.doc.find(this.hoverId);
+ const REF = 100, refFont = `${REF}px ${FONT}`, LINE = 1.2;
+ const view = R(0, 0, this.width, this.height);
+ const fit = v => {
let words = v.n.name.split(/\s+/).filter(Boolean);
if (!words.length) words = ['?'];
if (v.n === cutN) words[0] = '✂ ' + words[0];
if (v.n.collapsed && v.n.kids.length) words.push(`[+${countDesc(v.n)}]`);
- const px = clamp(Math.trunc(dk ? v.lenPx * 0.11 : v.lenPx * 0.14), 11, 28);
- const font = `${px}px ${FONT}`;
- const lineH = Math.round(px * 1.25);
-
- let c = v.s, rr = v.r;
- if (!beside) {
- if (dk && !hidesKids(v.n)) {
- c = C(v.s.x, v.s.y - v.r * 0.82);
- rr = Math.min(v.r * 0.1, 12) + 2;
- if (v.r > 200 && c.y < 24 && v.s.y + v.r > 80)
- c = C(clamp(c.x, 80, this.width - 80), clamp(24, v.s.y - v.r + 24, v.s.y));
- }
- if (!force && !has(nearView, c)) return null;
+ let best = null;
+ for (const o of this.wrapOptions(words, refFont)) { // the text's half-diagonal within the disc
+ const px = Math.min(INSIDE_MAX_FONT, INSIDE_FILL * v.rr * REF / Math.hypot(o.width / 2, o.lines.length * LINE * REF / 2));
+ if (!best || px > best.px) best = { lines: o.lines, px };
}
- const opts = this.wrapOptions(words, font);
- const cs = [];
- opts.forEach((o, k) => {
- const w = Math.ceil(o.width) + 2 * padX, h = lineH * o.lines.length + 2 * padY;
- if (beside) {
- const maxRings = (v.lenPx > 80 || force) ? 3 : 1;
- for (let ring = 0; ring < maxRings; ++ring) {
- const gap = v.r + 6 + ring * 22;
- for (const off of OFFS) {
- const ux = Math.cos(v.angle + off), uy = Math.sin(v.angle + off);
- cs.push({ cost: ring + Math.abs(off) * 0.25 + WRAP_COST * k,
- r: anchoredRect(w, h, v.s.x + ux * gap, v.s.y + uy * gap, ux, uy), k, leader: ring > 0 });
- }
- }
- return;
- }
- if (dk && !force && v.lenPx < 140 && w > v.r * 1.85) return;
- const mx = w / 2 + rr - 1, my = h / 2 + rr - 1;
- const steps = (v.lenPx > 90 || force) ? 3 : 2;
- for (let i = -steps; i <= steps; ++i)
- for (let j = -steps; j <= steps; ++j) {
- const dx = mx * i / 2, dy = my * j / 2;
- const r = rectWH(Math.round(c.x + dx - w / 2), Math.round(c.y + dy - h / 2), w, h);
- const q = C(clamp(c.x, r.x0, r.x1), clamp(c.y, r.y0, r.y1));
- const dist = Math.hypot(q.x - c.x, q.y - c.y);
- if (dist <= rr || (v.lenPx > 90 && dist <= rr + 36))
- cs.push({ cost: Math.abs(dx) / w + Math.abs(dy) / h + WRAP_COST * k + (dist > rr ? 1.5 : 0),
- r, k, leader: dist > rr + 4 });
- }
- });
- if (!cs.length) return null;
- if (segs.length) for (const cd of cs) if (onOwnStem(cd.r, v.n)) cd.cost += STEM_COST;
- cs.sort((a, b) => a.cost - b.cost);
- for (const cd of cs)
- if (!blocked(cd.r, own)) return { box: cd.r, lines: opts[cd.k].lines, font, lineH, n: v.n, target: c, forced: false, leader: cd.leader };
- if (!force) return null;
- return { box: cs[0].r, lines: opts[cs[0].k].lines, font, lineH, n: v.n, target: c, forced: true, leader: false };
+ return best;
};
-
- const minLen = dk ? LABEL_MIN_SCREEN_LEN : 24;
- const cands = [];
- items.forEach((v, i) => { if (v.n === sel || v.branchPx >= minLen) cands.push(i); });
- const big = Math.max(this.width, this.height) * 1.2;
- const prio = v => [v.n !== sel ? 1 : 0, v.lenPx > big ? 1 : 0, -this.lay.weight(v.n), v.depth, -v.lenPx];
- const cmp = (a, b) => { for (let i = 0; i < a.length; ++i) if (a[i] !== b[i]) return a[i] - b[i]; return 0; };
- const keyed = cands.map(i => [prio(items[i]), i]).sort((a, b) => cmp(a[0], b[0]));
-
- const labels = [];
- let hovShown = false;
- for (const [, i] of keyed) {
- if (labels.length >= MAX_LABELS) break;
- const l = makeLabel(items[i], i, items[i].n === sel);
- if (l) { placed.push(l.box); labels.push(l); hovShown ||= l.n === hov; }
- }
- if (hov && !hovShown) {
- const i = items.findIndex(v => v.n === hov);
- if (i >= 0) { const l = makeLabel(items[i], i, true); if (l) labels.push(l); }
- }
-
+ const lum = ([r, g, b]) => 0.299 * r + 0.587 * g + 0.114 * b;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
- for (const l of labels) {
- const b = l.box, cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
- if (l.leader) {
- ctx.setLineDash([1.5, 3]);
- ctx.lineWidth = 1.2;
- ctx.strokeStyle = css(t.dim);
- ctx.beginPath(); ctx.moveTo(l.target.x, l.target.y); ctx.lineTo(cx, cy); ctx.stroke();
- ctx.setLineDash([]);
+ let drawn = 0;
+ const small = [];
+ for (const it of this.items) {
+ const band = this.disks() && !hidesKids(it.n);
+ const v = { ...it, c: band ? C(it.s.x, it.s.y - it.r * 0.8) : it.s, rr: band ? it.r * 0.15 : it.r };
+ if (v.rr < INSIDE_MIN_FONT || !hits(view, R(v.c.x - v.rr, v.c.y - v.rr, v.c.x + v.rr, v.c.y + v.rr))) {
+ if (v.n === sel || v.n === hov) small.push(v);
+ continue;
}
- const isSel = l.n === sel, isHov = l.n === hov;
+ const f = fit(v);
+ if (f.px < INSIDE_MIN_FONT) { if (v.n === sel || v.n === hov) small.push(v); continue; }
+ if (drawn++ >= MAX_LABELS * 4) break;
+ const px = Math.floor(f.px), lineH = px * LINE;
+ const fill = this.inCut(v.n) ? darker(t.cut, 160) : this.nodeColor(v.n, v.depth, this.disks() ? 0.55 : 1);
+ ctx.font = `${px}px ${FONT}`;
+ ctx.fillStyle = lum(fill) > 140 ? '#10131e' : '#f4f6fb';
+ const top = v.c.y - (f.lines.length - 1) * lineH / 2;
+ f.lines.forEach((s, i) => ctx.fillText(s, v.c.x, top + i * lineH + 0.5));
+ }
+ for (const v of small) { // the selection and the hovered clade are always named
+ const px = 13, font = `${px}px ${FONT}`, name = v.n.name || '?';
+ const w = this.measure(font, name) + 10, h = px + 6;
+ const b = rectWH(Math.round(v.s.x - w / 2), Math.round(v.s.y - v.r - 6 - h), w, h);
ctx.beginPath();
- ctx.roundRect(b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0, 5);
- ctx.fillStyle = isHov || l.forced ? t.labelBgHover : t.labelBg;
+ ctx.roundRect(b.x0, b.y0, w, h, 5);
+ ctx.fillStyle = t.labelBgHover;
ctx.fill();
- if (isSel || isHov) { ctx.lineWidth = 1; ctx.strokeStyle = css(isSel ? t.accent : t.dim); ctx.stroke(); }
- ctx.font = l.font;
- ctx.fillStyle = css(isSel ? t.accent : this.inCut(l.n) ? t.cut : t.fg);
- const top = cy - (l.lines.length - 1) * l.lineH / 2;
- l.lines.forEach((s, i) => ctx.fillText(s, cx, top + i * l.lineH + 0.5));
- this.labelHits.push([b, l.n.id]);
+ ctx.lineWidth = 1; ctx.strokeStyle = css(v.n === sel ? t.accent : t.dim); ctx.stroke();
+ ctx.font = font;
+ ctx.fillStyle = css(v.n === sel ? t.accent : t.fg);
+ ctx.fillText(name, v.s.x, (b.y0 + b.y1) / 2 + 0.5);
+ this.labelHits.push([b, v.n.id]);
}
}
diff --git a/web/style.css b/web/style.css
index c329233..3277aae 100644
--- a/web/style.css
+++ b/web/style.css
@@ -151,6 +151,7 @@ button { cursor: pointer; }
.kids li:hover { background: var(--btn); }
.info { white-space: pre-wrap; overflow-wrap: anywhere; }
.info.none { color: var(--dim); font-style: italic; }
+.info a { color: var(--link); }
.pics { display: flex; flex-wrap: wrap; gap: 6px; }
.pics:empty { display: none; }
.pics .pic { position: relative; }