24#include <QGraphicsSceneMouseEvent>
30#include <unordered_set>
41using namespace SILICON::core;
44std::atomic<uint64_t> nextGraphicalWireRouteId{1};
54 uint64_t expected = nextGraphicalWireRouteId.load();
56 && !nextGraphicalWireRouteId.compare_exchange_weak(expected,
id + 1)) {}
67 if (!segment ||
segments.contains(segment))
85 for (
const auto& wire :
bus)
97 segment->setToolTip(reason.value_or(
""));
108 if (
bus.size() == 1 &&
bus[0]) {
109 switch (
bus[0]->getCurrentState()) {
114 qWarning() <<
"Unhandled wire status in getColor()";
130 std::vector<QPointF> vertices;
132 for (
const auto segment :
segments) {
133 const auto scenePoints = segment->getScenePoints();
134 const auto sceneFirst = scenePoints.front();
135 const auto sceneLast = scenePoints.back();
137 if (!segment->isFirstPointJunction())
138 vertices.push_back(sceneFirst);
139 if (!segment->isLastPointJunction())
140 vertices.push_back(sceneLast);
148 QPainterPath combinedPath;
151 combinedPath.addPath(segment->mapToScene(segment->centerlineShape()).simplified());
161 setFlag(QGraphicsItem::ItemSendsGeometryChanges);
162 setFlag(QGraphicsItem::ItemIsSelectable,
true);
163 setAcceptHoverEvents(
true);
197 throw std::logic_error(
"setGraphicalWire: oldWire is null unexpectedly");
201 throw std::logic_error(
"setGraphicalWire: old wire has no manager");
207 throw std::logic_error(
"setGraphicalWire: failed to create wire");
214 std::vector<QPointF> localPoints;
215 localPoints.reserve(newShowPoints.size());
216 for (
const auto& pt : newShowPoints)
217 localPoints.push_back(mapFromScene(pt));
232 std::vector<QPointF> proposed =
points;
236 qDebug() <<
"[GraphicalWireSegment] addPoints: invalid or self-intersecting route, "
241 points = std::move(proposed);
249 prepareGeometryChange();
256 for (
unsigned int i = 1; i < this->
points.size(); i++)
257 path.lineTo(this->points[i]);
266 if (
auto* diagram = qobject_cast<DiagramScene*>(scene()))
267 diagram->expandSceneBounds(sceneBoundingRect());
273 const QStyleOptionGraphicsItem* option, QWidget* widget)
279 painter->setPen(QPen(color, 3));
280 painter->drawPath(
path);
287 painter->setPen(QPen(color, 3));
288 painter->drawEllipse(
points.front(), 3, 3);
291 painter->setPen(QPen(color, 3));
292 painter->drawEllipse(
points.back(), 3, 3);
297 painter->setPen(Qt::NoPen);
298 for (
size_t i = 0; i <
points.size(); ++i) {
303 pointColor.setAlpha(160);
304 painter->setBrush(pointColor);
313 const qreal totalLength =
path.length();
314 const bool drawDecorations = (size > 1) && (totalLength >= 2 *
INTERVAL);
316 if (!drawDecorations)
319 painter->setPen(QPen(color, 2.0));
320 QFont font(
"NovaMono");
322 font.setPointSizeF(QFontInfo(painter->font()).pointSizeF() * 0.8);
323 painter->setFont(font);
325 const QString sizeText = QString::number(size);
330 for (qreal dist =
INTERVAL; dist < totalLength; dist +=
INTERVAL, ++counter) {
331 const bool drawSlash = (counter % 2 == 0);
332 const bool drawBox = ((counter - 1) % 4 == 0);
335 if (!drawSlash && !drawBox)
338 const qreal percent =
path.percentAtLength(dist);
339 const qreal pathAngle =
path.angleAtPercent(percent);
344 painter->translate(
path.pointAtPercent(percent));
348 painter->rotate(-pathAngle);
354 painter->drawLine(QPointF(-HALF_LEN, 0), QPointF(HALF_LEN, 0));
355 }
else if (drawBox) {
358 if (pathAngle == 180.0)
359 painter->rotate(180.0);
362 painter->drawRoundedRect(boxRect, 5, 5);
364 painter->drawText(boxRect, sizeText, QTextOption(Qt::AlignCenter));
373 return this->
path.boundingRect()
374 .united(this->
showPath.boundingRect())
375 .adjusted(-5, -5, 5, 5)
381 QPainterPathStroker stroker;
383 return stroker.createStroke(this->
path);
388 return QPainterPathStroker().createStroke(
path);
393 constexpr qreal HIT_WIDTH = 10.0;
395 return QLineF(point,
points.front()).length() <= HIT_WIDTH / 2.0;
397 QPainterPathStroker stroker;
398 stroker.setWidth(HIT_WIDTH);
399 return stroker.createStroke(
path).contains(point);
404 return points | std::views::transform([
this](
const QPointF& point) {
405 return mapToScene(point);
407 | std::ranges::to<std::vector>();
411 if (newPoints.empty())
412 throw std::invalid_argument(
"setPoints: points must not be empty");
413 prepareGeometryChange();
414 points = std::move(newPoints);
420 for (
size_t i = 0; i <
points.size(); ++i) {
433 auto [p1, p2] = segment;
435 const QPointF dir = p2 - p1;
436 const qreal dirSq = QPointF::dotProduct(dir, dir);
438 if (qFuzzyIsNull(dirSq))
441 const qreal t = QPointF::dotProduct(localPos - p1, dir) / dirSq;
444 if (t >= 0.0 && t <= 1.0) {
445 const QPointF diff = localPos - (p1 + dir * t);
446 if (QPointF::dotProduct(diff, diff) <= radiusSq)
447 return static_cast<size_t>(i);
475 throw std::invalid_argument(
"isAlignedWith: other is null");
477 throw std::logic_error(
"isAlignedWith: cannot compare segment with itself");
479 throw std::logic_error(
"isAlignedWith: segments must have at least 2 points");
481 throw std::logic_error(
"isAlignedWith: segment not in a scene");
485 QPointF inwardDirection;
488 const std::array endpoints = {
494 const std::array otherEndpoints = {
496 other->mapToScene(other->
points[1])
497 - other->mapToScene(other->
points.front())},
499 other->mapToScene(other->
points[other->
points.size() - 2])
500 - other->mapToScene(other->
points.back())},
503 for (
const Endpoint& endpoint : endpoints) {
504 for (
const Endpoint& otherEndpoint : otherEndpoints) {
505 if (endpoint.point != otherEndpoint.point)
508 const QPointF& a = endpoint.inwardDirection;
509 const QPointF& b = otherEndpoint.inwardDirection;
510 const qreal cross = a.x() * b.y() - a.y() * b.x();
511 const qreal dot = a.x() * b.x() + a.y() * b.y();
515 if (qFuzzyIsNull(cross) && dot < 0.0)
524 if (event->button() == Qt::LeftButton) {
525 auto* ds = qobject_cast<DiagramScene*>(scene());
526 const bool selecting =
event->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
527 if (ds && !selecting && !(isSelected() && ds->hasWireGroupSelection())
528 && ds->beginWireDrag(
this, event->scenePos(), event->pos())) {
530 ds->clearSelection();
541 auto* ds = qobject_cast<DiagramScene*>(scene());
542 if (ds && ds->isDraggingWire(
this)) {
543 ds->updateWireDrag(
this, event->scenePos());
547 GraphicalItem::mouseMoveEvent(event);
552 auto* ds = qobject_cast<DiagramScene*>(scene());
553 if (!ds || !ds->isDraggingWire(
this)) {
557 if (event->button() != Qt::LeftButton)
559 ds->finishWireDrag(
this);
565 auto* ds = qobject_cast<DiagramScene*>(scene());
566 if (!ds || ds->getInteractionMode() != InteractionMode::NORMAL_MODE) {
567 GraphicalItem::hoverMoveEvent(event);
579 setCursor(Qt::SizeAllCursor);
581 setCursor(
points[*edgeIndex].y() ==
points[*edgeIndex + 1].y()
582 ? Qt::SizeVerCursor : Qt::SizeHorCursor);
586 GraphicalItem::hoverMoveEvent(event);
601 if (
auto* ds = qobject_cast<DiagramScene*>(scene()); ds && ds->isDraggingWire(
this))
602 ds->cancelWireDrag();
613 manager->removeSegment(
this);
618 nlohmann::ordered_json j;
622 auto jsonPoints =
getScenePoints() | std::views::transform([](
const QPointF& p) {
623 return nlohmann::ordered_json{{
"x", p.x()}, {
"y", p.y()}};
625 | std::ranges::to<std::vector>();
627 j[
"points"] = jsonPoints;
631 if (bus.size() > 0 && bus[0])
632 j[
"wireId"] = bus[0]->getId();
virtual void modeChanged(InteractionMode mode)
Called when the interaction mode changes.
GraphicalItem(ItemCategory category=ItemCategory::GraphicalItem, QGraphicsItem *parent=nullptr)
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
The visible, selectable polyline wire on the diagram scene.
std::vector< QPointF > showPoints
Temporary points while drawing.
void setLastPointJunction(bool v)
Sets last endpoint junction status.
void setPoints(std::vector< QPointF > newPoints)
Replaces all points at once.
void updatePath()
Updates the internal path shapes.
QPainterPath shape() const override
Gets the shape for hit testing.
QPainterPath showPath
The temporary path while drawing.
QPainterPath centerlineShape() const
Narrow painted centerline used by component collision checks.
bool lastJunction
Junction flag for last endpoint.
void setFirstPointJunction(bool v)
Sets first endpoint junction status.
static constexpr int BOX_WIDTH
Width of bus size label box.
QPointF firstPoint() const
Gets the first point.
nlohmann::ordered_json serialize() const
Serializes the wire segment to JSON.
static constexpr int SLASH_ANGLE
Angle for slash decorations.
std::optional< size_t > edgeIndexAt(QPointF localPos) const
Finds the first edge within the grab radius of a local position.
static constexpr int INTERVAL
Interval for bus size decorations.
static constexpr int BOX_HEIGHT
Height of bus size label box.
static constexpr double POINT_RADIUS
Radius of draggable points.
void setGraphicalWire(GraphicalWire *newWire)
Sets the logical wire, optionally propagating to touching siblings.
void updateTopology() override
GraphicalWireSegment(QPointF firstPoint, QGraphicsItem *parent=nullptr)
Constructs a segment starting at the given point.
std::vector< QPointF > points
The segment points.
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override
Handles hover for point highlighting.
QPointF lastPoint() const
Gets the last point.
static constexpr int SLASH_LENGTH
Length of slash decorations.
GraphicalWire * graphicalWire
The logical wire this segment belongs to.
std::optional< size_t > hoveredPointIndex
Currently hovered point index.
std::vector< QPointF > getScenePoints() const
Gets all points mapped into scene coordinates.
std::optional< size_t > pointIndexAt(QPointF localPos) const
Gets the index of the point nearest to localPos.
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
Handles mouse release.
void modeChanged(InteractionMode mode) override
Clears the drag cursor and resets hover highlighting outside normal mode.
void setShowPoints(const std::vector< QPointF > &newShowPoints)
Sets temporary points shown while drawing.
bool isPointOnPath(QPointF point) const
Checks if a point is on the wire path.
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
Handles mouse press for point dragging.
void addPoints()
Confirms the show points as actual wire points.
static constexpr double GRAB_RADIUS
Grab radius for point selection.
QRectF boundingRect() const override
Gets the bounding rectangle.
bool firstJunction
Junction flag for first endpoint.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
Paints the wire segment.
~GraphicalWireSegment() override
bool isAlignedWith(const GraphicalWireSegment *other) const
Checks whether another segment is a straight continuation.
QPainterPath path
The main path.
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override
Handles mouse move for point dragging.
Logical wire entity that groups segments sharing the same bus.
void addSegment(GraphicalWireSegment *segment)
Adds a segment to this wire.
QColor getColor() const
Gets the color for this wire based on bus size.
void removeSegment(GraphicalWireSegment *segment)
Removes a segment from this wire.
WireManager * getManager() const
Gets the wire manager.
GraphicalWire()
Creates a wire with a unique route identifier.
void restoreRouteId(uint64_t id)
Restores a saved identifier and advances the identifier allocator.
QPainterPath shape() const
Gets the combined shape of all segments.
const std::unordered_set< GraphicalWireSegment * > & getSegments() const
Gets all segments belonging to this wire.
void setBusSize(unsigned int size)
Sets the bus size.
std::optional< QString > connectionError
void setConnectionError(std::optional< QString > reason)
Updates the connection error and refreshes segment tooltips and painting.
void clearBusState()
Clears the state of all wires in the bus.
std::vector< QPointF > getVertices() const
Gets vertices at wire endpoints that are not junctions.
std::unordered_set< GraphicalWireSegment * > segments
Set of segments belonging to this wire.
static const QColor & getColor(theme::ColorToken token)
std::vector< QPointF > canonicalizeOrthogonalRoute(std::vector< QPointF > points)
Removes consecutive duplicates and redundant collinear interior points.
bool orthogonalRouteSelfIntersects(const std::span< const QPointF > points)
Detects crossings, touches, or retraced portions within one route.
bool isOrthogonalRoute(const std::span< const QPointF > points)
Returns whether every consecutive route segment is axis-aligned.
DiagramScene::InteractionMode InteractionMode
Alias for DiagramScene::InteractionMode.