#include #include "canvas.h" #include #include "vectorops.h" #include "sketchgeom.h" #include "backgroundimage.h" #include "sketch.h" #include "model3d.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace c2d { // ---- palette ------------------------------------------------------------- static const QColor kViewBg(0x15, 0x17, 0x1c); static const QColor kBoardFill(0x21, 0x24, 0x2b); static const QColor kBoardEdge(0x4a, 0x52, 0x60); static const QColor kGridMinor(0x28, 0x2c, 0x35); static const QColor kGridMajor(0x34, 0x3a, 0x46); static const QColor kAxisX(0x8a, 0x4a, 0x4a); static const QColor kAxisY(0x4a, 0x7a, 0x4a); static const QColor kElement(0xd8, 0xdc, 0xe4); static const QColor kSelected(0xf2, 0xa5, 0x36); // amber static const QColor kPreview(0x5c, 0xc8, 0x8a); static const QColor kBandWindow(0x9f, 0xc8, 0xf2); // left-to-right select band static const QColor kBandCrossing(0x7f, 0xd4, 0x8a); // right-to-left select band static const QColor kConstruction(0x8a, 0xa4, 0xc8); // dashed reference lines static const QColor kFullyConstrained(0x7c, 0xd6, 0xc2); // nothing can move it any more // How close (screen px) a click must land to pick a curve or a node: the // element items' hit corridor and the node editor's hit tests share it, so a // double-click that inserts a node is never a click that deselects the path. static const double kHitPx = 7.0; // Can the pen's nodes so far close into a shape? Three nodes always can; two // only when a curve handle bows them apart; closed straight, there and back, // they would enclose nothing. static bool penClosable(const QVector &nodes) { if (nodes.size() >= 3) return true; if (nodes.size() < 2) return false; const QPointF a = nodes.first().p, b = nodes.last().p; const QLineF chord(a, b); if (chord.length() < 1e-9) return false; auto off = [&](const QPointF &h) { const QPointF d = b - a, v = h - a; return std::fabs(d.x() * v.y() - d.y() * v.x()) / chord.length() > 1e-6; }; return off(nodes.first().in) || off(nodes.first().out) || off(nodes.last().in) || off(nodes.last().out); } // Delete a node in the node editor. A closed subpath left with two nodes // that cannot close (straight there and back) opens into a line, as the pen // would have drawn it. static bool removePathNode(SubPath &sp, int node) { if (!sp.removeNode(node)) return false; if (sp.closed && !penClosable(sp.nodes)) { sp.closed = false; sp.nodes.first().in = sp.nodes.first().p; sp.nodes.last().out = sp.nodes.last().p; } return true; } // Element item with CAD-style state rendering: closed shapes get a faint fill // (which also makes their interior clickable), hover brightens the outline, // selection turns it amber — no dashed Qt selection rectangle. class ElemItem : public QGraphicsPathItem { public: ElemItem(const QPainterPath &path, bool closed, bool construction = false, bool point = false, bool fully = false) : QGraphicsPathItem(path), m_closed(closed && !construction && !point), m_construction(construction), m_point(point), m_fully(fully) { setAcceptHoverEvents(true); } void paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *) override { QPen pen; pen.setCosmetic(true); if (isSelected()) { pen.setColor(kSelected); pen.setWidthF(2.2); } else if (m_hover) { pen.setColor(QColor(0x9f, 0xc8, 0xf2)); pen.setWidthF(1.8); } else { pen.setColor(m_fully ? kFullyConstrained : m_construction ? kConstruction : kElement); pen.setWidthF(1.3); } // Construction geometry is dashed (and never filled); a sketch // point is a cross of fixed screen size over its tiny circle. if (m_construction) pen.setStyle(Qt::DashLine); p->setPen(pen); if (m_point) { const double k = 5.0 / qMax(1e-9, std::fabs(p->worldTransform().m11())); const QPointF c = path().boundingRect().center(); p->drawLine(c - QPointF(k, k), c + QPointF(k, k)); p->drawLine(c - QPointF(k, -k), c + QPointF(k, -k)); return; } if (m_closed) { QColor fill = isSelected() ? QColor(kSelected) : QColor(Qt::white); fill.setAlpha(isSelected() ? 30 : 14); p->setBrush(fill); } else { p->setBrush(Qt::NoBrush); } p->drawPath(path()); } bool isClosed() const { return m_closed; } bool isPoint() const { return m_point; } // Hit tolerance in scene units (kHitPx at the current zoom). The item's // pen is never drawn (paint() uses its own cosmetic pen); its width // only sizes the stroke QGraphicsPathItem::shape() and boundingRect() // are built from, and setPen() tells the scene index the bounds moved. void setHitTolerance(double mm) { if (qFuzzyCompare(pen().widthF(), 2 * mm)) return; QPen hit = pen(); hit.setWidthF(2 * mm); setPen(hit); } QPainterPath shape() const override { // Closed shapes select from anywhere inside; open paths and // construction lines from a corridor of kHitPx either side. if (m_point) { const double r = pen().widthF() / 2; QPainterPath hit; hit.addEllipse(path().boundingRect().center(), r, r); return hit; } return m_closed ? path() : QGraphicsPathItem::shape(); } protected: void hoverEnterEvent(QGraphicsSceneHoverEvent *) override { m_hover = true; update(); } void hoverLeaveEvent(QGraphicsSceneHoverEvent *) override { m_hover = false; update(); } private: bool m_closed; bool m_construction, m_point, m_fully; bool m_hover = false; }; // A toolpath preview overlay: drawn, never picked. A plain QGraphicsPathItem // answers every scene hit test (hover finds the items under the cursor on // each mouse move) by stroking its whole path again, which stalls the UI on // a preview of a few hundred thousand segments. class OverlayItem : public QGraphicsPathItem { public: OverlayItem(const QPainterPath &path, const QPen &pen) : QGraphicsPathItem(path) { setPen(pen); setAcceptedMouseButtons(Qt::NoButton); } QPainterPath shape() const override { return QPainterPath(); } bool contains(const QPointF &) const override { return false; } // QGraphicsPathItem sizes its bounds from shape(), which is empty here. // A full pen width each side of the path covers every cap and join the // overlay pens use (round, square, bevel), without stroking the path. QRectF boundingRect() const override { const QPainterPath p = path(); if (p.isEmpty()) return QRectF(); const double w = pen().style() == Qt::NoPen ? 0.0 : qMax(0.0, pen().widthF()); return p.controlPointRect().adjusted(-w, -w, w, w); } }; // ---- undo commands ------------------------------------------------------- // Each command mutates the Document, then re-syncs the canvas and notifies. namespace { void refresh(Canvas *c) { c->rebuild(); emit c->documentChanged(); } class AddCmd : public QUndoCommand { public: AddCmd(Canvas *c, Document *d, const Element &e) : m_c(c), m_d(d), m_e(e) { setText(QStringLiteral("add %1").arg(e.geometryType)); } void redo() override { m_d->addElement(m_e); refresh(m_c); } void undo() override { m_d->removeElementById(m_e.id); refresh(m_c); } private: Canvas *m_c; Document *m_d; Element m_e; }; // Undo puts every element back at the index it had: the element order is // the z-order and the order the vectors are machined and selected in. class DeleteCmd : public QUndoCommand { public: DeleteCmd(Canvas *c, Document *d, const QVector &es) : m_c(c), m_d(d) { setText(QStringLiteral("delete %1 element(s)").arg(es.size())); const QVector &all = d->elements(); for (const Element &e : es) for (int i = 0; i < all.size(); ++i) if (all.at(i).id == e.id) { m_removed.append({i, all.at(i)}); break; } std::sort(m_removed.begin(), m_removed.end(), [](const auto &a, const auto &b) { return a.first < b.first; }); // A deleted shape leaves the toolpaths that cut it too; it stayed // behind as a "?" tile and a vector count that was too high. QSet gone; for (const auto &p : m_removed) gone.insert(p.second.id); for (const Toolpath &t : d->toolpaths()) { const QJsonArray refs = t.json.value("elements").toArray(); QJsonArray kept; for (const QJsonValue &v : refs) if (!gone.contains(v.toObject().value("uuid").toString())) kept.append(v); if (kept.size() == refs.size()) continue; Toolpath after = t; after.json.insert(QStringLiteral("elements"), kept); // Left with no vectors by this delete (not made without any): // export skips it rather than, say, facing the whole stock. // Undo puts the toolpath back whole, flag and all. if (kept.isEmpty()) after.json.insert(QStringLiteral("vectors_removed"), true); m_tps.append({t, after}); } } void redo() override { for (const auto &p : m_removed) m_d->removeElementById(p.second.id); for (const auto &p : m_tps) m_d->replaceToolpath(p.second); refresh(m_c); } void undo() override { QVector &els = m_d->elementsRef(); for (const auto &p : m_removed) // low index first els.insert(qMin(p.first, int(els.size())), p.second); for (const auto &p : m_tps) m_d->replaceToolpath(p.first); refresh(m_c); } private: Canvas *m_c; Document *m_d; QVector> m_removed; QVector> m_tps; // before, after }; // The element order after a drag in the shape strip; undo puts the old order back. class OrderCmd : public QUndoCommand { public: OrderCmd(Canvas *c, Document *d, const QStringList &before, const QStringList &after) : m_c(c), m_d(d), m_before(before), m_after(after) { setText(QStringLiteral("reorder shapes")); } void redo() override { apply(m_after); } void undo() override { apply(m_before); } private: void apply(const QStringList &order) { QVector &els = m_d->elementsRef(); QVector out; for (const QString &id : order) for (const Element &e : els) if (e.id == id) { out.append(e); break; } if (out.size() == els.size()) els = out; refresh(m_c); } Canvas *m_c; Document *m_d; QStringList m_before, m_after; }; // Copies added as one step. class AddManyCmd : public QUndoCommand { public: AddManyCmd(Canvas *c, Document *d, const QVector &es) : m_c(c), m_d(d), m_es(es) { setText(QStringLiteral("duplicate %1 shape(s)").arg(es.size())); } void redo() override { for (const Element &e : m_es) m_d->addElement(e); refresh(m_c); } void undo() override { for (const Element &e : m_es) m_d->removeElementById(e.id); refresh(m_c); } private: Canvas *m_c; Document *m_d; QVector m_es; }; // Elements and the toolpath that machines them, added as one step (the // inlay male generator). class InsertGeneratedCmd : public QUndoCommand { public: InsertGeneratedCmd(Canvas *c, Document *d, const QVector &els, const Toolpath &tp) : m_c(c), m_d(d), m_els(els), m_tp(tp) { setText(QStringLiteral("generate %1").arg(tp.json.value("name").toString())); } void redo() override { for (const Element &e : m_els) m_d->addElement(e); m_d->addToolpath(m_tp); refresh(m_c); } void undo() override { m_d->removeToolpath(m_tp.uuid); for (const Element &e : m_els) m_d->removeElementById(e.id); refresh(m_c); } private: Canvas *m_c; Document *m_d; QVector m_els; Toolpath m_tp; }; class EditCmd : public QUndoCommand { public: EditCmd(Canvas *c, Document *d, const Element &before, const Element &after) : m_c(c), m_d(d), m_before(before), m_after(after) { setText(QStringLiteral("edit %1").arg(before.geometryType)); } void redo() override { m_d->replaceElement(m_after); refresh(m_c); } void undo() override { m_d->replaceElement(m_before); refresh(m_c); } private: Canvas *m_c; Document *m_d; Element m_before, m_after; }; // Swap a set of elements for another set (convert-to-path: a text becomes // several glyph paths). Afters are appended, so the z-order may change. class ReplaceCmd : public QUndoCommand { public: // `piecesOf` maps each replaced element's id to the ids of the elements // that take its place (convert to paths, break): every toolpath that // machined it then machines all of them, not only the piece that kept // its id. ReplaceCmd(Canvas *c, Document *d, const QVector &before, const QVector &after, const QString &text, const QHash &piecesOf = {}) : m_c(c), m_d(d), m_before(before), m_after(after) { setText(text); // Where the originals were: undo puts them back there (z-order and // machining order), not at the end. const QVector &all = d->elements(); for (const Element &e : before) { int at = int(all.size()); for (int i = 0; i < all.size(); ++i) if (all.at(i).id == e.id) { at = i; break; } m_beforeAt.append(at); } QSet afterIds; for (const Element &e : after) afterIds.insert(e.id); for (auto it = piecesOf.constBegin(); it != piecesOf.constEnd(); ++it) { QStringList kept; for (const QString &n : it.value()) if (afterIds.contains(n)) kept << n; m_piecesOf.insert(it.key(), kept); } for (const Toolpath &t : d->toolpaths()) { const QJsonArray refs = t.json.value("elements").toArray(); QJsonArray kept; QSet seen; bool hit = false; for (const QJsonValue &v : refs) { const QString id = v.toObject().value("uuid").toString(); if (!piecesOf.contains(id)) { if (!seen.contains(id)) { kept.append(v); seen.insert(id); } continue; } hit = true; for (const QString &n : piecesOf.value(id)) if (afterIds.contains(n) && !seen.contains(n)) { kept.append(QJsonObject{{QStringLiteral("uuid"), n}}); seen.insert(n); } } if (!hit || kept == refs) continue; Toolpath tpAfter = t; tpAfter.json.insert(QStringLiteral("elements"), kept); m_tps.append({t, tpAfter}); } } void redo() override { for (const auto &p : m_tps) m_d->replaceToolpath(p.second); for (const Element &e : m_before) m_d->removeElementById(e.id); for (const Element &e : m_after) m_d->addElement(e); // 3D "From vectors" components follow their vectors like toolpaths // do: one built on a replaced element uses all of its pieces, not // only the piece that kept its id. Each original separately, so a // component keeps only the pieces of the elements it used. m_model.clear(); for (auto it = m_piecesOf.constBegin(); it != m_piecesOf.constEnd(); ++it) { const ModelVectorRefs was = retargetModelVectors(*m_d, {it.key()}, it.value()); for (auto w = was.constBegin(); w != was.constEnd(); ++w) if (!m_model.contains(w.key())) // the first is the one before the edit m_model.insert(w.key(), w.value()); } // Last, as in undo: whoever listens to documentChanged must find // the components already on their new vectors. refresh(m_c); } void undo() override { for (const auto &p : m_tps) m_d->replaceToolpath(p.first); restoreModelVectors(*m_d, m_model); for (const Element &e : m_after) m_d->removeElementById(e.id); QVector order(m_before.size()); std::iota(order.begin(), order.end(), 0); std::sort(order.begin(), order.end(), [this](int a, int b) { return m_beforeAt.at(a) < m_beforeAt.at(b); }); QVector &els = m_d->elementsRef(); for (int k : order) // low index first els.insert(qMin(m_beforeAt.at(k), int(els.size())), m_before.at(k)); refresh(m_c); } private: Canvas *m_c; Document *m_d; QVector m_before, m_after; QVector m_beforeAt; QVector> m_tps; QHash m_piecesOf; // replaced id -> the pieces now in the document ModelVectorRefs m_model; // 3D components' vectors before redo }; class TpEditCmd : public QUndoCommand { public: TpEditCmd(Canvas *c, Document *d, const Toolpath &before, const Toolpath &after) : m_c(c), m_d(d), m_before(before), m_after(after) { setText(QStringLiteral("edit toolpath %1").arg(before.json.value("name").toString())); } void redo() override { m_d->replaceToolpath(m_after); refresh(m_c); } void undo() override { m_d->replaceToolpath(m_before); refresh(m_c); } private: Canvas *m_c; Document *m_d; Toolpath m_before, m_after; }; class MoveCmd : public QUndoCommand { public: MoveCmd(Canvas *c, Document *d, const QVector> &moves) : m_c(c), m_d(d), m_moves(moves) { setText(QStringLiteral("move %1 element(s)").arg(moves.size())); } void redo() override { apply(1.0); } void undo() override { apply(-1.0); } private: void apply(double sign) { for (const auto &m : m_moves) if (Element *e = m_d->elementById(m.first)) e->translate(sign * m.second.x(), sign * m.second.y()); refresh(m_c); } Canvas *m_c; Document *m_d; QVector> m_moves; }; } // namespace // ---- canvas -------------------------------------------------------------- Canvas::Canvas(QWidget *parent) : QGraphicsView(parent), m_scene(new QGraphicsScene(this)), m_undo(new QUndoStack(this)) { setScene(m_scene); setRenderHint(QPainter::Antialiasing, true); // The select band is the canvas's own (window or crossing by drag // direction), not QGraphicsView's rubber band. setDragMode(QGraphicsView::NoDrag); setBackgroundBrush(kViewBg); setMouseTracking(true); // Flip Y so CC's Y-up space maps to Qt's Y-down scene. scale(1.0, -1.0); // No scrollbars: the hand tool, the middle button and the wheel move the // view, and the scene leaves room around the board to move it in. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Touchscreens and pads: two fingers pinch to zoom and move the view; // one finger still arrives as the mouse. viewport()->setAttribute(Qt::WA_AcceptTouchEvents); viewport()->grabGesture(Qt::PinchGesture); // An undo, redo or new step replaces the design's state under a // dimension label being dragged: the drag is dropped without putting // its label back, or "back" would undo the undo with no step of its own. // A step that did not touch the label (not a parametric one) leaves it // where the drag last put it: that goes back, as no step will record it. connect(m_undo, &QUndoStack::indexChanged, this, [this] { if (m_dragDim.isEmpty()) return; if (m_doc) { const int i = m_doc->parametric().indexOfUid(m_dragDim); if (i >= 0 && m_doc->parametric().constraints.at(i).label == m_dragDimLast) m_doc->parametricRef().constraints[i].label = m_dragDimLabel0; } m_dragDim.clear(); viewport()->update(); }); // Zoom out / in and the zoom % + cursor position, bottom right on the // canvas, where they sit with the drawing instead of under the panels. m_hud = new QWidget(this); m_hud->setObjectName(QStringLiteral("canvasHud")); m_hud->setStyleSheet(QStringLiteral( "#canvasHud { background: rgba(22,24,29,215); border-radius: 8px; }" "#canvasHud QToolButton { font-size: 20px; font-weight: 600; min-width: 40px;" " min-height: 36px; border-radius: 6px; background: #2a2e36; color: #d8dce4; }" "#canvasHud QToolButton:pressed { background: #3a404b; }" "#canvasHud QLabel { color: #aab1bd; padding: 0 6px; }")); auto *hl = new QHBoxLayout(m_hud); hl->setContentsMargins(6, 4, 6, 4); hl->setSpacing(6); auto *zoomOut = new QToolButton(m_hud); zoomOut->setText(QStringLiteral("\u2212")); zoomOut->setToolTip(tr("Zoom out (-)")); zoomOut->setAutoRepeat(true); auto *zoomIn = new QToolButton(m_hud); zoomIn->setText(QStringLiteral("+")); zoomIn->setToolTip(tr("Zoom in (+)")); zoomIn->setAutoRepeat(true); m_hudText = new QLabel(m_hud); hl->addWidget(zoomOut); hl->addWidget(zoomIn); hl->addWidget(m_hudText); connect(zoomOut, &QToolButton::clicked, this, [this] { zoomBy(1.0 / 1.25); }); connect(zoomIn, &QToolButton::clicked, this, [this] { zoomBy(1.25); }); connect(this, &Canvas::cursorMoved, this, [this](QPointF p) { m_hudPos = p; m_hudHasPos = true; updateHud(); }); connect(this, &Canvas::zoomChanged, this, [this] { updateHud(); }); updateHud(); // The stock size, top left, as on the Simulate page. m_stockLabel = new QLabel(this); m_stockLabel->setObjectName(QStringLiteral("canvasStock")); m_stockLabel->setAttribute(Qt::WA_TransparentForMouseEvents); m_stockLabel->setStyleSheet(QStringLiteral( "#canvasStock { background: rgba(22,24,29,215); color: #aab1bd; border-radius: 8px;" " padding: 5px 10px; }")); m_stockLabel->hide(); connect(m_scene, &QGraphicsScene::selectionChanged, this, &Canvas::onSelectionChanged); } Canvas::~Canvas() { // The scene is a child QObject and dies after this destructor has run; // its selectionChanged (emitted while its items are deleted) must not // reach the half-destroyed Canvas. disconnect(m_scene, nullptr, this, nullptr); m_scene->blockSignals(true); } void Canvas::onSelectionChanged() { QStringList ids; for (QGraphicsItem *it : m_scene->selectedItems()) if (it->data(0).isValid()) ids << it->data(0).toString(); if (m_tool == NodeEdit) syncEditTarget(); emit selectionChangedIds(ids); viewport()->update(); } double Canvas::pxToMm(double px) const { return px / qMax(1e-9, qAbs(transform().m11())); } // The items' hit corridor is kHitPx on screen, so it is re-sized whenever // the zoom changed since the last time (checked on every mouse event too, as // the view transform can change without going through zoomBy / zoomFit). void Canvas::syncHitTolerance() { const double s = qAbs(transform().m11()); if (s == m_hitScale) return; m_hitScale = s; const double tol = pxToMm(kHitPx); for (QGraphicsItem *it : m_scene->items()) if (auto *e = dynamic_cast(it)) e->setHitTolerance(tol); } void Canvas::clearPreview() { if (m_preview) { m_scene->removeItem(m_preview); delete m_preview; m_preview = nullptr; } } QGraphicsPathItem *Canvas::itemFor(const QString &id) const { for (QGraphicsItem *it : m_scene->items()) if (it->data(0).isValid() && it->data(0).toString() == id) return qgraphicsitem_cast(it); return nullptr; } QList Canvas::itemsFor(const QStringList &ids) const { QList out; if (ids.isEmpty()) return out; const QSet want(ids.begin(), ids.end()); for (QGraphicsItem *it : m_scene->items()) if (it->data(0).isValid() && want.contains(it->data(0).toString())) if (auto *pi = qgraphicsitem_cast(it)) out << pi; return out; } // Area (fill tool): the face the click is in, bounded by every closed shape // around it and any it overlaps - not whole shapes. A face whose rings are // existing shapes (a shape, or a shape and its islands) selects those; any // other ring (where shapes overlap) is added as a closed path, so the // toolpath made from the selection cuts only that face. void Canvas::selectAreaAt(const QPointF &p, bool add) { QList> closed; QVector paths; for (QGraphicsItem *it : m_scene->items()) if (auto *e = dynamic_cast(it)) if (e->isClosed() && e->data(0).isValid()) { closed.append({e->data(0).toString(), e->mapToScene(e->path())}); paths << closed.last().second; } QStringList ids = add ? selectedElementIds() : QStringList(); const QVector face = vec::fillFace(paths, p); if (face.isEmpty() || !m_doc) { selectElements(ids); return; } auto pathOf = [](const QVector &rings) { QPainterPath r; r.setFillRule(Qt::OddEvenFill); for (const QPolygonF &g : rings) { r.addPolygon(g); r.closeSubpath(); } return r; }; // Same region: what is in one and not the other is a sliver at most. auto same = [&](const QPainterPath &a, const QPainterPath &shape, bool hole = false) { // fillFace() shrinks and regrows the face by 0.01 mm, which blunts // sharp tips (a 10-degree point loses over 0.1 mm); the shape gets // the same treatment before it is compared. A hole of the face is // the outside of its island, so there it is the other way round: // the island's tips stay sharp. QPainterPath b = shape; if (a.boundingRect().adjusted(-1, -1, 1, 1).contains(shape.boundingRect()) && shape.boundingRect().adjusted(-1, -1, 1, 1).contains(a.boundingRect())) { QVector back; if (hole) { // The island as fillFace() makes a hole of it: the face of a // box around it, holes only - the very same pipeline, so a // hair-thin tip loses exactly what it lost in the face. const QRectF box = shape.boundingRect().adjusted(-10, -10, 10, 10); QPainterPath frame; frame.addRect(box); const QVector f = vec::fillFace({frame, shape}, box.topLeft() + QPointF(5, 5)); // Only when the island came back whole: a multi-ring island // ("O" text) gives other holes, and is not this face's hole. int own = 0; for (const QPolygonF &g : shape.toSubpathPolygons()) own += g.size() >= 3 ? 1 : 0; // And only when the island's own even-odd region (what a // toolpath cuts) fills the hole: a one-ring "O" with a hair // slit, or a horseshoe whose tips nearly meet, closes up as a // hole here, but selecting it would cut its counter or room. double ownArea = 0, holeArea = 0, perim = 0; for (const QPolygonF &g : vec::offsetRings({shape}, {}, 0)) ownArea += vec::ringArea(g); for (const QPolygonF &g : f.mid(1)) { holeArea += std::fabs(vec::ringArea(g)); for (int i = 0; i < g.size(); ++i) perim += QLineF(g.at(i), g.at((i + 1) % g.size())).length(); } if (f.size() - 1 == own && std::fabs(std::fabs(ownArea) - holeArea) <= perim * 0.02) back = f.mid(1); else return false; } else { const QVector in = vec::offsetRings({shape}, {}, -0.01); back = in.isEmpty() ? in : vec::offsetRings({pathOf(in)}, {}, 0.01); } if (!back.isEmpty()) b = pathOf(back); } // A pocket shape with an island inside is two rings; a lone outline // around it is one - not the same, however small the island. auto rings = [](const QPainterPath &p) { int n = 0; for (const QPolygonF &g : p.toSubpathPolygons()) n += g.size() >= 3 ? 1 : 0; return n; }; if (rings(a) != rings(b)) return false; if (!a.boundingRect().adjusted(-0.05, -0.05, 0.05, 0.05).contains(b.boundingRect()) || !b.boundingRect().adjusted(-0.05, -0.05, 0.05, 0.05).contains(a.boundingRect())) return false; // Every corner of each lies on the other's outline. An area rule // (even 0.02 mm per mm of outline) let a notch of a few mm on a big // shape count as the whole shape; a notch's corners are off the // outline by its own size. auto segDist = [](const QPointF &p, const QPointF &s, const QPointF &e) { const QPointF d = e - s; const double l2 = QPointF::dotProduct(d, d); const double t = l2 > 0 ? std::clamp(QPointF::dotProduct(p - s, d) / l2, 0.0, 1.0) : 0.0; return QLineF(p, s + t * d).length(); }; // Qt flattens curves for 1-unit pixels; in mm that is a coarse // polygon (a 5 mm circle off its own outline by more than 0.1 mm). auto fine = [](const QPainterPath &p) { QList out = p.toSubpathPolygons(QTransform::fromScale(100, 100)); for (QPolygonF &g : out) g = QTransform::fromScale(0.01, 0.01).map(g); return out; }; auto near = [&segDist, &fine](const QPainterPath &from, const QPainterPath &to) { const QList tg = fine(to); for (const QPolygonF &g : fine(from)) for (const QPointF &v : g) { double best = 1e18; for (const QPolygonF &h : tg) for (int i = 0; i + 1 < h.size(); ++i) best = std::min(best, segDist(v, h.at(i), h.at(i + 1))); if (best > 0.1) return false; } return true; }; return near(a, b) && near(b, a); }; auto keep = [&ids](const QString &id) { if (!ids.contains(id)) ids << id; }; // One shape is the whole face (a text glyph with its counter, say). for (const auto &c : closed) if (same(pathOf(face), c.second)) { keep(c.first); selectElements(ids); return; } // An island of several rings with no counters ("TL" text, an "i"): each // glyph is its own hole of the face, so none matches the whole element // alone. When every ring of it is one of the holes, it is the element. auto subpaths = [](const QPainterPath &p) { QList out; for (int i = 0; i < p.elementCount(); ++i) { const QPainterPath::Element e = p.elementAt(i); if (e.isMoveTo()) { out.append(QPainterPath()); out.last().moveTo(e); } else if (out.isEmpty()) { continue; } else if (e.isLineTo()) { out.last().lineTo(e); } else if (e.isCurveTo() && i + 2 < p.elementCount()) { out.last().cubicTo(e, p.elementAt(i + 1), p.elementAt(i + 2)); i += 2; } } return out; }; QSet taken; // face rings an island already accounts for for (const auto &c : closed) { const QList parts = subpaths(c.second); if (parts.size() < 2) continue; QSet mine; for (const QPainterPath &part : parts) for (int r = 1; r < face.size(); ++r) if (!taken.contains(r) && !mine.contains(r) && same(pathOf({face.at(r)}), part, true)) { mine.insert(r); break; } if (mine.size() == parts.size()) { taken.unite(mine); keep(c.first); } } QVector fresh; for (int fi = 0; fi < face.size(); ++fi) { if (taken.contains(fi)) continue; const QPolygonF &ring = face.at(fi); QString match; for (const auto &c : closed) if (same(pathOf({ring}), c.second, &ring != &face.first())) { match = c.first; break; } if (match.isEmpty()) fresh << ring; else keep(match); } if (!fresh.isEmpty()) { const QVector els = vec::elementsFromRings(fresh, m_doc->defaultLayer()); m_undo->beginMacro(tr("fill area")); for (const Element &e : els) { m_undo->push(new AddCmd(this, m_doc, e)); keep(e.id); } m_undo->endMacro(); emit statusHint(tr("Area — the overlap was added as a closed path, so a toolpath cuts only this area")); } selectElements(ids); } void Canvas::selectElements(const QStringList &ids) { m_scene->blockSignals(true); m_scene->clearSelection(); for (QGraphicsPathItem *it : itemsFor(ids)) it->setSelected(true); m_scene->blockSignals(false); onSelectionChanged(); } void Canvas::showElement(const QString &id) { QGraphicsPathItem *it = itemFor(id); if (!it) return; selectElements({id}); centerOn(it->mapRectToScene(it->path().boundingRect()).center()); viewport()->update(); } void Canvas::editText(const QString &id, const QJsonObject &changes) { if (!m_doc || changes.isEmpty()) return; Element *e = m_doc->elementById(id); if (!e || e->geometryType != QLatin1String("text")) return; const Element after = Element::regenText(*e, changes); if (after.raw == e->raw) return; m_undo->push(new EditCmd(this, m_doc, *e, after)); } void Canvas::convertToPaths(const QStringList &ids) { if (!m_doc) return; QVector before, after; QHash piecesOf; for (const QString &id : ids) { Element *e = m_doc->elementById(id); if (!e || e->geometryType == QLatin1String("path") || Element::isPoint(*e)) continue; // a sketch point has no outline to cut: it stays a point before.append(*e); const QVector pieces = Element::toPaths(*e); for (const Element &p : pieces) piecesOf[e->id] << p.id; after += pieces; } if (before.isEmpty()) return; if (after.isEmpty()) { // Element::toPaths drops degenerate contours, so a text of spaces (or // a font that renders nothing) yields none: replacing here would // delete the element and put nothing in its place. emit statusHint(tr("nothing to convert: the selection has no outline")); return; } if (before.size() == 1 && after.size() == 1) { pushEdit(new EditCmd(this, m_doc, before.first(), after.first()), ids); } else { pushEdit(new ReplaceCmd(this, m_doc, before, after, tr("convert %1 element(s) to paths").arg(before.size()), piecesOf), ids); } QStringList newIds; for (const Element &e : after) newIds << e.id; selectElements(newIds); emit statusHint(tr("%1 path(s) — press N to edit nodes").arg(after.size())); } void Canvas::emitZoom() { syncHitTolerance(); emit zoomChanged(qAbs(transform().m11()) * 100.0); } // Holds a zoom step inside a sane range: unbounded, held-down zoom-out drives // the scale to zero (and the view to NaN), zoom-in to an unusable blur. static double limitZoom(double current, double factor) { constexpr double kMin = 0.02, kMax = 2000.0; // view pixels per mm const double now = qAbs(current); if (!(now > 0) || !(factor > 0) || !std::isfinite(factor)) return 1.0; // Only the side the zoom moves toward is limited: a view already past a // limit (fit to a tiny shape) must still be able to move back. if (factor > 1.0) return qMin(factor, qMax(1.0, kMax / now)); return qMax(factor, qMin(1.0, kMin / now)); } void Canvas::zoomBy(double factor) { factor = limitZoom(transform().m11(), factor); setTransformationAnchor(QGraphicsView::AnchorViewCenter); scale(factor, factor); emitZoom(); } void Canvas::updateHud() { if (!m_hudText) return; const QString pos = m_hudHasPos ? QStringLiteral("X %1 Y %2 mm").arg(m_hudPos.x(), 0, 'f', 2).arg(m_hudPos.y(), 0, 'f', 2) : QStringLiteral("X \u2014 Y \u2014"); const QString text = QStringLiteral("%1% %2").arg(qRound(qAbs(transform().m11()) * 100.0)).arg(pos); // This runs on every mouse move. A readout that still reads the same // keeps its size and place; a resize places the bar from resizeEvent. if (text == m_hudText->text()) return; m_hudText->setText(text); placeHud(); } // "Stock 470 × 470 × 10 mm" from the open design; hidden with no design. void Canvas::updateStockLabel() { if (!m_stockLabel) return; const double w = m_doc ? m_doc->boardWidth() : 0, h = m_doc ? m_doc->boardHeight() : 0; if (!(w > 0 && h > 0)) { m_stockLabel->hide(); return; } const double t = m_doc->params().value("thickness", "0").toDouble(); m_stockLabel->setText(t > 0 ? QStringLiteral("Stock %1 \u00d7 %2 \u00d7 %3 mm").arg(w, 0, 'g', 5).arg(h, 0, 'g', 5).arg(t, 0, 'g', 4) : QStringLiteral("Stock %1 \u00d7 %2 mm").arg(w, 0, 'g', 5).arg(h, 0, 'g', 5)); m_stockLabel->adjustSize(); m_stockLabel->move(10, 10); m_stockLabel->show(); m_stockLabel->raise(); } void Canvas::placeHud() { if (!m_hud || m_hud->parentWidget() != this) return; m_hud->adjustSize(); m_hud->move(width() - m_hud->width() - 10, height() - m_hud->height() - 10); m_hud->raise(); } void Canvas::editElement(const QString &id, const QHash ¶ms) { if (!m_doc) return; Element *e = m_doc->elementById(id); if (!e) return; const Element after = Element::regen(*e, params); if (after.raw == e->raw) return; pushEdit(new EditCmd(this, m_doc, *e, after), {id}); } void Canvas::moveElementBy(const QString &id, double dx, double dy) { if (!m_doc || (qFuzzyIsNull(dx) && qFuzzyIsNull(dy))) return; if (m_doc->elementById(id)) pushEdit(new MoveCmd(this, m_doc, {{id, QPointF(dx, dy)}}), {id}); } QStringList Canvas::selectedElementIds() const { QStringList ids; for (QGraphicsItem *it : m_scene->selectedItems()) if (it->data(0).isValid()) ids << it->data(0).toString(); return ids; } void Canvas::selectIds(const QStringList &ids) { const QSet want(ids.begin(), ids.end()); // One change signal, not one per item: each rebuilt the whole id list // (a few hundred selected shapes froze an array or a boolean for seconds). m_scene->blockSignals(true); for (QGraphicsItem *it : m_scene->items()) if (it->data(0).isValid()) it->setSelected(want.contains(it->data(0).toString())); m_scene->blockSignals(false); onSelectionChanged(); } void Canvas::editToolpath(const QString &uuid, const QJsonObject &newJson) { if (!m_doc) return; Toolpath *t = m_doc->toolpathByUuid(uuid); if (!t || t->json == newJson) return; Toolpath after = *t; after.json = newJson; // Picking its vectors again (or taking the last one off on purpose) // is the user's choice: the "lost its vectors" mark that keeps an // emptied Facing from skimming the whole board no longer applies. if (newJson.value(QStringLiteral("elements")) != t->json.value(QStringLiteral("elements"))) after.json.remove(QStringLiteral("vectors_removed")); if (t->json == after.json) return; m_undo->push(new TpEditCmd(this, m_doc, *t, after)); } void Canvas::insertGenerated(const QVector &els, const Toolpath &tp) { if (!m_doc) return; m_undo->push(new InsertGeneratedCmd(this, m_doc, els, tp)); } // Exactly one selected, parametrically resizable element? Handle sits at the // east point (circle/polygon) or the top-right corner (rectangle; of the // rectangle as turned by its rotation). bool Canvas::resizeHandle(QString *id, QPointF *pos, QString *type) const { if (!m_doc || m_tool != Select) return false; const auto sel = m_scene->selectedItems(); if (sel.size() != 1 || !sel.first()->data(0).isValid()) return false; Element *e = const_cast(m_doc)->elementById(sel.first()->data(0).toString()); // A sketch point has a radius only so it can be drawn; it is moved, never // resized. if (!e || Element::isPoint(*e)) return false; const QJsonArray c = e->raw.value("center").toArray(); if (c.size() != 2) return false; const QPointF center(c.at(0).toDouble(), c.at(1).toDouble()); if (e->geometryType == QLatin1String("circle") || e->geometryType == QLatin1String("regular_polygon")) { *pos = center + QPointF(e->raw.value("radius").toDouble(), 0); } else if (e->geometryType == QLatin1String("rectangle")) { QTransform turn; turn.rotate(e->raw.value("rotation").toDouble()); *pos = center + turn.map(QPointF(e->raw.value("width").toDouble() / 2, e->raw.value("height").toDouble() / 2)); } else { return false; } // On a small shape the handle covers most of it, so a press meant to // move the shape would resize it. Offer the handle only when it sits well // clear of the centre on screen; otherwise the drag moves the shape. if (QLineF(center, *pos).length() * qAbs(transform().m11()) < 16.0) return false; *id = e->id; *type = e->geometryType; return true; } QHash Canvas::resizeTo(QPointF cur) const { QHash p; if (m_resizeType == QLatin1String("rectangle")) { // Width and height run along the rectangle's own axes. QTransform untwist; untwist.rotate(-m_resizeRot); const QPointF d = untwist.map(cur - m_resizeCenter); p.insert("width", qMax(0.2, 2 * qAbs(d.x()))); p.insert("height", qMax(0.2, 2 * qAbs(d.y()))); } else { p.insert("radius", qMax(0.1, QLineF(m_resizeCenter, cur).length())); } return p; } namespace { // Does segment a-b reach into r (edges included)? Liang-Barsky. bool segTouches(QPointF a, QPointF b, const QRectF &r) { double t0 = 0, t1 = 1; const double dx = b.x() - a.x(), dy = b.y() - a.y(); const double ps[4] = {-dx, dx, -dy, dy}; const double qs[4] = {a.x() - r.left(), r.right() - a.x(), a.y() - r.top(), r.bottom() - a.y()}; for (int i = 0; i < 4; ++i) { if (ps[i] == 0) { if (qs[i] < 0) return false; continue; } const double t = qs[i] / ps[i]; if (ps[i] < 0) { if (t > t1) return false; t0 = qMax(t0, t); } else { if (t < t0) return false; t1 = qMin(t1, t); } } return true; } // Whether r touches the item's line: a closed shape only by its outline, // not by lying inside it. bool bandTouches(const QGraphicsPathItem *it, bool closed, bool point, const QRectF &r) { const QPainterPath path = it->mapToScene(it->path()); const QRectF b = path.boundingRect(); // QRectF::intersects is false for a straight line's flat box. if (b.right() < r.left() || b.left() > r.right() || b.bottom() < r.top() || b.top() > r.bottom()) return false; if (point) return r.contains(path.boundingRect().center()); for (const QPolygonF &poly : path.toSubpathPolygons()) { if (poly.size() == 1 && r.contains(poly.first())) return true; for (int i = 1; i < poly.size(); ++i) if (segTouches(poly[i - 1], poly[i], r)) return true; if (closed && poly.size() > 2 && segTouches(poly.last(), poly.first(), r)) return true; } return false; } } // namespace // The band ends at the edge of the drawing: dragged on over the panels or // the menus it kept growing into the part of the drawing that is off screen // and picked up shapes nobody could see (Phobic, 2026-10-26). QPoint Canvas::bandPoint(const QPoint &p) const { const QRect v = viewport()->rect(); return QPoint(qBound(v.left(), p.x(), v.right()), qBound(v.top(), p.y(), v.bottom())); } void Canvas::endBand() { if (!m_band) return; m_band = false; m_bandKeep.clear(); viewport()->update(); } namespace { // A finger, not a mouse: Qt hands an unhandled touch on as a mouse event // that still names the touch screen. bool fromTouch(const QMouseEvent *e) { const QInputDevice *d = e->device(); return d && d->type() == QInputDevice::DeviceType::TouchScreen; } } // namespace // Select by band: left to right selects what lies wholly inside, right to // left whatever line the band touches (Phobic, 2026-10-25). Direction is // the drag's X only, as in AutoCAD and Fusion. void Canvas::applyBand() { const QRect vr = QRect(m_bandStart, m_bandEnd).normalized(); // A click or a wobble of a few pixels is no band: the press already // set the selection. if (vr.width() < 3 && vr.height() < 3) return; const QRectF r = mapToScene(vr).boundingRect(); const bool crossing = m_bandEnd.x() < m_bandStart.x(); bool changed = false; m_scene->blockSignals(true); for (QGraphicsItem *g : m_scene->items()) { if (!g->data(0).isValid() || !(g->flags() & QGraphicsItem::ItemIsSelectable) || !g->isVisible()) continue; auto *it = qgraphicsitem_cast(g); if (!it) continue; const auto *e = dynamic_cast(it); const bool point = e && e->isPoint(); bool hit; if (crossing) { hit = bandTouches(it, e && e->isClosed(), point, r); } else { const QRectF b = it->mapToScene(it->path()).boundingRect(); hit = point ? r.contains(b.center()) : b.left() >= r.left() && b.right() <= r.right() && b.top() >= r.top() && b.bottom() <= r.bottom(); } const bool want = hit || m_bandKeep.contains(g); if (g->isSelected() != want) { g->setSelected(want); changed = true; } } m_scene->blockSignals(false); if (changed) onSelectionChanged(); } void Canvas::drawForeground(QPainter *p, const QRectF &rect) { QGraphicsView::drawForeground(p, rect); // Select band, in viewport pixels: window blue and solid, crossing // green and dashed (as AutoCAD and Fusion). The pad draws the same. if (m_band && m_bandStart != m_bandEnd) { const bool crossing = m_bandEnd.x() < m_bandStart.x(); const QColor c = crossing ? kBandCrossing : kBandWindow; QColor fill = c; fill.setAlpha(30); QPen pen(c); pen.setCosmetic(true); pen.setWidth(1); if (crossing) pen.setStyle(Qt::DashLine); p->save(); p->resetTransform(); p->setRenderHint(QPainter::Antialiasing, false); p->setPen(pen); p->setBrush(fill); p->drawRect(QRect(m_bandStart, m_bandEnd).normalized()); p->restore(); } // Toolpath -> shapes. Drawn first, and before every early return below, so // the halo stays visible whatever tool is active. A wide translucent pass // makes it readable over dark stock, a thin solid pass keeps the outline // crisp; both cosmetic, so the halo does not thicken as you zoom in. if (!m_highlightIds.isEmpty() && m_highlightPartial) { // Only what is left after the toolpaths above: amber over a dim // dashed outline of the toolpath's own shapes. p->save(); p->setBrush(Qt::NoBrush); QPen dim(QColor(0xff, 0xa5, 0x2a, 0x90)); dim.setCosmetic(true); dim.setWidth(1); dim.setStyle(Qt::DashLine); p->setPen(dim); for (const QGraphicsPathItem *it : itemsFor(m_highlightIds)) p->drawPath(it->mapToScene(it->path())); p->setBrush(QColor(0xff, 0xa5, 0x2a, 0x40)); for (int pass = 0; pass < 2; ++pass) { QPen hp(pass == 0 ? QColor(0xff, 0xa5, 0x2a, 0x60) : QColor(0xff, 0xa5, 0x2a)); hp.setCosmetic(true); hp.setWidth(pass == 0 ? 9 : 2); hp.setJoinStyle(Qt::RoundJoin); p->setPen(hp); p->drawPath(m_highlightLeft); p->setBrush(Qt::NoBrush); } p->restore(); } else if (!m_highlightIds.isEmpty()) { p->save(); p->setBrush(Qt::NoBrush); for (int pass = 0; pass < 2; ++pass) { QPen hp(pass == 0 ? QColor(0xff, 0xa5, 0x2a, 0x60) : QColor(0xff, 0xa5, 0x2a)); hp.setCosmetic(true); hp.setWidth(pass == 0 ? 9 : 2); hp.setJoinStyle(Qt::RoundJoin); hp.setCapStyle(Qt::RoundCap); p->setPen(hp); for (const QGraphicsPathItem *it : itemsFor(m_highlightIds)) p->drawPath(it->mapToScene(it->path())); } p->restore(); } drawParametric(p); if (m_tool == NodeEdit && !m_model.isEmpty()) { drawNodes(p); return; } if (m_tool == DrawPath && !m_penNodes.isEmpty()) { // Pen tool: anchors so far, plus the handles of the node being dragged. const double s = pxToMm(3.5); p->setPen(QPen(QColor(0x1a, 0x1a, 0x1a), 0)); p->setBrush(kPreview); for (const PathNode &n : m_penNodes) p->drawRect(QRectF(n.p.x() - s, n.p.y() - s, 2 * s, 2 * s)); const PathNode &last = m_penNodes.last(); if (last.hasOut() || last.hasIn()) { QPen hp(QColor(0x9f, 0xc8, 0xf2)); hp.setCosmetic(true); p->setPen(hp); p->setBrush(Qt::NoBrush); p->drawLine(QLineF(last.in, last.out)); p->setBrush(QColor(0x9f, 0xc8, 0xf2)); p->drawEllipse(last.in, s, s); p->drawEllipse(last.out, s, s); } // Closing hint: ring around the first anchor when it can be closed. if (penClosable(m_penNodes)) { p->setPen(QPen(kPreview, 0)); p->setBrush(Qt::NoBrush); p->drawEllipse(m_penNodes.first().p, pxToMm(8), pxToMm(8)); } return; } QString id, type; QPointF pos; if (!m_resizing && !resizeHandle(&id, &pos, &type)) return; if (m_resizing) return; // handle hidden while dragging; the preview shows the shape const double s = pxToMm(4.0); p->setPen(QPen(QColor(0x1a, 0x1a, 0x1a), 0)); p->setBrush(kSelected); p->drawRect(QRectF(pos.x() - s, pos.y() - s, 2 * s, 2 * s)); } // Node editor overlay: tangent lines, handle circles, anchor squares. The // selected node is amber; smooth/symmetric anchors are drawn as diamonds so // the kind is visible without a menu. void Canvas::drawNodes(QPainter *p) const { const double s = pxToMm(3.5); const QColor handleCol(0x9f, 0xc8, 0xf2); for (int si = 0; si < m_model.subs.size(); ++si) { const SubPath &sub = m_model.subs.at(si); QPen hp(handleCol); hp.setCosmetic(true); p->setPen(hp); p->setBrush(Qt::NoBrush); for (const PathNode &n : sub.nodes) { if (n.hasIn()) p->drawLine(QLineF(n.p, n.in)); if (n.hasOut()) p->drawLine(QLineF(n.p, n.out)); } p->setPen(QPen(QColor(0x1a, 0x1a, 0x1a), 0)); p->setBrush(handleCol); for (const PathNode &n : sub.nodes) { if (n.hasIn()) p->drawEllipse(n.in, s, s); if (n.hasOut()) p->drawEllipse(n.out, s, s); } for (int ni = 0; ni < sub.nodes.size(); ++ni) { const PathNode &n = sub.nodes.at(ni); const bool sel = (si == m_selSub && ni == m_selNode); p->setBrush(sel ? kSelected : QColor(0xf4, 0xf6, 0xfa)); if (n.kind == PathNode::Corner) { p->drawRect(QRectF(n.p.x() - s, n.p.y() - s, 2 * s, 2 * s)); } else { const double d = s * 1.35; QPolygonF dia; dia << QPointF(n.p.x(), n.p.y() + d) << QPointF(n.p.x() + d, n.p.y()) << QPointF(n.p.x(), n.p.y() - d) << QPointF(n.p.x() - d, n.p.y()); p->drawPolygon(dia); } } } } // A node drag shows its live shape on the item; when the drag is dropped // without a commit, the item goes back to the element's own path. void Canvas::restoreEditItem() { if (m_grab == GrabNone || m_editId.isEmpty() || !m_doc) return; if (const Element *e = m_doc->elementById(m_editId)) if (QGraphicsPathItem *it = itemFor(m_editId)) it->setPath(e->painterPath); } void Canvas::syncEditTarget() { const QStringList ids = selectedElementIds(); restoreEditItem(); m_editId.clear(); m_model = PathModel(); if (m_doc && ids.size() == 1) { Element *e = m_doc->elementById(ids.first()); if (e && Element::isPoint(*e)) { emit statusHint(tr("A sketch point has no nodes — drag it to move it")); } else if (e) { m_editId = e->id; m_model = Element::pathModel(*e); if (m_model.isEmpty()) emit statusHint(tr("Text has no nodes — right-click → Convert to path first")); else if (e->geometryType != QLatin1String("path")) emit statusHint(tr("%1 — editing a node converts it to a path").arg(e->geometryType)); } } m_selSub = m_selNode = -1; m_grab = GrabNone; viewport()->update(); } bool Canvas::hitNode(const QPointF &pos, int *sub, int *node, NodeGrab *what) const { const double tol = pxToMm(kHitPx); // Handles first (they can sit on top of anchors), selected node's first. for (int pass = 0; pass < 2; ++pass) { for (int si = 0; si < m_model.subs.size(); ++si) { const SubPath &sp = m_model.subs.at(si); for (int ni = 0; ni < sp.nodes.size(); ++ni) { const bool sel = (si == m_selSub && ni == m_selNode); if ((pass == 0) != sel) continue; const PathNode &n = sp.nodes.at(ni); if (n.hasOut() && QLineF(pos, n.out).length() <= tol) { *sub = si; *node = ni; *what = GrabOut; return true; } if (n.hasIn() && QLineF(pos, n.in).length() <= tol) { *sub = si; *node = ni; *what = GrabIn; return true; } } } } for (int si = 0; si < m_model.subs.size(); ++si) { const SubPath &sp = m_model.subs.at(si); for (int ni = 0; ni < sp.nodes.size(); ++ni) if (QLineF(pos, sp.nodes.at(ni).p).length() <= tol) { *sub = si; *node = ni; *what = GrabAnchor; return true; } } return false; } bool Canvas::hitSegment(const QPointF &pos, int *sub, int *seg, double *t) const { const double tol = pxToMm(kHitPx); double best = tol; bool hit = false; for (int si = 0; si < m_model.subs.size(); ++si) { int sg; double tt; const double d = m_model.subs.at(si).closest(pos, &sg, &tt); if (sg >= 0 && d < best) { best = d; *sub = si; *seg = sg; *t = tt; hit = true; } } return hit; } void Canvas::previewModel() { if (QGraphicsPathItem *it = itemFor(m_editId)) it->setPath(m_model.painterPath()); viewport()->update(); } void Canvas::commitModel(const QString &what) { if (!m_doc || m_editId.isEmpty()) return; Element *e = m_doc->elementById(m_editId); if (!e) return; const Element after = Element::withPathModel(*e, m_model); if (after.raw == e->raw) { previewModel(); return; } const int keepSub = m_selSub, keepNode = m_selNode; auto *cmd = new EditCmd(this, m_doc, *e, after); cmd->setText(what); pushEdit(cmd, {m_editId}); // rebuild() re-decodes the model m_selSub = keepSub; m_selNode = keepNode; if (m_selSub >= m_model.subs.size() || (m_selSub >= 0 && m_selNode >= m_model.subs.at(m_selSub).nodes.size())) m_selSub = m_selNode = -1; viewport()->update(); } void Canvas::setBackgroundImage(const BackgroundImage *bg) { m_bg = bg; viewport()->update(); } void Canvas::setDocument(Document *doc) { m_doc = doc; m_fitted = false; m_undo->clear(); cancelDrawing(); // Nothing half done on the old design may land in the new one. closeDimEditor(); m_picks.clear(); m_dimPlacing = false; m_dragDim.clear(); m_hoverConstraint.clear(); selectConstraint(QString()); // A selection carried over by id would show on the canvas while the // panels, handed the new document after this, show none. m_scene->clearSelection(); endBand(); // a band on the old design selects nothing in the new one m_deferredPress.valid = false; // The old design's toolpath preview and highlight must not follow it. clearToolpathPreview(); setVectorHighlight({}); rebuild(); } double Canvas::gridSpacing() const { if (!m_doc) return 0; if (m_doc->params().value("grid_enabled", "1") == "0") return 0; const double s = m_doc->params().value("grid_spacing", "5").toDouble(); return s > 0 ? s : 0; } QPointF Canvas::snap(QPointF p) const { const double g = m_snap ? gridSpacing() : 0; if (g <= 0) return p; return QPointF(qRound(p.x() / g) * g, qRound(p.y() / g) * g); } void Canvas::setTool(Tool t) { // An open value editor belongs to the tool it was opened with. if (m_dimEdit && m_dimEdit->isVisible()) { commitDimEditor(false); closeDimEditor(); } if ((m_tool == DrawPath && t != DrawPath) || !m_clicks.isEmpty() || isModifyTool(m_tool) || !m_splinePts.isEmpty() || !m_tanLines.isEmpty() || m_preview) cancelDrawing(); restoreEditItem(); // A Select drag cut off by a tool key: the moved items go back, as a node // drag does (the release only saves a move in Select, so the shape stayed // drawn moved while the design kept it in place). if (m_tool == Select && t != Select) { if (QGraphicsItem *g = m_scene->mouseGrabberItem()) g->ungrabMouse(); for (QGraphicsItem *it : m_scene->items()) if (it->data(0).isValid() && !it->pos().isNull()) it->setPos(0, 0); } m_tool = t; m_drawing = false; m_grab = GrabNone; m_band = false; m_bandKeep.clear(); m_deferredPress.valid = false; // a tap of the old tool lands nowhere viewport()->setCursor(t == Pan ? Qt::OpenHandCursor : t == SelectArea ? Qt::PointingHandCursor : t == Select || t == NodeEdit ? Qt::ArrowCursor : Qt::CrossCursor); const bool selectable = (t == Select || t == NodeEdit || t == Pan || t == SelectArea); for (QGraphicsItem *it : m_scene->items()) { if (it->data(0).isValid()) { it->setFlag(QGraphicsItem::ItemIsSelectable, selectable); it->setFlag(QGraphicsItem::ItemIsMovable, t == Select); } } switch (t) { case Select: emit statusHint(tr("Select — click/drag to select, drag to move, Del to delete, right-click for Convert to path")); break; case DrawCircle: case DrawRect: resetSketch(); sketchHint(); break; case DrawEllipse: emit statusHint(tr("Ellipse — drag across its bounding box; hold Ctrl to drag from the center")); break; case DrawSlot: case DrawConic: case DrawArc: emit statusHint(clickHint()); break; case DrawPoint: emit statusHint(tr("Point — click to place a sketch point (drilling toolpaths drill at it)")); break; case DrawSpline: emit statusHint(tr("Spline — click the points it passes through; Enter or double-click finishes, click near the start closes, Esc cancels")); break; case Trim: emit statusHint(tr("Trim — click the piece of a curve to cut away, up to where other curves cross it")); break; case Extend: emit statusHint(tr("Extend — click near the end of an open curve to run it on to the next curve")); break; case Break: emit statusHint(tr("Break — click a curve to split it where other curves cross it")); break; case Measure: emit statusHint(tr("Measure — drag from one point to another (snaps to the grid when Snap is on)")); break; case DrawPolygon: emit statusHint(m_polyMode == PolyEdge ? clickHint() : m_polyMode == PolyCircumscribed ? tr("Polygon (circumscribed) — press at the center, drag to the middle of an edge") : tr("Polygon (inscribed) — press at the center, drag to a corner")); break; case DrawPath: emit statusHint(tr("Path — click = corner, click-drag = curve; Enter finishes, click near start closes, Esc cancels")); break; case DrawText: emit statusHint(tr("Text — click to place the baseline start")); break; case SelectArea: emit statusHint(tr("Area — click inside an area, like a fill: selects just that area (not the shapes inside it); Shift adds")); break; case Pan: emit statusHint(tr("Hand — drag to move the view; the wheel or - / + zoom")); break; case NodeEdit: emit statusHint(tr("Nodes — drag anchors/handles (Alt breaks symmetry), double-click a segment to add, Del removes, right-click a node for its kind")); break; case Constrain: case Dimension: break; // resetPicks() below says what to click } if (t == Constrain || t == Dimension || !m_picks.isEmpty() || m_dimPlacing) resetPicks(); if (t == NodeEdit) syncEditTarget(); else { m_editId.clear(); m_model = PathModel(); } viewport()->update(); emit toolChanged(t); } void Canvas::zoomFit() { if (!m_doc) return; // Something selected: fill the window with it, centred. Else the plate. QRectF sel; for (QGraphicsItem *it : m_scene->selectedItems()) if (it->data(0).isValid()) { // The geometry, not the item's bounds: those include the wide // invisible hit pen, which is mostly margin when zoomed out. if (auto *pi = qgraphicsitem_cast(it)) sel |= pi->mapRectToScene(pi->path().boundingRect()); else sel |= it->sceneBoundingRect(); } if (sel.width() > 0 || sel.height() > 0) { const double m = qMax(qMax(sel.width(), sel.height()) * 0.04, 0.5); fitInView(sel.adjusted(-m, -m, m, m), Qt::KeepAspectRatio); centerOn(sel.center()); emitZoom(); return; } const double w = m_doc->boardWidth(), h = m_doc->boardHeight(); if (w > 0 && h > 0) fitInView(QRectF(-10, -10, w + 20, h + 20), Qt::KeepAspectRatio); emitZoom(); } void Canvas::rebuild() { updateStockLabel(); // The scene is rebuilt from scratch; keep the selection (and with it the // node-edit target and the properties panel) across the edit. const QStringList selected = selectedElementIds(); // A band being dragged keeps what Ctrl held selected by id: the items // it pointed at are deleted with the scene. // (Only while it is dragged: a band ended by a tool change may leave // its set behind, pointing at nothing.) QSet bandKeepIds; if (m_band) for (QGraphicsItem *it : std::as_const(m_bandKeep)) if (it->data(0).isValid()) bandKeepIds.insert(it->data(0).toString()); m_bandKeep.clear(); m_scene->blockSignals(true); m_preview = nullptr; // owned by the scene; clear() deletes it m_resizing = false; // its preview is gone with the scene m_previewItems.clear(); // likewise m_modifyModels.clear(); // decoded from the elements as they were m_modifyDecoded.clear(); m_scene->clear(); if (!m_doc) { m_scene->blockSignals(false); onSelectionChanged(); return; } const double w = m_doc->boardWidth(); const double h = m_doc->boardHeight(); // Margin so the rubber band / fit has somewhere to breathe. m_scene->setSceneRect(QRectF(-w * 2 - 200, -h * 2 - 200, w * 5 + 400, h * 5 + 400)); const bool selectable = (m_tool == Select || m_tool == NodeEdit || m_tool == Pan || m_tool == SelectArea); refreshParametricState(); m_hitScale = qAbs(transform().m11()); const double hitTol = pxToMm(kHitPx); for (const Element &e : m_doc->elements()) { // Open paths are the only unfilled type; a path row of point_type 4 // marks a closed one. bool closed = e.geometryType != QLatin1String("path"); if (!closed) for (const auto &v : e.raw.value("point_type").toArray()) if (v.toInt() == 4) { closed = true; break; } auto *item = new ElemItem(e.painterPath, closed, Element::isConstruction(e), Element::isPoint(e), m_full.contains(e.id)); item->setHitTolerance(hitTol); // Stacking by size, not by the order the shapes were added: a closed // shape is selectable from anywhere inside it, so a big outline added // after a small hole covered the hole completely and the hole could // not be clicked at all (imported DXF files list the outline last, // 2026-10-24). The smaller the shape's box, the higher it sits; equal // sizes keep their order. Open paths and points have tiny boxes, so // they stay on top of the closed shapes they run across. The preview // overlays sit at z 5 and 6, above all of this (z stays under 4). { const QRectF bb = e.painterPath.boundingRect(); item->setZValue(4.0 / (1.0 + std::sqrt(qMax(0.0, bb.width() * bb.height())))); } m_scene->addItem(item); item->setToolTip(QStringLiteral("%1 %2").arg(e.geometryType, e.id)); item->setData(0, e.id); // scene item -> element item->setFlag(QGraphicsItem::ItemIsSelectable, selectable); item->setFlag(QGraphicsItem::ItemIsMovable, m_tool == Select); if (selected.contains(e.id)) item->setSelected(true); if (m_band && bandKeepIds.contains(e.id)) m_bandKeep.insert(item); } if (!m_previewOps.isEmpty()) renderPreviewOps(); m_scene->blockSignals(false); onSelectionChanged(); // First-load fit. Only trust the viewport once it has been laid out; // otherwise fitInView() scales to a placeholder size (0% zoom). The // resizeEvent below picks it up when the real geometry arrives. if (!m_fitted && w > 0 && h > 0 && isVisible() && viewport()->width() > 100) { zoomFit(); m_fitted = true; } } void Canvas::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); placeHud(); updateStockLabel(); if (!m_fitted && m_doc && m_doc->boardWidth() > 0 && m_doc->boardHeight() > 0 && viewport()->width() > 100) { zoomFit(); m_fitted = true; } } void Canvas::setVectorHighlight(const QStringList &ids) { if (m_highlightIds == ids && !m_highlightPartial) return; m_highlightIds = ids; m_highlightPartial = false; m_highlightLeft = QPainterPath(); viewport()->update(); } void Canvas::setVectorHighlight(const QStringList &ids, const QPainterPath &left) { m_highlightIds = ids; m_highlightPartial = true; m_highlightLeft = left; viewport()->update(); } // Only the overlay items are replaced: the preview is regenerated in the // background whenever the model changes, and a full rebuild() here would // pull the scene out from under a drag, a node edit or a shape being drawn. void Canvas::setToolpathPreview(const QVector &ops) { removePreviewItems(); m_previewOps = ops; if (!m_previewOps.isEmpty()) renderPreviewOps(); } void Canvas::clearToolpathPreview() { removePreviewItems(); m_previewOps.clear(); } void Canvas::removePreviewItems() { for (QGraphicsItem *it : std::as_const(m_previewItems)) { m_scene->removeItem(it); delete it; } m_previewItems.clear(); } // Draw the generated machine motion over the vectors: rapids as dashed gray, // cutting moves colored shallow-yellow → deep-red by Z, arcs sampled to // segments. Overlay items are unselectable and sit above the elements. // // Simple mode (the default, View > Simplified toolpath preview): the swept // area is one opaque yellow stroke the width of the bit, so a pocket is a // solid patch instead of a hatch, and only every 5th ring of a cut chain is // drawn as a line on top (always the first and last ring; a chain with no // closed ring, like a contour, is drawn in full). A ring is found as the // point where the XY path returns to the vertex where that ring began; the // link move to the next ring stays down between rings. void Canvas::renderPreviewOps() { double zMin = 0; for (const Op &op : m_previewOps) if ((op.kind == Op::Feed || op.kind == Op::Arc) && op.z < zMin) zMin = op.z; const int NB = 8; auto bucketOf = [&](double z) { if (zMin >= -1e-9) return 0; return qBound(0, int((z / zMin) * NB), NB - 1); }; QVector cut(NB); QPainterPath rapids; QPainterPath sweep; // simple mode: centre line of every cut with the current bit double toolDia = 0; // ...and of the bits before it: each is stroked at its own width, so a // job with several tools does not show them all as wide as the last one. struct Sweep { double dia; QPainterPath path; }; QVector sweeps; struct Piece { int bucket; int ring; QPainterPath path; }; QVector chain; // simple mode: the current cut chain int ring = 0; double ringLen = 0, rsx = 0, rsy = 0; bool linkPending = false, chainOpen = false; auto flushChain = [&]() { // `ring` counts the rings closed so far. A chain that ends as a ring // closes (linkPending: no link move followed) has no piece numbered // `ring`; its last ring is the one before. const int last = linkPending ? ring - 1 : ring; for (const Piece &p : chain) { sweep.addPath(p.path); const bool keep = ring == 0 || p.ring == 0 || p.ring == last || p.ring % 5 == 0; if (keep) cut[p.bucket].addPath(p.path); } chain.clear(); ring = 0; ringLen = 0; linkPending = false; chainOpen = false; }; // One cut move from (x0,y0) to (x1,y1): in simple mode it joins the // current chain and may close a ring; otherwise it is drawn as it is. auto addCut = [&](int b, const QPainterPath &seg, double x0, double y0, double x1, double y1, double len) { if (!m_simplePreview) { cut[b].addPath(seg); return; } if (!chainOpen) { chainOpen = true; rsx = x0; rsy = y0; ringLen = 0; ring = 0; linkPending = false; } chain.append({b, ring, seg}); if (linkPending) { // the link to the next ring: it ends where that ring begins rsx = x1; rsy = y1; ringLen = 0; linkPending = false; return; } ringLen += len; (void)x0; (void)y0; if (ringLen > 1.0 && qAbs(x1 - rsx) < 1e-3 && qAbs(y1 - rsy) < 1e-3) { ++ring; linkPending = true; } }; double x = 0, y = 0; bool have = false; for (const Op &op : m_previewOps) { switch (op.kind) { case Op::Tool: if (op.x > 0 && op.x != toolDia) { // A bit of another width: what was cut so far keeps its own. if (m_simplePreview) { flushChain(); if (!sweep.isEmpty()) { sweeps.append({toolDia, sweep}); sweep = QPainterPath(); } } toolDia = op.x; } break; case Op::Rapid: if (m_simplePreview) flushChain(); if (have && (op.x != x || op.y != y)) { rapids.moveTo(x, y); rapids.lineTo(op.x, op.y); } x = op.x; y = op.y; have = true; break; case Op::Feed: { const int b = bucketOf(op.z); if (have) { if (op.x == x && op.y == y) { // pure plunge: mark with a tiny diamond; it also ends a chain if (m_simplePreview) flushChain(); cut[b].moveTo(x - 0.4, y); cut[b].lineTo(x, y + 0.4); cut[b].lineTo(x + 0.4, y); cut[b].lineTo(x, y - 0.4); cut[b].closeSubpath(); } else { QPainterPath seg; seg.moveTo(x, y); seg.lineTo(op.x, op.y); addCut(b, seg, x, y, op.x, op.y, QLineF(x, y, op.x, op.y).length()); } } x = op.x; y = op.y; have = true; break; } case Op::Arc: { const int b = bucketOf(op.z); const double cx = x + op.ci, cy = y + op.cj; const double r = QLineF(QPointF(cx, cy), QPointF(x, y)).length(); double a0 = qAtan2(y - cy, x - cx); double a1 = qAtan2(op.y - cy, op.x - cx); // G2 = clockwise in Y-up space = decreasing angle. if (op.cw) { while (a1 >= a0 - 1e-12) a1 -= 2 * M_PI; } else { while (a1 <= a0 + 1e-12) a1 += 2 * M_PI; } const int steps = qMax(8, int(qAbs(a1 - a0) / (M_PI / 36))); QPainterPath seg; seg.moveTo(x, y); for (int i = 1; i <= steps; ++i) { const double a = a0 + (a1 - a0) * i / steps; seg.lineTo(cx + r * qCos(a), cy + r * qSin(a)); } addCut(b, seg, x, y, op.x, op.y, r * qAbs(a1 - a0)); x = op.x; y = op.y; have = true; break; } default: break; } } if (m_simplePreview) flushChain(); QPen rapidPen(QColor(0x8a, 0x94, 0xa6, 140)); rapidPen.setCosmetic(true); rapidPen.setStyle(Qt::DashLine); auto *ri = new OverlayItem(rapids, rapidPen); ri->setZValue(5); m_scene->addItem(ri); m_previewItems.append(ri); if (m_simplePreview && !sweep.isEmpty()) sweeps.append({toolDia, sweep}); for (const Sweep &s : std::as_const(sweeps)) { QPen fillPen(QColor(0xff, 0xd6, 0x00)); // opaque: overlaps do not stack fillPen.setCosmetic(s.dia <= 0); fillPen.setWidthF(s.dia > 0 ? s.dia : 2.0); fillPen.setCapStyle(Qt::RoundCap); fillPen.setJoinStyle(Qt::RoundJoin); auto *fi = new OverlayItem(s.path, fillPen); fi->setZValue(5.5); m_scene->addItem(fi); m_previewItems.append(fi); } for (int b = 0; b < NB; ++b) { if (cut.at(b).isEmpty()) continue; const double f = NB > 1 ? double(b) / (NB - 1) : 0; QColor col = m_simplePreview ? QColor::fromHsvF(0.10 * (1.0 - f), 1.0, 0.80) // orange→red on the yellow : QColor::fromHsvF(0.14 * (1.0 - f), 0.9, 1.0); // yellow→red col.setAlpha(m_simplePreview ? 255 : 200); QPen pen(col); pen.setCosmetic(true); pen.setWidthF(1.4); auto *it = new OverlayItem(cut.at(b), pen); it->setZValue(6); m_scene->addItem(it); m_previewItems.append(it); } } void Canvas::setSimplePreview(bool on) { if (m_simplePreview == on) return; m_simplePreview = on; if (!m_previewOps.isEmpty()) { removePreviewItems(); renderPreviewOps(); } } void Canvas::drawBackground(QPainter *p, const QRectF &rect) { QGraphicsView::drawBackground(p, rect); if (!m_doc) return; const double w = m_doc->boardWidth(), h = m_doc->boardHeight(); if (w <= 0 || h <= 0) return; const QRectF board(0, 0, w, h); p->setPen(QPen(kBoardEdge, 0)); p->setBrush(kBoardFill); p->drawRect(board); if (m_bg) m_bg->paint(p); // under the grid and the vectors // Grid: minor lines at grid_spacing, majors every 5th. Skip minors when // they would sit closer than ~6 px on screen. const double g = gridSpacing(); if (g > 0) { const double pxPerMm = transform().m11(); const bool minors = g * pxPerMm >= 6.0; QPen minorPen(kGridMinor, 0), majorPen(kGridMajor, 0); // Only the lines that can show in the exposed rect are walked (2 px // more each side, for the pen and its antialiasing), and only the // majors when the minors are off: a fine grid on a big board used to // cost a pass over every line of the board at every paint. const double pad = 2.0 / qMax(1e-9, std::fabs(p->worldTransform().m11())); auto gridLines = [&](double from, double to, double extent, bool vertical) { const double top = 4e18; // any spacing keeps the line number inside qint64 const double a = std::ceil((from - pad) / g), b = std::floor((to + pad) / g); if (!(b >= 1.0) || !(a <= top)) // nothing exposed on the board (or not a number) return; qint64 i = a > 1.0 ? qint64(a) : 1; const qint64 last = b < top ? qint64(b) : qint64(top); if (!minors) i += (5 - i % 5) % 5; // the first major at or after i for (; i <= last && i * g < extent; i += minors ? 1 : 5) { p->setPen(i % 5 == 0 ? majorPen : minorPen); p->drawLine(vertical ? QLineF(i * g, 0, i * g, h) : QLineF(0, i * g, w, i * g)); } }; gridLines(rect.left(), rect.right(), w, true); gridLines(rect.top(), rect.bottom(), h, false); } // Origin axes along the board's bottom/left edges. p->setPen(QPen(kAxisX, 0)); p->drawLine(QLineF(0, 0, qMin(w, 15.0), 0)); p->setPen(QPen(kAxisY, 0)); p->drawLine(QLineF(0, 0, 0, qMin(h, 15.0))); } // The box a rectangle / ellipse drag spans: corner to corner, or (Ctrl) // centered on the press point with the cursor at a corner. static QRectF dragBox(const QPointF &anchor, const QPointF &cur, bool fromCenter) { if (!fromCenter) return QRectF(anchor, cur).normalized(); const QPointF d(std::fabs(cur.x() - anchor.x()), std::fabs(cur.y() - anchor.y())); return QRectF(anchor - d, anchor + d); } // "Measure" readout: length, the X / Y components and the angle (CCW from +X). static QString measureText(const QPointF &a, const QPointF &b) { const QPointF d = b - a; return QObject::tr("%1 mm ΔX %2 ΔY %3 %4°") .arg(std::hypot(d.x(), d.y()), 0, 'f', 3) .arg(d.x(), 0, 'f', 3) .arg(d.y(), 0, 'f', 3) .arg(qRadiansToDegrees(std::atan2(d.y(), d.x())), 0, 'f', 2); } // Distance from p to the infinite line through a and b (to a when a == b). static double lineDistance(const QPointF &p, const QPointF &a, const QPointF &b) { const QPointF d = b - a; const double len = std::hypot(d.x(), d.y()); if (len < 1e-12) return QLineF(p, a).length(); return std::fabs(d.x() * (p.y() - a.y()) - d.y() * (p.x() - a.x())) / len; } bool Canvas::clickTool() const { return isClickTool(m_tool) || (m_tool == DrawPolygon && m_polyMode == PolyEdge); } int Canvas::clicksNeeded() const { if (m_tool == DrawArc) return m_arcMode == ArcTangent ? 2 : 3; if (m_tool == DrawSlot) return m_slotMode == SlotArc3Point ? 4 : 3; return 3; // edge polygon } QString Canvas::clickHint() const { const int n = m_clicks.size(); if (m_tool == DrawArc) { switch (m_arcMode) { case Arc3Point: return n == 0 ? tr("Arc (3-point) — click the start") : n == 1 ? tr("Arc: click the end point") : tr("Arc: click a point the arc passes through"); case ArcCenter: return n == 0 ? tr("Arc (center point) — click the center") : n == 1 ? tr("Arc: click the start (sets the radius)") : tr("Arc: move round the way it should go, click the end"); case ArcTangent: return n == 0 ? tr("Arc (tangent) — click near the end of an open line or curve") : tr("Arc: click the end point"); } } if (m_tool == DrawSlot) { switch (m_slotMode) { case SlotCenterToCenter: return n == 0 ? tr("Slot (center to center) — click the first end's center") : n == 1 ? tr("Slot: click the second center") : tr("Slot: click to set the width"); case SlotOverall: return n == 0 ? tr("Slot (overall) — click one end of the slot") : n == 1 ? tr("Slot: click the other end") : tr("Slot: click to set the width"); case SlotCenterPoint: return n == 0 ? tr("Slot (center point) — click the slot's middle") : n == 1 ? tr("Slot: click one end's center") : tr("Slot: click to set the width"); case SlotArc3Point: return n == 0 ? tr("Arc slot — click the start of its centerline") : n == 1 ? tr("Arc slot: click the end of the centerline") : n == 2 ? tr("Arc slot: click a point the centerline passes through") : tr("Arc slot: click to set the width"); } } if (m_tool == DrawConic) return n == 0 ? tr("Conic — click the start") : n == 1 ? tr("Conic: click the end") : tr("Conic: click the apex its end tangents meet at (rho sets the fullness)"); return n == 0 ? tr("Polygon (edge) — click one end of an edge") : n == 1 ? tr("Polygon: click the other end of the edge") : tr("Polygon: click the side it goes on"); } bool Canvas::clickShape(const QVector &pts, Element *out) const { if (!m_doc || pts.size() < clicksNeeded()) return false; const QJsonObject layer = m_doc->defaultLayer(); const QPointF a = pts.at(0), b = pts.at(1); PathModel m; if (m_tool == DrawSlot) { const QPointF c = pts.at(2); if (QLineF(a, b).length() < 1e-6) return false; if (m_slotMode == SlotArc3Point) { QPointF o; double r = 0; if (!sketch::circleThrough(a, c, b, &o, &r)) return false; m = sketch::arcSlot(a, b, c, 2 * std::fabs(QLineF(o, pts.at(3)).length() - r)); } else { const double w = 2 * lineDistance(c, a, b); if (w <= 0.1) return false; m = m_slotMode == SlotOverall ? sketch::slotOverall(a, b, w) : m_slotMode == SlotCenterPoint ? sketch::slotCenterPoint(a, b, w) : sketch::slot(a, b, w); } } else if (m_tool == DrawConic) { if (QLineF(a, b).length() < 1e-6) return false; m = sketch::conic(a, b, pts.at(2), m_conicRho); } else if (m_tool == DrawArc) { m = m_arcMode == ArcCenter ? sketch::arcCenter(a, b, pts.at(2), m_arcTurn >= 0) : m_arcMode == ArcTangent ? sketch::arcTangent(a, m_tanDir, b) : sketch::arc3(a, b, pts.at(2)); } else if (m_tool == DrawPolygon) { QPointF ctr; double r = 0, rot = 0; if (sketch::polygonEdge(a, b, pts.at(2), m_polySides, &ctr, &r, &rot).isEmpty() || lineDistance(pts.at(2), a, b) < 1e-9) return false; *out = Element::makePolygon(ctr, r, m_polySides, layer, rot); return true; } if (m.isEmpty()) return false; *out = Element::makeBezierPath(m, layer); return true; } QPainterPath Canvas::clickPreview(const QPointF &cur) const { QPainterPath p; if (m_clicks.isEmpty()) return p; QVector pts = m_clicks; pts.append(cur); Element e; if (pts.size() >= clicksNeeded() && clickShape(pts, &e)) { p = e.painterPath; if (m_tool == DrawSlot && m_slotMode != SlotArc3Point) { p.moveTo(pts.at(0)); // the line clicked, for reference p.lineTo(pts.at(1)); } if (m_tool == DrawConic) { // the two end tangents through the apex p.moveTo(pts.at(0)); p.lineTo(pts.at(2)); p.lineTo(pts.at(1)); } return p; } if (m_tool == DrawSlot && m_slotMode == SlotArc3Point && pts.size() == 3) return sketch::arc3(pts.at(0), pts.at(1), pts.at(2)).painterPath(); if (m_tool == DrawArc && m_arcMode == ArcCenter && pts.size() == 2) p.addEllipse(pts.at(0), QLineF(pts.at(0), cur).length(), QLineF(pts.at(0), cur).length()); p.moveTo(pts.first()); for (int i = 1; i < pts.size(); ++i) p.lineTo(pts.at(i)); return p; } void Canvas::trackArcTurn(const QPointF &cur) { if (m_tool != DrawArc || m_arcMode != ArcCenter || m_clicks.size() != 2) return; const QPointF c = m_clicks.first(); if (QLineF(c, cur).length() < 1e-9) return; const double ang = std::atan2(cur.y() - c.y(), cur.x() - c.x()); double d = ang - m_arcLastAng; while (d > M_PI) d -= 2 * M_PI; while (d <= -M_PI) d += 2 * M_PI; m_arcTurn += d; m_arcLastAng = ang; } bool Canvas::pickOpenEnd(const QPointF &q, QPointF *end, QPointF *dir) const { if (!m_doc) return false; double best = pxToMm(10); bool found = false; for (const Element &e : m_doc->elements()) { if (Element::isPoint(e)) continue; const PathModel m = Element::pathModel(e); for (const SubPath &sp : m.subs) { if (sp.closed || sp.nodes.size() < 2) continue; const int n = sp.nodes.size(); const PathNode &f = sp.nodes.first(), &l = sp.nodes.last(); // Leaving an end means carrying on the way the curve arrives there. // Its own handle, else the next node's handle (an S after a // line), else the chord. const PathNode &f1 = sp.nodes.at(1), &l1 = sp.nodes.at(n - 2); const QPointF outFirst = f.hasOut() ? f.p - f.out : f1.hasIn() ? f.p - f1.in : f.p - f1.p; const QPointF outLast = l.hasIn() ? l.p - l.in : l1.hasOut() ? l.p - l1.out : l.p - l1.p; for (const auto &cand : {qMakePair(f.p, outFirst), qMakePair(l.p, outLast)}) { const double d = QLineF(cand.first, q).length(); if (d <= best && std::hypot(cand.second.x(), cand.second.y()) > 1e-9) { best = d; *end = cand.first; *dir = cand.second; found = true; } } } } return found; } void Canvas::clickToolPress(const QPointF &posIn) { QPointF pos = posIn; if (!m_clicks.isEmpty() && QLineF(pos, m_clicks.last()).length() < 1e-6) return; // a double-click's second press, or a click on the same spot if (m_tool == DrawArc && m_arcMode == ArcTangent && m_clicks.isEmpty()) { QPointF end, dir; if (!pickOpenEnd(pos, &end, &dir)) { emit statusHint(tr("No open end there — click near the end of a line or curve")); return; } pos = end; m_tanDir = dir; } m_clicks.append(pos); if (m_tool == DrawArc && m_arcMode == ArcCenter && m_clicks.size() == 2) { m_arcTurn = 0; m_arcLastAng = std::atan2(pos.y() - m_clicks.first().y(), pos.x() - m_clicks.first().x()); } if (m_clicks.size() < clicksNeeded()) { if (!m_preview) { QPen pen(kPreview); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); m_preview = m_scene->addPath(QPainterPath(), pen); } m_preview->setPath(clickPreview(pos)); emit statusHint(clickHint()); viewport()->update(); return; } trackArcTurn(pos); Element e; if (clickShape(m_clicks, &e)) m_undo->push(new AddCmd(this, m_doc, e)); cancelDrawing(); emit statusHint(clickHint()); viewport()->update(); } void Canvas::finishSpline(bool closed) { while (m_splinePts.size() >= 2 && QLineF(m_splinePts.last(), m_splinePts.at(m_splinePts.size() - 2)).length() < 1e-9) m_splinePts.removeLast(); if (m_doc && m_splinePts.size() >= 2) { const PathModel m = sketch::fitSpline(m_splinePts, closed && m_splinePts.size() >= 3); if (!m.isEmpty()) { m_undo->push(new AddCmd(this, m_doc, Element::makeBezierPath(m, m_doc->defaultLayer()))); emit statusHint(m.subs.first().closed ? tr("Closed spline added") : tr("Spline added")); } } cancelDrawing(); viewport()->update(); } void Canvas::toggleConstruction(const QStringList &ids) { if (!m_doc) return; QVector els; bool allOn = true; for (const QString &id : ids) if (const Element *e = m_doc->elementById(id)) { els.append(*e); allOn = allOn && Element::isConstruction(*e); } if (els.isEmpty()) return; const bool on = !allOn; m_undo->beginMacro(on ? tr("make %1 vector(s) construction").arg(els.size()) : tr("make %1 vector(s) normal").arg(els.size())); for (const Element &e : els) if (Element::isConstruction(e) != on) m_undo->push(new EditCmd(this, m_doc, e, Element::withConstruction(e, on))); m_undo->endMacro(); emit statusHint(on ? tr("%1 vector(s) are construction geometry: drawn dashed, never machined") .arg(els.size()) : tr("%1 vector(s) are normal geometry again").arg(els.size())); } // ---- trim / extend / break ---------------------------------------------------- bool Canvas::modifyTarget(const QPointF &q, QString *id, PathModel *model, QVector *others) const { if (!m_doc) return false; const double tol = pxToMm(8); double best = tol; int bestIdx = -1; const QVector &els = m_doc->elements(); // Each element is decoded once and kept until the next rebuild(), and // only when it is needed: this runs on every mouse move, and decoding // every element each time made the tools drag on a big drawing. if (m_modifyModels.size() != els.size() || m_modifyDecoded.size() != els.size()) { m_modifyModels = QVector(els.size()); m_modifyDecoded = QVector(els.size(), false); } auto modelAt = [&](int i) -> const PathModel & { if (!m_modifyDecoded.at(i)) { // Text and sketch points: empty, never a target nor a bound. m_modifyModels[i] = Element::isPoint(els.at(i)) ? PathModel() : Element::pathModel(els.at(i)); m_modifyDecoded[i] = true; } return m_modifyModels.at(i); }; for (int i = 0; i < els.size(); ++i) { int sub; double g; if (!els.at(i).painterPath.boundingRect().adjusted(-tol, -tol, tol, tol).contains(q)) continue; const PathModel &pm = modelAt(i); if (sketch::pick(pm, q, best, &sub, &g)) { const SubPath &sp = pm.subs.at(sub); const int seg = qMin(int(g), sp.segmentCount() - 1); best = QLineF(sp.pointAt(seg, g - seg), q).length(); bestIdx = i; } } if (bestIdx < 0) return false; *id = els.at(bestIdx).id; *model = modelAt(bestIdx); others->clear(); for (int i = 0; i < els.size(); ++i) { if (i == bestIdx) continue; const PathModel &pm = modelAt(i); if (!pm.isEmpty()) others->append(pm); } return true; } QPainterPath Canvas::modifyPreview(const QPointF &q) const { QString id; PathModel m; QVector others; if (!modifyTarget(q, &id, &m, &others)) return QPainterPath(); const double tol = pxToMm(8); int sub; double g; if (!sketch::pick(m, q, tol, &sub, &g)) return QPainterPath(); if (m_tool == Extend) { PathModel grown = m; if (!sketch::extend(grown, q, tol, others)) return QPainterPath(); // Just the new stretch: from the old end to the new one. const SubPath &a = m.subs.at(sub), &b = grown.subs.at(sub); const bool atEnd = QLineF(q, a.nodes.last().p).length() < QLineF(q, a.nodes.first().p).length(); QPainterPath p(atEnd ? a.nodes.last().p : a.nodes.first().p); p.lineTo(atEnd ? b.nodes.last().p : b.nodes.first().p); return p; } double from, to; sketch::pieceAround(m, sub, g, sketch::crossings(m, sub, others), &from, &to); PathModel piece; piece.subs.append(sketch::subRange(m.subs.at(sub), from, to)); return piece.painterPath(); } void Canvas::modifyAt(const QPointF &q) { QString id; PathModel m; QVector others; // An edit never works from paths decoded earlier: should the elements // have changed without a rebuild(), only a hover preview may be stale. m_modifyModels.clear(); m_modifyDecoded.clear(); if (!modifyTarget(q, &id, &m, &others)) { emit statusHint(tr("No curve there")); return; } // A shape locked with Fix stays as it is: a trim, extend or break of it // would only be put back (and a break would leave its pieces behind). if (param::lockedElements(*m_doc).contains(id)) { emit statusHint(tr("This shape is locked with Fix: remove the Fix to change it")); return; } const Element before = *m_doc->elementById(id); const double tol = pxToMm(8); switch (m_tool) { case Trim: { bool hit = false; const PathModel rest = sketch::trim(m, q, tol, others, &hit); if (!hit) return; if (rest.isEmpty()) pushEdit(new DeleteCmd(this, m_doc, {before}), {before.id}); else pushEdit(new EditCmd(this, m_doc, before, Element::withPathModel(before, rest)), {before.id}); emit statusHint(rest.isEmpty() ? tr("Trimmed: nothing crossed it, so the whole curve went") : tr("Trimmed")); break; } case Extend: { if (!sketch::extend(m, q, tol, others)) { emit statusHint(tr("Nothing ahead to extend to (closed curves have no ends)")); return; } pushEdit(new EditCmd(this, m_doc, before, Element::withPathModel(before, m)), {before.id}); emit statusHint(tr("Extended")); break; } case Break: { const QVector parts = sketch::breakAt(m, q, tol, others); if (parts.isEmpty()) { emit statusHint(tr("Nothing crosses this curve: nothing to break at")); return; } QVector after; after.append(Element::withPathModel(before, parts.first())); for (int i = 1; i < parts.size(); ++i) after.append(Element::pieceOf(before, parts.at(i))); QHash piecesOf; for (const Element &e : after) piecesOf[before.id] << e.id; pushEdit(new ReplaceCmd(this, m_doc, {before}, after, tr("break into %1 pieces").arg(after.size()), piecesOf), {before.id}); emit statusHint(tr("Broken into %1 pieces").arg(after.size())); break; } default: break; } if (m_preview) m_preview->setPath(modifyPreview(q)); } // Polygon by dragging from the center: inscribed puts a corner under the // cursor, circumscribed the middle of an edge (Fusion's two center modes). static void polygonDrag(QPointF c, QPointF cur, int sides, bool circumscribed, double *radius, double *rotationDeg) { const double d = QLineF(c, cur).length(); const double ang = d > 1e-12 ? std::atan2(cur.y() - c.y(), cur.x() - c.x()) : 0.0; const double half = M_PI / qMax(3, sides); *radius = circumscribed ? d / std::cos(half) : d; *rotationDeg = qRadiansToDegrees(circumscribed ? ang + half : ang); } QPainterPath Canvas::previewPath(const QPointF &cur) const { QPainterPath p; switch (m_tool) { case DrawCircle: { const double r = QLineF(m_anchor, cur).length(); p.addEllipse(m_anchor, r, r); break; } case DrawRect: p.addRect(dragBox(m_anchor, cur, m_fromCenter)); break; case DrawEllipse: { const QRectF b = dragBox(m_anchor, cur, m_fromCenter); p.addEllipse(b); break; } case Measure: { p.moveTo(m_anchor); p.lineTo(cur); // Small crosses on both ends. const double k = pxToMm(5); for (const QPointF &e : {m_anchor, cur}) { p.moveTo(e - QPointF(k, k)); p.lineTo(e + QPointF(k, k)); p.moveTo(e - QPointF(k, -k)); p.lineTo(e + QPointF(k, -k)); } break; } case DrawPolygon: { double r = 0, rot = 0; polygonDrag(m_anchor, cur, m_polySides, m_polyMode == PolyCircumscribed, &r, &rot); for (int i = 0; i <= m_polySides; ++i) { const double a = 2.0 * M_PI * i / m_polySides + qDegreesToRadians(rot); const QPointF v = m_anchor + QPointF(r * qCos(a), r * qSin(a)); if (i == 0) p.moveTo(v); else p.lineTo(v); } break; } case DrawPath: if (!m_penNodes.isEmpty()) { PathModel m; SubPath sp; sp.nodes = m_penNodes; if (!m_penDrag) { // Rubber segment to the cursor: a corner would land there. PathNode c; c.p = c.in = c.out = cur; sp.nodes.append(c); } m.subs.append(sp); p = m.painterPath(); } break; default: break; } return p; } void Canvas::cancelDrawing() { m_deferredPress.valid = false; m_drawing = false; m_clicks.clear(); m_tanLines.clear(); m_penNodes.clear(); m_penDrag = false; m_splinePts.clear(); m_arcTurn = 0; m_resizing = false; // a resize drag cancelled, not committed on release clearPreview(); } void Canvas::finishPath(bool closed) { // A double-click's second press leaves a duplicate of the previous node. while (m_penNodes.size() >= 2 && QLineF(m_penNodes.last().p, m_penNodes.at(m_penNodes.size() - 2).p).length() < 1e-9) m_penNodes.removeLast(); if (m_doc && m_penNodes.size() >= 2) { PathModel m; SubPath sp; sp.nodes = m_penNodes; sp.closed = closed && penClosable(m_penNodes); if (!sp.closed) { // no segment arrives at the first / leaves the last node sp.nodes.first().in = sp.nodes.first().p; sp.nodes.last().out = sp.nodes.last().p; } m.subs.append(sp); const Element e = Element::makeBezierPath(m, m_doc->defaultLayer()); m_undo->push(new AddCmd(this, m_doc, e)); emit statusHint(sp.closed ? tr("Closed path added") : tr("Path added")); } cancelDrawing(); viewport()->update(); } void Canvas::mousePressEvent(QMouseEvent *event) { if (m_pinching) { if (fromTouch(event)) { event->accept(); // a finger of the pinch: the pinch has the view return; } m_pinching = false; // a real mouse: whatever pinch there was is over } if (fromTouch(event)) m_touchPress = {true, int(m_clicks.size()), int(m_tanLines.size()), int(m_penNodes.size()), int(m_splinePts.size()), selectedElementIds(), false}; else m_touchPress = TouchPress(); syncHitTolerance(); // A press that lands outside the drawing is not on the drawing. On the // CNC PC's touch screen a tap on a toolbar button (Contour) also reached // the canvas, as a press above its top edge: it started a select band // there and replaced the selection the button was about to use // (Phobic, 2026-10-27). Nothing outside the drawing changes the selection. // (A mouse press always lands on the drawing; tests press anywhere.) if (fromTouch(event) && !viewport()->rect().contains(event->pos())) { endBand(); event->ignore(); return; } // A band still open at a new press lost its release (a touch that ended // somewhere else): it ends here, without stretching to the new point. endBand(); m_deferredPress.valid = false; // a press whose release never came if (!m_replaying && fromTouch(event) && event->button() == Qt::LeftButton && commitsOnPress(event->pos())) { m_deferredPress = {true, event->position(), event->globalPosition(), event->modifiers(), false}; event->accept(); return; } if (event->button() == Qt::MiddleButton || (m_tool == Pan && event->button() == Qt::LeftButton)) { m_panning = true; m_panLast = event->pos(); viewport()->setCursor(Qt::ClosedHandCursor); event->accept(); return; } if (parametricPress(event)) return; // Select closed area: the face around the click, like a fill tool. if (m_tool == SelectArea && event->button() == Qt::LeftButton) { selectAreaAt(mapToScene(event->pos()), event->modifiers() & Qt::ShiftModifier); event->accept(); return; } // Resize-handle grab (Select mode, single selection). if (m_tool == Select && event->button() == Qt::LeftButton) { QString id, type; QPointF hpos; if (resizeHandle(&id, &hpos, &type)) { const double tol = 8.0 / qMax(1e-9, qAbs(transform().m11())); if (QLineF(mapToScene(event->pos()), hpos).length() <= tol) { Element *e = m_doc->elementById(id); const QJsonArray c = e->raw.value("center").toArray(); m_resizing = true; m_resizeId = id; m_resizeType = type; m_resizeCenter = QPointF(c.at(0).toDouble(), c.at(1).toDouble()); m_resizeRot = type == QLatin1String("rectangle") ? e->raw.value("rotation").toDouble() : 0; QPen pen(kSelected); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); clearPreview(); // one live outline at a time, never orphaned m_preview = m_scene->addPath(QPainterPath(), pen); viewport()->update(); event->accept(); return; } } } if (m_tool == DrawText && m_doc && event->button() == Qt::LeftButton) { const QPointF pos = snap(mapToScene(event->pos())); bool ok = false; const QString text = QInputDialog::getText( this, tr("Add text"), tr("Text:"), QLineEdit::Normal, {}, &ok); if (ok && !text.trimmed().isEmpty()) { const double h = QInputDialog::getDouble( this, tr("Add text"), tr("Height (mm):"), 10.0, 0.5, 500.0, 1, &ok); if (ok) m_undo->push(new AddCmd(this, m_doc, Element::makeText(text, pos, h, QStringLiteral("Helvetica"), m_doc->defaultLayer()))); } event->accept(); return; } if (m_tool == DrawPoint && m_doc && event->button() == Qt::LeftButton) { const QPointF pos = snap(mapToScene(event->pos())); m_undo->push(new AddCmd(this, m_doc, Element::makePoint(pos, m_doc->defaultLayer()))); emit statusHint(tr("Point at %1, %2 mm").arg(pos.x(), 0, 'f', 2).arg(pos.y(), 0, 'f', 2)); event->accept(); return; } if (m_tool == DrawSpline && m_doc && event->button() == Qt::LeftButton) { const QPointF raw = mapToScene(event->pos()); const QPointF pos = snap(raw); if (m_splinePts.size() >= 3 && QLineF(raw, m_splinePts.first()).length() <= pxToMm(8)) { finishSpline(true); event->accept(); return; } if (m_splinePts.isEmpty() || QLineF(pos, m_splinePts.last()).length() > 1e-9) m_splinePts.append(pos); if (!m_preview) { QPen pen(kPreview); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); m_preview = m_scene->addPath(QPainterPath(), pen); } m_preview->setPath(sketch::fitSpline(m_splinePts, false).painterPath()); emit statusHint(tr("Spline: %1 point(s) — Enter or double-click finishes, click near the start closes, Esc cancels") .arg(m_splinePts.size())); viewport()->update(); event->accept(); return; } if (m_tool == DrawPath && m_doc && event->button() == Qt::LeftButton) { const QPointF pos = snap(mapToScene(event->pos())); // Clicking near the start point closes the path. Two straight nodes // closed would be a zero-area there-and-back, so that click ends // them as an open line instead. if (m_penNodes.size() >= 2) { if (QLineF(mapToScene(event->pos()), m_penNodes.first().p).length() <= pxToMm(8)) { finishPath(penClosable(m_penNodes)); event->accept(); return; } } PathNode n; n.p = n.in = n.out = pos; m_penNodes.append(n); m_penDrag = true; // drag pulls out symmetric handles if (!m_preview) { QPen pen(kPreview); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); m_preview = m_scene->addPath(QPainterPath(), pen); } m_preview->setPath(previewPath(pos)); emit statusHint(tr("Path: %1 node(s) — drag for a curve; Enter finishes, click near start closes, Esc cancels") .arg(m_penNodes.size())); viewport()->update(); event->accept(); return; } if (m_tool == NodeEdit && m_doc && event->button() == Qt::LeftButton && !m_model.isEmpty()) { const QPointF pos = mapToScene(event->pos()); int sub, node; NodeGrab what; if (hitNode(pos, &sub, &node, &what)) { m_selSub = sub; m_selNode = node; m_grab = what; m_grabBreak = event->modifiers() & (Qt::AltModifier | Qt::ShiftModifier); viewport()->update(); event->accept(); return; } m_selSub = m_selNode = -1; // click elsewhere: (re)select elements viewport()->update(); } if (clickTool() && m_doc && event->button() == Qt::LeftButton) { // The tangent arc's first click picks a curve end: never snapped. const bool picks = m_tool == DrawArc && m_arcMode == ArcTangent && m_clicks.isEmpty(); const QPointF at = mapToScene(event->pos()); clickToolPress(picks ? at : snap(at)); event->accept(); return; } if (isModifyTool(m_tool) && m_doc && event->button() == Qt::LeftButton) { modifyAt(mapToScene(event->pos())); // never snapped: it picks a curve event->accept(); return; } // NodeEdit selects and edits; it never starts a new shape, so it must not // reach the drawing branch (which would swallow the click before the // scene sees it, leaving nothing selectable with the tool). if (sketchTool() && m_doc && event->button() == Qt::LeftButton) { if (!m_preview) { QPen pen(kPreview); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); m_preview = m_scene->addPath(QPainterPath(), pen); } const QPointF at = mapToScene(event->pos()); if (m_tanLines.size() < sketchLinesNeeded()) { QLineF edge; if (pickEdge(at, &edge)) m_tanLines.append(edge); else emit statusHint(tr("No edge there — click on an existing line")); m_preview->setPath(sketchPath(snap(at))); if (m_tanLines.size() < sketchLinesNeeded() || !m_clicks.isEmpty()) sketchHint(); else emit statusHint(tr("Move to choose the circle, click to place it")); } else { m_drawing = true; m_clicks.append(snap(at)); if (m_clicks.size() >= sketchPointsNeeded()) finishSketch(m_clicks.takeLast()); else sketchHint(); } event->accept(); return; } if (m_tool != Select && m_tool != DrawPath && m_tool != NodeEdit && m_doc && event->button() == Qt::LeftButton) { m_drawing = true; m_anchor = snap(mapToScene(event->pos())); m_fromCenter = event->modifiers() & Qt::ControlModifier; QPen pen(kPreview); pen.setCosmetic(true); pen.setStyle(Qt::DashLine); clearPreview(); m_preview = m_scene->addPath(QPainterPath(), pen); event->accept(); return; } // Click-cycling: remember a lone selection and where the press landed, so // a second click on the same spot can step to the shape underneath. m_cycleFrom.clear(); if (m_tool == Select && event->button() == Qt::LeftButton && !(event->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier | Qt::AltModifier))) { const auto sel = m_scene->selectedItems(); if (sel.size() == 1 && sel.first()->data(0).isValid()) { m_cycleFrom = sel.first()->data(0).toString(); m_cyclePress = event->pos(); } } // A finger on empty board (Select, no Ctrl) leaves the selection as it // is until the band it starts says otherwise: it may be the first finger // of a pinch, which must not change the selection. A mouse press there // clears it at once, as ever. bool touchOnEmpty = false; if (fromTouch(event) && m_tool == Select && event->button() == Qt::LeftButton && !(event->modifiers() & Qt::ControlModifier)) { touchOnEmpty = true; for (QGraphicsItem *it : items(event->pos())) if (it->data(0).isValid() && (it->flags() & QGraphicsItem::ItemIsSelectable)) { touchOnEmpty = false; break; } } if (!touchOnEmpty) QGraphicsView::mousePressEvent(event); pressedEmpty(event); } // Select tool, press on empty board: start the select band. The press // before this already cleared the selection unless Ctrl was held, and the // toolpath list lets go of its toolpath too. void Canvas::pressedEmpty(QMouseEvent *event) { if (m_tool == Select && event->button() == Qt::LeftButton && !m_scene->mouseGrabberItem()) { m_band = true; m_bandStart = m_bandEnd = bandPoint(event->pos()); m_bandKeep.clear(); if (event->modifiers() & Qt::ControlModifier) for (QGraphicsItem *it : m_scene->selectedItems()) m_bandKeep.insert(it); else if (fromTouch(event)) m_touchPress.emptyPending = true; // said at the release, if no pinch else emit emptyPressed(); } } void Canvas::mouseMoveEvent(QMouseEvent *event) { if (m_pinching && fromTouch(event)) { event->accept(); return; } syncHitTolerance(); if (m_panning) { const QPoint d = event->pos() - m_panLast; m_panLast = event->pos(); horizontalScrollBar()->setValue(horizontalScrollBar()->value() - d.x()); verticalScrollBar()->setValue(verticalScrollBar()->value() - d.y()); event->accept(); return; } const QPointF cc = mapToScene(event->pos()); emit cursorMoved(cc); if (parametricMove(event)) return; if (m_resizing && m_preview && m_doc) { if (Element *e = m_doc->elementById(m_resizeId)) { const QHash p = resizeTo(snap(cc)); if (m_resizeType == QLatin1String("rectangle")) { emit statusHint(tr("%1 × %2 mm").arg(p["width"], 0, 'f', 2).arg(p["height"], 0, 'f', 2)); } else { emit statusHint(tr("r = %1 mm").arg(p["radius"], 0, 'f', 2)); } m_preview->setPath(Element::regen(*e, p).painterPath); } event->accept(); return; } if (m_tool == NodeEdit && m_grab != GrabNone && !m_model.isEmpty()) { SubPath &sp = m_model.subs[m_selSub]; PathNode &n = sp.nodes[m_selNode]; const bool breakSym = m_grabBreak || (event->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)); if (m_grab == GrabAnchor) { const QPointF to = snap(cc); const QPointF d = to - n.p; n.p = to; n.in += d; n.out += d; } else { sp.moveHandle(m_selNode, m_grab == GrabOut, cc, breakSym); } previewModel(); emit statusHint(tr("node %1: %2, %3 mm").arg(m_selNode) .arg(n.p.x(), 0, 'f', 2).arg(n.p.y(), 0, 'f', 2)); event->accept(); return; } if (m_tool == DrawPath && m_penDrag && !m_penNodes.isEmpty() && m_preview) { // Pull the new node's handles out symmetrically; a tiny drag stays a corner. PathNode &n = m_penNodes.last(); if (QLineF(cc, n.p).length() > pxToMm(3)) { n.out = cc; n.in = n.p - (cc - n.p); n.kind = PathNode::Symmetric; } else { n.in = n.out = n.p; n.kind = PathNode::Corner; } m_preview->setPath(previewPath(cc)); viewport()->update(); event->accept(); return; } if (isModifyTool(m_tool) && m_doc) { if (!m_preview) { QPen pen(QColor(0xe0, 0x50, 0x50), 2.5); pen.setCosmetic(true); if (m_tool == Extend) pen.setStyle(Qt::DashLine); m_preview = m_scene->addPath(QPainterPath(), pen); } m_preview->setPath(modifyPreview(cc)); event->accept(); return; } if (m_tool == DrawSpline && !m_splinePts.isEmpty() && m_preview) { m_preview->setPath(sketch::fitSpline(QVector(m_splinePts) << snap(cc), false) .painterPath()); viewport()->update(); event->accept(); return; } if (clickTool() && !m_clicks.isEmpty() && m_preview) { const QPointF cur = snap(cc); trackArcTurn(cur); m_preview->setPath(clickPreview(cur)); if (m_tool == DrawSlot && m_slotMode == SlotCenterToCenter && m_clicks.size() == 2) emit statusHint(tr("slot %1 mm long, %2 mm wide") .arg(QLineF(m_clicks.at(0), m_clicks.at(1)).length() + 2 * lineDistance(cur, m_clicks.at(0), m_clicks.at(1)), 0, 'f', 2) .arg(2 * lineDistance(cur, m_clicks.at(0), m_clicks.at(1)), 0, 'f', 2)); else emit statusHint(tr("%1 mm from the last point") .arg(QLineF(m_clicks.last(), cur).length(), 0, 'f', 2)); event->accept(); return; } if (sketchTool() && m_preview) { m_preview->setPath(sketchPath(snap(cc))); viewport()->update(); event->accept(); return; } if (m_band) { if (!(event->buttons() & Qt::LeftButton)) { endBand(); // the release never came: a hover must not drag the band } else if (fromTouch(event) && !viewport()->rect().contains(event->pos())) { // A finger off the drawing (or a touch Qt sent here from a button) // leaves the band where it was; only a mouse drag runs to the edge. } else { m_bandEnd = bandPoint(event->pos()); applyBand(); viewport()->update(); } event->accept(); return; } if ((m_drawing || (m_tool == DrawPath && !m_penNodes.isEmpty())) && m_preview) { const QPointF cur = snap(cc); if (m_drawing) m_fromCenter = event->modifiers() & Qt::ControlModifier; m_preview->setPath(previewPath(cur)); switch (m_tool) { case DrawCircle: case DrawPolygon: emit statusHint(tr("r = %1 mm").arg(QLineF(m_anchor, cur).length(), 0, 'f', 2)); break; case Measure: emit statusHint(measureText(m_anchor, cur)); break; case DrawRect: case DrawEllipse: { const QRectF r = dragBox(m_anchor, cur, m_fromCenter); emit statusHint(tr("%1 × %2 mm").arg(r.width(), 0, 'f', 2).arg(r.height(), 0, 'f', 2)); break; } default: break; } event->accept(); return; } QGraphicsView::mouseMoveEvent(event); } void Canvas::mouseReleaseEvent(QMouseEvent *event) { // A finger lifted: what its press noted is done with, whichever way // this release goes. const auto done = qScopeGuard([this, touch = fromTouch(event)] { if (touch) m_touchPress = TouchPress(); }); if (m_pinching && fromTouch(event)) { // The pinch's last finger up: the next touch is a tap or drag again. m_pinching = false; event->accept(); return; } if (fromTouch(event) && m_touchPress.emptyPending) { // A finger on empty board lets go of the toolpath when it lifts (not // at once: it may be the first finger of a pinch, which keeps it). m_touchPress.emptyPending = false; // A tap (no band drawn): it lets go of the shapes too, as a mouse // press there does. A band drawn picks its own selection. if (QLineF(m_bandStart, m_bandEnd).length() < pxToMm(4)) m_scene->clearSelection(); emit emptyPressed(); } if (m_deferredPress.valid && fromTouch(event) && event->button() == Qt::LeftButton) { // The finger came up without a pinch: the tap does now what a mouse // press does at once. Where the finger went down, unless it moved on // (the preview followed it): then where it came up, as drawn. A // finger that slid off the start a path closes at still closes it. const DeferredPress d = m_deferredPress; m_deferredPress.valid = false; const bool moved = QLineF(mapToScene(d.pos.toPoint()), mapToScene(event->pos())).length() > pxToMm(4); QPointF at = d.pos, atGlobal = d.globalPos; if (moved && commitsOnPress(event->pos())) { at = event->position(); atGlobal = event->globalPosition(); } // Only if it still commits there: a double tap may have finished the // shape meanwhile. if (commitsOnPress(at.toPoint())) { QMouseEvent press(QEvent::MouseButtonPress, at, atGlobal, Qt::LeftButton, Qt::LeftButton, d.mods, event->pointingDevice()); m_replaying = true; mousePressEvent(&press); m_replaying = false; if (d.dbl) { // The double tap's double-click, after its press as with a // mouse (edit a dimension, ...). QMouseEvent dbl(QEvent::MouseButtonDblClick, at, atGlobal, Qt::LeftButton, Qt::LeftButton, d.mods, event->pointingDevice()); mouseDoubleClickEvent(&dbl); } } event->accept(); return; } if (m_panning && (event->button() == Qt::MiddleButton || (m_tool == Pan && event->button() == Qt::LeftButton))) { m_panning = false; viewport()->setCursor(m_tool == Pan ? Qt::OpenHandCursor : m_tool == Select ? Qt::ArrowCursor : Qt::CrossCursor); event->accept(); return; } if (parametricRelease(event)) return; if (m_band && event->button() == Qt::LeftButton) { if (!fromTouch(event) || viewport()->rect().contains(event->pos())) { m_bandEnd = bandPoint(event->pos()); applyBand(); } endBand(); event->accept(); return; } if (m_tool == NodeEdit && m_grab != GrabNone) { m_grab = GrabNone; commitModel(tr("move node")); event->accept(); return; } if (m_tool == DrawPath && m_penDrag) { m_penDrag = false; if (m_preview) m_preview->setPath(previewPath(mapToScene(event->pos()))); viewport()->update(); event->accept(); return; } if (m_resizing && m_doc) { m_resizing = false; if (m_preview) { m_scene->removeItem(m_preview); delete m_preview; m_preview = nullptr; } editElement(m_resizeId, resizeTo(snap(mapToScene(event->pos())))); event->accept(); return; } // Sketch tools take a point per click; a press-drag-release counts the // release as the next point too, so the old drag gesture still works. if (sketchTool() && event->button() == Qt::LeftButton) { if (m_drawing && !m_clicks.isEmpty() && m_doc) { const QPointF cur = snap(mapToScene(event->pos())); if (QLineF(cur, m_clicks.last()).length() > pxToMm(4)) { if (m_clicks.size() + 1 >= sketchPointsNeeded()) finishSketch(cur); else { m_clicks.append(cur); sketchHint(); } } } event->accept(); return; } if (m_drawing && m_doc) { m_drawing = false; m_fromCenter = event->modifiers() & Qt::ControlModifier; const QPointF cur = snap(mapToScene(event->pos())); if (m_preview) { m_scene->removeItem(m_preview); delete m_preview; m_preview = nullptr; } const QJsonObject layer = m_doc->defaultLayer(); const double r = QLineF(m_anchor, cur).length(); switch (m_tool) { case DrawCircle: if (r > 0.1) m_undo->push(new AddCmd(this, m_doc, Element::makeCircle(m_anchor, r, layer))); break; case DrawRect: { const QRectF rect = dragBox(m_anchor, cur, m_fromCenter); if (rect.width() > 0.1 && rect.height() > 0.1) m_undo->push(new AddCmd(this, m_doc, Element::makeRectangle(rect.center(), rect.width(), rect.height(), layer))); break; } case Measure: emit statusHint(measureText(m_anchor, cur)); break; case DrawEllipse: { const QRectF b = dragBox(m_anchor, cur, m_fromCenter); if (b.width() > 0.1 && b.height() > 0.1) m_undo->push(new AddCmd(this, m_doc, Element::makeBezierPath( sketch::ellipse(b.center(), b.width() / 2, b.height() / 2), layer))); break; } case DrawPolygon: { double pr = 0, rot = 0; polygonDrag(m_anchor, cur, m_polySides, m_polyMode == PolyCircumscribed, &pr, &rot); if (r > 0.1) m_undo->push(new AddCmd(this, m_doc, Element::makePolygon(m_anchor, pr, m_polySides, layer, rot))); break; } default: break; } event->accept(); return; } QGraphicsView::mouseReleaseEvent(event); cycleSelection(event); // Select tool: commit any moved items back into the document. An item that // was dragged has a non-zero pos(); scene coords are CC mm, so the delta // applies directly. if (m_tool == Select && m_doc) { QVector> moves; bool dragged = false; for (QGraphicsItem *it : m_scene->selectedItems()) { QPointF d = it->pos(); if (!d.isNull() && it->data(0).isValid()) { dragged = true; if (m_snap) { // The delta is snapped, not the destination, so a drag // shorter than half a cell rounds away to nothing. d = snap(d); if (d.isNull()) continue; } moves.append({it->data(0).toString(), d}); } } if (!moves.isEmpty()) { QStringList moved; for (const auto &mv : moves) moved << mv.first; pushEdit(new MoveCmd(this, m_doc, moves), moved); } else if (dragged) // Every delta snapped away. Without this the items keep the pos() // the drag gave them: the shape sits in its new place on screen // while the document, the properties panel and the g-code all // still have the old one, until some unrelated edit rebuilds. rebuild(); } } // A plain click that lands on the shape already selected, with another shape // stacked under the same spot, steps to the next shape down (and wraps). void Canvas::cycleSelection(QMouseEvent *event) { const QString from = m_cycleFrom; m_cycleFrom.clear(); if (from.isEmpty() || m_tool != Select || event->button() != Qt::LeftButton || (event->pos() - m_cyclePress).manhattanLength() > 4) return; QList stack; for (QGraphicsItem *it : items(event->pos())) if (it->data(0).isValid() && it->isVisible()) stack.append(it); int at = -1; for (int i = 0; i < stack.size(); ++i) if (stack.at(i)->data(0).toString() == from) at = i; // The press itself selected the topmost shape; `from` is what was selected // before it, so the step goes from there. if (at < 0 || stack.size() < 2) return; QGraphicsItem *next = stack.at((at + 1) % stack.size()); m_scene->clearSelection(); next->setSelected(true); } void Canvas::mouseDoubleClickEvent(QMouseEvent *event) { if (m_pinching && fromTouch(event)) { event->accept(); return; } // A double tap's second press waits for its release like the first: the // double-click must not act before that press has (see m_deferredPress). if (fromTouch(event) && m_deferredPress.valid) { m_deferredPress.dbl = true; // run at the release, after the press event->accept(); return; } syncHitTolerance(); if (overlayOn() && event->button() == Qt::LeftButton) { const QString uid = hitConstraint(event->pos()); const int i = m_doc ? m_doc->parametric().indexOfUid(uid) : -1; if (i >= 0 && m_doc->parametric().constraints.at(i).isDimension()) { editDimension(uid); event->accept(); return; } } if (m_tool == DrawPath && !m_penNodes.isEmpty()) { finishPath(false); event->accept(); return; } if (m_tool == DrawSpline && !m_splinePts.isEmpty()) { finishSpline(false); event->accept(); return; } if (m_tool == NodeEdit && m_doc && !m_model.isEmpty() && event->button() == Qt::LeftButton) { const QPointF pos = mapToScene(event->pos()); int sub, node, seg; double t; NodeGrab what; if (!hitNode(pos, &sub, &node, &what) && hitSegment(pos, &sub, &seg, &t)) { m_grab = GrabNone; const int idx = m_model.subs[sub].insertNode(seg, t); m_selSub = sub; m_selNode = idx; commitModel(tr("insert node")); event->accept(); return; } } if (fromTouch(event) && !viewport()->rect().contains(event->pos())) { endBand(); event->ignore(); return; } endBand(); QGraphicsView::mouseDoubleClickEvent(event); // Two quick taps on the board: the second one comes as a double-click, // and must still start a band and let go of the toolpath. pressedEmpty(event); } void Canvas::contextMenuEvent(QContextMenuEvent *event) { if (!m_doc) return; if (parametricMenu(event)) return; const QPointF pos = mapToScene(event->pos()); QMenu menu(this); if (m_tool == NodeEdit && !m_model.isEmpty()) { int sub, node; NodeGrab what; if (hitNode(pos, &sub, &node, &what)) { m_selSub = sub; m_selNode = node; viewport()->update(); const PathNode::Kind cur = m_model.subs.at(sub).nodes.at(node).kind; // menu.exec() runs the event loop: a design replaced meanwhile // (a pad sync) empties or renumbers the model under the menu. const QString editing = m_editId; auto stillThere = [this, editing, sub, node] { return m_tool == NodeEdit && m_editId == editing && sub >= 0 && sub < m_model.subs.size() && node >= 0 && node < m_model.subs.at(sub).nodes.size(); }; auto kindAct = [&](const QString &name, PathNode::Kind k) { QAction *a = menu.addAction(name); a->setCheckable(true); a->setChecked(cur == k); connect(a, &QAction::triggered, this, [this, sub, node, k, stillThere] { if (!stillThere()) return; m_model.subs[sub].setKind(node, k); commitModel(tr("node kind")); }); }; kindAct(tr("Corner"), PathNode::Corner); kindAct(tr("Smooth"), PathNode::Smooth); kindAct(tr("Symmetric"), PathNode::Symmetric); menu.addSeparator(); connect(menu.addAction(tr("Straight lines (retract handles)")), &QAction::triggered, this, [this, sub, node, stillThere] { if (!stillThere()) return; m_model.subs[sub].retract(node); commitModel(tr("retract handles")); }); connect(menu.addAction(tr("Delete node")), &QAction::triggered, this, [this, sub, node, stillThere] { if (stillThere() && removePathNode(m_model.subs[sub], node)) { m_selSub = m_selNode = -1; commitModel(tr("delete node")); } }); menu.exec(event->globalPos()); return; } } // Element menu (Select or Nodes tool): pick the item under the cursor if // it is not part of the selection. // Preview overlays sit on top and carry no element: look through them. for (QGraphicsItem *it : items(event->pos())) { if (!it->data(0).isValid()) continue; if (!it->isSelected()) { m_scene->clearSelection(); it->setSelected(true); } break; } const QStringList ids = selectedElementIds(); if (ids.isEmpty()) return; bool convertible = false; for (const QString &id : ids) if (Element *e = m_doc->elementById(id)) if (e->geometryType != QLatin1String("path")) convertible = true; QAction *conv = menu.addAction(tr("Convert to path")); conv->setEnabled(convertible); connect(conv, &QAction::triggered, this, [this, ids] { convertToPaths(ids); }); // Not off the Design page: the Nodes tool is on the drawing palette, // which Toolpaths hides, and its taps would edit instead of picking. if (m_tool != NodeEdit && m_parametricVisible) connect(menu.addAction(tr("Edit nodes (N)")), &QAction::triggered, this, [this] { setTool(NodeEdit); }); connect(menu.addAction(tr("Delete")), &QAction::triggered, this, [this, ids] { QVector victims; for (const QString &id : ids) if (Element *e = m_doc->elementById(id)) victims.append(*e); if (!victims.isEmpty()) pushEdit(new DeleteCmd(this, m_doc, victims), {}); }); menu.exec(event->globalPos()); } void Canvas::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) m_deferredPress.valid = false; // a finger's tap still waiting is cancelled too if (parametricKey(event)) return; if (m_tool == NodeEdit && m_selSub >= 0 && m_doc && (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)) { if (removePathNode(m_model.subs[m_selSub], m_selNode)) { m_selSub = m_selNode = -1; commitModel(tr("delete node")); } else { emit statusHint(tr("A path keeps at least two nodes — delete the element instead")); } return; } if (m_tool == NodeEdit && event->key() == Qt::Key_Escape && (m_selSub >= 0 || m_grab != GrabNone)) { // Mid-drag, Escape cancels the drag: the nodes go back to the // element's own (a grab left on node -1 crashed the next move). const bool dragging = m_grab != GrabNone; m_grab = GrabNone; m_selSub = m_selNode = -1; if (dragging) { syncEditTarget(); previewModel(); } viewport()->update(); return; } if (m_tool == DrawPath && !m_penNodes.isEmpty()) { if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { finishPath(false); return; } if (event->key() == Qt::Key_Escape) { cancelDrawing(); emit statusHint(tr("Path cancelled")); return; } } if (m_tool == DrawSpline && !m_splinePts.isEmpty()) { if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { finishSpline(false); return; } if (event->key() == Qt::Key_Escape) { cancelDrawing(); emit statusHint(tr("Spline cancelled")); return; } } if (event->key() == Qt::Key_Escape && (m_drawing || m_preview)) { cancelDrawing(); return; } if (m_doc && (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)) { if (!m_scene->selectedItems().isEmpty()) { deleteSelected(); return; } } QGraphicsView::keyPressEvent(event); } void Canvas::moveElementTo(const QString &id, int index) { if (!m_doc) return; QStringList before; for (const Element &e : m_doc->elements()) before << e.id; const int from = before.indexOf(id); if (from < 0) return; QStringList after = before; after.move(from, qBound(0, index, int(after.size()) - 1)); if (after != before) m_undo->push(new OrderCmd(this, m_doc, before, after)); } void Canvas::duplicateElements(const QStringList &ids) { if (!m_doc) return; QVector copies; QStringList newIds; for (const QString &id : ids) { const Element *e = m_doc->elementById(id); if (!e) continue; Element c = *e; c.id = QUuid::createUuid().toString(); c.raw.insert(QStringLiteral("id"), c.id); c.translate(5, -5); newIds << c.id; copies.append(c); } if (copies.isEmpty()) return; m_undo->push(new AddManyCmd(this, m_doc, copies)); selectElements(newIds); } void Canvas::deleteElements(const QStringList &ids) { if (!m_doc) return; QVector victims; for (const QString &id : ids) if (const Element *e = m_doc->elementById(id)) victims.append(*e); if (!victims.isEmpty()) pushEdit(new DeleteCmd(this, m_doc, victims), {}); } void Canvas::deleteSelected() { if (!m_doc) return; QVector victims; for (QGraphicsItem *it : m_scene->selectedItems()) { if (it->data(0).isValid()) if (Element *e = m_doc->elementById(it->data(0).toString())) victims.append(*e); } if (!victims.isEmpty()) pushEdit(new DeleteCmd(this, m_doc, victims), {}); } bool Canvas::commitsOnPress(const QPoint &viewportPos) const { if (!m_doc) return false; switch (m_tool) { case Constrain: case Dimension: case DrawPoint: case DrawText: case Trim: case Extend: case Break: case SelectArea: return true; default: break; } const QPointF at = mapToScene(viewportPos); if (clickTool()) return m_clicks.size() + 1 >= clicksNeeded(); if (sketchTool()) return m_tanLines.size() >= sketchLinesNeeded() && m_clicks.size() + 1 >= sketchPointsNeeded(); if (m_tool == DrawPath) return m_penNodes.size() >= 2 && QLineF(at, m_penNodes.first().p).length() <= pxToMm(8); if (m_tool == DrawSpline) return m_splinePts.size() >= 3 && QLineF(at, m_splinePts.first()).length() <= pxToMm(8); return false; } // The first finger began a drag or a shape: the pinch wins. Its touch also // came as a mouse press, which may have started a select band, grabbed a // shape to move, a node or a dimension label to drag, or placed a node of a // path: all of that is let go, and that finger's mouse events are ignored // until it is lifted. What earlier taps placed (the nodes of a path, the // first clicks of an arc) stays: the pinch only zooms the view on them. void Canvas::pinchStarted() { m_pinching = true; m_deferredPress.valid = false; // its tap never happens const TouchPress press = m_touchPress; m_touchPress = TouchPress(); // nor does its tap on empty board happen if (press.valid) { auto rollBack = [](auto &v, int n) { if (v.size() > n) v.resize(n); }; rollBack(m_clicks, press.clicks); rollBack(m_tanLines, press.tanLines); rollBack(m_penNodes, press.penNodes); rollBack(m_splinePts, press.splinePts); } m_penDrag = false; m_resizing = false; // a resize drag cancelled, not committed // A drag-shape (ellipse, measure...) lives only while its press is held; // a sketch shape's earlier clicks keep it going. m_drawing = sketchTool() && !m_clicks.isEmpty(); if (m_clicks.isEmpty()) m_arcTurn = 0; if (m_clicks.isEmpty() && m_tanLines.isEmpty() && m_penNodes.isEmpty() && m_splinePts.isEmpty()) clearPreview(); else if (m_preview && m_tool == DrawPath && !m_penNodes.isEmpty()) m_preview->setPath(previewPath(m_penNodes.last().p)); else if (m_preview && m_tool == DrawSpline && !m_splinePts.isEmpty()) m_preview->setPath(sketch::fitSpline(m_splinePts, false).painterPath()); cancelDimDrag(); endBand(); m_panning = false; // A node being dragged goes back as Esc puts it: the model too, or the // next node edit would commit the moved node inside its own undo step. if (m_tool == NodeEdit && m_grab != GrabNone) { syncEditTarget(); previewModel(); } restoreEditItem(); m_grab = GrabNone; if (QGraphicsItem *g = m_scene->mouseGrabberItem()) g->ungrabMouse(); for (QGraphicsItem *it : m_scene->items()) if (it->data(0).isValid() && !it->pos().isNull()) it->setPos(0, 0); // The finger's press cleared or replaced the selection (or picked the // node-edit target): what was selected before it is selected again. QStringList now = selectedElementIds(), was = press.selection; now.sort(); was.sort(); if (press.valid && now != was) { selectElements(press.selection); if (m_tool == NodeEdit) { syncEditTarget(); previewModel(); } } viewport()->update(); } bool Canvas::viewportEvent(QEvent *event) { if (event->type() == QEvent::TouchCancel) endBand(); // the system took the finger away: no band left hanging if (event->type() == QEvent::TouchBegin) m_pinching = false; // a new touch: any pinch before it is over if (event->type() != QEvent::Gesture) return QGraphicsView::viewportEvent(event); auto *ge = static_cast(event); auto *pg = static_cast(ge->gesture(Qt::PinchGesture)); if (!pg) return QGraphicsView::viewportEvent(event); if (pg->state() == Qt::GestureStarted) pinchStarted(); const double f = pg->scaleFactor(); if (f > 0.0 && std::isfinite(f) && qAbs(f - 1.0) > 1e-4) { // Zoom about the point between the fingers, as the wheel does about the mouse. const QPoint at = viewport()->mapFromGlobal(pg->centerPoint().toPoint()); const QPointF before = mapToScene(at); const double fl = limitZoom(transform().m11(), f); scale(fl, fl); const QPoint moved = mapFromScene(before) - at; horizontalScrollBar()->setValue(horizontalScrollBar()->value() + moved.x()); verticalScrollBar()->setValue(verticalScrollBar()->value() + moved.y()); } // Moving the fingers together moves the view, like the hand tool. const QPoint d = (pg->centerPoint() - pg->lastCenterPoint()).toPoint(); horizontalScrollBar()->setValue(horizontalScrollBar()->value() - d.x()); verticalScrollBar()->setValue(verticalScrollBar()->value() - d.y()); emitZoom(); ge->accept(pg); return true; } void Canvas::wheelEvent(QWheelEvent *event) { const int dy = event->angleDelta().y(); if (dy == 0) { QGraphicsView::wheelEvent(event); return; } // horizontal scroll: pan, not zoom // 2 % per wheel notch (120 units). Touchpads and pinches send smaller // deltas, many per gesture, so the step scales with the delta. const double factor = limitZoom(transform().m11(), qPow(1.02, dy / 120.0)); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); scale(factor, factor); emitZoom(); } // ---- Fusion-style sketch circles and rectangles --------------------------- void Canvas::setCircleMode(CircleMode m) { m_deferredPress.valid = false; // a tap waiting for its release was for the old mode m_circleMode = m; if (m_tool == DrawCircle) { cancelDrawing(); sketchHint(); } } void Canvas::setRectMode(RectMode m) { m_deferredPress.valid = false; // a tap waiting for its release was for the old mode m_rectMode = m; if (m_tool == DrawRect) { cancelDrawing(); sketchHint(); } } void Canvas::setArcMode(ArcMode m) { m_deferredPress.valid = false; // a tap waiting for its release was for the old mode m_arcMode = m; if (m_tool == DrawArc) { cancelDrawing(); emit statusHint(clickHint()); } } void Canvas::setPolygonMode(PolygonMode m) { m_deferredPress.valid = false; // a tap waiting for its release was for the old mode m_polyMode = m; if (m_tool == DrawPolygon) setTool(DrawPolygon); // cancels and shows the mode's hint } void Canvas::setSlotMode(SlotMode m) { m_deferredPress.valid = false; // a tap waiting for its release was for the old mode m_slotMode = m; if (m_tool == DrawSlot) { cancelDrawing(); emit statusHint(clickHint()); } } void Canvas::resetSketch() { m_clicks.clear(); m_tanLines.clear(); if (m_preview) { m_scene->removeItem(m_preview); delete m_preview; m_preview = nullptr; } } int Canvas::sketchLinesNeeded() const { if (m_tool != DrawCircle) return 0; if (m_circleMode == Circle2Tangent) return 2; if (m_circleMode == Circle3Tangent) return 3; return 0; } int Canvas::sketchPointsNeeded() const { if (m_tool == DrawCircle) { switch (m_circleMode) { case CircleCenterDiameter: case Circle2Point: return 2; case Circle3Point: return 3; case Circle2Tangent: case Circle3Tangent: return 1; // where to put it } } return m_rectMode == Rect3Point ? 3 : 2; } void Canvas::sketchHint() { const int n = m_clicks.size(), l = m_tanLines.size(); QString h; if (m_tool == DrawCircle) { switch (m_circleMode) { case CircleCenterDiameter: h = n == 0 ? tr("Circle (center) — click the center") : tr("Click or drag to the radius"); break; case Circle2Point: h = n == 0 ? tr("Circle (2-point) — click one end of the diameter") : tr("Click the other end of the diameter"); break; case Circle3Point: h = n == 0 ? tr("Circle (3-point) — click the first point on the circle") : n == 1 ? tr("Click the second point") : tr("Click the third point"); break; case Circle2Tangent: h = l < 2 ? tr("Circle (2-tangent) — click line %1 of 2").arg(l + 1) : tr("Move to choose the circle, click to place it"); break; case Circle3Tangent: h = l < 3 ? tr("Circle (3-tangent) — click line %1 of 3").arg(l + 1) : tr("Move to choose the circle, click to place it"); break; } } else { switch (m_rectMode) { case Rect2Point: h = n == 0 ? tr("Rectangle (2-point) — click the first corner") : tr("Click or drag to the opposite corner"); break; case Rect3Point: h = n == 0 ? tr("Rectangle (3-point) — click the start of the first edge") : n == 1 ? tr("Click the end of the first edge") : tr("Click to set the height"); break; case RectCenter: h = n == 0 ? tr("Rectangle (center) — click the center") : tr("Click or drag to a corner"); break; } } emit statusHint(h + tr(" · Esc cancels")); } // Nearest straight piece of any element's outline within a few pixels. // Curves are flattened, so picking one gives its tangent at that spot. bool Canvas::pickEdge(const QPointF &at, QLineF *edge) const { if (!m_doc) return false; double best = pxToMm(8); bool found = false; for (const Element &e : m_doc->elements()) { if (!e.painterPath.boundingRect().adjusted(-best, -best, best, best).contains(at)) continue; for (const QPolygonF &poly : e.painterPath.toSubpathPolygons()) { for (int i = 0; i + 1 < poly.size(); ++i) { const QLineF seg(poly.at(i), poly.at(i + 1)); const double len2 = seg.dx() * seg.dx() + seg.dy() * seg.dy(); if (len2 < 1e-12) continue; double t = ((at.x() - seg.x1()) * seg.dx() + (at.y() - seg.y1()) * seg.dy()) / len2; t = qBound(0.0, t, 1.0); const double d = QLineF(seg.pointAt(t), at).length(); if (d < best) { best = d; *edge = seg; found = true; } } } } return found; } namespace { struct SketchShape { enum Kind { None, Circle, Polygon } kind = None; QPointF center; double radius = 0; QVector corners; }; QVector boxCorners(const QPointF &a, const QPointF &b) { const QRectF r = QRectF(a, b).normalized(); return {r.topLeft(), r.topRight(), r.bottomRight(), r.bottomLeft()}; } } // namespace static SketchShape sketchShape(Canvas::Tool tool, Canvas::CircleMode cm, Canvas::RectMode rm, const QVector &pts, const QVector &lines, const QPointF &cur) { SketchShape s; const int n = pts.size(); auto circle = [&](const sketch::Circle &c) { if (c.valid) { s.kind = SketchShape::Circle; s.center = c.center; s.radius = c.radius; } }; if (tool == Canvas::DrawCircle) { switch (cm) { case Canvas::CircleCenterDiameter: if (n >= 1) circle({pts[0], QLineF(pts[0], cur).length(), true}); break; case Canvas::Circle2Point: if (n >= 1) circle({(pts[0] + cur) / 2.0, QLineF(pts[0], cur).length() / 2.0, true}); break; case Canvas::Circle3Point: if (n >= 2) circle(sketch::circleThrough3(pts[0], pts[1], cur)); break; case Canvas::Circle2Tangent: if (lines.size() >= 2) circle(sketch::circleTangent2(lines[0], lines[1], cur)); break; case Canvas::Circle3Tangent: if (lines.size() >= 3) circle(sketch::circleTangent3(lines[0], lines[1], lines[2], cur)); break; } } else if (n >= 1) { QVector c; switch (rm) { case Canvas::Rect2Point: c = boxCorners(pts[0], cur); break; case Canvas::RectCenter: c = boxCorners(pts[0] * 2.0 - cur, cur); break; case Canvas::Rect3Point: if (n >= 2) c = sketch::rect3Point(pts[0], pts[1], cur); break; } if (c.size() == 4) { s.kind = SketchShape::Polygon; s.corners = c; } } if (s.kind == SketchShape::Circle && s.radius < 1e-9) s.kind = SketchShape::None; return s; } QPainterPath Canvas::sketchPath(const QPointF &cur) const { QPainterPath p; for (const QLineF &l : m_tanLines) { // picked edges, drawn long const QPointF d = (l.p2() - l.p1()) / qMax(1e-9, l.length()) * pxToMm(30); p.moveTo(l.p1() - d); p.lineTo(l.p2() + d); } if (m_tool == DrawRect && m_rectMode == Rect3Point && m_clicks.size() == 1) { p.moveTo(m_clicks[0]); // first edge rubber band p.lineTo(cur); } if (m_tool == DrawCircle && m_circleMode == Circle3Point && m_clicks.size() == 1) { p.moveTo(m_clicks[0]); p.lineTo(cur); } if (m_tanLines.size() < sketchLinesNeeded()) return p; const SketchShape s = sketchShape(m_tool, m_circleMode, m_rectMode, m_clicks, m_tanLines, cur); if (s.kind == SketchShape::Circle) p.addEllipse(s.center, s.radius, s.radius); else if (s.kind == SketchShape::Polygon) p.addPolygon(QPolygonF(s.corners) << s.corners.first()); return p; } void Canvas::finishSketch(const QPointF &cur) { const SketchShape s = sketchShape(m_tool, m_circleMode, m_rectMode, m_clicks, m_tanLines, cur); resetSketch(); m_drawing = false; if (m_doc) { const QJsonObject layer = m_doc->defaultLayer(); if (s.kind == SketchShape::Circle && s.radius > 0.05) { m_undo->push(new AddCmd(this, m_doc, Element::makeCircle(s.center, s.radius, layer))); } else if (s.kind == SketchShape::Polygon) { const QRectF box = QPolygonF(s.corners).boundingRect(); if (QLineF(s.corners[0], s.corners[1]).length() > 0.05 && QLineF(s.corners[1], s.corners[2]).length() > 0.05) { // A tilted rectangle has no CC rectangle form: it becomes a path. if (sketch::isAxisAligned(s.corners)) m_undo->push(new AddCmd(this, m_doc, Element::makeRectangle( box.center(), box.width(), box.height(), layer))); else m_undo->push(new AddCmd(this, m_doc, Element::makePath(s.corners, true, layer))); } } } sketchHint(); } } // namespace c2d