From 00e032ab7cb57003bcb8c8e1a78fecf8f3f1b1fb Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:03:12 +0000 Subject: [PATCH 01/17] Add pictures to clade notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pictures can be dragged onto a clade in the tree (which highlights the clade it will go to), onto the side panel (the selected clade), or into the Edit and Add boxes, where they can also be pasted or picked with "Add pictures…". The side panel shows them as thumbnails; clicking or double-clicking one opens a viewer with previous/next and Remove. Every change is a normal undoable edit. Pictures are stored in the cladogram file as an optional "images" list of PNG or JPEG data URLs, so a tree stays one self-contained file that both apps read. They are scaled to at most 1200 px and saved as JPEG (quality 85), or PNG when they have transparency. On the desktop, undo snapshots copy the pictures, so the history now also keeps to a 256 MB budget of picture data besides its 200 steps. --- README.md | 2 + main.cpp | 332 ++++++++++++++++++++++++++++++++++++++++++++++-- web/index.html | 24 ++++ web/js/app.js | 181 ++++++++++++++++++++++++-- web/js/model.js | 20 +-- web/style.css | 13 ++ 6 files changed, 540 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 58d9596..2a539ea 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ You can also [use TreeFern in your browser](https://docrountree.github.io/treefe - **Rectangular cladogram**: the right-angled tree of journal figures, with the tips aligned in a column and labelled beside it, and clade names placed along their branches. - **Circular cladogram**: the same tree around a circle, with the root at the centre and the tip labels radiating outward. - **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. @@ -154,6 +155,7 @@ A cladogram is a JSON object with the id of the root clade and a flat list of cl | `info` | string | Free-form notes, shown in the side panel | | `collapsed` | boolean | Whether the clade's descendants are hidden | | `title` | string | Optional, at the top level: the name the web app's Samples menu shows for a file in `samples/` (otherwise the root clade's name) | +| `images` | array of strings | Optional pictures for the notes, as PNG or JPEG data URLs (`data:image/jpeg;base64,…`) | | `color` | string | Optional colour as `"#rrggbb"`, inherited by the clade's descendants; omitted when the clade uses its mother clade's colour | Because the format is plain JSON, files can be generated or edited by scripts and other tools while TreeFern is open; it reloads them automatically. Clades whose parent chain does not reach the root are ignored when a file is loaded. diff --git a/main.cpp b/main.cpp index 9431da7..84f4b69 100644 --- a/main.cpp +++ b/main.cpp @@ -15,8 +15,9 @@ // 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?}, …]} -// color is an optional "#rrggbb" that the clade's subtree inherits. +// 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 #include @@ -41,6 +42,10 @@ 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 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 @@ -140,6 +145,7 @@ 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> kids; Node* parent = nullptr; @@ -283,9 +289,11 @@ class Model : public QObject { return {}; } void commit() { - undo_.push_back(std::exchange(current_, toJson(root_.get()))); - if (undo_.size() > 200) undo_.erase(undo_.begin()); + 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(); @@ -303,19 +311,28 @@ class Model : public QObject { QDateTime lastMtime_; QFileSystemWatcher watcher_; // Undo history: whole-tree snapshots. current_ is the tree as of the last commit. - QJsonObject current_; - std::vector undo_, redo_; + struct Snapshot { QJsonObject json; qsizetype bytes = 0; }; // bytes: the picture data it holds + Snapshot current_; + std::vector 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_ = toJson(root_.get()); + current_ = snapshot(); undo_.clear(); redo_.clear(); } - QString step(std::vector& from, std::vector& to, const char* done) { + QString step(std::vector& from, std::vector& to, const char* done) { if (from.empty()) return QString("Nothing to %1").arg(&from == &undo_ ? "undo" : "redo"); QString err; - auto tree = fromJson(from.back(), err); + auto tree = fromJson(from.back().json, err); if (!tree) return err; to.push_back(std::exchange(current_, from.back())); from.pop_back(); @@ -349,6 +366,14 @@ class Model : public QObject { 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(); @@ -379,7 +404,8 @@ class Model : public QObject { recs.push_back({std::unique_ptr(new Node{id, o.value("name").toString("Unnamed"), o.value("info").toString(), o.value("collapsed").toBool(false), - readColor(o.value("color").toString())}), + readColor(o.value("color").toString()), + readImages(o.value("images"))}), o.value("parent").toString()}); } const QString rootId = top.value("root").toString(); @@ -423,6 +449,7 @@ class Model : public QObject { 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()); } @@ -1001,6 +1028,12 @@ class Canvas : public QWidget { relayout(false); } + // Dropping pictures: the clade under p, highlighted while dragging over it. + const Node* nodeAt(QPointF p) const { return hitTest(p); } + void setDragHover(const QString& id) { + if (id != hoverId) { hoverId = id; update(); } + } + bool disks() const { return lay.style == Layout::Disks; } bool clado() const { return Layout::isClado(lay.style); } @@ -2001,6 +2034,111 @@ void Canvas::drawCladoLabels(QPainter& p, const std::vector& segs) { } } +// ----------------------------------------------------------- pictures --- +// Pictures are kept in the file with the notes, so they are scaled to at most +// IMAGE_MAX_SIDE px and stored as JPEG, or as PNG when they have transparency. +static QString imageToDataUrl(QImage img) { + if (img.isNull()) return {}; + if (std::max(img.width(), img.height()) > IMAGE_MAX_SIDE) + img = img.scaled(IMAGE_MAX_SIDE, IMAGE_MAX_SIDE, Qt::KeepAspectRatio, Qt::SmoothTransformation); + bool alpha = false; + if (img.hasAlphaChannel()) { + const QImage a = img.convertToFormat(QImage::Format_ARGB32); + for (int y = 0; y < a.height() && !alpha; ++y) { + const QRgb* row = reinterpret_cast(a.constScanLine(y)); + for (int x = 0; x < a.width(); ++x) + if (qAlpha(row[x]) < 255) { alpha = true; break; } + } + } + QByteArray bytes; + QBuffer buf(&bytes); + buf.open(QIODevice::WriteOnly); + const bool ok = alpha ? img.save(&buf, "PNG") : img.convertToFormat(QImage::Format_RGB32).save(&buf, "JPG", IMAGE_QUALITY); + if (!ok) return {}; + return QString("data:image/%1;base64,").arg(alpha ? "png" : "jpeg") + QString::fromLatin1(bytes.toBase64()); +} + +static QImage imageFromDataUrl(const QString& url) { + return QImage::fromData(QByteArray::fromBase64(url.mid(url.indexOf(',') + 1).toLatin1())); +} + +// Pictures in dropped or pasted data: image files, or the image itself. +static bool mimeHasImages(const QMimeData* m) { + if (!m) return false; + if (m->hasImage()) return true; + for (const QUrl& u : m->urls()) + if (u.isLocalFile() && !QImageReader::imageFormat(u.toLocalFile()).isEmpty()) return true; + return false; +} +static QList imagesFromMime(const QMimeData* m) { + QList out; + for (const QUrl& u : m->urls()) + if (u.isLocalFile()) + if (QImage img(u.toLocalFile()); !img.isNull()) out << img; + if (out.isEmpty() && m->hasImage()) out << qvariant_cast(m->imageData()); + return out; +} + +// A row of thumbnails; double-clicking one opens it. +static QListWidget* thumbnailList() { + auto list = new QListWidget; + list->setViewMode(QListView::IconMode); + list->setIconSize(QSize(96, 72)); + list->setFlow(QListView::LeftToRight); + list->setWrapping(true); + list->setResizeMode(QListView::Adjust); + list->setMovement(QListView::Static); + list->setSpacing(4); + list->setMaximumHeight(180); + return list; +} +static void fillThumbnails(QListWidget* list, const QStringList& images) { + list->clear(); + for (const QString& s : images) + new QListWidgetItem(QIcon(QPixmap::fromImage(imageFromDataUrl(s).scaled(192, 144, Qt::KeepAspectRatio, Qt::SmoothTransformation))), {}, list); + list->setVisible(!images.isEmpty()); +} + +// Shows the pictures get() one at a time from `start`; remove(i) deletes picture i. +static void showPictures(QWidget* parent, const std::function& get, int start, const std::function& remove) { + QDialog dlg(parent); + dlg.setWindowTitle("Picture"); + auto img = new QLabel; + img->setAlignment(Qt::AlignCenter); + img->setMinimumSize(320, 240); + auto caption = new QLabel; + caption->setStyleSheet(colorCss(T.dim)); + auto buttons = new QDialogButtonBox(QDialogButtonBox::Close); + QPushButton* prev = buttons->addButton("‹ Previous", QDialogButtonBox::ActionRole); + QPushButton* next = buttons->addButton("Next ›", QDialogButtonBox::ActionRole); + QPushButton* del = buttons->addButton("Remove", QDialogButtonBox::DestructiveRole); + auto v = new QVBoxLayout(&dlg); + v->addWidget(img, 1); + v->addWidget(caption); + v->addWidget(buttons); + int i = start; + auto draw = [&] { + const QStringList list = get(); + if (list.isEmpty()) return dlg.reject(); + i = std::clamp(i, 0, int(list.size()) - 1); + const QPixmap px = QPixmap::fromImage(imageFromDataUrl(list[i])); + const QSize room = (parent->screen() ? parent->screen()->availableSize() : QSize(1280, 800)) * 0.75; + img->setPixmap(px.width() > room.width() || px.height() > room.height() + ? px.scaled(room, Qt::KeepAspectRatio, Qt::SmoothTransformation) : px); + caption->setText(QString("Picture %1 of %2").arg(i + 1).arg(list.size())); + prev->setEnabled(i > 0); + next->setEnabled(i + 1 < list.size()); + }; + QObject::connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); + QObject::connect(prev, &QPushButton::clicked, &dlg, [&] { --i; draw(); }); + QObject::connect(next, &QPushButton::clicked, &dlg, [&] { ++i; draw(); }); + QObject::connect(del, &QPushButton::clicked, &dlg, [&] { remove(i); draw(); }); + QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isEnabled()) prev->click(); }); + QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isEnabled()) next->click(); }); + draw(); + dlg.exec(); +} + // --------------------------------------------------------- info panel --- // Side panel: clade search plus details and actions for the selected clade. class InfoPanel : public QWidget { @@ -2025,6 +2163,8 @@ class InfoPanel : public QWidget { up->setFlat(true); info->setPlaceholderText("(no info — press E, double-click the node, or click 'Edit')"); empty->setWordWrap(true); + picsHint->setWordWrap(true); + setAcceptDrops(true); auto grid = new QGridLayout; for (int i = 0; i < acts.size(); ++i) { @@ -2045,6 +2185,9 @@ class InfoPanel : public QWidget { nv->addWidget(up); nv->addWidget(new QLabel("Info:")); nv->addWidget(info, 1); + nv->addWidget(new QLabel("Pictures:")); + nv->addWidget(pics); + nv->addWidget(picsHint); auto v = new QVBoxLayout(this); v->addWidget(search); v->addWidget(results); @@ -2056,6 +2199,7 @@ class InfoPanel : public QWidget { connect(kids, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { emit selectRequested(it->data(Qt::UserRole).toString()); }); connect(up, &QPushButton::clicked, this, [this] { emit selectRequested(upId); }); + connect(pics, &QListWidget::itemActivated, this, [this](QListWidgetItem* it) { emit pictureOpened(pics->row(it)); }); connect(crumbs, &QLabel::linkActivated, this, [this](const QString& link) { if (link != "more") return emit selectRequested(link); crumbsOpen = shownId; @@ -2069,6 +2213,7 @@ class InfoPanel : public QWidget { title->setStyleSheet(colorCss(T.accent)); meta->setStyleSheet(colorCss(T.dim)); empty->setStyleSheet(colorCss(T.dim)); + picsHint->setStyleSheet(colorCss(T.dim)); up->setStyleSheet("text-align:left; " + colorCss(T.link)); if (const Node* n = model->find(shownId); n && nodeBox->isVisible()) setCrumbs(n); } @@ -2091,6 +2236,7 @@ class InfoPanel : public QWidget { up->setVisible(n->parent); if (n->parent) up->setText("‹ up to " + n->parent->name); info->setPlainText(n->info); + if (n->images != shownImages) fillThumbnails(pics, shownImages = n->images); } // The clades above n, root first; a long trail folds its middle into a "…" @@ -2151,8 +2297,21 @@ class InfoPanel : public QWidget { signals: void selectRequested(const QString& id); void searchChosen(const QString& id); + void picturesDropped(const QList& images); // onto the panel: for the shown clade + void pictureOpened(int index); protected: + void dragEnterEvent(QDragEnterEvent* e) override { + if (nodeBox->isVisible() && mimeHasImages(e->mimeData())) e->acceptProposedAction(); + } + void dropEvent(QDropEvent* e) override { + if (!nodeBox->isVisible()) return; + if (const auto imgs = imagesFromMime(e->mimeData()); !imgs.isEmpty()) { + e->acceptProposedAction(); + emit picturesDropped(imgs); + } + } + // Up/Down/Enter in the search box drive the result list; Esc clears it. // Claiming these as ShortcutOverride stops the window's single-key // shortcuts (navigation, deselect) from firing while typing. @@ -2185,6 +2344,9 @@ class InfoPanel : public QWidget { QListWidget* kids = new QListWidget; QPushButton* up = new QPushButton; QTextBrowser* info = new QTextBrowser; + QListWidget* pics = thumbnailList(); + QLabel* picsHint = new QLabel("Drop pictures here, or onto a clade in the tree; double-click one to view or remove it."); + QStringList shownImages; QString upId, shownId, crumbsOpen; // crumbsOpen: the clade whose trail is unfolded void choose(QListWidgetItem* it) { @@ -2207,6 +2369,92 @@ class KeyHook : public QObject { std::function f_; }; +// Lets an object handle another's events first; the handler returns true to consume one. +class EventHook : public QObject { +public: + explicit EventHook(std::function f) : f_(std::move(f)) {} +protected: + bool eventFilter(QObject* o, QEvent* e) override { return f_(o, e) || QObject::eventFilter(o, e); } +private: + std::function f_; +}; + +// The pictures of a clade being edited: thumbnails with Add and Remove, and +// pictures dropped anywhere on its dialog or pasted into its text fields. +class PicStrip : public QWidget { +public: + QStringList images; + + PicStrip(QDialog* dlg, const QStringList& start, std::initializer_list edits) : images(start) { + auto add = new QPushButton("Add pictures…"); + auto del = new QPushButton("Remove picture"); + auto hint = new QLabel("or drop or paste them here"); + hint->setStyleSheet(colorCss(T.dim)); + auto row = new QHBoxLayout; + row->addWidget(add); + row->addWidget(del); + row->addWidget(hint, 1); + auto v = new QVBoxLayout(this); + v->setContentsMargins(0, 0, 0, 0); + v->addWidget(list); + v->addLayout(row); + connect(add, &QPushButton::clicked, this, [this] { + QList imgs; + for (const QString& p : QFileDialog::getOpenFileNames(this, "Add pictures", {}, "Images (*.png *.jpg *.jpeg *.gif *.bmp *.webp)")) + if (QImage img(p); !img.isNull()) imgs << img; + addImages(imgs); + }); + connect(del, &QPushButton::clicked, this, [this] { + if (const int i = list->currentRow(); i >= 0) { images.removeAt(i); fillThumbnails(list, images); } + }); + connect(list, &QListWidget::itemActivated, this, [this](QListWidgetItem* it) { + showPictures(this, [this] { return images; }, list->row(it), [this](int i) { images.removeAt(i); fillThumbnails(list, images); }); + }); + fillThumbnails(list, images); + // The text fields would take a dropped file as text, so drops go to the dialog. + dlg->setAcceptDrops(true); + dlg->installEventFilter(&hook); + for (QWidget* w : edits) { + w->setAcceptDrops(false); + w->installEventFilter(&hook); + } + this->dlg = dlg; + } + + void addImages(const QList& imgs) { + for (const QImage& img : imgs) + if (const QString url = imageToDataUrl(img); !url.isEmpty()) images << url; + fillThumbnails(list, images); + } + +private: + QListWidget* list = thumbnailList(); + QDialog* dlg = nullptr; + EventHook hook{[this](QObject* o, QEvent* e) { + switch (e->type()) { + case QEvent::DragEnter: + case QEvent::DragMove: + if (o != dlg || !mimeHasImages(static_cast(e)->mimeData())) return false; + static_cast(e)->acceptProposedAction(); + return true; + case QEvent::Drop: + if (o != dlg || !mimeHasImages(static_cast(e)->mimeData())) return false; + static_cast(e)->acceptProposedAction(); + addImages(imagesFromMime(static_cast(e)->mimeData())); + return true; + case QEvent::KeyPress: + if (o != dlg && static_cast(e)->matches(QKeySequence::Paste)) + if (const QMimeData* m = QGuiApplication::clipboard()->mimeData(); mimeHasImages(m)) { + addImages(imagesFromMime(m)); + return true; + } + return false; + default: + return false; + } + }}; +}; + // -------------------------------------------------------- main window --- static const char* FILE_FILTER = "Cladogram JSON (*.json);;All files (*)"; @@ -2323,6 +2571,18 @@ class MainWindow : public QMainWindow { connect(canvas, &Canvas::clicked, this, &MainWindow::select); connect(panel, &InfoPanel::selectRequested, this, &MainWindow::select); connect(panel, &InfoPanel::searchChosen, this, &MainWindow::jumpTo); + connect(panel, &InfoPanel::picturesDropped, this, [this](const QList& imgs) { addPictures(canvas->selId, imgs); }); + connect(panel, &InfoPanel::pictureOpened, this, [this](int i) { + const QString id = canvas->selId; + showPictures(this, [this, id] { const Node* n = model.find(id); return n ? n->images : QStringList(); }, i, [this, id](int k) { + Node* n = model.find(id); + if (!n || k >= n->images.size()) return; + n->images.removeAt(k); + model.commit(); + model.status = QString("Removed a picture from '%1'").arg(n->name); + updateHud(); + }); + }); connect(canvas, &Canvas::doubleClicked, this, [this](const QString& id) { select(id); actEdit(); }); connect(canvas, &Canvas::contextMenu, this, [this](const QString& id, const QPoint& g) { if (!id.isEmpty()) select(id); @@ -2367,9 +2627,25 @@ class MainWindow : public QMainWindow { protected: void dragEnterEvent(QDragEnterEvent* e) override { - if (e->mimeData()->hasUrls()) e->acceptProposedAction(); + if (e->mimeData()->hasUrls() || mimeHasImages(e->mimeData())) e->acceptProposedAction(); + } + // Pictures dragged over the tree highlight the clade they would be added to. + void dragMoveEvent(QDragMoveEvent* e) override { + e->acceptProposedAction(); + const Node* n = mimeHasImages(e->mimeData()) ? pictureTarget(e->position()) : nullptr; + canvas->setDragHover(n ? n->id : QString()); } + void dragLeaveEvent(QDragLeaveEvent*) override { canvas->setDragHover({}); } void dropEvent(QDropEvent* e) override { + canvas->setDragHover({}); + if (mimeHasImages(e->mimeData())) { + if (const Node* n = pictureTarget(e->position())) addPictures(n->id, imagesFromMime(e->mimeData())); + else { + model.status = "Drop pictures onto a clade to add them to its notes"; + updateHud(); + } + return; + } const auto urls = e->mimeData()->urls(); if (!urls.isEmpty() && urls.first().isLocalFile()) openPath(urls.first().toLocalFile()); } @@ -2387,6 +2663,28 @@ class MainWindow : public QMainWindow { std::vector styleActs; // indexed by Layout::Style Node* sel() const { return model.find(canvas->selId); } + + // The clade a picture dropped at window position p goes to: the one under + // it in the tree, else the selection. + const Node* pictureTarget(QPointF p) const { + const QPointF q = canvas->mapFrom(this, p.toPoint()); + if (canvas->rect().contains(q.toPoint())) + if (const Node* n = canvas->nodeAt(q)) return n; + return sel(); + } + + void addPictures(const QString& id, const QList& imgs) { + Node* n = model.find(id); + if (!n) return; + QStringList urls; + for (const QImage& img : imgs) + if (const QString u = imageToDataUrl(img); !u.isEmpty()) urls << u; + if (urls.isEmpty()) return; + n->images += urls; + model.commit(); + model.status = QString("Added %1 to '%2'").arg(urls.size() == 1 ? QString("a picture") : QString("%1 pictures").arg(urls.size()), n->name); + updateHud(); + } void select(const QString& id) { canvas->selId = id; refresh(); } void fillCladeMenu(QMenu* m, QAction* extra = nullptr) { @@ -2797,7 +3095,7 @@ class MainWindow : public QMainWindow { // replace the tree, so nodes are re-looked-up by id afterwards. enum class Next { Done, Daughter, Sister }; - struct NewClade { QString name, info; Next next; }; + struct NewClade { QString name, info; QStringList images; Next next; }; // Name (and info) of one new clade. Enter in the name or Add: add it and // stop; Shift+Enter: add it, then a daughter of it; Tab: add it, then a sister. @@ -2824,6 +3122,8 @@ class MainWindow : public QMainWindow { form->addSpacing(6); form->addWidget(new QLabel("Info:")); form->addWidget(infoEdit, 1); + auto pics = new PicStrip(&dlg, {}, {nameEdit, infoEdit}); + form->addWidget(pics); form->addWidget(hint); form->addWidget(buttons); @@ -2850,7 +3150,7 @@ class MainWindow : public QMainWindow { connect(new QShortcut(seq, &dlg), &QShortcut::activated, &dlg, [&] { finish(Next::Done); }); nameEdit->setFocus(); if (dlg.exec() != QDialog::Accepted) return std::nullopt; - return NewClade{nameEdit->text().trimmed(), infoEdit->toPlainText(), next}; + return NewClade{nameEdit->text().trimmed(), infoEdit->toPlainText(), pics->images, next}; } // Adds clades until the user stops; each is its own undo step. sister: @@ -2865,6 +3165,7 @@ class MainWindow : public QMainWindow { const auto r = askNewClade(p->name); if (!r || !(p = model.find(parentId))) return; Node* c = p->addChild(Node::make(r->name, r->info)); + c->images = r->images; p->collapsed = false; canvas->selId = c->id; model.commit(); @@ -2939,6 +3240,8 @@ class MainWindow : public QMainWindow { form->addSpacing(6); form->addWidget(new QLabel("Info:")); form->addWidget(infoEdit, 1); + auto pics = new PicStrip(&dlg, n->images, {nameEdit, infoEdit}); + form->addWidget(pics); form->addWidget(hint); form->addWidget(buttons); @@ -2954,9 +3257,10 @@ class MainWindow : public QMainWindow { if (dlg.exec() != QDialog::Accepted || !(n = model.find(id))) return; const QString newName = nameEdit->text().trimmed(), newInfo = infoEdit->toPlainText(); - if (newName.isEmpty() || (newName == n->name && newInfo == n->info)) return; + if (newName.isEmpty() || (newName == n->name && newInfo == n->info && pics->images == n->images)) return; n->name = newName; n->info = newInfo; + n->images = pics->images; model.commit(); } diff --git a/web/index.html b/web/index.html index e7ae19e..33cc624 100644 --- a/web/index.html +++ b/web/index.html @@ -73,6 +73,9 @@

Subclades

    Info

    +

    Pictures

    +
    +

    Drop pictures here, or onto a clade in the tree.

    @@ -87,6 +90,11 @@

    Info

    Edit clade

    +
    +
    + + or drop or paste them here +

    Enter in the name, or Ctrl+Enter anywhere: OK. Esc: cancel.

    @@ -123,6 +131,21 @@

    Export image

    + +
    + +

    +
    + + + + +
    +
    +
    + + +

    @@ -158,6 +181,7 @@

    Mouse

    Click / double-clickSelect / edit a clade Right-clickClade menu HoverShow a clade's info + Drag a pictureOnto a clade in the tree, the side panel or the Edit box, to add it to the notes Drag / wheelPan / zoom (Shift: faster)

    Keyboard

    diff --git a/web/js/app.js b/web/js/app.js index 14f6d7f..9906f25 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -2,7 +2,7 @@ import { Doc, fromJson, toJson, makeNode, walk, depth, countDesc, contains } from './model.js'; import { TreeView, THEMES } from './view.js'; import { STANDARD, STYLES, STYLE_NAMES, DEFAULT_SPREAD, DEFAULT_SHRINK, DEFAULT_CURL } from './layout.js'; -import { DEG } from './geom.js'; +import { DEG, C, clamp } from './geom.js'; let SAMPLES = []; // [{file, title}], listed from samples/ when the site is built (see build-site.sh) const MAX_SEARCH = 200, MAX_RECENT = 8; @@ -188,6 +188,14 @@ function renderPanel() { const info = $('info'); info.textContent = n.info || '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 => { + const m = doc.find(id); + if (!m) return; + m.images = m.images.filter((_, j) => j !== i); + doc.commit(); + setStatus(`Removed a picture from '${m.name}'`); + }); } // The clades above the selection, root first; long trails fold their middle @@ -267,13 +275,16 @@ function navigate(d) { } // ---------------------------------------------------------------- editing -let dlgResolve = null, dlgRapid = false; +let dlgResolve = null, dlgRapid = false, dlgImages = []; const EDIT_HINT = 'Enter in the name, or Ctrl+Enter anywhere: OK. Esc: cancel.'; const RAPID_HINT = 'Enter or Add: add it and stop. Shift+Enter: add it, then a daughter of it. Tab: add it, then a sister. Esc: stop.'; // rapid: adding clades one after another; resolves with next = 'child', 'sister' or 'done'. -function openEditDialog({ title, name = '', info = '', withInfo = true, rapid = false }) { +function openEditDialog({ title, name = '', info = '', images = [], withInfo = true, rapid = false }) { const dlg = $('editDlg'); dlgRapid = rapid; + dlgImages = images.slice(); + renderEditPics(); + $('editPicsRow').hidden = !withInfo; $('editTitle').textContent = title; $('editName').value = name; $('editInfo').value = info; @@ -307,7 +318,7 @@ function finishEdit(ok, next = 'done') { $('editDlg').close(); const r = dlgResolve; dlgResolve = null; - r?.(ok ? { name, info, next } : null); + r?.(ok ? { name, info, next, images: dlgImages.slice() } : null); } $('editDlg').addEventListener('cancel', e => { e.preventDefault(); finishEdit(false); }); $('editDlg').addEventListener('keydown', e => { @@ -329,7 +340,7 @@ async function actAdd(sister = false) { if (!p) return; const r = await openEditDialog({ title: `New clade under '${p.name}'`, rapid: true }); if (!r || !(p = doc.find(parentId))) return; - const c = doc.addChild(p, r.name, r.info); + const c = doc.addChild(p, r.name, r.info, r.images); view.selId = c.id; refresh(); if (r.next === 'done') return; @@ -341,13 +352,144 @@ async function actEdit() { let n = sel(); if (!n) return; const id = n.id; - const r = await openEditDialog({ title: 'Edit clade', name: n.name, info: n.info }); + const r = await openEditDialog({ title: 'Edit clade', name: n.name, info: n.info, images: n.images }); if (!r || !(n = doc.find(id))) return; - if (r.name === n.name && r.info === n.info) return; + const samePics = r.images.length === n.images.length && r.images.every((s, i) => s === n.images[i]); + if (r.name === n.name && r.info === n.info && samePics) return; n.name = r.name; n.info = r.info; + if (!samePics) n.images = r.images; + doc.commit(); +} + +// ---------------------------------------------------------------- pictures +// Pictures are kept in the file with the notes, so they are scaled to at most +// IMAGE_MAX_SIDE px and stored as JPEG, or as PNG when they have transparency. +const IMAGE_MAX_SIDE = 1200, IMAGE_QUALITY = 0.85; +const isImage = f => /^image\/(png|jpeg|gif|webp|bmp)$/.test(f.type); +const imageFiles = dt => [...(dt?.files || [])].filter(isImage); +const dragHasImages = dt => [...(dt?.items || [])].some(i => i.kind === 'file' && i.type.startsWith('image/')); + +async function toDataUrl(file) { + const bmp = await createImageBitmap(file); + const k = Math.min(1, IMAGE_MAX_SIDE / Math.max(bmp.width, bmp.height)); + const c = document.createElement('canvas'); + c.width = Math.max(1, Math.round(bmp.width * k)); + c.height = Math.max(1, Math.round(bmp.height * k)); + const g = c.getContext('2d'); + g.drawImage(bmp, 0, 0, c.width, c.height); + bmp.close?.(); + let alpha = false; + if (file.type !== 'image/jpeg') { + const px = g.getImageData(0, 0, c.width, c.height).data; + for (let i = 3; i < px.length; i += 4) if (px[i] < 255) { alpha = true; break; } + } + return alpha ? c.toDataURL('image/png') : c.toDataURL('image/jpeg', IMAGE_QUALITY); +} + +// The pictures among `files`, converted; unreadable ones are reported and skipped. +async function readPictures(files) { + const urls = []; + for (const f of files) + if (isImage(f)) { + try { urls.push(await toDataUrl(f)); } + catch { setStatus(`Cannot read the picture ${f.name}`, true); } + } + return urls; +} + +async function addPictures(id, files) { + const urls = await readPictures(files); + const n = doc.find(id); + if (!n || !urls.length) return; + n.images = [...n.images, ...urls]; doc.commit(); + setStatus(`Added ${urls.length === 1 ? 'a picture' : urls.length + ' pictures'} to '${n.name}'`); +} + +// Thumbnails of get() in box; clicking one opens the viewer, which can remove it. +function renderPics(box, get, remove) { + box.replaceChildren(); + get().forEach((src, i) => { + const d = document.createElement('div'), img = document.createElement('img'); + d.className = 'pic'; + img.src = src; + img.alt = `Picture ${i + 1}`; + img.addEventListener('click', () => showPicture(get, i, remove)); + d.append(img); + box.append(d); + }); +} + +function renderEditPics() { + const remove = i => { dlgImages.splice(i, 1); renderEditPics(); }; + renderPics($('editPics'), () => dlgImages, remove); + [...$('editPics').children].forEach((d, i) => { + const x = document.createElement('button'); + x.type = 'button'; + x.textContent = '×'; + x.title = 'Remove this picture'; + x.addEventListener('click', () => remove(i)); + d.append(x); + }); +} +async function addEditPics(files) { + dlgImages.push(...await readPictures(files)); + renderEditPics(); +} +$('editAddPics').addEventListener('click', () => { $('picInput').onchange = () => addEditPics([...$('picInput').files]); $('picInput').value = ''; $('picInput').click(); }); +$('editDlg').addEventListener('paste', e => { + const files = imageFiles(e.clipboardData); + if (!files.length) return; + e.preventDefault(); + addEditPics(files); +}); + +// Drop targets: the edit box (its pending pictures), the side panel (the +// selected clade) and, in the global handler below, the clade under the pointer. +for (const [el, drop] of [[$('editDlg'), files => addEditPics(files)], + [$('panel'), files => { const n = sel(); if (n) addPictures(n.id, files); }]]) { + el.addEventListener('dragover', e => { + if (!dragHasImages(e.dataTransfer) || (el === $('panel') && !sel())) return; + e.preventDefault(); + e.stopPropagation(); + el.classList.add('drop-target'); + }); + el.addEventListener('dragleave', e => { if (!el.contains(e.relatedTarget)) el.classList.remove('drop-target'); }); + el.addEventListener('drop', e => { + el.classList.remove('drop-target'); + const files = imageFiles(e.dataTransfer); + if (!files.length) return; + e.preventDefault(); + e.stopPropagation(); + dragDepth = 0; + $('dropZone').hidden = true; + drop(files); + }); +} + +let picView = null; // the viewer's {get, i, remove} +function showPicture(get, i, remove) { + picView = { get, i, remove }; + drawPicture(); + if (!$('picDlg').open) $('picDlg').showModal(); } +function drawPicture() { + const list = picView.get(); + if (!list.length) return $('picDlg').close(); + picView.i = clamp(picView.i, 0, list.length - 1); + $('picBig').src = list[picView.i]; + $('picCaption').textContent = `Picture ${picView.i + 1} of ${list.length}`; + $('picPrev').disabled = picView.i === 0; + $('picNext').disabled = picView.i === list.length - 1; +} +$('picPrev').addEventListener('click', () => { --picView.i; drawPicture(); }); +$('picNext').addEventListener('click', () => { ++picView.i; drawPicture(); }); +$('picRemove').addEventListener('click', () => { picView.remove(picView.i); drawPicture(); }); +$('picDlg').addEventListener('keydown', e => { + if (e.key === 'ArrowLeft' && !$('picPrev').disabled) { $('picPrev').click(); e.preventDefault(); } + if (e.key === 'ArrowRight' && !$('picNext').disabled) { $('picNext').click(); e.preventDefault(); } +}); function actCollapse() { const n = sel(); @@ -731,13 +873,32 @@ async function newDoc() { // Drag and drop a file anywhere on the page. let dragDepth = 0; -addEventListener('dragenter', e => { if (e.dataTransfer?.types.includes('Files')) { ++dragDepth; $('dropZone').hidden = false; } }); -addEventListener('dragleave', () => { if (--dragDepth <= 0) { dragDepth = 0; $('dropZone').hidden = true; } }); -addEventListener('dragover', e => e.preventDefault()); +// Pictures dragged over the tree highlight the clade they would be added to. +const treePoint = e => { const r = $('tree').getBoundingClientRect(); return C(e.clientX - r.left, e.clientY - r.top); }; +const overTree = e => $('tree').contains(e.target); +function dragHover(id) { if (view.hoverId !== id) { view.hoverId = id; view.draw(); } } +addEventListener('dragenter', e => { + if (!e.dataTransfer?.types.includes('Files')) return; + ++dragDepth; + if (!dragHasImages(e.dataTransfer)) $('dropZone').hidden = false; +}); +addEventListener('dragleave', () => { if (--dragDepth <= 0) { dragDepth = 0; $('dropZone').hidden = true; dragHover(''); } }); +addEventListener('dragover', e => { + e.preventDefault(); + if (dragHasImages(e.dataTransfer)) dragHover(overTree(e) ? view.hitTest(treePoint(e), 14)?.id || '' : ''); +}); addEventListener('drop', async e => { e.preventDefault(); dragDepth = 0; $('dropZone').hidden = true; + dragHover(''); + const pics = imageFiles(e.dataTransfer); + if (pics.length) { + const n = (overTree(e) && view.hitTest(treePoint(e), 14)) || sel(); + if (n) addPictures(n.id, pics); + else setStatus('Drop pictures onto a clade to add them to its notes', true); + return; + } const item = [...(e.dataTransfer?.items || [])].find(i => i.kind === 'file'); if (!item) return; const h = item.getAsFileSystemHandle ? await item.getAsFileSystemHandle().catch(() => null) : null; diff --git a/web/js/model.js b/web/js/model.js index f9ff328..66f3f40 100644 --- a/web/js/model.js +++ b/web/js/model.js @@ -1,7 +1,8 @@ // The cladogram tree, its JSON file format, and undo history. // File format (shared with the desktop app): -// {"root": id, "nodes": [{id, parent?, name, info, collapsed, color?}, ...]} -// color is an optional "#rrggbb" that the clade's subtree inherits. +// {"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. export function newId() { const a = new Uint8Array(5); @@ -9,11 +10,13 @@ export function newId() { return Array.from(a, b => b.toString(16).padStart(2, '0')).join(''); } -export function makeNode(name, info = '', id = newId(), collapsed = false, color = '') { - return { id, name, info, collapsed, color, kids: [], parent: null }; +export function makeNode(name, info = '', id = newId(), collapsed = false, color = '', images = []) { + return { id, name, info, collapsed, color, images, kids: [], parent: null }; } const readColor = c => typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c) ? c.toLowerCase() : ''; +export const IMAGE_URL = /^data:image\/(png|jpeg);base64,[A-Za-z0-9+/]+=*$/; +const readImages = v => Array.isArray(v) ? v.filter(s => typeof s === 'string' && IMAGE_URL.test(s)) : []; export const hidesKids = n => n.collapsed || n.kids.length === 0; @@ -65,7 +68,7 @@ export function fromJson(top) { if (!id || byId.has(id)) id = newId(); byId.set(id, recs.length); recs.push({ n: makeNode(typeof o.name === 'string' ? o.name : 'Unnamed', typeof o.info === 'string' ? o.info : '', - id, o.collapsed === true, readColor(o.color)), + id, o.collapsed === true, readColor(o.color), readImages(o.images)), parent: typeof o.parent === 'string' ? o.parent : '' }); } const rootIdx = byId.get(top.root); @@ -98,7 +101,7 @@ function fromNested(top) { if (!id || seen.has(id)) id = newId(); seen.add(id); return makeNode(typeof o.name === 'string' ? o.name : 'Unnamed', typeof o.info === 'string' ? o.info : '', id, - o.collapsed === true, readColor(o.color)); + o.collapsed === true, readColor(o.color), readImages(o.images)); }; const root = mk(top), stack = [[top, root]]; while (stack.length) { @@ -116,6 +119,7 @@ export function toJson(root) { if (n.parent) o.parent = n.parent.id; Object.assign(o, { name: n.name, info: n.info, collapsed: n.collapsed }); if (n.color) o.color = n.color; + if (n.images.length) o.images = n.images.slice(); nodes.push(o); }); return { root: root.id, nodes }; @@ -172,8 +176,8 @@ export class Doc { undo() { return this.step(this.undoStack, this.redoStack); } redo() { return this.step(this.redoStack, this.undoStack); } - addChild(n, name, info = '') { - const c = addChild(n, makeNode(name, info)); + addChild(n, name, info = '', images = []) { + const c = addChild(n, makeNode(name, info, undefined, false, '', images)); n.collapsed = false; this.commit(); return c; diff --git a/web/style.css b/web/style.css index ded9efd..01118fc 100644 --- a/web/style.css +++ b/web/style.css @@ -151,6 +151,19 @@ 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; } +.pics { display: flex; flex-wrap: wrap; gap: 6px; } +.pics:empty { display: none; } +.pics .pic { position: relative; } +.pics img { display: block; height: 72px; max-width: 140px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); cursor: zoom-in; background: var(--chrome-2); } +.pics .pic button { position: absolute; top: 2px; right: 2px; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; background: rgba(0,0,0,.6); color: #fff; font-size: 13px; line-height: 20px; } +.pics-hint { color: var(--dim); font-size: 12px; margin: 4px 0 0; } +.panel.drop-target { outline: 2px dashed var(--accent); outline-offset: -6px; } +.edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } +.edit-pics-row .pics { width: 100%; } +#editDlg.drop-target { outline: 2px dashed var(--accent); } +.pic-dlg { width: min(960px, calc(100vw - 24px)); } +.pic-dlg img { display: block; max-width: 100%; max-height: calc(100vh - 180px); margin: 0 auto; border-radius: 6px; } +.dlg-buttons button.danger-text { color: var(--danger); } /* ---- popup menus */ .menu-pop { From 9be23111c6fae8ec11e02f28ab37dffdd7553144 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:20:59 +0000 Subject: [PATCH 02/17] Show pictures full screen when clicked The picture viewer now fills the screen, on a black background, with the picture scaled to fit and rescaled when the window changes size; Previous, Next, Remove and Close stay along the bottom, and Esc closes it. On the desktop the window is maximised and also sized to the screen, so it fills it without a window manager too. --- main.cpp | 42 +++++++++++++++++++++++++++--------------- web/style.css | 9 +++++++-- 2 files changed, 34 insertions(+), 17 deletions(-) diff --git a/main.cpp b/main.cpp index 84f4b69..b52e702 100644 --- a/main.cpp +++ b/main.cpp @@ -2034,6 +2034,16 @@ void Canvas::drawCladoLabels(QPainter& p, const std::vector& segs) { } } +// Lets an object handle another's events first; the handler returns true to consume one. +class EventHook : public QObject { +public: + explicit EventHook(std::function f) : f_(std::move(f)) {} +protected: + bool eventFilter(QObject* o, QEvent* e) override { return f_(o, e) || QObject::eventFilter(o, e); } +private: + std::function f_; +}; + // ----------------------------------------------------------- pictures --- // Pictures are kept in the file with the notes, so they are scaled to at most // IMAGE_MAX_SIDE px and stored as JPEG, or as PNG when they have transparency. @@ -2103,9 +2113,11 @@ static void fillThumbnails(QListWidget* list, const QStringList& images) { static void showPictures(QWidget* parent, const std::function& get, int start, const std::function& remove) { QDialog dlg(parent); dlg.setWindowTitle("Picture"); + dlg.setStyleSheet("QDialog { background: black; } QLabel { color: #aaa; }"); auto img = new QLabel; img->setAlignment(Qt::AlignCenter); - img->setMinimumSize(320, 240); + img->setMinimumSize(1, 1); + img->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); // the picture follows the window, not the reverse auto caption = new QLabel; caption->setStyleSheet(colorCss(T.dim)); auto buttons = new QDialogButtonBox(QDialogButtonBox::Close); @@ -2117,14 +2129,22 @@ static void showPictures(QWidget* parent, const std::function& ge v->addWidget(caption); v->addWidget(buttons); int i = start; + QPixmap px; + auto fit = [&] { // the picture as large as the window allows + if (px.isNull()) return; + const double dpr = img->devicePixelRatioF(); + QPixmap shown = px.scaled(img->size() * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); + shown.setDevicePixelRatio(dpr); + img->setPixmap(shown); + }; + EventHook resized([&](QObject*, QEvent* e) { if (e->type() == QEvent::Resize) fit(); return false; }); + img->installEventFilter(&resized); auto draw = [&] { const QStringList list = get(); if (list.isEmpty()) return dlg.reject(); i = std::clamp(i, 0, int(list.size()) - 1); - const QPixmap px = QPixmap::fromImage(imageFromDataUrl(list[i])); - const QSize room = (parent->screen() ? parent->screen()->availableSize() : QSize(1280, 800)) * 0.75; - img->setPixmap(px.width() > room.width() || px.height() > room.height() - ? px.scaled(room, Qt::KeepAspectRatio, Qt::SmoothTransformation) : px); + px = QPixmap::fromImage(imageFromDataUrl(list[i])); + fit(); caption->setText(QString("Picture %1 of %2").arg(i + 1).arg(list.size())); prev->setEnabled(i > 0); next->setEnabled(i + 1 < list.size()); @@ -2136,6 +2156,8 @@ static void showPictures(QWidget* parent, const std::function& ge QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isEnabled()) prev->click(); }); QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isEnabled()) next->click(); }); draw(); + if (QScreen* sc = parent->screen()) dlg.setGeometry(sc->availableGeometry()); // also without a window manager + dlg.setWindowState(Qt::WindowMaximized); dlg.exec(); } @@ -2369,16 +2391,6 @@ class KeyHook : public QObject { std::function f_; }; -// Lets an object handle another's events first; the handler returns true to consume one. -class EventHook : public QObject { -public: - explicit EventHook(std::function f) : f_(std::move(f)) {} -protected: - bool eventFilter(QObject* o, QEvent* e) override { return f_(o, e) || QObject::eventFilter(o, e); } -private: - std::function f_; -}; - // The pictures of a clade being edited: thumbnails with Add and Remove, and // pictures dropped anywhere on its dialog or pasted into its text fields. class PicStrip : public QWidget { diff --git a/web/style.css b/web/style.css index 01118fc..b8bbbc7 100644 --- a/web/style.css +++ b/web/style.css @@ -161,8 +161,13 @@ button { cursor: pointer; } .edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } .edit-pics-row .pics { width: 100%; } #editDlg.drop-target { outline: 2px dashed var(--accent); } -.pic-dlg { width: min(960px, calc(100vw - 24px)); } -.pic-dlg img { display: block; max-width: 100%; max-height: calc(100vh - 180px); margin: 0 auto; border-radius: 6px; } +/* the picture viewer fills the screen; the picture is scaled to fit it */ +.pic-dlg { width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; border: 0; border-radius: 0; background: #000; color: #ddd; } +.pic-dlg::backdrop { background: #000; } +.pic-dlg form { height: 100%; padding: 12px; gap: 8px; } +.pic-dlg img { flex: 1; min-height: 0; width: 100%; object-fit: contain; } +.pic-dlg .dlg-hint { color: #aaa; text-align: center; } +.pic-dlg .dlg-buttons { justify-content: center; margin: 0; } .dlg-buttons button.danger-text { color: var(--danger); } /* ---- popup menus */ From 2546691ba1f555b70a4808f49226d6e55b5d4649 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:30:03 +0000 Subject: [PATCH 03/17] Picture viewer takes the edit box's place; Ctrl+Tab adds a sister The picture viewer is now the size of the edit box instead of full screen. Opened from the edit box, it takes its exact place and the edit box, with anything typed in it, comes back when the viewer closes; opened from the side panel it is the same size, centred. The picture is still scaled to fit the window. In the add box, Ctrl+Tab adds the clade and starts a sister, from the name or the info, and plain Tab moves to the info box as usual. Browser tabs keep Ctrl+Tab for switching tabs, so on the web it works in the installed app; in a tab the "Add, then a sister" button does the same. --- README.md | 2 +- main.cpp | 28 +++++++++++++++++++--------- web/index.html | 2 +- web/js/app.js | 28 +++++++++++++++++++++++----- web/style.css | 13 ++++++------- 5 files changed, 50 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 2a539ea..93b50fe 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ Typical workflow: 1. Click a clade to select it. Its name, position in the tree and notes appear in the side panel. 2. Press **F** to focus the camera on the clade's node. 3. Press the **up arrow** key to select the daughter clade, or the **down arrow** to select the mother clade. -4. Press **A** or **D** to add a daughter clade, **S** to add a sister clade, or **E** to edit the clade's name and notes. While adding, press **Enter** to add the clade, **Shift+Enter** to add it and start a daughter of it, or **Tab** to add it and start a sister. +4. Press **A** or **D** to add a daughter clade, **S** to add a sister clade, or **E** to edit the clade's name and notes. While adding, press **Enter** to add the clade, **Shift+Enter** to add it and start a daughter of it, or **Ctrl+Tab** to add it and start a sister (on the web, in the installed app; in a browser tab, Ctrl+Tab switches tabs, so use the button). **Tab** moves to the info box. 5. To move a subtree, select it and press **X**, then select the new mother clade and press **V**. 6. Press **K** to colour the clade and everything inside it. 7. Press **Ctrl+Z** to undo any mistake. diff --git a/main.cpp b/main.cpp index b52e702..92e4b79 100644 --- a/main.cpp +++ b/main.cpp @@ -2109,11 +2109,11 @@ static void fillThumbnails(QListWidget* list, const QStringList& images) { list->setVisible(!images.isEmpty()); } -// Shows the pictures get() one at a time from `start`; remove(i) deletes picture i. +// Shows the pictures get() one at a time from `start`, scaled to the window; +// remove(i) deletes picture i. static void showPictures(QWidget* parent, const std::function& get, int start, const std::function& remove) { QDialog dlg(parent); dlg.setWindowTitle("Picture"); - dlg.setStyleSheet("QDialog { background: black; } QLabel { color: #aaa; }"); auto img = new QLabel; img->setAlignment(Qt::AlignCenter); img->setMinimumSize(1, 1); @@ -2156,8 +2156,10 @@ static void showPictures(QWidget* parent, const std::function& ge QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isEnabled()) prev->click(); }); QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isEnabled()) next->click(); }); draw(); - if (QScreen* sc = parent->screen()) dlg.setGeometry(sc->availableGeometry()); // also without a window manager - dlg.setWindowState(Qt::WindowMaximized); + // The size of the edit box; opened from one, it sits exactly over it (hiding + // it would end its edit), so closing the viewer brings the edit box back. + if (auto box = qobject_cast(parent->window())) dlg.setGeometry(box->geometry()); + else dlg.resize(560, 420); dlg.exec(); } @@ -3110,7 +3112,8 @@ class MainWindow : public QMainWindow { struct NewClade { QString name, info; QStringList images; Next next; }; // Name (and info) of one new clade. Enter in the name or Add: add it and - // stop; Shift+Enter: add it, then a daughter of it; Tab: add it, then a sister. + // stop; Shift+Enter: add it, then a daughter of it; Ctrl+Tab: add it, then a + // sister. Tab moves on to the info as usual. // An empty name, Esc or Cancel stops. std::optional askNewClade(const QString& parentName) { QDialog dlg(this); @@ -3120,7 +3123,7 @@ class MainWindow : public QMainWindow { auto infoEdit = new QPlainTextEdit; infoEdit->setPlaceholderText("(no info)"); auto hint = new QLabel("Enter or Add: add it and stop · Shift+Enter: add it, then a daughter of it · " - "Tab: add it, then a sister · Esc: stop"); + "Ctrl+Tab: add it, then a sister · Tab: to the info · Esc: stop"); hint->setWordWrap(true); hint->setStyleSheet(colorCss(T.dim)); auto buttons = new QDialogButtonBox(QDialogButtonBox::Cancel); @@ -3145,15 +3148,22 @@ class MainWindow : public QMainWindow { nameEdit->text().trimmed().isEmpty() ? dlg.reject() : dlg.accept(); }; KeyHook hook([&](QKeyEvent* e) { - if (e->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) return false; + const auto mods = e->modifiers(); + if (e->key() == Qt::Key_Tab && mods == Qt::ControlModifier) { finish(Next::Sister); return true; } + if (mods & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) return false; if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { - finish(e->modifiers() & Qt::ShiftModifier ? Next::Daughter : Next::Done); + finish(mods & Qt::ShiftModifier ? Next::Daughter : Next::Done); return true; } - if (e->key() == Qt::Key_Tab) { finish(Next::Sister); return true; } return false; }); nameEdit->installEventFilter(&hook); + KeyHook infoHook([&](QKeyEvent* e) { // Ctrl+Tab from the info too + if (e->key() != Qt::Key_Tab || e->modifiers() != Qt::ControlModifier) return false; + finish(Next::Sister); + return true; + }); + infoEdit->installEventFilter(&infoHook); connect(sister, &QPushButton::clicked, &dlg, [&] { finish(Next::Sister); }); connect(daughter, &QPushButton::clicked, &dlg, [&] { finish(Next::Daughter); }); connect(add, &QPushButton::clicked, &dlg, [&] { finish(Next::Done); }); diff --git a/web/index.html b/web/index.html index 33cc624..f0c7be6 100644 --- a/web/index.html +++ b/web/index.html @@ -188,7 +188,7 @@

    Keyboard

    - + diff --git a/web/js/app.js b/web/js/app.js index 9906f25..bbc7fac 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -277,7 +277,7 @@ function navigate(d) { // ---------------------------------------------------------------- editing let dlgResolve = null, dlgRapid = false, dlgImages = []; const EDIT_HINT = 'Enter in the name, or Ctrl+Enter anywhere: OK. Esc: cancel.'; -const RAPID_HINT = 'Enter or Add: add it and stop. Shift+Enter: add it, then a daughter of it. Tab: add it, then a sister. Esc: stop.'; +const RAPID_HINT = 'Enter or Add: add it and stop. Shift+Enter: add it, then a daughter of it. Ctrl+Tab: add it, then a sister. Tab: to the info. Esc: stop.'; // rapid: adding clades one after another; resolves with next = 'child', 'sister' or 'done'. function openEditDialog({ title, name = '', info = '', images = [], withInfo = true, rapid = false }) { const dlg = $('editDlg'); @@ -307,7 +307,11 @@ $('editDaughter').addEventListener('click', () => finishEdit(true, 'child')); $('editName').addEventListener('keydown', e => { if (!dlgRapid || e.ctrlKey || e.metaKey || e.altKey || e.isComposing) return; if (e.key === 'Enter') { e.preventDefault(); finishEdit(true, e.shiftKey ? 'child' : 'done'); } - else if (e.key === 'Tab' && !e.shiftKey) { e.preventDefault(); finishEdit(true, 'sister'); } +}); +// Ctrl+Tab: add it, then a sister. Browser tabs keep Ctrl+Tab for themselves; an +// installed app's window passes it on. Plain Tab moves on to the info as usual. +$('editDlg').addEventListener('keydown', e => { + if (dlgRapid && e.key === 'Tab' && e.ctrlKey && !e.shiftKey && !e.altKey) { e.preventDefault(); finishEdit(true, 'sister'); } }); function finishEdit(ok, next = 'done') { const name = $('editName').value.trim(), info = $('editInfo').value; @@ -468,12 +472,26 @@ for (const [el, drop] of [[$('editDlg'), files => addEditPics(files)], }); } -let picView = null; // the viewer's {get, i, remove} +let picView = null; // the viewer's {get, i, remove, back}; back: the edit box it stands in for function showPicture(get, i, remove) { - picView = { get, i, remove }; + const back = $('editDlg').open; + picView = { get, i, remove, back }; + const d = $('picDlg'); + if (back) { // take the edit box's place and size; it comes back when the viewer closes + const r = $('editDlg').getBoundingClientRect(); + d.style.width = r.width + 'px'; + d.style.height = r.height + 'px'; + $('editDlg').close(); + } else d.style.width = d.style.height = ''; drawPicture(); - if (!$('picDlg').open) $('picDlg').showModal(); + if (!d.open) d.showModal(); } +$('picDlg').addEventListener('close', () => { + if (!picView?.back) return; + picView.back = false; + $('editDlg').showModal(); + $('editInfo').focus(); +}); function drawPicture() { const list = picView.get(); if (!list.length) return $('picDlg').close(); diff --git a/web/style.css b/web/style.css index b8bbbc7..a4a506e 100644 --- a/web/style.css +++ b/web/style.css @@ -161,13 +161,12 @@ button { cursor: pointer; } .edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } .edit-pics-row .pics { width: 100%; } #editDlg.drop-target { outline: 2px dashed var(--accent); } -/* the picture viewer fills the screen; the picture is scaled to fit it */ -.pic-dlg { width: 100vw; height: 100vh; max-width: none; max-height: none; margin: 0; border: 0; border-radius: 0; background: #000; color: #ddd; } -.pic-dlg::backdrop { background: #000; } -.pic-dlg form { height: 100%; padding: 12px; gap: 8px; } -.pic-dlg img { flex: 1; min-height: 0; width: 100%; object-fit: contain; } -.pic-dlg .dlg-hint { color: #aaa; text-align: center; } -.pic-dlg .dlg-buttons { justify-content: center; margin: 0; } +/* the picture viewer is the size of the edit box, whose place it takes when opened from it */ +.pic-dlg { width: min(560px, calc(100vw - 24px)); height: min(520px, calc(100vh - 32px)); } +.pic-dlg form { height: 100%; gap: 8px; } +.pic-dlg img { flex: 1; min-height: 0; width: 100%; object-fit: contain; border-radius: 6px; } +.pic-dlg .dlg-hint { text-align: center; } +.pic-dlg .dlg-buttons { margin: 0; } .dlg-buttons button.danger-text { color: var(--danger); } /* ---- popup menus */ From 25e217840ed4f40e62573d52860a3276f8905907 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:35:53 +0000 Subject: [PATCH 04/17] Add a sister with Shift+Tab instead of Ctrl+Tab in the add box Shift+Tab, from the name or the info, adds the clade and starts a sister; it works in browser tabs as well as the apps. Tab still moves to the info box. --- README.md | 2 +- main.cpp | 15 ++++++++++----- web/index.html | 2 +- web/js/app.js | 7 +++---- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 93b50fe..61084a2 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ Typical workflow: 1. Click a clade to select it. Its name, position in the tree and notes appear in the side panel. 2. Press **F** to focus the camera on the clade's node. 3. Press the **up arrow** key to select the daughter clade, or the **down arrow** to select the mother clade. -4. Press **A** or **D** to add a daughter clade, **S** to add a sister clade, or **E** to edit the clade's name and notes. While adding, press **Enter** to add the clade, **Shift+Enter** to add it and start a daughter of it, or **Ctrl+Tab** to add it and start a sister (on the web, in the installed app; in a browser tab, Ctrl+Tab switches tabs, so use the button). **Tab** moves to the info box. +4. Press **A** or **D** to add a daughter clade, **S** to add a sister clade, or **E** to edit the clade's name and notes. While adding, press **Enter** to add the clade, **Shift+Enter** to add it and start a daughter of it, or **Shift+Tab** to add it and start a sister. **Tab** moves to the info box. 5. To move a subtree, select it and press **X**, then select the new mother clade and press **V**. 6. Press **K** to colour the clade and everything inside it. 7. Press **Ctrl+Z** to undo any mistake. diff --git a/main.cpp b/main.cpp index 92e4b79..ccd1570 100644 --- a/main.cpp +++ b/main.cpp @@ -3109,10 +3109,15 @@ class MainWindow : public QMainWindow { // replace the tree, so nodes are re-looked-up by id afterwards. enum class Next { Done, Daughter, Sister }; + // Qt reports Shift+Tab as Backtab. + static bool isShiftTab(const QKeyEvent* e) { + return (e->key() == Qt::Key_Backtab || e->key() == Qt::Key_Tab) && e->modifiers() == Qt::ShiftModifier; + } + struct NewClade { QString name, info; QStringList images; Next next; }; // Name (and info) of one new clade. Enter in the name or Add: add it and - // stop; Shift+Enter: add it, then a daughter of it; Ctrl+Tab: add it, then a + // stop; Shift+Enter: add it, then a daughter of it; Shift+Tab: add it, then a // sister. Tab moves on to the info as usual. // An empty name, Esc or Cancel stops. std::optional askNewClade(const QString& parentName) { @@ -3123,7 +3128,7 @@ class MainWindow : public QMainWindow { auto infoEdit = new QPlainTextEdit; infoEdit->setPlaceholderText("(no info)"); auto hint = new QLabel("Enter or Add: add it and stop · Shift+Enter: add it, then a daughter of it · " - "Ctrl+Tab: add it, then a sister · Tab: to the info · Esc: stop"); + "Shift+Tab: add it, then a sister · Tab: to the info · Esc: stop"); hint->setWordWrap(true); hint->setStyleSheet(colorCss(T.dim)); auto buttons = new QDialogButtonBox(QDialogButtonBox::Cancel); @@ -3149,7 +3154,7 @@ class MainWindow : public QMainWindow { }; KeyHook hook([&](QKeyEvent* e) { const auto mods = e->modifiers(); - if (e->key() == Qt::Key_Tab && mods == Qt::ControlModifier) { finish(Next::Sister); return true; } + if (isShiftTab(e)) { finish(Next::Sister); return true; } if (mods & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) return false; if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { finish(mods & Qt::ShiftModifier ? Next::Daughter : Next::Done); @@ -3158,8 +3163,8 @@ class MainWindow : public QMainWindow { return false; }); nameEdit->installEventFilter(&hook); - KeyHook infoHook([&](QKeyEvent* e) { // Ctrl+Tab from the info too - if (e->key() != Qt::Key_Tab || e->modifiers() != Qt::ControlModifier) return false; + KeyHook infoHook([&](QKeyEvent* e) { // Shift+Tab from the info too + if (!isShiftTab(e)) return false; finish(Next::Sister); return true; }); diff --git a/web/index.html b/web/index.html index f0c7be6..d52dbe1 100644 --- a/web/index.html +++ b/web/index.html @@ -188,7 +188,7 @@

    Keyboard

    Ctrl+KCommand palette: every action, by name
    SAdd a sister clade (same keys as below once the box is open)
    A or DAdd daughter clades. In the name box, Enter adds it, Shift+Enter adds it and starts a daughter of it, Tab adds it and starts a sister
    A or DAdd daughter clades. In the name box, Enter adds it, Shift+Enter adds it and starts a daughter of it, Ctrl+Tab adds it and starts a sister (in the installed app; in a browser tab use the button), and Tab moves to the info
    E or REdit name and info
    CCollapse or expand
    KColour the clade and everything in it
    - + diff --git a/web/js/app.js b/web/js/app.js index bbc7fac..15ab2da 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -277,7 +277,7 @@ function navigate(d) { // ---------------------------------------------------------------- editing let dlgResolve = null, dlgRapid = false, dlgImages = []; const EDIT_HINT = 'Enter in the name, or Ctrl+Enter anywhere: OK. Esc: cancel.'; -const RAPID_HINT = 'Enter or Add: add it and stop. Shift+Enter: add it, then a daughter of it. Ctrl+Tab: add it, then a sister. Tab: to the info. Esc: stop.'; +const RAPID_HINT = 'Enter or Add: add it and stop. Shift+Enter: add it, then a daughter of it. Shift+Tab: add it, then a sister. Tab: to the info. Esc: stop.'; // rapid: adding clades one after another; resolves with next = 'child', 'sister' or 'done'. function openEditDialog({ title, name = '', info = '', images = [], withInfo = true, rapid = false }) { const dlg = $('editDlg'); @@ -308,10 +308,9 @@ $('editName').addEventListener('keydown', e => { if (!dlgRapid || e.ctrlKey || e.metaKey || e.altKey || e.isComposing) return; if (e.key === 'Enter') { e.preventDefault(); finishEdit(true, e.shiftKey ? 'child' : 'done'); } }); -// Ctrl+Tab: add it, then a sister. Browser tabs keep Ctrl+Tab for themselves; an -// installed app's window passes it on. Plain Tab moves on to the info as usual. +// Shift+Tab: add it, then a sister. Plain Tab moves on to the info as usual. $('editDlg').addEventListener('keydown', e => { - if (dlgRapid && e.key === 'Tab' && e.ctrlKey && !e.shiftKey && !e.altKey) { e.preventDefault(); finishEdit(true, 'sister'); } + if (dlgRapid && e.key === 'Tab' && e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) { e.preventDefault(); finishEdit(true, 'sister'); } }); function finishEdit(ok, next = 'done') { const name = $('editName').value.trim(), info = $('editInfo').value; From de66e1d96cd03985edc4eb6d04bb902b36fc173e Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:30:01 -0500 Subject: [PATCH 05/17] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61084a2..8c0202c 100644 --- a/README.md +++ b/README.md @@ -39,13 +39,13 @@ You can also [use TreeFern in your browser](https://docrountree.github.io/treefe - **Standard**: a tapered branching tree in which heavier daughter clades curve away from their mother clade, inspired by the [OneZoom](https://www.onezoom.org/) viewer. Spread, shrink and curl can be adjusted from the keyboard. - **Disks**: nested circle packing, with each daughter clade drawn as a disk inside its mother clade. - **Rectangular cladogram**: the right-angled tree of journal figures, with the tips aligned in a column and labelled beside it, and clade names placed along their branches. - - **Circular cladogram**: the same tree around a circle, with the root at the centre and the tip labels radiating outward. + - **Circular cladogram**: the same tree around a circle, with the root at the center and the tip labels radiating outward. - **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. Image sizes are capped to what memory allows, and SVGs of more than 20,000 clades are refused because most programs cannot open them. +- **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. @@ -156,7 +156,7 @@ A cladogram is a JSON object with the id of the root clade and a flat list of cl | `collapsed` | boolean | Whether the clade's descendants are hidden | | `title` | string | Optional, at the top level: the name the web app's Samples menu shows for a file in `samples/` (otherwise the root clade's name) | | `images` | array of strings | Optional pictures for the notes, as PNG or JPEG data URLs (`data:image/jpeg;base64,…`) | -| `color` | string | Optional colour as `"#rrggbb"`, inherited by the clade's descendants; omitted when the clade uses its mother clade's colour | +| `color` | string | Optional color as `"#rrggbb"`, inherited by the clade's descendants; omitted when the clade uses its mother clade's colour | Because the format is plain JSON, files can be generated or edited by scripts and other tools while TreeFern is open; it reloads them automatically. Clades whose parent chain does not reach the root are ignored when a file is loaded. From 69ec177960d89a8e89ac2487c8aaf86d5f682d88 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:33:49 +0000 Subject: [PATCH 06/17] Open a picture with a single click on the desktop Thumbnails in the side panel and in the edit and add boxes now open the viewer on one click, as on the web. --- main.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/main.cpp b/main.cpp index ccd1570..f7176d1 100644 --- a/main.cpp +++ b/main.cpp @@ -2089,7 +2089,7 @@ static QList imagesFromMime(const QMimeData* m) { return out; } -// A row of thumbnails; double-clicking one opens it. +// A row of thumbnails; clicking one opens it. static QListWidget* thumbnailList() { auto list = new QListWidget; list->setViewMode(QListView::IconMode); @@ -2223,7 +2223,7 @@ class InfoPanel : public QWidget { connect(kids, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { emit selectRequested(it->data(Qt::UserRole).toString()); }); connect(up, &QPushButton::clicked, this, [this] { emit selectRequested(upId); }); - connect(pics, &QListWidget::itemActivated, this, [this](QListWidgetItem* it) { emit pictureOpened(pics->row(it)); }); + connect(pics, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { emit pictureOpened(pics->row(it)); }); connect(crumbs, &QLabel::linkActivated, this, [this](const QString& link) { if (link != "more") return emit selectRequested(link); crumbsOpen = shownId; @@ -2369,7 +2369,7 @@ class InfoPanel : public QWidget { QPushButton* up = new QPushButton; QTextBrowser* info = new QTextBrowser; QListWidget* pics = thumbnailList(); - QLabel* picsHint = new QLabel("Drop pictures here, or onto a clade in the tree; double-click one to view or remove it."); + QLabel* picsHint = new QLabel("Drop pictures here, or onto a clade in the tree; click one to view or remove it."); QStringList shownImages; QString upId, shownId, crumbsOpen; // crumbsOpen: the clade whose trail is unfolded @@ -2421,7 +2421,7 @@ class PicStrip : public QWidget { connect(del, &QPushButton::clicked, this, [this] { if (const int i = list->currentRow(); i >= 0) { images.removeAt(i); fillThumbnails(list, images); } }); - connect(list, &QListWidget::itemActivated, this, [this](QListWidgetItem* it) { + connect(list, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { showPictures(this, [this] { return images; }, list->row(it), [this](int i) { images.removeAt(i); fillThumbnails(list, images); }); }); fillThumbnails(list, images); From 2f2fb05c78c4339319e6bec183b15d02efea3d6c Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:13:10 +0000 Subject: [PATCH 07/17] Corner x buttons for pictures instead of remove and close buttons Every thumbnail, in the side panel and in the edit and add boxes, has a little white x in a black circle in its top right corner that removes the picture. The panel's hint, the "Remove picture" button and the viewer's Remove and Close buttons are gone. The viewer closes with a slightly larger black x in a translucent grey circle on the picture's top right corner, or with Esc. With several pictures, round arrows on the picture's sides (and the arrow keys) step through them, and "2 of 3" shows below; with one, neither appears. On the desktop the thumbnail list is now as tall as the rows it fills, up to two, so a few pictures no longer need scrolling. --- main.cpp | 141 ++++++++++++++++++++++++++++++++----------------- web/index.html | 16 +++--- web/js/app.js | 57 +++++++++++--------- web/style.css | 18 ++++--- 4 files changed, 144 insertions(+), 88 deletions(-) diff --git a/main.cpp b/main.cpp index f7176d1..d66c59a 100644 --- a/main.cpp +++ b/main.cpp @@ -2093,25 +2093,68 @@ static QList imagesFromMime(const QMimeData* m) { static QListWidget* thumbnailList() { auto list = new QListWidget; list->setViewMode(QListView::IconMode); - list->setIconSize(QSize(96, 72)); list->setFlow(QListView::LeftToRight); list->setWrapping(true); list->setResizeMode(QListView::Adjust); list->setMovement(QListView::Static); + list->setSelectionMode(QAbstractItemView::NoSelection); list->setSpacing(4); - list->setMaximumHeight(180); return list; } -static void fillThumbnails(QListWidget* list, const QStringList& images) { + +// A round mark in a corner: a little white x in a black circle on thumbnails, +// a larger black mark in a translucent grey circle in the viewer. +static QToolButton* roundButton(QWidget* parent, const QString& text, int size, const char* colours) { + auto b = new QToolButton(parent); + b->setText(text); + b->setFixedSize(size, size); + b->setCursor(Qt::PointingHandCursor); + b->setStyleSheet(QString("QToolButton { %1 border: none; border-radius: %2px; padding: 0; font-size: %3px; font-weight: bold; }") + .arg(colours).arg(size / 2).arg(size * 2 / 3)); + return b; +} + +// Thumbnails of `images`: clicking one calls open(i), its corner x remove(i). +static void fillThumbnails(QListWidget* list, const QStringList& images, + const std::function& open, const std::function& remove) { + constexpr int W = 96, H = 72, PAD = 4, X = 18; list->clear(); - for (const QString& s : images) - new QListWidgetItem(QIcon(QPixmap::fromImage(imageFromDataUrl(s).scaled(192, 144, Qt::KeepAspectRatio, Qt::SmoothTransformation))), {}, list); + for (int i = 0; i < images.size(); ++i) { + auto item = new QListWidgetItem(list); + item->setSizeHint(QSize(W + 2 * PAD, H + 2 * PAD)); + auto cell = new QWidget; + auto pic = new QLabel(cell); + const QPixmap px = QPixmap::fromImage(imageFromDataUrl(images[i]).scaled(W, H, Qt::KeepAspectRatio, Qt::SmoothTransformation)); + pic->setPixmap(px); + pic->setGeometry(PAD + (W - px.width()) / 2, PAD + (H - px.height()) / 2, px.width(), px.height()); + pic->setCursor(Qt::PointingHandCursor); + pic->setToolTip("View this picture"); + (new EventHook([open, i](QObject*, QEvent* e) { + if (e->type() != QEvent::MouseButtonRelease || static_cast(e)->button() != Qt::LeftButton) return false; + open(i); + return true; + }))->setParent(pic); + pic->installEventFilter(pic->findChild()); + QToolButton* x = roundButton(cell, "×", X, "background: black; color: white;"); + x->setToolTip("Remove this picture"); + x->move(pic->geometry().right() - X - 1, pic->geometry().top() + 3); + // Removing refills the list, which deletes this button: do it once its click is over. + QObject::connect(x, &QToolButton::clicked, list, [list, remove, i] { QTimer::singleShot(0, list, [remove, i] { remove(i); }); }); + list->setItemWidget(item, cell); + } list->setVisible(!images.isEmpty()); + // Tall enough for the rows the thumbnails fill at the current width, up to + // two; beyond that the list scrolls. + const int cellW = W + 2 * PAD + 2 * list->spacing(), cellH = H + 2 * PAD + 2 * list->spacing(); + const int perRow = std::max(1, (list->width() - 2 * list->frameWidth()) / cellW); + const int rows = std::min(2, int(images.size() + perRow - 1) / perRow); + list->setFixedHeight(rows * cellH + 2 * list->frameWidth() + 4); } -// Shows the pictures get() one at a time from `start`, scaled to the window; -// remove(i) deletes picture i. -static void showPictures(QWidget* parent, const std::function& get, int start, const std::function& remove) { +// Shows the pictures get() one at a time from `start`, scaled to the window. +// A grey round x on the picture's corner (or Esc) closes it; with several +// pictures, round arrows on its sides (or the arrow keys) step through them. +static void showPictures(QWidget* parent, const std::function& get, int start) { QDialog dlg(parent); dlg.setWindowTitle("Picture"); auto img = new QLabel; @@ -2119,23 +2162,31 @@ static void showPictures(QWidget* parent, const std::function& ge img->setMinimumSize(1, 1); img->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); // the picture follows the window, not the reverse auto caption = new QLabel; + caption->setAlignment(Qt::AlignCenter); caption->setStyleSheet(colorCss(T.dim)); - auto buttons = new QDialogButtonBox(QDialogButtonBox::Close); - QPushButton* prev = buttons->addButton("‹ Previous", QDialogButtonBox::ActionRole); - QPushButton* next = buttons->addButton("Next ›", QDialogButtonBox::ActionRole); - QPushButton* del = buttons->addButton("Remove", QDialogButtonBox::DestructiveRole); + const char* grey = "background: rgba(128, 128, 128, 140); color: black;"; + QToolButton* close = roundButton(img, "×", 30, grey); + QToolButton* prev = roundButton(img, "‹", 30, grey); + QToolButton* next = roundButton(img, "›", 30, grey); + close->setToolTip("Close (Esc)"); + prev->setToolTip("Previous (←)"); + next->setToolTip("Next (→)"); auto v = new QVBoxLayout(&dlg); v->addWidget(img, 1); v->addWidget(caption); - v->addWidget(buttons); int i = start; QPixmap px; - auto fit = [&] { // the picture as large as the window allows + auto fit = [&] { // the picture as large as the window allows, its buttons on it if (px.isNull()) return; const double dpr = img->devicePixelRatioF(); QPixmap shown = px.scaled(img->size() * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); shown.setDevicePixelRatio(dpr); img->setPixmap(shown); + const QSizeF s = shown.deviceIndependentSize(); + const double x0 = (img->width() - s.width()) / 2, y0 = (img->height() - s.height()) / 2; + close->move(int(x0 + s.width() - 36), int(y0 + 6)); + prev->move(int(x0 + 6), int(y0 + s.height() / 2 - 15)); + next->move(int(x0 + s.width() - 36), int(y0 + s.height() / 2 - 15)); }; EventHook resized([&](QObject*, QEvent* e) { if (e->type() == QEvent::Resize) fit(); return false; }); img->installEventFilter(&resized); @@ -2145,16 +2196,17 @@ static void showPictures(QWidget* parent, const std::function& ge i = std::clamp(i, 0, int(list.size()) - 1); px = QPixmap::fromImage(imageFromDataUrl(list[i])); fit(); - caption->setText(QString("Picture %1 of %2").arg(i + 1).arg(list.size())); - prev->setEnabled(i > 0); - next->setEnabled(i + 1 < list.size()); + const bool many = list.size() > 1; + caption->setText(many ? QString("%1 of %2").arg(i + 1).arg(list.size()) : QString()); + caption->setVisible(many); + prev->setVisible(many && i > 0); + next->setVisible(many && i + 1 < list.size()); }; - QObject::connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); - QObject::connect(prev, &QPushButton::clicked, &dlg, [&] { --i; draw(); }); - QObject::connect(next, &QPushButton::clicked, &dlg, [&] { ++i; draw(); }); - QObject::connect(del, &QPushButton::clicked, &dlg, [&] { remove(i); draw(); }); - QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isEnabled()) prev->click(); }); - QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isEnabled()) next->click(); }); + QObject::connect(close, &QToolButton::clicked, &dlg, &QDialog::reject); + QObject::connect(prev, &QToolButton::clicked, &dlg, [&] { --i; draw(); }); + QObject::connect(next, &QToolButton::clicked, &dlg, [&] { ++i; draw(); }); + QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isVisible()) prev->click(); }); + QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isVisible()) next->click(); }); draw(); // The size of the edit box; opened from one, it sits exactly over it (hiding // it would end its edit), so closing the viewer brings the edit box back. @@ -2187,7 +2239,6 @@ class InfoPanel : public QWidget { up->setFlat(true); info->setPlaceholderText("(no info — press E, double-click the node, or click 'Edit')"); empty->setWordWrap(true); - picsHint->setWordWrap(true); setAcceptDrops(true); auto grid = new QGridLayout; @@ -2211,7 +2262,6 @@ class InfoPanel : public QWidget { nv->addWidget(info, 1); nv->addWidget(new QLabel("Pictures:")); nv->addWidget(pics); - nv->addWidget(picsHint); auto v = new QVBoxLayout(this); v->addWidget(search); v->addWidget(results); @@ -2223,7 +2273,6 @@ class InfoPanel : public QWidget { connect(kids, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { emit selectRequested(it->data(Qt::UserRole).toString()); }); connect(up, &QPushButton::clicked, this, [this] { emit selectRequested(upId); }); - connect(pics, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { emit pictureOpened(pics->row(it)); }); connect(crumbs, &QLabel::linkActivated, this, [this](const QString& link) { if (link != "more") return emit selectRequested(link); crumbsOpen = shownId; @@ -2237,7 +2286,6 @@ class InfoPanel : public QWidget { title->setStyleSheet(colorCss(T.accent)); meta->setStyleSheet(colorCss(T.dim)); empty->setStyleSheet(colorCss(T.dim)); - picsHint->setStyleSheet(colorCss(T.dim)); up->setStyleSheet("text-align:left; " + colorCss(T.link)); if (const Node* n = model->find(shownId); n && nodeBox->isVisible()) setCrumbs(n); } @@ -2260,7 +2308,8 @@ class InfoPanel : public QWidget { up->setVisible(n->parent); if (n->parent) up->setText("‹ up to " + n->parent->name); info->setPlainText(n->info); - if (n->images != shownImages) fillThumbnails(pics, shownImages = n->images); + if (n->images != shownImages) + fillThumbnails(pics, shownImages = n->images, [this](int i) { emit pictureOpened(i); }, [this](int i) { emit pictureRemoved(i); }); } // The clades above n, root first; a long trail folds its middle into a "…" @@ -2323,6 +2372,7 @@ class InfoPanel : public QWidget { void searchChosen(const QString& id); void picturesDropped(const QList& images); // onto the panel: for the shown clade void pictureOpened(int index); + void pictureRemoved(int index); protected: void dragEnterEvent(QDragEnterEvent* e) override { @@ -2369,7 +2419,6 @@ class InfoPanel : public QWidget { QPushButton* up = new QPushButton; QTextBrowser* info = new QTextBrowser; QListWidget* pics = thumbnailList(); - QLabel* picsHint = new QLabel("Drop pictures here, or onto a clade in the tree; click one to view or remove it."); QStringList shownImages; QString upId, shownId, crumbsOpen; // crumbsOpen: the clade whose trail is unfolded @@ -2401,12 +2450,10 @@ class PicStrip : public QWidget { PicStrip(QDialog* dlg, const QStringList& start, std::initializer_list edits) : images(start) { auto add = new QPushButton("Add pictures…"); - auto del = new QPushButton("Remove picture"); auto hint = new QLabel("or drop or paste them here"); hint->setStyleSheet(colorCss(T.dim)); auto row = new QHBoxLayout; row->addWidget(add); - row->addWidget(del); row->addWidget(hint, 1); auto v = new QVBoxLayout(this); v->setContentsMargins(0, 0, 0, 0); @@ -2418,13 +2465,7 @@ class PicStrip : public QWidget { if (QImage img(p); !img.isNull()) imgs << img; addImages(imgs); }); - connect(del, &QPushButton::clicked, this, [this] { - if (const int i = list->currentRow(); i >= 0) { images.removeAt(i); fillThumbnails(list, images); } - }); - connect(list, &QListWidget::itemClicked, this, [this](QListWidgetItem* it) { - showPictures(this, [this] { return images; }, list->row(it), [this](int i) { images.removeAt(i); fillThumbnails(list, images); }); - }); - fillThumbnails(list, images); + refill(); // The text fields would take a dropped file as text, so drops go to the dialog. dlg->setAcceptDrops(true); dlg->installEventFilter(&hook); @@ -2438,7 +2479,12 @@ class PicStrip : public QWidget { void addImages(const QList& imgs) { for (const QImage& img : imgs) if (const QString url = imageToDataUrl(img); !url.isEmpty()) images << url; - fillThumbnails(list, images); + refill(); + } + + void refill() { + fillThumbnails(list, images, [this](int i) { showPictures(this, [this] { return images; }, i); }, + [this](int i) { images.removeAt(i); refill(); }); } private: @@ -2588,14 +2634,15 @@ class MainWindow : public QMainWindow { connect(panel, &InfoPanel::picturesDropped, this, [this](const QList& imgs) { addPictures(canvas->selId, imgs); }); connect(panel, &InfoPanel::pictureOpened, this, [this](int i) { const QString id = canvas->selId; - showPictures(this, [this, id] { const Node* n = model.find(id); return n ? n->images : QStringList(); }, i, [this, id](int k) { - Node* n = model.find(id); - if (!n || k >= n->images.size()) return; - n->images.removeAt(k); - model.commit(); - model.status = QString("Removed a picture from '%1'").arg(n->name); - updateHud(); - }); + showPictures(this, [this, id] { const Node* n = model.find(id); return n ? n->images : QStringList(); }, i); + }); + connect(panel, &InfoPanel::pictureRemoved, this, [this](int i) { + Node* n = sel(); + if (!n || i >= n->images.size()) return; + n->images.removeAt(i); + model.commit(); + model.status = QString("Removed a picture from '%1'").arg(n->name); + updateHud(); }); connect(canvas, &Canvas::doubleClicked, this, [this](const QString& id) { select(id); actEdit(); }); connect(canvas, &Canvas::contextMenu, this, [this](const QString& id, const QPoint& g) { diff --git a/web/index.html b/web/index.html index d52dbe1..42569f6 100644 --- a/web/index.html +++ b/web/index.html @@ -75,7 +75,6 @@

    Info

    Pictures

    -

    Drop pictures here, or onto a clade in the tree.

    @@ -132,16 +131,13 @@

    Export image

    - +
    -

    -
    - - - - -
    - + + + +
    +

    diff --git a/web/js/app.js b/web/js/app.js index 15ab2da..dc7c9bf 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -410,32 +410,27 @@ async function addPictures(id, files) { setStatus(`Added ${urls.length === 1 ? 'a picture' : urls.length + ' pictures'} to '${n.name}'`); } -// Thumbnails of get() in box; clicking one opens the viewer, which can remove it. +// Thumbnails of get() in box: clicking one opens the viewer, its corner x removes it. function renderPics(box, get, remove) { box.replaceChildren(); get().forEach((src, i) => { - const d = document.createElement('div'), img = document.createElement('img'); + const d = document.createElement('div'), img = document.createElement('img'), x = document.createElement('button'); d.className = 'pic'; img.src = src; img.alt = `Picture ${i + 1}`; - img.addEventListener('click', () => showPicture(get, i, remove)); - d.append(img); - box.append(d); - }); -} - -function renderEditPics() { - const remove = i => { dlgImages.splice(i, 1); renderEditPics(); }; - renderPics($('editPics'), () => dlgImages, remove); - [...$('editPics').children].forEach((d, i) => { - const x = document.createElement('button'); + img.addEventListener('click', () => showPicture(get, i)); x.type = 'button'; x.textContent = '×'; x.title = 'Remove this picture'; x.addEventListener('click', () => remove(i)); - d.append(x); + d.append(img, x); + box.append(d); }); } + +function renderEditPics() { + renderPics($('editPics'), () => dlgImages, i => { dlgImages.splice(i, 1); renderEditPics(); }); +} async function addEditPics(files) { dlgImages.push(...await readPictures(files)); renderEditPics(); @@ -471,10 +466,10 @@ for (const [el, drop] of [[$('editDlg'), files => addEditPics(files)], }); } -let picView = null; // the viewer's {get, i, remove, back}; back: the edit box it stands in for -function showPicture(get, i, remove) { +let picView = null; // the viewer's {get, i, back}; back: the edit box it stands in for +function showPicture(get, i) { const back = $('editDlg').open; - picView = { get, i, remove, back }; + picView = { get, i, back }; const d = $('picDlg'); if (back) { // take the edit box's place and size; it comes back when the viewer closes const r = $('editDlg').getBoundingClientRect(); @@ -495,17 +490,31 @@ function drawPicture() { const list = picView.get(); if (!list.length) return $('picDlg').close(); picView.i = clamp(picView.i, 0, list.length - 1); + const many = list.length > 1; $('picBig').src = list[picView.i]; - $('picCaption').textContent = `Picture ${picView.i + 1} of ${list.length}`; - $('picPrev').disabled = picView.i === 0; - $('picNext').disabled = picView.i === list.length - 1; -} + $('picCaption').textContent = many ? `${picView.i + 1} of ${list.length}` : ''; + $('picPrev').hidden = !many || picView.i === 0; + $('picNext').hidden = !many || picView.i === list.length - 1; + placePictureButtons(); +} +// The buttons sit on the picture as shown (object-fit: contain), not on its frame. +function placePictureButtons() { + const img = $('picBig'), f = $('picFrame'); + const W = f.clientWidth, H = f.clientHeight, w = img.naturalWidth, h = img.naturalHeight; + if (!w || !h) return; + const k = Math.min(W / w, H / h), x0 = (W - w * k) / 2, y0 = (H - h * k) / 2; + Object.assign($('picClose').style, { left: (x0 + w * k - 36) + 'px', top: (y0 + 6) + 'px' }); + for (const [b, x] of [[$('picPrev'), x0 + 6], [$('picNext'), x0 + w * k - 36]]) + Object.assign(b.style, { left: x + 'px', top: (y0 + h * k / 2 - 15) + 'px' }); +} +$('picBig').addEventListener('load', placePictureButtons); +addEventListener('resize', () => { if ($('picDlg').open) placePictureButtons(); }); $('picPrev').addEventListener('click', () => { --picView.i; drawPicture(); }); $('picNext').addEventListener('click', () => { ++picView.i; drawPicture(); }); -$('picRemove').addEventListener('click', () => { picView.remove(picView.i); drawPicture(); }); +$('picClose').addEventListener('click', () => $('picDlg').close()); $('picDlg').addEventListener('keydown', e => { - if (e.key === 'ArrowLeft' && !$('picPrev').disabled) { $('picPrev').click(); e.preventDefault(); } - if (e.key === 'ArrowRight' && !$('picNext').disabled) { $('picNext').click(); e.preventDefault(); } + if (e.key === 'ArrowLeft' && !$('picPrev').hidden) { $('picPrev').click(); e.preventDefault(); } + if (e.key === 'ArrowRight' && !$('picNext').hidden) { $('picNext').click(); e.preventDefault(); } }); function actCollapse() { diff --git a/web/style.css b/web/style.css index a4a506e..22015c4 100644 --- a/web/style.css +++ b/web/style.css @@ -155,19 +155,23 @@ button { cursor: pointer; } .pics:empty { display: none; } .pics .pic { position: relative; } .pics img { display: block; height: 72px; max-width: 140px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); cursor: zoom-in; background: var(--chrome-2); } -.pics .pic button { position: absolute; top: 2px; right: 2px; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; background: rgba(0,0,0,.6); color: #fff; font-size: 13px; line-height: 20px; } -.pics-hint { color: var(--dim); font-size: 12px; margin: 4px 0 0; } +/* remove: a little white x in a little black circle in the corner */ +.pics .pic button { position: absolute; top: 3px; right: 3px; width: 18px; height: 18px; padding: 0; border: 0; border-radius: 50%; background: #000; color: #fff; font-size: 13px; line-height: 18px; } .panel.drop-target { outline: 2px dashed var(--accent); outline-offset: -6px; } .edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } .edit-pics-row .pics { width: 100%; } #editDlg.drop-target { outline: 2px dashed var(--accent); } /* the picture viewer is the size of the edit box, whose place it takes when opened from it */ -.pic-dlg { width: min(560px, calc(100vw - 24px)); height: min(520px, calc(100vh - 32px)); } -.pic-dlg form { height: 100%; gap: 8px; } -.pic-dlg img { flex: 1; min-height: 0; width: 100%; object-fit: contain; border-radius: 6px; } +.pic-dlg { width: min(560px, calc(100vw - 24px)); height: min(520px, calc(100vh - 32px)); padding: 12px; } +.pic-dlg[open] { display: flex; flex-direction: column; gap: 6px; } +.pic-frame { position: relative; flex: 1; min-height: 0; } +#picBig { display: block; width: 100%; height: 100%; object-fit: contain; } +/* close and arrows: a black mark in a translucent grey circle, placed on the picture itself */ +.pic-btn { position: absolute; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%; + background: rgba(128, 128, 128, .55); color: #000; font-size: 22px; line-height: 30px; } +.pic-btn:hover { background: rgba(160, 160, 160, .8); } .pic-dlg .dlg-hint { text-align: center; } -.pic-dlg .dlg-buttons { margin: 0; } -.dlg-buttons button.danger-text { color: var(--danger); } +.pic-dlg .dlg-hint:empty { display: none; } /* ---- popup menus */ .menu-pop { From c7349706878d98f3256f531852b76ef5d4618ea7 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:19:19 +0000 Subject: [PATCH 08/17] Show the edit box's pictures as a one-row sideways carousel In the edit and add boxes the pictures are now a single row that scrolls sideways, with a scroll bar, a horizontal swipe, or an ordinary mouse wheel. Adding a picture scrolls to it. The side panel keeps its rows. --- main.cpp | 33 ++++++++++++++++++++++++++++++--- web/js/app.js | 13 ++++++++++++- web/style.css | 3 +++ 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/main.cpp b/main.cpp index d66c59a..d99be0f 100644 --- a/main.cpp +++ b/main.cpp @@ -2090,11 +2090,26 @@ static QList imagesFromMime(const QMimeData* m) { } // A row of thumbnails; clicking one opens it. -static QListWidget* thumbnailList() { +// carousel: one row that scrolls sideways (also with an ordinary mouse wheel). +static QListWidget* thumbnailList(bool carousel = false) { auto list = new QListWidget; list->setViewMode(QListView::IconMode); list->setFlow(QListView::LeftToRight); - list->setWrapping(true); + list->setWrapping(!carousel); + list->setProperty("carousel", carousel); + if (carousel) { + list->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + list->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + auto wheel = new EventHook([list](QObject*, QEvent* e) { + if (e->type() != QEvent::Wheel) return false; + const QPoint d = static_cast(e)->angleDelta(); + if (d.x() || !d.y()) return false; + list->horizontalScrollBar()->setValue(list->horizontalScrollBar()->value() - d.y()); + return true; + }); + wheel->setParent(list); + list->viewport()->installEventFilter(wheel); + } list->setResizeMode(QListView::Adjust); list->setMovement(QListView::Static); list->setSelectionMode(QAbstractItemView::NoSelection); @@ -2146,6 +2161,10 @@ static void fillThumbnails(QListWidget* list, const QStringList& images, // Tall enough for the rows the thumbnails fill at the current width, up to // two; beyond that the list scrolls. const int cellW = W + 2 * PAD + 2 * list->spacing(), cellH = H + 2 * PAD + 2 * list->spacing(); + if (list->property("carousel").toBool()) { // one row, plus room for its scroll bar + list->setFixedHeight(cellH + list->horizontalScrollBar()->sizeHint().height() + 2 * list->frameWidth() + 4); + return; + } const int perRow = std::max(1, (list->width() - 2 * list->frameWidth()) / cellW); const int rows = std::min(2, int(images.size() + perRow - 1) / perRow); list->setFixedHeight(rows * cellH + 2 * list->frameWidth() + 4); @@ -2466,6 +2485,9 @@ class PicStrip : public QWidget { addImages(imgs); }); refill(); + connect(list->horizontalScrollBar(), &QScrollBar::rangeChanged, this, [this](int, int max) { + if (toEnd) list->horizontalScrollBar()->setValue(max); + }); // The text fields would take a dropped file as text, so drops go to the dialog. dlg->setAcceptDrops(true); dlg->installEventFilter(&hook); @@ -2479,7 +2501,11 @@ class PicStrip : public QWidget { void addImages(const QList& imgs) { for (const QImage& img : imgs) if (const QString url = imageToDataUrl(img); !url.isEmpty()) images << url; + // Show what was just added: the row is laid out again in steps, so follow + // its end for a moment. + toEnd = true; refill(); + QTimer::singleShot(300, this, [this] { toEnd = false; }); } void refill() { @@ -2488,7 +2514,8 @@ class PicStrip : public QWidget { } private: - QListWidget* list = thumbnailList(); + QListWidget* list = thumbnailList(true); + bool toEnd = false; QDialog* dlg = nullptr; EventHook hook{[this](QObject* o, QEvent* e) { switch (e->type()) { diff --git a/web/js/app.js b/web/js/app.js index dc7c9bf..78e8d1d 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -434,7 +434,18 @@ function renderEditPics() { async function addEditPics(files) { dlgImages.push(...await readPictures(files)); renderEditPics(); -} + // show what was just added, once its thumbnail has loaded and the row its full width + const box = $('editPics'), last = box.lastElementChild?.querySelector('img'); + const toEnd = () => { box.scrollLeft = box.scrollWidth; }; + toEnd(); + last?.addEventListener('load', toEnd, { once: true }); +} +// An ordinary mouse wheel scrolls the row sideways. +$('editPics').addEventListener('wheel', e => { + if (e.deltaX || !e.deltaY || e.ctrlKey) return; + e.preventDefault(); + $('editPics').scrollLeft += e.deltaY * (e.deltaMode === 1 ? 40 : 1); +}, { passive: false }); $('editAddPics').addEventListener('click', () => { $('picInput').onchange = () => addEditPics([...$('picInput').files]); $('picInput').value = ''; $('picInput').click(); }); $('editDlg').addEventListener('paste', e => { const files = imageFiles(e.clipboardData); diff --git a/web/style.css b/web/style.css index 22015c4..4e87ef2 100644 --- a/web/style.css +++ b/web/style.css @@ -160,6 +160,9 @@ button { cursor: pointer; } .panel.drop-target { outline: 2px dashed var(--accent); outline-offset: -6px; } .edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } .edit-pics-row .pics { width: 100%; } +/* the edit box shows its pictures as one row that scrolls sideways */ +#editPics { flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scroll-snap-type: x proximity; padding-bottom: 4px; } +#editPics .pic { flex: none; scroll-snap-align: start; } #editDlg.drop-target { outline: 2px dashed var(--accent); } /* the picture viewer is the size of the edit box, whose place it takes when opened from it */ .pic-dlg { width: min(560px, calc(100vw - 24px)); height: min(520px, calc(100vh - 32px)); padding: 12px; } From 2991200ba9bcbead2c332b3e4021488758ba96c8 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:25:47 +0000 Subject: [PATCH 09/17] Add arrow buttons to the edit box's picture carousel Small grey round arrows sit on the middle of the carousel's left and right edges. Each shows only while the row can scroll its way, and moves it by one picture, lining the next (or previous) picture up with the start. --- main.cpp | 69 +++++++++++++++++++++++++++++++++++++++++--------- web/index.html | 6 ++++- web/js/app.js | 21 ++++++++++++++- web/style.css | 9 ++++++- 4 files changed, 90 insertions(+), 15 deletions(-) diff --git a/main.cpp b/main.cpp index d99be0f..c3a20d6 100644 --- a/main.cpp +++ b/main.cpp @@ -2090,6 +2090,18 @@ static QList imagesFromMime(const QMimeData* m) { } // A row of thumbnails; clicking one opens it. +// A round mark in a corner: a little white x in a black circle on thumbnails, +// a larger black mark in a translucent grey circle in the viewer. +static QToolButton* roundButton(QWidget* parent, const QString& text, int size, const char* colours) { + auto b = new QToolButton(parent); + b->setText(text); + b->setFixedSize(size, size); + b->setCursor(Qt::PointingHandCursor); + b->setStyleSheet(QString("QToolButton { %1 border: none; border-radius: %2px; padding: 0; font-size: %3px; font-weight: bold; }") + .arg(colours).arg(size / 2).arg(size * 2 / 3)); + return b; +} + // carousel: one row that scrolls sideways (also with an ordinary mouse wheel). static QListWidget* thumbnailList(bool carousel = false) { auto list = new QListWidget; @@ -2109,6 +2121,51 @@ static QListWidget* thumbnailList(bool carousel = false) { }); wheel->setParent(list); list->viewport()->installEventFilter(wheel); + // Arrows on the middle of each edge, shown while the row can scroll that + // way; each moves it by one picture, lining the next (or previous) one up + // with the start. + const char* grey = "background: rgba(128, 128, 128, 160); color: black;"; + QToolButton* back = roundButton(list, "‹", 24, grey); + QToolButton* next = roundButton(list, "›", 24, grey); + back->setToolTip("Previous picture"); + next->setToolTip("Next picture"); + QScrollBar* bar = list->horizontalScrollBar(); + auto place = [list, back, next, bar] { + const QRect v = list->viewport()->geometry(); + const int y = v.top() + (v.height() - back->height()) / 2; + back->move(v.left() + 4, y); + next->move(v.right() - 3 - next->width(), y); + back->setVisible(bar->value() > bar->minimum()); + next->setVisible(bar->value() < bar->maximum()); + back->raise(); + next->raise(); + }; + QObject::connect(bar, &QScrollBar::valueChanged, list, place); + QObject::connect(bar, &QScrollBar::rangeChanged, list, place); + auto resized = new EventHook([place](QObject*, QEvent* e) { + if (e->type() == QEvent::Resize || e->type() == QEvent::Show) place(); + return false; + }); + resized->setParent(list); + list->installEventFilter(resized); + auto step = [list, bar](int dir) { + // A picture lined up with the row's start is at x = 0 (the first one at + // the spacing, before anything has scrolled). + const int pad = list->spacing(); + int to = dir > 0 ? bar->maximum() : bar->minimum(); + for (int i = 0; i < list->count(); ++i) { + const int x = list->visualItemRect(list->item(i)).left(); + if (dir > 0 && x > pad + 1) { to = bar->value() + x; break; } + if (dir < 0 && x < -1) to = bar->value() + x; + } + if (to <= pad) to = bar->minimum(); + auto anim = new QPropertyAnimation(bar, "value", bar); + anim->setDuration(180); + anim->setEndValue(std::clamp(to, bar->minimum(), bar->maximum())); + anim->start(QAbstractAnimation::DeleteWhenStopped); + }; + QObject::connect(back, &QToolButton::clicked, list, [step] { step(-1); }); + QObject::connect(next, &QToolButton::clicked, list, [step] { step(1); }); } list->setResizeMode(QListView::Adjust); list->setMovement(QListView::Static); @@ -2117,18 +2174,6 @@ static QListWidget* thumbnailList(bool carousel = false) { return list; } -// A round mark in a corner: a little white x in a black circle on thumbnails, -// a larger black mark in a translucent grey circle in the viewer. -static QToolButton* roundButton(QWidget* parent, const QString& text, int size, const char* colours) { - auto b = new QToolButton(parent); - b->setText(text); - b->setFixedSize(size, size); - b->setCursor(Qt::PointingHandCursor); - b->setStyleSheet(QString("QToolButton { %1 border: none; border-radius: %2px; padding: 0; font-size: %3px; font-weight: bold; }") - .arg(colours).arg(size / 2).arg(size * 2 / 3)); - return b; -} - // Thumbnails of `images`: clicking one calls open(i), its corner x remove(i). static void fillThumbnails(QListWidget* list, const QStringList& images, const std::function& open, const std::function& remove) { diff --git a/web/index.html b/web/index.html index 42569f6..1a9203f 100644 --- a/web/index.html +++ b/web/index.html @@ -90,7 +90,11 @@

    Edit clade

    -
    + or drop or paste them here
    diff --git a/web/js/app.js b/web/js/app.js index 78e8d1d..f58ee3e 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -293,6 +293,7 @@ function openEditDialog({ title, name = '', info = '', images = [], withInfo = t $('editSister').hidden = $('editDaughter').hidden = !rapid; $('editOk').textContent = rapid ? 'Add' : 'OK'; dlg.showModal(); + updateCarousel(); // its size is known only now $('editName').focus(); $('editName').select(); return new Promise(res => { dlgResolve = res; }); @@ -430,7 +431,25 @@ function renderPics(box, get, remove) { function renderEditPics() { renderPics($('editPics'), () => dlgImages, i => { dlgImages.splice(i, 1); renderEditPics(); }); -} + for (const img of $('editPics').querySelectorAll('img')) img.addEventListener('load', updateCarousel, { once: true }); + updateCarousel(); +} +// The carousel's arrows show only while it can scroll their way; each moves it +// by one picture, lining the next (or previous) one up with the start. +function updateCarousel() { + const b = $('editPics'), max = b.scrollWidth - b.clientWidth; + $('carBack').hidden = b.scrollLeft <= 1; + $('carNext').hidden = b.scrollLeft >= max - 1; +} +function stepCarousel(dir) { + const b = $('editPics'), at = b.scrollLeft, starts = [...b.children].map(c => c.offsetLeft); + const to = dir > 0 ? starts.find(x => x > at + 1) : starts.filter(x => x < at - 1).at(-1); + b.scrollTo({ left: to ?? (dir > 0 ? b.scrollWidth : 0), behavior: 'smooth' }); +} +$('editPics').addEventListener('scroll', updateCarousel); +addEventListener('resize', () => { if ($('editDlg').open) updateCarousel(); }); +$('carBack').addEventListener('click', () => stepCarousel(-1)); +$('carNext').addEventListener('click', () => stepCarousel(1)); async function addEditPics(files) { dlgImages.push(...await readPictures(files)); renderEditPics(); diff --git a/web/style.css b/web/style.css index 4e87ef2..cbb6c9a 100644 --- a/web/style.css +++ b/web/style.css @@ -161,7 +161,14 @@ button { cursor: pointer; } .edit-pics-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } .edit-pics-row .pics { width: 100%; } /* the edit box shows its pictures as one row that scrolls sideways */ -#editPics { flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scroll-snap-type: x proximity; padding-bottom: 4px; } +.edit-pics-row .carousel { position: relative; width: 100%; } +#editPics { position: relative; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scroll-snap-type: x proximity; padding-bottom: 4px; } +/* arrows on the middle of each edge, shown while the row can scroll that way */ +.car-btn { position: absolute; top: calc(50% - 14px); width: 24px; height: 24px; padding: 0; border: 0; border-radius: 50%; + background: rgba(128, 128, 128, .6); color: #000; font-size: 18px; line-height: 24px; } +.car-btn:hover { background: rgba(160, 160, 160, .85); } +.car-btn.back { left: 4px; } +.car-btn.next { right: 4px; } #editPics .pic { flex: none; scroll-snap-align: start; } #editDlg.drop-target { outline: 2px dashed var(--accent); } /* the picture viewer is the size of the edit box, whose place it takes when opened from it */ From 92b58a48bf623f2a810e9f54b6f5210f73669b48 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:30:23 +0000 Subject: [PATCH 10/17] Fix the build with newer Qt: keep the click filter's pointer Recent Qt versions refuse QObject::findChild on classes without Q_OBJECT. The thumbnail's click filter was looked up again with findChild only to install it; keep the pointer instead. --- main.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/main.cpp b/main.cpp index c3a20d6..51ef999 100644 --- a/main.cpp +++ b/main.cpp @@ -2189,12 +2189,13 @@ static void fillThumbnails(QListWidget* list, const QStringList& images, pic->setGeometry(PAD + (W - px.width()) / 2, PAD + (H - px.height()) / 2, px.width(), px.height()); pic->setCursor(Qt::PointingHandCursor); pic->setToolTip("View this picture"); - (new EventHook([open, i](QObject*, QEvent* e) { + auto click = new EventHook([open, i](QObject*, QEvent* e) { if (e->type() != QEvent::MouseButtonRelease || static_cast(e)->button() != Qt::LeftButton) return false; open(i); return true; - }))->setParent(pic); - pic->installEventFilter(pic->findChild()); + }); + click->setParent(pic); + pic->installEventFilter(click); QToolButton* x = roundButton(cell, "×", X, "background: black; color: white;"); x->setToolTip("Remove this picture"); x->move(pic->geometry().right() - X - 1, pic->geometry().top() + 3); From 7e11a4aede6e867f0fbbd08bad4d188dfbbae423 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:39:26 +0000 Subject: [PATCH 11/17] Make the picture viewer 1.5 times the edit box's area The viewer is now about 1.22 times the edit box's width and height, centred on it, and kept within the window or screen. Opened from the side panel it is 1.5 times the area of a standard edit box. --- main.cpp | 20 ++++++++++++++++---- web/js/app.js | 9 +++++---- web/style.css | 3 ++- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/main.cpp b/main.cpp index 51ef999..f048107 100644 --- a/main.cpp +++ b/main.cpp @@ -45,6 +45,7 @@ constexpr int CONFIRM_DELETE_OVER = 30; // ask before deleting more clades than // 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 @@ -2273,10 +2274,21 @@ static void showPictures(QWidget* parent, const std::function& ge QObject::connect(new QShortcut(Qt::Key_Left, &dlg), &QShortcut::activated, &dlg, [&] { if (prev->isVisible()) prev->click(); }); QObject::connect(new QShortcut(Qt::Key_Right, &dlg), &QShortcut::activated, &dlg, [&] { if (next->isVisible()) next->click(); }); draw(); - // The size of the edit box; opened from one, it sits exactly over it (hiding - // it would end its edit), so closing the viewer brings the edit box back. - if (auto box = qobject_cast(parent->window())) dlg.setGeometry(box->geometry()); - else dlg.resize(560, 420); + // 1.5 times the edit box's area, centred on it: opened from one, it covers it + // (hiding it would end its edit), so closing the viewer brings the edit box + // back. Kept within the screen. + const double k = std::sqrt(PIC_AREA); + auto box = qobject_cast(parent->window()); + const QRect from = box ? box->geometry() : QRect(QPoint(), QSize(560, 420)).translated(parent->window()->geometry().center() - QPoint(280, 210)); + QRect r(QPoint(), (QSizeF(from.size()) * k).toSize()); + r.moveCenter(from.center()); + if (QScreen* sc = parent->screen()) { + const QRect avail = sc->availableGeometry(); + r.setSize(r.size().boundedTo(avail.size())); + r.moveLeft(std::clamp(r.left(), avail.left(), avail.right() - r.width() + 1)); + r.moveTop(std::clamp(r.top(), avail.top(), avail.bottom() - r.height() + 1)); + } + dlg.setGeometry(r); dlg.exec(); } diff --git a/web/js/app.js b/web/js/app.js index f58ee3e..40f2a73 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -496,15 +496,16 @@ for (const [el, drop] of [[$('editDlg'), files => addEditPics(files)], }); } +const PIC_AREA = 1.5; // the viewer's area, as a multiple of the edit box's let picView = null; // the viewer's {get, i, back}; back: the edit box it stands in for function showPicture(get, i) { const back = $('editDlg').open; picView = { get, i, back }; const d = $('picDlg'); - if (back) { // take the edit box's place and size; it comes back when the viewer closes - const r = $('editDlg').getBoundingClientRect(); - d.style.width = r.width + 'px'; - d.style.height = r.height + 'px'; + if (back) { // take the edit box's place at 1.5 times its area; it comes back when the viewer closes + const r = $('editDlg').getBoundingClientRect(), k = Math.sqrt(PIC_AREA); + d.style.width = r.width * k + 'px'; + d.style.height = r.height * k + 'px'; $('editDlg').close(); } else d.style.width = d.style.height = ''; drawPicture(); diff --git a/web/style.css b/web/style.css index cbb6c9a..3460edb 100644 --- a/web/style.css +++ b/web/style.css @@ -172,7 +172,8 @@ button { cursor: pointer; } #editPics .pic { flex: none; scroll-snap-align: start; } #editDlg.drop-target { outline: 2px dashed var(--accent); } /* the picture viewer is the size of the edit box, whose place it takes when opened from it */ -.pic-dlg { width: min(560px, calc(100vw - 24px)); height: min(520px, calc(100vh - 32px)); padding: 12px; } +/* 1.5 times the edit box's area (1.2247 = the square root of 1.5), within the window */ +.pic-dlg { width: min(686px, calc(100vw - 24px)); height: min(637px, calc(100vh - 32px)); max-width: calc(100vw - 24px); max-height: calc(100vh - 32px); padding: 12px; } .pic-dlg[open] { display: flex; flex-direction: column; gap: 6px; } .pic-frame { position: relative; flex: 1; min-height: 0; } #picBig { display: block; width: 100%; height: 100%; object-fit: contain; } From 5bea51199b14be0b588e9c0ddd116e5bf2d3068c Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:48:19 +0000 Subject: [PATCH 12/17] Put the picture viewer's close button on the box's corner --- main.cpp | 7 ++++--- web/index.html | 2 +- web/js/app.js | 3 +-- web/style.css | 1 + 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/main.cpp b/main.cpp index f048107..e05a5f5 100644 --- a/main.cpp +++ b/main.cpp @@ -2231,7 +2231,7 @@ static void showPictures(QWidget* parent, const std::function& ge caption->setAlignment(Qt::AlignCenter); caption->setStyleSheet(colorCss(T.dim)); const char* grey = "background: rgba(128, 128, 128, 140); color: black;"; - QToolButton* close = roundButton(img, "×", 30, grey); + QToolButton* close = roundButton(&dlg, "×", 30, grey); // on the box's corner QToolButton* prev = roundButton(img, "‹", 30, grey); QToolButton* next = roundButton(img, "›", 30, grey); close->setToolTip("Close (Esc)"); @@ -2242,7 +2242,7 @@ static void showPictures(QWidget* parent, const std::function& ge v->addWidget(caption); int i = start; QPixmap px; - auto fit = [&] { // the picture as large as the window allows, its buttons on it + auto fit = [&] { // the picture as large as the window allows, its arrows on it if (px.isNull()) return; const double dpr = img->devicePixelRatioF(); QPixmap shown = px.scaled(img->size() * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); @@ -2250,7 +2250,8 @@ static void showPictures(QWidget* parent, const std::function& ge img->setPixmap(shown); const QSizeF s = shown.deviceIndependentSize(); const double x0 = (img->width() - s.width()) / 2, y0 = (img->height() - s.height()) / 2; - close->move(int(x0 + s.width() - 36), int(y0 + 6)); + close->move(dlg.width() - close->width() - 6, 6); + close->raise(); prev->move(int(x0 + 6), int(y0 + s.height() / 2 - 15)); next->move(int(x0 + s.width() - 36), int(y0 + s.height() / 2 - 15)); }; diff --git a/web/index.html b/web/index.html index 1a9203f..16aa090 100644 --- a/web/index.html +++ b/web/index.html @@ -139,9 +139,9 @@

    Export image

    -

    + diff --git a/web/js/app.js b/web/js/app.js index 40f2a73..7e440e4 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -528,13 +528,12 @@ function drawPicture() { $('picNext').hidden = !many || picView.i === list.length - 1; placePictureButtons(); } -// The buttons sit on the picture as shown (object-fit: contain), not on its frame. +// The arrows sit on the picture as shown (object-fit: contain), not on its frame. function placePictureButtons() { const img = $('picBig'), f = $('picFrame'); const W = f.clientWidth, H = f.clientHeight, w = img.naturalWidth, h = img.naturalHeight; if (!w || !h) return; const k = Math.min(W / w, H / h), x0 = (W - w * k) / 2, y0 = (H - h * k) / 2; - Object.assign($('picClose').style, { left: (x0 + w * k - 36) + 'px', top: (y0 + 6) + 'px' }); for (const [b, x] of [[$('picPrev'), x0 + 6], [$('picNext'), x0 + w * k - 36]]) Object.assign(b.style, { left: x + 'px', top: (y0 + h * k / 2 - 15) + 'px' }); } diff --git a/web/style.css b/web/style.css index 3460edb..c329233 100644 --- a/web/style.css +++ b/web/style.css @@ -181,6 +181,7 @@ button { cursor: pointer; } .pic-btn { position: absolute; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%; background: rgba(128, 128, 128, .55); color: #000; font-size: 22px; line-height: 30px; } .pic-btn:hover { background: rgba(160, 160, 160, .8); } +.pic-close { top: 6px; right: 6px; z-index: 1; } /* on the box's corner */ .pic-dlg .dlg-hint { text-align: center; } .pic-dlg .dlg-hint:empty { display: none; } From 90b7eba9411f96fcb81bbe0ae0f96a9db0e1faf0 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:53:20 +0000 Subject: [PATCH 13/17] Close boxes one at a time by clicking outside them --- main.cpp | 71 +++++++++++++++++++++++++++++++++++++++++---------- web/js/app.js | 18 ++++++++++++- 2 files changed, 75 insertions(+), 14 deletions(-) diff --git a/main.cpp b/main.cpp index e05a5f5..e856ebc 100644 --- a/main.cpp +++ b/main.cpp @@ -2045,6 +2045,48 @@ class EventHook : public QObject { std::function f_; }; +// QDialog::exec(), except that a click outside the box closes it as Esc would, +// one box per click: a box opened from another closes first. Qt drops clicks on +// windows a modal box blocks, so the box is shown non-modal and keeps input from +// the other windows itself. +static int runBox(QDialog& d) { + static QList open; + auto inside = [&d](QWidget* w) { + for (; w; w = w->parentWidget()) + if (w == &d) return true; + return false; + }; + EventHook hook([&](QObject* o, QEvent* e) { + if (open.isEmpty() || open.last() != &d || !o->isWidgetType()) return false; + switch (e->type()) { + case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: + case QEvent::MouseMove: case QEvent::Wheel: case QEvent::KeyPress: case QEvent::KeyRelease: + case QEvent::ShortcutOverride: case QEvent::ContextMenu: case QEvent::DragEnter: case QEvent::Drop: + break; + default: + return false; + } + if (QApplication::activePopupWidget() || inside(static_cast(o))) return false; + if (e->type() == QEvent::MouseButtonPress) { + QKeyEvent esc(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); + QCoreApplication::sendEvent(&d, &esc); + } + return true; // the rest of the app waits for the box, as with exec() + }); + d.setModal(false); + open.append(&d); + qApp->installEventFilter(&hook); + QEventLoop loop; + QObject::connect(&d, &QDialog::finished, &loop, &QEventLoop::quit); + d.show(); + d.activateWindow(); + if (d.isVisible()) loop.exec(QEventLoop::DialogExec); + qApp->removeEventFilter(&hook); + open.removeAll(&d); + if (!open.isEmpty()) open.last()->activateWindow(); + return d.result(); +} + // ----------------------------------------------------------- pictures --- // Pictures are kept in the file with the notes, so they are scaled to at most // IMAGE_MAX_SIDE px and stored as JPEG, or as PNG when they have transparency. @@ -2290,7 +2332,7 @@ static void showPictures(QWidget* parent, const std::function& ge r.moveTop(std::clamp(r.top(), avail.top(), avail.bottom() - r.height() + 1)); } dlg.setGeometry(r); - dlg.exec(); + runBox(dlg); } // --------------------------------------------------------- info panel --- @@ -2765,7 +2807,7 @@ class MainWindow : public QMainWindow { auto bNew = box.addButton("New…", QMessageBox::AcceptRole); auto bSample = box.addButton("New from sample…", QMessageBox::AcceptRole); box.addButton(QMessageBox::Cancel); - box.exec(); + runBox(box); if (box.clickedButton() == bOpen) fileOpen(); else if (box.clickedButton() == bNew) fileNew(); else if (box.clickedButton() == bSample) fileNew(true); @@ -2956,10 +2998,12 @@ class MainWindow : public QMainWindow { if (p.isEmpty()) return; std::unique_ptr tree = sample ? sampleTree() : nullptr; if (!tree) { - bool ok; - const QString name = QInputDialog::getText(this, "New cladogram", "Name of the root clade:", - QLineEdit::Normal, "Root", &ok).trimmed(); - if (!ok) return; + QInputDialog in(this); + in.setWindowTitle("New cladogram"); + in.setLabelText("Name of the root clade:"); + in.setTextValue("Root"); + if (runBox(in) != QDialog::Accepted) return; + const QString name = in.textValue().trimmed(); tree = Node::make(name.isEmpty() ? "Root" : name); } switched(model.create(p, std::move(tree)), "Cannot create file"); @@ -3031,7 +3075,7 @@ class MainWindow : public QMainWindow { bool toClipboard = false; connect(copy, &QPushButton::clicked, &dlg, [&] { toClipboard = true; dlg.accept(); }); showInfo(); - if (dlg.exec() != QDialog::Accepted || !model.isOpen()) return; + if (runBox(dlg) != QDialog::Accepted || !model.isOpen()) return; const bool whole = area->checkedId() == 1, svg = format->checkedId() == 1 && !toClipboard; const double factor = factors[scale->checkedId()]; @@ -3234,7 +3278,7 @@ class MainWindow : public QMainWindow { connect(list, &QTreeWidget::itemClicked, &dlg, [&](QTreeWidgetItem* it) { choose(it); }); fill(); input->setFocus(); - if (dlg.exec() == QDialog::Accepted && chosen) chosen->trigger(); + if (runBox(dlg) == QDialog::Accepted && chosen) chosen->trigger(); } // ---- clade actions @@ -3309,7 +3353,7 @@ class MainWindow : public QMainWindow { for (auto seq : {QKeySequence("Ctrl+Return"), QKeySequence("Ctrl+Enter")}) connect(new QShortcut(seq, &dlg), &QShortcut::activated, &dlg, [&] { finish(Next::Done); }); nameEdit->setFocus(); - if (dlg.exec() != QDialog::Accepted) return std::nullopt; + if (runBox(dlg) != QDialog::Accepted) return std::nullopt; return NewClade{nameEdit->text().trimmed(), infoEdit->toPlainText(), pics->images, next}; } @@ -3367,8 +3411,9 @@ class MainWindow : public QMainWindow { m.addSeparator(); m.addAction("Custom colour…", this, [this, set, id] { const Node* cur = model.find(id); - const QColor c = QColorDialog::getColor(QColor(cur && !cur->color.isEmpty() ? cur->color : "#4f8fe0"), this, "Clade colour"); - if (c.isValid()) set(c.name()); + QColorDialog cd(QColor(cur && !cur->color.isEmpty() ? cur->color : "#4f8fe0"), this); + cd.setWindowTitle("Clade colour"); + if (runBox(cd) == QDialog::Accepted && cd.selectedColor().isValid()) set(cd.selectedColor().name()); }); QAction* inherit = m.addAction(n->parent ? "Same as mother clade" : "Default colours", this, [set] { set({}); }); inherit->setCheckable(true); @@ -3414,7 +3459,7 @@ class MainWindow : public QMainWindow { for (auto seq : {QKeySequence("Ctrl+Return"), QKeySequence("Ctrl+Enter")}) connect(new QShortcut(seq, &dlg), &QShortcut::activated, &dlg, acceptIfValid); nameEdit->setFocus(); - if (dlg.exec() != QDialog::Accepted || !(n = model.find(id))) return; + if (runBox(dlg) != QDialog::Accepted || !(n = model.find(id))) return; const QString newName = nameEdit->text().trimmed(), newInfo = infoEdit->toPlainText(); if (newName.isEmpty() || (newName == n->name && newInfo == n->info && pics->images == n->images)) return; @@ -3442,7 +3487,7 @@ class MainWindow : public QMainWindow { .arg(inside + 1).arg(n->name).arg(inside)); QPushButton* del = box.addButton("Delete", QMessageBox::DestructiveRole); box.setDefaultButton(QMessageBox::Cancel); - box.exec(); + runBox(box); if (box.clickedButton() != del || !(n = model.find(id))) return; } const QString parentId = n->parent ? n->parent->id : QString(); diff --git a/web/js/app.js b/web/js/app.js index 7e440e4..5ffc46c 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -1272,7 +1272,23 @@ $('paletteInput').addEventListener('keydown', e => { else if (e.key === 'Enter') { e.preventDefault(); if (palShown[palCur] && !palShown[palCur].it.disabled) runPaletteItem(palShown[palCur].it); } }); $('paletteForm').addEventListener('submit', e => e.preventDefault()); -$('paletteDlg').addEventListener('click', e => { if (e.target === $('paletteDlg')) $('paletteDlg').close(); }); // backdrop + +// A click outside a box closes it as Esc would, one box per click (the picture +// viewer gives way to the Edit box it came from). Both the press and the release +// must be outside, so a drag that strays off the box does not close it. +const outside = (d, e) => { + const r = d.getBoundingClientRect(); + return e.target === d && (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom); +}; +for (const d of document.querySelectorAll('dialog')) { + let pressed = false; + d.addEventListener('pointerdown', e => { pressed = outside(d, e); }); + d.addEventListener('click', e => { + if (!pressed || !outside(d, e)) return; + pressed = false; + if (d.dispatchEvent(new Event('cancel', { cancelable: true }))) d.close(); + }); +} // ---------------------------------------------------------------- keyboard addEventListener('keydown', e => { From a6c570f20e96894018027c783291e15006b81d7d Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:03:32 +0000 Subject: [PATCH 14/17] Catch clicks outside a box at the window, including touch and pen --- main.cpp | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/main.cpp b/main.cpp index e856ebc..767daa9 100644 --- a/main.cpp +++ b/main.cpp @@ -2051,23 +2051,36 @@ class EventHook : public QObject { // the other windows itself. static int runBox(QDialog& d) { static QList open; - auto inside = [&d](QWidget* w) { + auto inside = [&d](QObject* o) { + // Input reaches a window before its widgets, so it is caught there first. + QWidget* w = o->isWidgetType() ? static_cast(o) : nullptr; + if (auto win = qobject_cast(o)) + for (QWidget* t : QApplication::topLevelWidgets()) + if (t->windowHandle() == win) w = t; + if (!w) return true; // not a window or widget: let it be for (; w; w = w->parentWidget()) if (w == &d) return true; return false; }; EventHook hook([&](QObject* o, QEvent* e) { - if (open.isEmpty() || open.last() != &d || !o->isWidgetType()) return false; - switch (e->type()) { + if (open.isEmpty() || open.last() != &d) return false; + const QEvent::Type t = e->type(); + switch (t) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::Wheel: case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::ShortcutOverride: case QEvent::ContextMenu: case QEvent::DragEnter: case QEvent::Drop: + case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: + case QEvent::TabletPress: case QEvent::TabletMove: case QEvent::TabletRelease: break; default: return false; } - if (QApplication::activePopupWidget() || inside(static_cast(o))) return false; - if (e->type() == QEvent::MouseButtonPress) { + if (QApplication::activePopupWidget() || inside(o)) return false; + // A touch or pen press also arrives again as a mouse press: one close for both. + static QElapsedTimer last; + if ((t == QEvent::MouseButtonPress || t == QEvent::TouchBegin || t == QEvent::TabletPress) + && (!last.isValid() || last.elapsed() > 50)) { + last.start(); QKeyEvent esc(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); QCoreApplication::sendEvent(&d, &esc); } From c3c60abcb90e0f9e27da08640cf24e1726978853 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:09:35 +0000 Subject: [PATCH 15/17] Close the box directly on an outside click, not with a synthetic Esc --- main.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index 767daa9..ed8fd38 100644 --- a/main.cpp +++ b/main.cpp @@ -2081,8 +2081,11 @@ static int runBox(QDialog& d) { if ((t == QEvent::MouseButtonPress || t == QEvent::TouchBegin || t == QEvent::TabletPress) && (!last.isValid() || last.elapsed() > 50)) { last.start(); - QKeyEvent esc(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); - QCoreApplication::sendEvent(&d, &esc); + // What Esc does, done directly: a key sent to a box that is not the + // active window (as under dwm) would go on to the main window. + auto mb = qobject_cast(&d); + if (mb && mb->escapeButton()) mb->escapeButton()->click(); + else d.reject(); } return true; // the rest of the app waits for the box, as with exec() }); From a2ff3dc7c006d119e831809e2bc0738e5eae2cc4 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:11:43 +0000 Subject: [PATCH 16/17] Keep the main window open while a box is, as a modal box did --- main.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/main.cpp b/main.cpp index ed8fd38..3169d2f 100644 --- a/main.cpp +++ b/main.cpp @@ -2065,6 +2065,8 @@ static int runBox(QDialog& d) { EventHook hook([&](QObject* o, QEvent* e) { if (open.isEmpty() || open.last() != &d) return false; const QEvent::Type t = e->type(); + if (t == QEvent::Close) // the window manager closing the main window, say + return e->spontaneous() && !inside(o); switch (t) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::Wheel: case QEvent::KeyPress: case QEvent::KeyRelease: From 667c4d9ff0ced884486850dc916dbdc0c3be83d1 Mon Sep 17 00:00:00 2001 From: Doc <62248488+DocRountree@users.noreply.github.com> Date: Thu, 22 Oct 2026 22:15:37 +0000 Subject: [PATCH 17/17] Closing the main window cancels any open boxes, then closes --- main.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index 3169d2f..61ed43f 100644 --- a/main.cpp +++ b/main.cpp @@ -2065,8 +2065,18 @@ static int runBox(QDialog& d) { EventHook hook([&](QObject* o, QEvent* e) { if (open.isEmpty() || open.last() != &d) return false; const QEvent::Type t = e->type(); - if (t == QEvent::Close) // the window manager closing the main window, say - return e->spontaneous() && !inside(o); + if (t == QEvent::Close) { + // Closing the main window from its title bar: every box is cancelled, + // as with Esc, and the window closes once they are gone. + if (!e->spontaneous() || inside(o)) return false; + for (QDialog* b : QList(open)) b->reject(); + QPointer win(o); + QTimer::singleShot(0, qApp, [win] { + if (auto w = qobject_cast(win.data())) w->close(); + else if (auto w = qobject_cast(win.data())) w->close(); + }); + return true; + } switch (t) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: case QEvent::Wheel: case QEvent::KeyPress: case QEvent::KeyRelease:
    Ctrl+KCommand palette: every action, by name
    SAdd a sister clade (same keys as below once the box is open)
    A or DAdd daughter clades. In the name box, Enter adds it, Shift+Enter adds it and starts a daughter of it, Ctrl+Tab adds it and starts a sister (in the installed app; in a browser tab use the button), and Tab moves to the info
    A or DAdd daughter clades. In the name box, Enter adds it, Shift+Enter adds it and starts a daughter of it, Shift+Tab adds it and starts a sister, and Tab moves to the info
    E or REdit name and info
    CCollapse or expand
    KColour the clade and everything in it