#include "vectoractions.h" #include "canvas.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 namespace c2d { namespace { // ---- undo commands ------------------------------------------------------- void refresh(Canvas *c, const QStringList &select) { c->rebuild(); emit c->documentChanged(); c->selectIds(select); } // Which results each consumed input turned into: input id -> result ids. using Lineage = QHash; // Toolpaths reference elements by uuid; when an operation consumes its // inputs, every toolpath that pointed at one of them is pointed at the // results *that input became* (`from`) instead - so a pocket on two circles // becomes a pocket on their weld, but a drill on the cut-outs of a Subtract // does not become a drill on the plate. A toolpath left with no vectors // stays, empty, the way deleting its shapes leaves it, and is marked // "vectors_removed" so the export can tell it from one that never had any // (an empty Facing would otherwise face the whole stock); `emptied` counts // those. Returns (before, after) pairs for the toolpaths that change; undo // puts the before (unmarked) copy back. QVector> retargetToolpaths(Document *d, const QSet &removed, const QVector &added, const Lineage &from, int *emptied) { QVector> out; if (removed.isEmpty()) return out; for (const Toolpath &t : d->toolpaths()) { const QJsonArray refs = t.json.value("elements").toArray(); bool hit = false; QJsonArray kept; QSet seen, wanted; for (const QJsonValue &v : refs) { const QString id = v.toObject().value("uuid").toString(); if (removed.contains(id)) { hit = true; for (const QString &r : from.value(id)) wanted.insert(r); continue; } kept.append(v); seen.insert(id); } if (!hit) continue; for (const Element &e : added) if (wanted.contains(e.id) && !seen.contains(e.id)) { kept.append(QJsonObject{{QStringLiteral("uuid"), e.id}}); seen.insert(e.id); } Toolpath after = t; after.json.insert(QStringLiteral("elements"), kept); if (kept.isEmpty()) { after.json.insert(QStringLiteral("vectors_removed"), true); if (emptied) ++*emptied; } out.append({t, after}); } return out; } // A path flattened finely: QPainterPath flattens curves to within half a // unit - half a millimetre here - so it is flattened 200x larger and // scaled back (about 2.5 µm). QVector fineOutline(const QPainterPath &p) { constexpr double k = 200.0; const QTransform down = QTransform::fromScale(1.0 / k, 1.0 / k); QVector out; for (const QPolygonF &poly : p.toSubpathPolygons(QTransform::fromScale(k, k))) out.append(down.map(poly)); return out; } double segDist2(const QPointF &p, const QPointF &a, const QPointF &b) { const QPointF ab = b - a; const double len2 = QPointF::dotProduct(ab, ab); const double t = len2 > 0 ? qBound(0.0, QPointF::dotProduct(p - a, ab) / len2, 1.0) : 0.0; const QPointF q = a + t * ab - p; return QPointF::dotProduct(q, q); } // Squared distance from `v` to the outline `polys` (closed subpaths also // get their closing side), or `cap2` when it is no nearer than that. double outlineDist2(const QPointF &v, const QVector &polys, bool closed, double cap2) { double best = cap2; for (const QPolygonF &poly : polys) { const int n = poly.size(); if (n == 0) continue; const QRectF b = poly.boundingRect(); const double dx = qMax(0.0, qMax(b.left() - v.x(), v.x() - b.right())); const double dy = qMax(0.0, qMax(b.top() - v.y(), v.y() - b.bottom())); if (dx * dx + dy * dy >= best) continue; if (n == 1) best = qMin(best, segDist2(v, poly.first(), poly.first())); for (int i = 1; i < n; ++i) best = qMin(best, segDist2(v, poly.at(i - 1), poly.at(i))); if (closed && n > 2 && poly.first() != poly.last()) best = qMin(best, segDist2(v, poly.last(), poly.first())); } return best; } // Whether a vertex of `ring` lies within `reach` of the outline `polys`. bool ringNear(const QVector &ring, const QVector &polys, bool closed, double reach) { const double r2 = reach * reach; for (const QPolygonF &rp : ring) for (const QPointF &v : rp) if (outlineDist2(v, polys, closed, r2 * 1.0000001) <= r2) return true; return false; } // Whether the outline of `ring` crosses the outline `polys`. bool outlinesCross(const QVector &ring, const QVector &polys, bool closed) { auto sides = [](const QPolygonF &p, bool wrap) { QVector s; for (int i = 1; i < p.size(); ++i) s.append(QLineF(p.at(i - 1), p.at(i))); if (wrap && p.size() > 2 && p.first() != p.last()) s.append(QLineF(p.last(), p.first())); return s; }; for (const QPolygonF &rp : ring) { const QVector rs = sides(rp, true); for (const QPolygonF &poly : polys) { if (!rp.boundingRect().intersects(poly.boundingRect())) continue; for (const QLineF &b : sides(poly, closed)) for (const QLineF &a : rs) if (a.intersects(b) == QLineF::BoundedIntersection) return true; } } return false; } // How the result rings nest: for each, the smallest other ring around it // (-1 for none) and whether it is a hole (inside an odd number of rings). struct Nesting { QVector parent; QVector hole; }; Nesting nestRings(const QVector &rings) { Nesting n; const int k = rings.size(); n.parent.fill(-1, k); n.hole.fill(false, k); QVector box; for (const Element &r : rings) box.append(r.painterPath.boundingRect()); for (int i = 0; i < k; ++i) { const QPainterPath &p = rings.at(i).painterPath; if (p.elementCount() == 0) continue; const QPointF at(p.elementAt(0).x, p.elementAt(0).y); int depth = 0; double smallest = 0; for (int j = 0; j < k; ++j) { if (j == i || !box.at(j).contains(box.at(i)) || !rings.at(j).painterPath.contains(at)) continue; ++depth; const double area = box.at(j).width() * box.at(j).height(); if (n.parent.at(i) < 0 || area < smallest) { n.parent[i] = j; smallest = area; } } n.hole[i] = depth % 2 == 1; } return n; } // Intersect: the result is the area common to all inputs, so it lies // inside each of them - every input became every result. Lineage everyResult(const QVector &inputs, const QVector &results) { QStringList ids; for (const Element &e : results) ids << e.id; Lineage from; for (const Element &e : inputs) from.insert(e.id, ids); return from; } // Union: an input became the welded outlines its area overlaps (each // outline's region less its own holes), and those outlines' holes. Inputs // that do not touch keep only their own outline. Lineage unionLineage(const QVector &inputs, const QVector &results) { const Nesting nest = nestRings(results); Lineage from; for (const Element &e : inputs) from.insert(e.id, QStringList()); for (int i = 0; i < results.size(); ++i) { if (nest.hole.at(i)) continue; QPainterPath region = results.at(i).painterPath; QStringList mine{results.at(i).id}; for (int j = 0; j < results.size(); ++j) if (nest.hole.at(j) && nest.parent.at(j) == i) { region.addPath(results.at(j).painterPath); mine << results.at(j).id; } region.setFillRule(Qt::OddEvenFill); const QRectF box = region.boundingRect(); for (const Element &e : inputs) if (box.intersects(e.painterPath.boundingRect()) && region.intersects(e.painterPath)) from[e.id] << mine; } // Not expected (every input lies in the weld), but never lose one. const Lineage all = everyResult(inputs, results); for (const Element &e : inputs) if (from.value(e.id).isEmpty()) from[e.id] = all.value(e.id); return from; } // Subtract: the results are what is left of the first input. A cut-away // input that left a hole in it becomes that hole (a drill or pocket on the // cut-outs keeps machining them); one that only notched the outline, or // missed it, becomes nothing. Lineage subtractLineage(const QVector &inputs, const QVector &results) { Lineage from; if (inputs.isEmpty()) return from; from = everyResult({inputs.first()}, results); const Nesting nest = nestRings(results); for (int i = 1; i < inputs.size(); ++i) { const Element &c = inputs.at(i); const QVector outline = fineOutline(c.painterPath); const QRectF zone = c.painterPath.boundingRect().adjusted(-0.02, -0.02, 0.02, 0.02); QStringList mine; for (int j = 0; j < results.size(); ++j) { if (!nest.hole.at(j) || !zone.intersects(results.at(j).painterPath.boundingRect())) continue; if (ringNear(results.at(j).painterPath.toSubpathPolygons(), outline, vec::isClosed(c), 0.02)) mine << results.at(j).id; } from.insert(c.id, mine); } return from; } // Offset: every input is offset in one region, so one result ring can come // from several inputs (outlines that grew into each other) and several // rings from one (a plate and its hole). Each ring runs at |delta| from the // outlines it was grown from and no nearer to any, so each of its vertices // is credited to the input outline nearest it, when that is within |delta| // plus a little: a neighbour just past the reach never takes it. An input // credited with no ring (its offset swallowed by a neighbour's) gets the // rings whose outline crosses or touches it or that lie inside its area; a // ring credited to no input goes to all of them. Lineage offsetLineage(const QVector &inputs, const QVector &results, double delta) { Lineage from; for (const Element &e : inputs) from.insert(e.id, QStringList()); const double reach = std::fabs(delta) * 1.01 + 0.02; const double reach2 = reach * reach; QVector> outlines; QVector zones; QVector closed; for (const Element &e : inputs) { outlines.append(fineOutline(e.painterPath)); zones.append(e.painterPath.boundingRect().adjusted(-reach, -reach, reach, reach)); closed.append(vec::isClosed(e)); } for (const Element &r : results) { const QVector ring = r.painterPath.toSubpathPolygons(); const QRectF box = r.painterPath.boundingRect(); QVector near; for (int i = 0; i < inputs.size(); ++i) if (zones.at(i).intersects(box) || zones.at(i).contains(box)) near.append(i); QSet credited; QVector d2(near.size()); for (const QPolygonF &rp : ring) for (const QPointF &v : rp) { double best = reach2 * 1.0000001; for (int k = 0; k < near.size(); ++k) { const int i = near.at(k); d2[k] = zones.at(i).contains(v) ? outlineDist2(v, outlines.at(i), closed.at(i), reach2 * 1.0000001) : reach2 * 1.0000001; best = qMin(best, d2.at(k)); } if (best > reach2) continue; // Ties (an input selected with its exact copy) all count. const double tie = std::pow(std::sqrt(best) + 1e-4, 2); for (int k = 0; k < near.size(); ++k) if (d2.at(k) <= tie) credited.insert(near.at(k)); } for (int i = 0; i < inputs.size(); ++i) if (credited.contains(i)) from[inputs.at(i).id] << r.id; if (credited.isEmpty()) for (const Element &e : inputs) from[e.id] << r.id; } for (int i = 0; i < inputs.size(); ++i) { const Element &e = inputs.at(i); QStringList &mine = from[e.id]; if (!mine.isEmpty()) continue; const QRectF ebox = e.painterPath.boundingRect().adjusted(-0.02, -0.02, 0.02, 0.02); for (const Element &r : results) { if (!ebox.intersects(r.painterPath.boundingRect())) continue; const QVector ring = r.painterPath.toSubpathPolygons(); bool inside = closed.at(i); for (const QPolygonF &rp : ring) for (const QPointF &v : rp) inside = inside && e.painterPath.contains(v); if (inside || ringNear(ring, outlines.at(i), closed.at(i), 0.02) || outlinesCross(ring, outlines.at(i), closed.at(i))) mine << r.id; } } return from; } // Replace `inputs` (unless kept) by `results`; results are inserted where the // first consumed input sat so the z-order stays put. `from` says which // results each input became, for the toolpaths that machined it. class ReplaceCmd : public QUndoCommand { public: ReplaceCmd(Canvas *c, Document *d, const QVector &inputs, const QVector &results, bool keepInputs, const QString &text, const Lineage &from) : m_c(c), m_d(d), m_results(results) { setText(text); if (!keepInputs) { QSet removed; const QVector &all = d->elements(); for (const Element &e : inputs) { for (int i = 0; i < all.size(); ++i) if (all.at(i).id == e.id) { m_removed.append({i, all.at(i)}); break; } removed.insert(e.id); } std::sort(m_removed.begin(), m_removed.end(), [](const auto &a, const auto &b) { return a.first < b.first; }); m_tps = retargetToolpaths(d, removed, results, from, &m_emptied); m_removedIds = removed; } for (const Element &e : results) m_resultIds << e.id; } void redo() override { QVector &els = m_d->elementsRef(); int at = els.size(); for (int i = m_removed.size() - 1; i >= 0; --i) { // high index first const int idx = m_removed.at(i).first; // The document can have been replaced under the undo stack (a // failed Open used to leave it empty). undo() already clamps; // without the same here, Redo indexed off the end of the vector. if (idx < 0 || idx >= els.size()) continue; els.removeAt(idx); at = idx; } for (int i = 0; i < m_results.size(); ++i) els.insert(at + i, m_results.at(i)); for (const auto &p : m_tps) m_d->replaceToolpath(p.second); // 3D components follow their vectors like toolpaths do. m_model = retargetModelVectors(*m_d, m_removedIds, m_resultIds); refresh(m_c, m_resultIds); } void undo() override { QStringList inputIds; for (const Element &e : m_results) m_d->removeElementById(e.id); QVector &els = m_d->elementsRef(); for (const auto &p : m_removed) { // low index first els.insert(qMin(p.first, els.size()), p.second); inputIds << p.second.id; } for (const auto &p : m_tps) m_d->replaceToolpath(p.first); restoreModelVectors(*m_d, m_model); refresh(m_c, inputIds); } // Toolpaths this edit leaves with no vectors (see retargetToolpaths). int emptiedToolpaths() const { return m_emptied; } private: Canvas *m_c; Document *m_d; QVector m_results; QVector> m_removed; QVector> m_tps; QStringList m_resultIds; QSet m_removedIds; ModelVectorRefs m_model; int m_emptied = 0; }; class MoveManyCmd : public QUndoCommand { public: MoveManyCmd(Canvas *c, Document *d, const QStringList &ids, const QVector &deltas, const QString &text) : m_c(c), m_d(d), m_ids(ids), m_deltas(deltas) { setText(text); } void redo() override { apply(1.0); } void undo() override { apply(-1.0); } private: void apply(double sign) { for (int i = 0; i < m_ids.size(); ++i) if (Element *e = m_d->elementById(m_ids.at(i))) e->translate(sign * m_deltas.at(i).x(), sign * m_deltas.at(i).y()); refresh(m_c, m_ids); } Canvas *m_c; Document *m_d; QStringList m_ids; QVector m_deltas; }; // Swap elements for edited versions of themselves (same ids, same places in // the z-order) — mirror's command. class ReshapeCmd : public QUndoCommand { public: ReshapeCmd(Canvas *c, Document *d, const QVector &before, const QVector &after, const QString &text) : m_c(c), m_d(d), m_before(before), m_after(after) { setText(text); } void redo() override { apply(m_after); } void undo() override { apply(m_before); } private: void apply(const QVector &els) { QStringList ids; for (const Element &e : els) { m_d->replaceElement(e); ids << e.id; } refresh(m_c, ids); } Canvas *m_c; Document *m_d; QVector m_before, m_after; }; // Add new elements on top of the drawing (the array's copies), and point the // toolpaths in `tps` at them as well. class AddElementsCmd : public QUndoCommand { public: AddElementsCmd(Canvas *c, Document *d, const QVector &added, const QVector> &tps, const QStringList &before, const QString &text) : m_c(c), m_d(d), m_added(added), m_tps(tps), m_before(before) { setText(text); } void redo() override { QStringList ids = m_before; for (const Element &e : m_added) { m_d->addElement(e); ids << e.id; } for (const auto &p : m_tps) m_d->replaceToolpath(p.second); refresh(m_c, ids); } void undo() override { for (const Element &e : m_added) m_d->removeElementById(e.id); for (const auto &p : m_tps) m_d->replaceToolpath(p.first); refresh(m_c, m_before); } private: Canvas *m_c; Document *m_d; QVector m_added; QVector> m_tps; QStringList m_before; }; // Toolpaths that machine an original also machine its copies: for every // toolpath referencing one of the keys of `copiesOf`, the copies' uuids are // appended to its vectors. QVector> extendToolpaths(Document *d, const QHash &copiesOf) { QVector> out; for (const Toolpath &t : d->toolpaths()) { QJsonArray refs = t.json.value("elements").toArray(); QSet seen; for (const QJsonValue &v : refs) seen.insert(v.toObject().value("uuid").toString()); bool hit = false; const QJsonArray orig = refs; for (const QJsonValue &v : orig) { for (const QString &id : copiesOf.value(v.toObject().value("uuid").toString())) { if (seen.contains(id)) continue; refs.append(QJsonObject{{QStringLiteral("uuid"), id}}); seen.insert(id); hit = true; } } if (!hit) continue; Toolpath after = t; after.json.insert(QStringLiteral("elements"), refs); out.append({t, after}); } return out; } // ---- icons --------------------------------------------------------------- QIcon vecIcon(const QString &kind) { QPixmap pm(20, 20); pm.fill(Qt::transparent); QPainter p(&pm); p.setRenderHint(QPainter::Antialiasing); const QColor ink(0xd8, 0xdc, 0xe4); QPen pen(ink, 1.5); p.setPen(pen); const QRectF a(3, 5, 10, 10), b(7, 5, 10, 10); if (kind == "union" || kind == "subtract" || kind == "intersect") { QPainterPath pa, pb; pa.addEllipse(a); pb.addEllipse(b); QPainterPath fill = kind == "union" ? pa.united(pb) : kind == "subtract" ? pa.subtracted(pb) : pa.intersected(pb); p.setBrush(QColor(ink.red(), ink.green(), ink.blue(), 110)); p.setPen(Qt::NoPen); p.drawPath(fill); p.setPen(pen); p.setBrush(Qt::NoBrush); p.drawEllipse(a); p.drawEllipse(b); } else if (kind == "offset") { p.drawRoundedRect(QRectF(6, 6, 8, 8), 1.5, 1.5); pen.setStyle(Qt::DotLine); p.setPen(pen); p.drawRoundedRect(QRectF(2.5, 2.5, 15, 15), 4, 4); } else if (kind == "center") { p.drawRect(QRectF(2.5, 2.5, 15, 15)); p.setBrush(ink); p.drawRect(QRectF(7, 7, 6, 6)); } else if (kind == "mirrorh") { p.drawLine(QLineF(10, 2, 10, 18)); p.setBrush(ink); p.drawPolygon(QPolygonF({QPointF(8, 4), QPointF(8, 16), QPointF(2, 16)})); p.setBrush(Qt::NoBrush); p.drawPolygon(QPolygonF({QPointF(12, 4), QPointF(12, 16), QPointF(18, 16)})); } else if (kind == "mirrorv") { p.drawLine(QLineF(2, 10, 18, 10)); p.setBrush(ink); p.drawPolygon(QPolygonF({QPointF(4, 8), QPointF(16, 8), QPointF(16, 2)})); p.setBrush(Qt::NoBrush); p.drawPolygon(QPolygonF({QPointF(4, 12), QPointF(16, 12), QPointF(16, 18)})); } else if (kind == "grid") { p.setBrush(ink); p.drawRect(QRectF(3, 3, 5, 5)); p.setBrush(Qt::NoBrush); for (const QPointF &o : {QPointF(12, 3), QPointF(3, 12), QPointF(12, 12)}) p.drawRect(QRectF(o, QSizeF(5, 5))); } else if (kind == "circular") { p.setBrush(ink); p.drawEllipse(QPointF(10, 3.5), 2.2, 2.2); p.setBrush(Qt::NoBrush); for (int i = 1; i < 6; ++i) { const double a = M_PI / 2 + i * 2 * M_PI / 6; p.drawEllipse(QPointF(10 + 6.5 * std::cos(a), 10 - 6.5 * std::sin(a)), 2.2, 2.2); } } else if (kind == "pathpattern") { QPen faint = p.pen(); faint.setStyle(Qt::DotLine); p.setPen(faint); QPainterPath curve(QPointF(2, 16)); curve.cubicTo(6, 2, 14, 2, 18, 16); p.drawPath(curve); p.setPen(QPen(ink, 1.4)); p.setBrush(ink); p.drawRect(QRectF(1, 13.5, 4, 4)); p.setBrush(Qt::NoBrush); for (const QPointF &o : {QPointF(8, 4.5), QPointF(16, 13.5)}) p.drawRect(QRectF(o, QSizeF(4, 4))); } else if (kind == "rotate") { p.drawArc(QRectF(3, 3, 14, 14), 30 * 16, 270 * 16); p.setBrush(ink); p.drawPolygon(QPolygonF({QPointF(13.5, 1.5), QPointF(17.5, 6.5), QPointF(11.5, 7.5)})); } else if (kind == "scale") { p.drawRect(QRectF(2.5, 9.5, 8, 8)); pen.setStyle(Qt::DotLine); p.setPen(pen); p.drawRect(QRectF(2.5, 2.5, 15, 15)); pen.setStyle(Qt::SolidLine); p.setPen(pen); p.drawLine(QLineF(10.5, 9.5, 16, 4)); } else if (kind == "move") { p.drawLine(QLineF(10, 2, 10, 18)); p.drawLine(QLineF(2, 10, 18, 10)); p.setBrush(ink); for (const auto &tri : {QPolygonF({QPointF(10, 1), QPointF(7.5, 4.5), QPointF(12.5, 4.5)}), QPolygonF({QPointF(10, 19), QPointF(7.5, 15.5), QPointF(12.5, 15.5)}), QPolygonF({QPointF(1, 10), QPointF(4.5, 7.5), QPointF(4.5, 12.5)}), QPolygonF({QPointF(19, 10), QPointF(15.5, 7.5), QPointF(15.5, 12.5)})}) p.drawPolygon(tri); } else if (kind == "fillet") { QPainterPath c; c.moveTo(3, 17); c.lineTo(3, 10); c.arcTo(QRectF(3, 3, 14, 14), 180, -90); c.lineTo(17, 3); p.drawPath(c); } else if (kind == "chamfer") { p.drawPolyline(QPolygonF({QPointF(3, 17), QPointF(3, 9), QPointF(9, 3), QPointF(17, 3)})); } else if (kind == "alignh") { p.drawLine(QLineF(10, 2, 10, 18)); p.setBrush(ink); p.drawRect(QRectF(4, 5, 12, 4)); p.drawRect(QRectF(6, 11, 8, 4)); } else if (kind == "alignv") { p.drawLine(QLineF(2, 10, 18, 10)); p.setBrush(ink); p.drawRect(QRectF(5, 4, 4, 12)); p.drawRect(QRectF(11, 6, 4, 8)); } return QIcon(pm); } } // namespace // ---- VectorActions --------------------------------------------------------- VectorActions::VectorActions(Canvas *canvas, QMenu *editMenu, QMainWindow *window) : QObject(window), m_canvas(canvas) { connect(m_canvas, &Canvas::selectionChangedIds, this, &VectorActions::onSelection); editMenu->addSeparator(); QMenu *m = editMenu->addMenu(QStringLiteral("&Vectors")); auto add = [&](QMenu *menu, const QString &text, const QKeySequence &key, QVector &group, auto slot, const QString &tip = QString()) { QAction *a = menu->addAction(text); if (!key.isEmpty()) a->setShortcut(key); a->setShortcutContext(Qt::WindowShortcut); a->setToolTip(tip.isEmpty() ? text : tip); a->setStatusTip(a->toolTip()); // Connected first, so it runs first. connect(a, &QAction::triggered, this, [this] { if (beforeAction) beforeAction(); }); connect(a, &QAction::triggered, this, slot); group.append(a); return a; }; const auto S = [](int k) { return QKeySequence(Qt::CTRL | Qt::SHIFT | k); }; const auto A = [](int k) { return QKeySequence(Qt::CTRL | Qt::ALT | k); }; QAction *unionAct = add(m, QStringLiteral("&Union (Weld)"), S(Qt::Key_U), m_needTwo, [this] { boolean(vec::BoolOp::Union); }, QStringLiteral("Weld the selected closed vectors into one outline (Ctrl+Shift+U)")); QAction *subAct = add(m, QStringLiteral("&Subtract"), S(Qt::Key_D), m_needTwo, [this] { boolean(vec::BoolOp::Subtract); }, QStringLiteral("First-selected vector minus the others (Ctrl+Shift+D)")); QAction *interAct = add(m, QStringLiteral("&Intersect"), S(Qt::Key_I), m_needTwo, [this] { boolean(vec::BoolOp::Intersect); }, QStringLiteral("Keep only the area common to all selected vectors (Ctrl+Shift+I)")); m->addSeparator(); QAction *offsetAct = add(m, QStringLiteral("&Offset…"), S(Qt::Key_O), m_needOne, [this] { offset(); }, QStringLiteral("Offset the selection inward or outward by a distance (Ctrl+Shift+O)")); m->addSeparator(); QMenu *al = m->addMenu(QStringLiteral("&Align")); add(al, QStringLiteral("&Left"), S(Qt::Key_Left), m_needTwo, [this] { align(vec::Align::Left); }); add(al, QStringLiteral("&Horizontal center"), S(Qt::Key_H), m_needTwo, [this] { align(vec::Align::HCenter); }); add(al, QStringLiteral("&Right"), S(Qt::Key_Right), m_needTwo, [this] { align(vec::Align::Right); }); al->addSeparator(); add(al, QStringLiteral("&Top"), S(Qt::Key_Up), m_needTwo, [this] { align(vec::Align::Top); }); add(al, QStringLiteral("&Vertical center"), S(Qt::Key_V), m_needTwo, [this] { align(vec::Align::VCenter); }); add(al, QStringLiteral("&Bottom"), S(Qt::Key_Down), m_needTwo, [this] { align(vec::Align::Bottom); }); QMenu *cs = m->addMenu(QStringLiteral("&Center on stock")); QAction *centerAct = add(cs, QStringLiteral("&Both"), S(Qt::Key_C), m_needOne, [this] { centerOnStock(vec::Center::Both); }, QStringLiteral("Center the selection on the stock (Ctrl+Shift+C)")); add(cs, QStringLiteral("&Horizontally"), QKeySequence(), m_needOne, [this] { centerOnStock(vec::Center::Horizontal); }); add(cs, QStringLiteral("&Vertically"), QKeySequence(), m_needOne, [this] { centerOnStock(vec::Center::Vertical); }); QMenu *ds = m->addMenu(QStringLiteral("&Distribute")); add(ds, QStringLiteral("&Horizontally"), A(Qt::Key_H), m_needThree, [this] { distribute(vec::Axis::Horizontal); }, QStringLiteral("Space the selected vectors' centers evenly left to right (Ctrl+Alt+H)")); add(ds, QStringLiteral("&Vertically"), A(Qt::Key_V), m_needThree, [this] { distribute(vec::Axis::Vertical); }, QStringLiteral("Space the selected vectors' centers evenly bottom to top (Ctrl+Alt+V)")); m->addSeparator(); QAction *mirrorH = add(m, QStringLiteral("&Mirror horizontally"), A(Qt::Key_M), m_needOne, [this] { mirror(vec::Axis::Horizontal); }, QStringLiteral("Flip the selection left to right about its own center (Ctrl+Alt+M)")); QAction *mirrorV = add(m, QStringLiteral("Mirror &vertically"), A(Qt::Key_F), m_needOne, [this] { mirror(vec::Axis::Vertical); }, QStringLiteral("Flip the selection top to bottom about its own center (Ctrl+Alt+F)")); QAction *gridAct = add(m, QStringLiteral("&Grid array…"), QKeySequence(), m_needOne, [this] { gridArrayDialog(); }, QStringLiteral("Copy the selection into rows and columns")); QAction *circAct = add(m, QStringLiteral("&Circular array…"), QKeySequence(), m_needOne, [this] { circularArrayDialog(); }, QStringLiteral("Copy the selection around a center point")); QAction *pathAct = add(m, QStringLiteral("&Pattern on path…"), QKeySequence(), m_needTwo, [this] { patternOnPathDialog(); }, QStringLiteral("Copy the selection along the vector selected last")); m->addSeparator(); QMenu *mod = m->addMenu(QStringLiteral("&Modify")); QAction *rotAct = add(mod, QStringLiteral("&Rotate…"), A(Qt::Key_R), m_needOne, [this] { rotateDialog(); }, QStringLiteral("Turn the selection about its center by an angle (Ctrl+Alt+R)")); add(mod, QStringLiteral("Rotate 90° counter-clockwise"), QKeySequence(), m_needOne, [this] { rotate(90); }); add(mod, QStringLiteral("Rotate 90° clockwise"), QKeySequence(), m_needOne, [this] { rotate(-90); }); QAction *scaleAct = add(mod, QStringLiteral("&Scale…"), A(Qt::Key_S), m_needOne, [this] { scaleDialog(); }, QStringLiteral("Resize the selection about its center, by percent or to a size (Ctrl+Alt+S)")); QAction *moveAct = add(mod, QStringLiteral("&Move / Copy…"), QKeySequence(), m_needOne, [this] { moveCopyDialog(); }, QStringLiteral("Move the selection by an exact distance, or step copies of it")); mod->addSeparator(); QAction *filletAct = add(mod, QStringLiteral("&Fillet corners…"), A(Qt::Key_E), m_needOne, [this] { cornersDialog(vec::CornerStyle::Fillet); }, QStringLiteral("Round the sharp corners of the selected vectors (Ctrl+Alt+E)")); QAction *chamferAct = add(mod, QStringLiteral("&Chamfer corners…"), A(Qt::Key_K), m_needOne, [this] { cornersDialog(vec::CornerStyle::Chamfer); }, QStringLiteral("Bevel the sharp corners of the selected vectors (Ctrl+Alt+K)")); rotAct->setIcon(vecIcon(QStringLiteral("rotate"))); scaleAct->setIcon(vecIcon(QStringLiteral("scale"))); moveAct->setIcon(vecIcon(QStringLiteral("move"))); filletAct->setIcon(vecIcon(QStringLiteral("fillet"))); chamferAct->setIcon(vecIcon(QStringLiteral("chamfer"))); mirrorH->setIcon(vecIcon(QStringLiteral("mirrorh"))); mirrorV->setIcon(vecIcon(QStringLiteral("mirrorv"))); gridAct->setIcon(vecIcon(QStringLiteral("grid"))); circAct->setIcon(vecIcon(QStringLiteral("circular"))); pathAct->setIcon(vecIcon(QStringLiteral("pathpattern"))); // Icon toolbar for the everyday ones. unionAct->setIcon(vecIcon(QStringLiteral("union"))); subAct->setIcon(vecIcon(QStringLiteral("subtract"))); interAct->setIcon(vecIcon(QStringLiteral("intersect"))); offsetAct->setIcon(vecIcon(QStringLiteral("offset"))); centerAct->setIcon(vecIcon(QStringLiteral("center"))); auto *tb = window->addToolBar(QStringLiteral("Vectors")); tb->setMovable(false); tb->setToolButtonStyle(Qt::ToolButtonIconOnly); tb->setIconSize(QSize(20, 20)); for (QAction *a : {unionAct, subAct, interAct, offsetAct, centerAct}) tb->addAction(a); tb->addSeparator(); for (QAction *a : {mirrorH, mirrorV, gridAct, circAct, pathAct}) tb->addAction(a); tb->addSeparator(); for (QAction *a : {rotAct, scaleAct, moveAct, filletAct, chamferAct}) tb->addAction(a); updateEnabled(); } void VectorActions::onSelection(const QStringList &ids) { // Keep the ids still selected, in their old order; append the newcomers. QStringList next; for (const QString &id : m_order) if (ids.contains(id)) next << id; QStringList fresh; for (const QString &id : ids) if (!next.contains(id)) fresh << id; if (fresh.size() > 1) { // Batch selection has no click order: biggest bounding box first, so // Subtract on a rubber-banded base + cut-outs does the expected thing. Document *d = m_canvas->document(); auto area = [d](const QString &id) { const Element *e = d ? d->elementById(id) : nullptr; const QRectF r = e ? e->painterPath.boundingRect() : QRectF(); return r.width() * r.height(); }; std::stable_sort(fresh.begin(), fresh.end(), [&](const QString &a, const QString &b) { return area(a) > area(b); }); } m_order = next + fresh; updateEnabled(); } void VectorActions::updateEnabled() { const int n = m_order.size(); for (QAction *a : m_needOne) a->setEnabled(n >= 1); for (QAction *a : m_needTwo) a->setEnabled(n >= 2); for (QAction *a : m_needThree) a->setEnabled(n >= 3); } QVector VectorActions::orderedSelection() const { QVector out; Document *d = m_canvas->document(); if (!d) return out; for (const QString &id : m_order) if (const Element *e = d->elementById(id)) out.append(*e); return out; } int VectorActions::pushReplace(const QVector &inputs, const QVector &results, bool keepInputs, const QString &text, const QHash &from) { QStringList ids; for (const Element &e : inputs) ids << e.id; auto *cmd = new ReplaceCmd(m_canvas, m_canvas->document(), inputs, results, keepInputs, text, from); const int emptied = cmd->emptiedToolpaths(); // before the stack owns it m_canvas->pushEdit(cmd, ids); return emptied; } // The action's own result, with any warning its edit raised (constraints // that can't hold, shapes held by Fix) kept after it rather than replaced. void VectorActions::reportDone(const QString &msg) { const QString warn = m_canvas->editWarning(); emit m_canvas->statusHint(warn.isEmpty() ? msg : msg + QStringLiteral("; ") + warn); } void VectorActions::pushMoves(const QStringList &ids, const QVector &deltas, const QString &text) { bool any = false; for (const QPointF &d : deltas) if (!qFuzzyIsNull(d.x()) || !qFuzzyIsNull(d.y())) { any = true; break; } if (!any) return; m_canvas->pushEdit(new MoveManyCmd(m_canvas, m_canvas->document(), ids, deltas, text), ids); } // Sketch points and construction geometry are references, never material: // Booleans and Offset leave them out (and so never consume them). static QVector shapesOnly(const QVector &els) { QVector out; for (const Element &e : els) if (!Element::isPoint(e) && !Element::isConstruction(e)) out.append(e); return out; } void VectorActions::boolean(vec::BoolOp op) { const QVector inputs = shapesOnly(orderedSelection()); if (inputs.size() < 2) { if (!orderedSelection().isEmpty()) emit m_canvas->statusHint(tr("Booleans need at least two closed vectors")); return; } // Only closed vectors take part - booleanElements skips the rest. They // must also be the only ones replaced: handing the whole selection to // pushReplace deleted every open path in it, without it ever having // contributed to the result. QVector closedInputs; for (const Element &e : inputs) if (vec::isClosed(e)) closedInputs.append(e); const QString name = op == vec::BoolOp::Union ? tr("union") : op == vec::BoolOp::Subtract ? tr("subtract") : tr("intersect"); if (closedInputs.size() < 2) { emit m_canvas->statusHint(tr("Booleans need at least two closed vectors")); return; } // Subtract is "the first selected vector minus the rest". If the first one // is open it is skipped entirely, every closed vector becomes a clip, and // the empty result got reported as "vectors do not overlap" - which was // never the reason. if (op == vec::BoolOp::Subtract && !vec::isClosed(inputs.first())) { emit m_canvas->statusHint( tr("Subtract takes the first selected vector minus the rest — " "select a closed vector first")); return; } const QVector results = vec::booleanElements(closedInputs, op); if (results.isEmpty()) { emit m_canvas->statusHint(tr("%1: empty result — vectors do not overlap").arg(name)); return; } // Subtract leaves only what is left of the first vector; the others are // cut away, and a toolpath on them follows only the holes they left, // never onto the base. Union: each input follows the outline it welded // into, not a disjoint neighbour's. const Lineage from = op == vec::BoolOp::Subtract ? subtractLineage(closedInputs, results) : op == vec::BoolOp::Union ? unionLineage(closedInputs, results) : everyResult(closedInputs, results); const int emptied = pushReplace(closedInputs, results, false, tr("%1 %2 vectors").arg(name).arg(closedInputs.size()), from); QString msg = tr("%1: %2 vector(s) → %3 closed path(s)") .arg(name).arg(closedInputs.size()).arg(results.size()); if (emptied) msg += tr("; %1 toolpath(s) on the cut-away vectors have no vectors left").arg(emptied); reportDone(msg); } void VectorActions::offset() { if (shapesOnly(orderedSelection()).isEmpty()) { if (!orderedSelection().isEmpty()) emit m_canvas->statusHint(tr("Offset: points and construction geometry are not offset")); return; } QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Offset vectors")); auto *form = new QFormLayout; auto *dist = new QDoubleSpinBox(&dlg); dist->setRange(0.001, 1000.0); dist->setDecimals(3); dist->setSuffix(QStringLiteral(" mm")); dist->setValue(3.175); form->addRow(tr("Distance"), dist); auto *outside = new QRadioButton(tr("Outside (grow)"), &dlg); auto *inside = new QRadioButton(tr("Inside (shrink)"), &dlg); outside->setChecked(true); auto *dirRow = new QVBoxLayout; dirRow->addWidget(outside); dirRow->addWidget(inside); form->addRow(tr("Direction"), dirRow); auto *keep = new QCheckBox(tr("Keep original vectors"), &dlg); keep->setChecked(true); form->addRow(QString(), keep); auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg); connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); auto *lay = new QVBoxLayout(&dlg); lay->addLayout(form); lay->addWidget(buttons); if (dlg.exec() != QDialog::Accepted) return; offsetBy(inside->isChecked() ? -dist->value() : dist->value(), keep->isChecked()); } void VectorActions::offsetBy(double delta, bool keepInputs) { const QVector inputs = shapesOnly(orderedSelection()); if (inputs.isEmpty()) return; const QVector results = vec::offsetElements(inputs, delta); if (results.isEmpty()) { emit m_canvas->statusHint(tr("Offset: nothing left — inset larger than the shape")); return; } // Each toolpath follows only the outlines grown (or shrunk) from its own // vectors: Offset runs on the whole selection as one region. const int emptied = pushReplace(inputs, results, keepInputs, tr("offset %1 vector(s) by %2 mm").arg(inputs.size()).arg(delta), keepInputs ? Lineage() : offsetLineage(inputs, results, delta)); QString msg = tr("Offset by %1 mm: %2 closed path(s)").arg(delta).arg(results.size()); if (emptied) msg += tr("; %1 toolpath(s) on the cut-away vectors have no vectors left").arg(emptied); reportDone(msg); } static QVector boxesOf(const QVector &els) { QVector b; for (const Element &e : els) b.append(e.painterPath.boundingRect()); return b; } static QStringList idsOf(const QVector &els) { QStringList ids; for (const Element &e : els) ids << e.id; return ids; } // The box around all of `els`. By hand: QRectF::isNull() and united() both // take a box of no size (a zero-length line) for "no box", which left such a // vector out of the selection's box. Only an empty path has no box. static QRectF selectionBox(const QVector &els) { QRectF box; bool have = false; for (const Element &e : els) { if (e.painterPath.isEmpty()) continue; const QRectF b = e.painterPath.boundingRect(); if (!have) { box = b; have = true; continue; } box = QRectF(QPointF(qMin(box.left(), b.left()), qMin(box.top(), b.top())), QPointF(qMax(box.right(), b.right()), qMax(box.bottom(), b.bottom()))); } return box; } void VectorActions::align(vec::Align mode) { const QVector els = orderedSelection(); if (els.size() < 2) return; const QVector boxes = boxesOf(els); const QRectF ref = selectionBox(els); pushMoves(idsOf(els), vec::alignDeltas(boxes, mode, ref), tr("align %1 vectors").arg(els.size())); } void VectorActions::centerOnStock(vec::Center mode) { const QVector els = orderedSelection(); Document *d = m_canvas->document(); if (els.isEmpty() || !d) return; const QRectF stock(0, 0, d->boardWidth(), d->boardHeight()); pushMoves(idsOf(els), vec::centerDeltas(boxesOf(els), mode, stock), tr("center %1 vector(s) on stock").arg(els.size())); } void VectorActions::distribute(vec::Axis axis) { const QVector els = orderedSelection(); if (els.size() < 3) return; pushMoves(idsOf(els), vec::distributeDeltas(boxesOf(els), axis), tr("distribute %1 vectors").arg(els.size())); } // ---- mirror and array ------------------------------------------------------ void VectorActions::mirror(vec::Axis axis) { const QVector before = orderedSelection(); if (before.isEmpty()) return; const QTransform t = vec::mirrorTransform(selectionBox(before), axis); QVector after; for (const Element &e : before) after.append(vec::transformElement(e, t)); const QString dir = axis == vec::Axis::Horizontal ? tr("horizontally") : tr("vertically"); pushReshape(before, after, tr("mirror %1 vector(s) %2").arg(before.size()).arg(dir), t); reportDone(tr("Mirrored %1 vector(s) %2").arg(before.size()).arg(dir)); } void VectorActions::pushCopies(const QVector &originals, const QVector &placements, bool joinToolpaths, const QString &text) { Document *d = m_canvas->document(); if (!d || originals.isEmpty() || placements.isEmpty()) return; QVector added; QHash copiesOf; for (const QTransform &t : placements) { const QVector copy = vec::copyElements(originals, t); for (int i = 0; i < copy.size(); ++i) copiesOf[originals.at(i).id] << copy.at(i).id; added += copy; } const auto tps = joinToolpaths ? extendToolpaths(d, copiesOf) : QVector>(); m_canvas->undoStack()->push( new AddElementsCmd(m_canvas, d, added, tps, idsOf(originals), text)); QString hint = tr("%1 cop(ies) of %2 vector(s)").arg(placements.size()).arg(originals.size()); if (!tps.isEmpty()) hint += tr("; added to %1 toolpath(s)").arg(tps.size()); emit m_canvas->statusHint(hint); } void VectorActions::gridArray(int cols, int rows, double gapX, double gapY, bool joinToolpaths) { const QVector els = orderedSelection(); if (els.isEmpty()) return; pushCopies(els, vec::gridTransforms(selectionBox(els), cols, rows, gapX, gapY), joinToolpaths, tr("grid array %1 x %2").arg(cols).arg(rows)); } void VectorActions::circularArray(QPointF center, int count, double spanDeg, bool rotate, bool joinToolpaths) { const QVector els = orderedSelection(); if (els.isEmpty()) return; pushCopies(els, vec::circularTransforms(selectionBox(els), center, count, spanDeg, rotate), joinToolpaths, tr("circular array of %1").arg(count)); } void VectorActions::patternOnPath(int count, double spacing, bool orient, bool joinToolpaths) { QVector els = orderedSelection(); if (els.size() < 2) return; const Element path = els.takeLast(); const QVector t = vec::pathTransforms(path.painterPath, count, spacing, orient); if (t.isEmpty()) { emit m_canvas->statusHint(tr("Nothing to place: the path is too short for a second item")); return; } pushCopies(els, t, joinToolpaths, tr("pattern of %1 on a path").arg(t.size() + 1)); } // The array dialogs share their tail: the toolpath option and the buttons. static QCheckBox *finishArrayDialog(QDialog &dlg, QFormLayout *form) { auto *join = new QCheckBox(QObject::tr("Add the copies to the originals' toolpaths"), &dlg); join->setChecked(true); join->setToolTip(QObject::tr("A toolpath that machines a selected vector machines its copies too")); form->addRow(QString(), join); auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg); QObject::connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); QObject::connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); auto *lay = new QVBoxLayout(&dlg); lay->addLayout(form); lay->addWidget(buttons); return join; } static QDoubleSpinBox *mmBox(QWidget *parent, double lo, double hi, double value) { auto *b = new QDoubleSpinBox(parent); b->setRange(lo, hi); b->setDecimals(3); b->setSuffix(QStringLiteral(" mm")); b->setValue(value); return b; } void VectorActions::gridArrayDialog() { const QVector els = orderedSelection(); if (els.isEmpty()) return; const QRectF box = selectionBox(els); QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Grid array")); auto *form = new QFormLayout; auto *cols = new QSpinBox(&dlg); cols->setRange(1, 500); cols->setValue(3); auto *rows = new QSpinBox(&dlg); rows->setRange(1, 500); rows->setValue(1); auto *gapX = mmBox(&dlg, -box.width(), 10000, 5.0); auto *gapY = mmBox(&dlg, -box.height(), 10000, 5.0); gapX->setToolTip(tr("Space between neighbouring copies, edge to edge")); gapY->setToolTip(gapX->toolTip()); form->addRow(tr("Columns"), cols); form->addRow(tr("Rows"), rows); form->addRow(tr("Gap X"), gapX); form->addRow(tr("Gap Y"), gapY); auto *size = new QLabel(&dlg); auto updateSize = [=] { const double w = cols->value() * box.width() + (cols->value() - 1) * gapX->value(); const double h = rows->value() * box.height() + (rows->value() - 1) * gapY->value(); size->setText(tr("%1 × %2 mm overall").arg(w, 0, 'f', 2).arg(h, 0, 'f', 2)); }; for (QSpinBox *b : {cols, rows}) connect(b, &QSpinBox::valueChanged, &dlg, updateSize); for (QDoubleSpinBox *b : {gapX, gapY}) connect(b, &QDoubleSpinBox::valueChanged, &dlg, updateSize); updateSize(); form->addRow(tr("Size"), size); QCheckBox *join = finishArrayDialog(dlg, form); if (dlg.exec() != QDialog::Accepted) return; if (cols->value() * rows->value() < 2) return; gridArray(cols->value(), rows->value(), gapX->value(), gapY->value(), join->isChecked()); } void VectorActions::circularArrayDialog() { const QVector els = orderedSelection(); Document *d = m_canvas->document(); if (els.isEmpty() || !d) return; const QRectF box = selectionBox(els); QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Circular array")); auto *form = new QFormLayout; auto *count = new QSpinBox(&dlg); count->setRange(2, 1000); count->setValue(6); count->setToolTip(tr("Number of items including the original")); // Default center: the stock's, unless the selection sits on it, in // which case a ring around the selection's own center would collapse — // then a point one selection-height below it. QPointF c(d->boardWidth() / 2.0, d->boardHeight() / 2.0); if (d->boardWidth() <= 0 || QLineF(c, box.center()).length() < 1e-3) c = box.center() - QPointF(0, qMax(box.height(), 10.0) * 2); auto *cx = mmBox(&dlg, -100000, 100000, c.x()); auto *cy = mmBox(&dlg, -100000, 100000, c.y()); auto *span = new QDoubleSpinBox(&dlg); span->setRange(-360, 360); span->setDecimals(2); span->setSuffix(QStringLiteral(" °")); span->setValue(360); span->setToolTip(tr("360° spreads the items evenly around the circle; less places the first " "and last at the ends of the arc. Positive is counter-clockwise.")); auto *rotate = new QCheckBox(tr("Rotate the copies"), &dlg); rotate->setChecked(true); form->addRow(tr("Items"), count); form->addRow(tr("Center X"), cx); form->addRow(tr("Center Y"), cy); form->addRow(tr("Angle"), span); form->addRow(QString(), rotate); QCheckBox *join = finishArrayDialog(dlg, form); if (dlg.exec() != QDialog::Accepted) return; circularArray(QPointF(cx->value(), cy->value()), count->value(), span->value(), rotate->isChecked(), join->isChecked()); } void VectorActions::patternOnPathDialog() { const QVector els = orderedSelection(); if (els.size() < 2) return; const Element &path = els.last(); QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Pattern on path")); auto *form = new QFormLayout; auto *pathLabel = new QLabel(tr("%1 (the vector selected last); %2 other vector(s) are copied") .arg(path.geometryType).arg(els.size() - 1), &dlg); pathLabel->setWordWrap(true); form->addRow(tr("Path"), pathLabel); auto *count = new QSpinBox(&dlg); count->setRange(2, 1000); count->setValue(5); count->setToolTip(tr("Number of items including the original")); auto *fit = new QCheckBox(tr("Spread over the whole path"), &dlg); fit->setChecked(true); auto *spacing = mmBox(&dlg, 0.01, 100000, 20.0); spacing->setToolTip(tr("Distance along the path from one item to the next")); spacing->setEnabled(false); connect(fit, &QCheckBox::toggled, spacing, [spacing](bool on) { spacing->setEnabled(!on); }); auto *orient = new QCheckBox(tr("Turn the copies with the path"), &dlg); orient->setChecked(true); form->addRow(tr("Items"), count); form->addRow(QString(), fit); form->addRow(tr("Spacing"), spacing); form->addRow(QString(), orient); QCheckBox *join = finishArrayDialog(dlg, form); if (dlg.exec() != QDialog::Accepted) return; patternOnPath(count->value(), fit->isChecked() ? 0.0 : spacing->value(), orient->isChecked(), join->isChecked()); } // ---- modify: rotate, scale, move / copy, fillet, chamfer -------------------- void VectorActions::pushReshape(const QVector &before, const QVector &after, const QString &text, const QTransform &moved) { if (before.isEmpty()) return; QStringList ids; for (const Element &e : after) ids << e.id; m_canvas->pushEdit(new ReshapeCmd(m_canvas, m_canvas->document(), before, after, text), ids, moved); } void VectorActions::rotate(double deg) { const QVector before = orderedSelection(); if (before.isEmpty() || qFuzzyIsNull(std::fmod(deg, 360.0))) return; const QTransform t = vec::rotateTransform(selectionBox(before).center(), deg); QVector after; for (const Element &e : before) after.append(vec::transformElement(e, t)); pushReshape(before, after, tr("rotate %1 vector(s) by %2°").arg(before.size()).arg(deg), t); reportDone(tr("Rotated %1 vector(s) by %2°").arg(before.size()).arg(deg)); } void VectorActions::scale(double sx, double sy) { const QVector before = orderedSelection(); if (before.isEmpty() || sx <= 0 || sy <= 0 || (qFuzzyCompare(sx, 1.0) && qFuzzyCompare(sy, 1.0))) return; const QTransform t = vec::scaleTransform(selectionBox(before).center(), sx, sy); QVector after; for (const Element &e : before) after.append(vec::transformElement(e, t)); pushReshape(before, after, tr("scale %1 vector(s) %2% × %3%").arg(before.size()).arg(sx * 100).arg(sy * 100), t); reportDone(tr("Scaled %1 vector(s) to %2% × %3%") .arg(before.size()).arg(sx * 100).arg(sy * 100)); } void VectorActions::moveCopy(double dx, double dy, int copies, bool joinToolpaths) { const QVector els = orderedSelection(); if (els.isEmpty() || (qFuzzyIsNull(dx) && qFuzzyIsNull(dy))) return; if (copies <= 0) { pushMoves(idsOf(els), QVector(els.size(), QPointF(dx, dy)), tr("move %1 vector(s)").arg(els.size())); return; } QVector steps; for (int i = 1; i <= copies; ++i) steps.append(QTransform::fromTranslate(i * dx, i * dy)); pushCopies(els, steps, joinToolpaths, tr("copy %1 vector(s) ×%2").arg(els.size()).arg(copies)); } void VectorActions::corners(vec::CornerStyle style, double size) { const QVector sel = orderedSelection(); if (sel.isEmpty() || size <= 0) return; QVector before, after; int total = 0; for (const Element &e : sel) { int k = 0; const Element r = vec::cornerElement(e, style, size, &k); if (!k) continue; before.append(e); after.append(r); total += k; } const bool fillet = style == vec::CornerStyle::Fillet; if (before.isEmpty()) { emit m_canvas->statusHint(tr("No sharp corners between straight edges in the selection")); return; } pushReshape(before, after, (fillet ? tr("fillet %1 corner(s)") : tr("chamfer %1 corner(s)")) .arg(total)); reportDone((fillet ? tr("Filleted %1 corner(s) at %2 mm") : tr("Chamfered %1 corner(s) at %2 mm")) .arg(total).arg(size)); } static QDialogButtonBox *okCancel(QDialog &dlg, QFormLayout *form) { auto *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg); QObject::connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept); QObject::connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); auto *lay = new QVBoxLayout(&dlg); lay->addLayout(form); lay->addWidget(buttons); return buttons; } void VectorActions::rotateDialog() { if (orderedSelection().isEmpty()) return; QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Rotate")); auto *form = new QFormLayout; auto *angle = new QDoubleSpinBox(&dlg); angle->setRange(-360, 360); angle->setDecimals(3); angle->setSuffix(QStringLiteral(" °")); angle->setValue(90); angle->setToolTip(tr("Positive is counter-clockwise")); form->addRow(tr("Angle"), angle); okCancel(dlg, form); if (dlg.exec() == QDialog::Accepted) rotate(angle->value()); } void VectorActions::scaleDialog() { const QVector els = orderedSelection(); if (els.isEmpty()) return; const QRectF box = selectionBox(els); QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Scale")); auto *form = new QFormLayout; auto pct = [&dlg] { auto *b = new QDoubleSpinBox(&dlg); b->setRange(0.1, 100000); b->setDecimals(3); b->setSuffix(QStringLiteral(" %")); b->setValue(100); return b; }; auto *px = pct(), *py = pct(); auto *w = mmBox(&dlg, 0.001, 100000, box.width()); auto *h = mmBox(&dlg, 0.001, 100000, box.height()); auto *lock = new QCheckBox(tr("Keep proportions"), &dlg); lock->setChecked(true); // A line or a row of points has no height to scale (or no width): that // axis can then only follow the other one. w->setEnabled(box.width() > 1e-9); px->setEnabled(box.width() > 1e-9); h->setEnabled(box.height() > 1e-9); py->setEnabled(box.height() > 1e-9); form->addRow(tr("Width"), w); form->addRow(tr("Height"), h); form->addRow(tr("Scale X"), px); form->addRow(tr("Scale Y"), py); form->addRow(QString(), lock); // Four linked fields: whichever was typed in drives the rest. bool busy = false; auto sync = [&](double fx, double fy) { if (busy) return; busy = true; if (lock->isChecked()) { if (fx > 0) fy = fx; else fx = fy; } if (fx > 0) { px->setValue(fx * 100); w->setValue(box.width() * fx); } if (fy > 0) { py->setValue(fy * 100); h->setValue(box.height() * fy); } busy = false; }; connect(px, &QDoubleSpinBox::valueChanged, &dlg, [&](double v) { sync(v / 100, -1); }); connect(py, &QDoubleSpinBox::valueChanged, &dlg, [&](double v) { sync(-1, v / 100); }); connect(w, &QDoubleSpinBox::valueChanged, &dlg, [&](double v) { if (box.width() > 1e-9) sync(v / box.width(), -1); }); connect(h, &QDoubleSpinBox::valueChanged, &dlg, [&](double v) { if (box.height() > 1e-9) sync(-1, v / box.height()); }); connect(lock, &QCheckBox::toggled, &dlg, [&](bool on) { if (on) sync(px->isEnabled() ? px->value() / 100 : -1, py->value() / 100); }); okCancel(dlg, form); if (dlg.exec() == QDialog::Accepted) { const double fx = px->isEnabled() ? px->value() / 100 : py->value() / 100; const double fy = py->isEnabled() ? py->value() / 100 : fx; scale(fx, fy); } } void VectorActions::moveCopyDialog() { if (orderedSelection().isEmpty()) return; QDialog dlg(m_canvas->window()); dlg.setWindowTitle(tr("Move / Copy")); auto *form = new QFormLayout; auto *dx = mmBox(&dlg, -100000, 100000, 10); auto *dy = mmBox(&dlg, -100000, 100000, 0); auto *copies = new QSpinBox(&dlg); copies->setRange(0, 1000); copies->setSpecialValueText(tr("none (move)")); copies->setToolTip(tr("0 moves the selection; more leaves it where it is and adds that many " "copies, each one step further")); form->addRow(tr("Move X"), dx); form->addRow(tr("Move Y"), dy); form->addRow(tr("Copies"), copies); QCheckBox *join = finishArrayDialog(dlg, form); join->setEnabled(false); connect(copies, &QSpinBox::valueChanged, &dlg, [join](int n) { join->setEnabled(n > 0); }); if (dlg.exec() == QDialog::Accepted) moveCopy(dx->value(), dy->value(), copies->value(), join->isChecked()); } void VectorActions::cornersDialog(vec::CornerStyle style) { if (orderedSelection().isEmpty()) return; const bool fillet = style == vec::CornerStyle::Fillet; QDialog dlg(m_canvas->window()); dlg.setWindowTitle(fillet ? tr("Fillet corners") : tr("Chamfer corners")); auto *form = new QFormLayout; auto *size = mmBox(&dlg, 0.001, 10000, 3.0); size->setToolTip(fillet ? tr("Radius of the rounded corners") : tr("How far back along each edge the bevel starts")); form->addRow(fillet ? tr("Radius") : tr("Distance"), size); auto *note = new QLabel(tr("Applies to every sharp corner between two straight edges " "of the selected vectors."), &dlg); note->setWordWrap(true); form->addRow(note); okCancel(dlg, form); if (dlg.exec() == QDialog::Accepted) corners(style, size->value()); } } // namespace c2d