SILICON
Loading...
Searching...
No Matches
graphicalItem.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "graphicalItem.hpp"
19#include <QScopedValueRollback>
20
21#include <algorithm>
22#include <atomic>
23#include <stdexcept>
24#include <utility>
25
26#include <QVariant>
27
33
34
35namespace SILICON::ui {
36using namespace SILICON::core;
37
38namespace {
39
40std::atomic<uint64_t> NextGraphicalItemUiId = 1;
41
42bool wireTouchesComponentPort(const GraphicalWire& wire,
43 const GraphicalComponent& component)
44{
45 const auto touchesPort = [&](const Port* port) {
46 const QPointF position = component.mapToScene(port->getPosition());
47 for (const auto* segment : wire.getSegments()) {
48 const auto points = segment->getScenePoints();
49 if (!points.empty() && (points.front() == position || points.back() == position))
50 return true;
51 }
52 return false;
53 };
54
55 return std::ranges::any_of(component.getPorts(), touchesPort);
56}
57
58}
59
60GraphicalItem::GraphicalItem(ItemCategory category, QGraphicsItem* parent)
61 : QGraphicsObject(parent), uiId(generateUiId())
62{
63 setData(std::to_underlying(ItemDataRole::Category),
64 std::to_underlying(category | ItemCategory::GraphicalItem));
65}
66
68{
69 if (owningScene)
70 owningScene->unregisterGraphicalItem(this);
71}
72
74{
75 return NextGraphicalItemUiId.fetch_add(1, std::memory_order_relaxed);
76}
77
79{
80 const QScopedValueRollback guard(settingGeometryPosition, true);
82 setPos(position);
83}
84
86{
87 if (collidingStatus == newStatus)
88 return;
89 collidingStatus = newStatus;
90 update();
91}
92
93void GraphicalItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
94{
95 QGraphicsObject::mousePressEvent(event);
96
97 if (event->button() == Qt::LeftButton) {
98 for (QGraphicsItem* item : scene()->selectedItems()) {
99 if (auto gi = dynamic_cast<GraphicalItem*>(item)) {
100 gi->setInitialPosition();
101 }
102 }
103 }
104}
105
106void GraphicalItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
107{
108 QGraphicsObject::mouseReleaseEvent(event);
109
110 const auto ds = qobject_cast<DiagramScene*>(scene());
111
112 if (!ds)
113 return;
114
115 auto topologyEdit = ds->finishMixedDrag();
116 auto wireMoves = ds->finishComponentDrag();
117
118 if (this->isColliding())
120
121 bool itemsActuallyMoved = false;
122 auto undoStack = ds->getUndoStack();
123 auto moveCmd = new MoveItemCommand();
124
125 for (QGraphicsItem* item : scene()->selectedItems()) {
126 if (const auto gi = dynamic_cast<GraphicalItem*>(item)) {
127 if (gi->pos() != gi->getInitialPosition()) {
128 itemsActuallyMoved = true;
129 moveCmd->addItemMove(gi, gi->getInitialPosition(), gi->pos());
130 gi->setInitialPosition(); // Update for the next interaction
131 }
132 }
133 }
134
135 if (itemsActuallyMoved) {
136 moveCmd->setWireMoves(std::move(wireMoves));
137 moveCmd->setTopologyEdit(std::move(topologyEdit));
138 if (undoStack)
139 undoStack->push(moveCmd);
140 else
141 delete moveCmd;
142 } else {
143 delete moveCmd;
144 }
145}
146
147QVariant GraphicalItem::itemChange(GraphicsItemChange change, const QVariant& value)
148{
149 auto* ds = dynamic_cast<DiagramScene*>(scene());
150 if (!ds)
151 return QGraphicsItem::itemChange(change, value);
152
153 if (change == ItemSceneHasChanged) {
154 // Keep the scene lookup table in sync as Qt reparents/moves items between scenes.
155 if (owningScene != ds) {
156 if (owningScene)
157 owningScene->unregisterGraphicalItem(this);
158
159 ds->registerGraphicalItem(this);
161 Qt::UniqueConnection);
162 }
163
164 modeChanged(ds->getInteractionMode());
165 ds->expandSceneBounds(sceneBoundingRect());
166 }
167
168 if (change == ItemPositionHasChanged || change == ItemRotationHasChanged
169 || change == ItemTransformHasChanged || change == ItemScaleHasChanged
170 || change == ItemTransformOriginPointHasChanged)
171 ds->expandSceneBounds(sceneBoundingRect());
172
173 if (change == ItemPositionChange) {
175 onPositionChanged(value.toPointF() - pos());
176 return value;
177 }
178 // ==== Collision detection ====
179 // Resize anchors can leave a fractional origin. Snap the shared drag delta so
180 // selected items still move together, while preserving that origin on undo.
181 const auto proposedPos =
182 isSelected() && ds->mouseGrabberItem()
184 + QPointF(DiagramScene::snapToGrid(value.toPointF() - initialPosition))
185 : QPointF(DiagramScene::snapToGrid(value.toPointF()));
186 const auto offset = proposedPos - pos();
187
189
190 const auto* component =
192 if (!ds->itemCollisionChecksEnabled()
193 || (component && !component->participatesInCollisions())) {
194 onPositionChanged(offset);
195 return proposedPos;
196 }
197
198 // Positions are in parent coordinates; collision geometry is in scene coordinates.
199 const QPointF sceneOffset = parentItem()
200 ? parentItem()->mapToScene(proposedPos) - parentItem()->mapToScene(pos())
201 : offset;
202 const auto newCollisionRect = mapRectToScene(getCollisionRect()).translated(sceneOffset);
203
204 // Find all graphics items that intersect with our collision rectangle
205 // Filter out: current item, other selected items (as they are moving too), child
206 // items, and items without valid types
207
208 /* FIXME: Because we are ignoring selected items for the collision check some things
209 * are not allowed (for example moving two different horizzontaly aligned items
210 * against a wall will lead to the overlapping of the two items without triggering
211 * collision detection */
212
213 const auto children = childItems();
214 const auto collidingItems =
215 scene()->items(newCollisionRect, Qt::IntersectsItemBoundingRect)
216 | std::views::filter([this, &children](auto item) {
217 return !(item == this || item->isSelected() || children.contains(item)
218 || item->type() <= UNKNOWN);
219 })
220 | std::ranges::to<std::vector>();
221
222 QPointF finalPos = proposedPos;
223 bool collisionRejected = false;
224 auto* movingComponent = category_cast<GraphicalComponent>(this, ItemCategory::Component);
225 auto* movingSegment = category_cast<GraphicalWireSegment>(this,
227
228 // Analyze each potentially colliding item to determine collision type
229 for (QGraphicsItem* collidingItem : collidingItems) {
230 auto* otherComponent = category_cast<GraphicalComponent>(
231 collidingItem, ItemCategory::Component);
232 if (otherComponent && !otherComponent->participatesInCollisions())
233 continue;
234 if (movingComponent && otherComponent) {
235 // Scene queries include visual bounds. Reject only physical overlap.
236 const auto* otherItem = static_cast<GraphicalItem*>(otherComponent);
237 if (!newCollisionRect.intersects(
238 otherItem->mapRectToScene(otherItem->getCollisionRect())))
239 continue;
240 movingComponent->setCollidingStatus(COLLIDING_WITH_COMPONENT);
241 otherComponent->setCollidingStatus(COLLIDING_WITH_COMPONENT);
242
243 finalPos = pos();
244 collisionRejected = true;
245 break; // Reject immediately, stop checking others
246 }
247
248 // Check component-wire collisions for both component and wire movement.
249 auto* collidingComponent = movingComponent ? movingComponent : otherComponent;
250 auto* collidingSegment = movingSegment ? movingSegment
253 if (!collidingComponent || !collidingSegment)
254 continue;
255 const auto* collidingWire = collidingSegment->getGraphicalWire();
256
257 if (!collidingWire)
258 continue;
259
260 // An attached net follows its component during a drag. Other nets must
261 // still prevent the component from moving onto their wires.
262 if (this == collidingComponent
263 && ds->getInteractionMode() == InteractionMode::NORMAL_MODE
264 && (ds->isDraggingComponent(collidingComponent)
265 ? ds->isWireAttachedToDraggedComponent(collidingComponent,
266 collidingWire)
267 : wireTouchesComponentPort(*collidingWire, *collidingComponent)))
268 continue;
269
270 // Container for exclusion zones around wire vertices
271 QPainterPath toBeSubtractedWire{};
272
273 // Get wire vertices and create the base collision shape
274 // GraphicalWire::shape() and getVertices() already return scene coordinates
275 auto vertices = collidingWire->getVertices();
276 QPainterPath collisionPath = collidingWire->shape();
277
278 // If dragged item is a wire segment, translate the path to match the proposed
279 // position
280 if (this->type() == WIRE_SEGMENT) {
281 collisionPath.translate(sceneOffset);
282 for (auto& vertex : vertices)
283 vertex += sceneOffset;
284 }
285
286 // Create circular exclusion zones (5px radius) around each wire vertex
287 // These represent port connection points that should not trigger collision
288 for (const auto vertex : vertices) {
289 toBeSubtractedWire.addEllipse(vertex, 5, 5);
290 }
291
292 // GraphicalWire::shape() already returns scene-coordinate paths, no mapToScene
293 // needed. Subtract the port exclusion zones from the wire's collision path.
294 collisionPath = collisionPath.subtracted(toBeSubtractedWire);
295
296 auto componentRect = collidingComponent->mapRectToScene(
297 collidingComponent->collisionRectForWires());
298 if (movingComponent)
299 componentRect.translate(sceneOffset);
300 const bool isCollidingWithWire = collisionPath.intersects(componentRect);
301
302 // If collision detected, mark the component and reject the position change
303 if (isCollidingWithWire) {
304 collidingComponent->setCollidingStatus(COLLIDING_WITH_WIRE);
305 finalPos = pos();
306 collisionRejected = true;
307 break; // Reject immediately
308 }
309 }
310
311 if (!collisionRejected) {
312 onPositionChanged(offset);
313 }
314
315 return finalPos;
316 }
317
318 if (change == ItemSelectedChange && isColliding())
320
321 // For all other item changes, use default Qt behavior
322 return QGraphicsItem::itemChange(change, value);
323}
324
326{
327 switch (mode) {
328 case InteractionMode::NORMAL_MODE:
329 setFlag(QGraphicsItem::ItemIsMovable);
330 setFlag(QGraphicsItem::ItemIsFocusable);
331 setFlag(QGraphicsItem::ItemIsSelectable);
332 break;
333 case InteractionMode::WIRE_CREATION_MODE:
334 case InteractionMode::COMPONENT_PLACING_MODE:
335 case InteractionMode::SIMULATION_MODE:
336 case InteractionMode::PAN_MODE:
337 setFlag(QGraphicsItem::ItemIsSelectable, false);
338 setFlag(QGraphicsItem::ItemIsMovable, false);
339 setFlag(QGraphicsItem::ItemIsFocusable, false);
340 break;
341 default: throw std::logic_error("Unhandled InteractionMode in modeChanged");
342 }
343}
344
345} // namespace SILICON::ui
Graphics scene for the circuit diagram editor.
void modeChanged(InteractionMode mode)
Emitted when the interaction mode changes.
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
Base class for graphical circuit components.
uint64_t uiId
Stable runtime identifier used by DiagramScene payloads.
static uint64_t generateUiId()
int type() const override
Returns the item type identifier.
CollidingStatus collidingStatus
Current collision status.
virtual void modeChanged(InteractionMode mode)
Called when the interaction mode changes.
virtual void onPositionChanged(QPointF offset)
Called when the item position changes.
QPointF initialPosition
Initial position before a move action starts.
void setCollidingStatus(CollidingStatus newStatus)
Sets the collision status.
DiagramScene * owningScene
Scene used for uiId registration bookkeeping during destruction.
void setGeometryPosition(QPointF position)
GraphicalItem(ItemCategory category=ItemCategory::GraphicalItem, QGraphicsItem *parent=nullptr)
virtual QRectF getCollisionRect() const =0
Gets the rectangle used for collision detection.
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
void mousePressEvent(QGraphicsSceneMouseEvent *event) override
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
Handles item change events.
bool isColliding() const
Checks if the item is colliding.
Logical wire entity that groups segments sharing the same bus.
Represents a connection point on a component.
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
CollidingStatus
Collision state of a graphical item.
@ WIRE_SEGMENT
Definition enums.hpp:75
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60
DiagramScene::InteractionMode InteractionMode
Alias for DiagramScene::InteractionMode.