28#include <unordered_set>
34#include <QProgressDialog>
35#include <QScopedValueRollback>
58using namespace SILICON::core;
64 template <
typename Visitor>
67 auto collect = [&](
const std::vector<Port*>& ports,
bool output) {
68 for (uint32_t index = 0; index < ports.size(); ++index) {
69 const QPointF position = component.mapToScene(ports[index]->getPosition());
73 collect(component.getInputPorts(),
false);
74 collect(component.getOutputPorts(),
true);
79 for (; item; item = item->parentItem()) {
80 if (
const auto* component =
87 qreal gridCoordinate(
const qreal coordinate)
92 QPointF snappedEdgePoint(
const QPointF point,
const QPointF a,
const QPointF b)
95 return {a.x(), std::clamp(gridCoordinate(point.y()),
96 std::min(a.y(), b.y()), std::max(a.y(), b.y()))};
98 return {std::clamp(gridCoordinate(point.x()),
99 std::min(a.x(), b.x()), std::max(a.x(), b.x())), a.y()};
108 connect(
this, &QGraphicsScene::selectionChanged,
this, [
this] {
111 if (!item || !item->isSelected() || selectedItems().size() != 1)
120 invalidate(sceneRect(), QGraphicsScene::AllLayers);
125 serializer = std::make_unique<DiagramSceneSerializer>(*
this);
130 csb->setParent(
this);
135 [
this](std::string typeName, QPointF) {
placeComponent(typeName); });
138 const auto flags =
static_cast<uint8_t
>(change);
153 std::vector<WireManager::PortAnchor> anchors;
154 for (
auto* item : items()) {
158 forEachPortAnchor(*component,
159 [&](
const auto& anchor) { anchors.push_back(anchor); });
188 std::vector<std::string> componentTypesForScene(
const DiagramScene& scene)
194 std::vector<GraphicalLogicComponent*>
195 logicComponentsInScene(
const QGraphicsScene& scene)
197 std::vector<GraphicalLogicComponent*> components;
199 for (
auto* item : scene.items()) {
202 if (component && component->getComponent())
203 components.push_back(component);
209 void assignDefaultComponentName(
const QGraphicsScene& scene,
212 const auto defaultName =
213 component.getComponent()->getPropertyValue<std::string>(
"name");
214 if (!defaultName || defaultName->empty())
217 std::size_t count = 1;
218 std::unordered_set<std::string, TransparentStringHash, TransparentStringEqual>
220 for (
const auto* existing : logicComponentsInScene(scene)) {
221 if (existing->getTypeName() == component.getTypeName())
223 if (
const auto name =
224 existing->getComponent()->getPropertyValue<std::string>(
"name"))
225 usedNames.insert(*name);
230 auto name = *defaultName + std::to_string(count);
231 while (usedNames.contains(name))
232 name = *defaultName + std::to_string(++count);
233 component.applyProperty(
"name", name);
236 Component_set coreComponentsFor(std::span<GraphicalLogicComponent* const> components)
239 for (
const auto* component : components) {
240 if (component && component->getComponent())
241 coreComponents.insert(component->getComponent());
243 return coreComponents;
247 std::span<GraphicalLogicComponent* const> components,
253 }
catch (
const std::exception& error) {
254 QMessageBox::warning(scene.views().isEmpty() ?
nullptr : scene.views().first(),
255 QObject::tr(
"Auto place"), QString::fromUtf8(error.what()));
258 if (result.cancelled)
261 const auto& wires = result.wires;
263 if (componentMap.empty())
266 const bool collisionChecksEnabled = scene.itemCollisionChecksEnabled();
267 scene.setItemCollisionChecksEnabled(
false);
268 for (
const auto& [io, side] : result.ioPortOrientations)
269 io->setPortOrientation(side);
270 for (
const auto& [component, position] : componentMap) {
271 component->setPos(position);
272 component->setInitialPosition();
274 scene.setItemCollisionChecksEnabled(collisionChecksEnabled);
276 scene.getWireManager().replaceSegments(scene, wires);
284 auto refreshedCircuit =
285 std::make_shared<Circuit>(coreComponentsFor(components),
false);
286 scene.setCircuit(std::move(refreshedCircuit));
304 QPointF bestPoint{gridCoordinate(scenePoint.x()), gridCoordinate(scenePoint.y())};
306 const QRectF query(scenePoint - QPointF(bestDistance, bestDistance),
307 QSizeF(2 * bestDistance, 2 * bestDistance));
310 const auto nearby = items(query, Qt::IntersectsItemBoundingRect);
312 const auto& registeredSegments =
wireManager.getSegments();
315 auto updateBest = [&](
const QPointF candidate,
317 const qreal distance = QLineF(scenePoint, candidate).length();
318 if (distance > bestDistance)
320 if (distance == bestDistance) {
322 if (!segment || !bestSegment || segment == bestSegment)
324 const auto first = std::ranges::find_if(registeredSegments, [&](
const auto* wire) {
325 return wire == segment || wire == bestSegment;
327 if (first == registeredSegments.end() || *first != segment)
330 bestDistance = distance;
331 bestPoint = candidate;
332 bestSegment = segment;
337 std::vector<const GraphicalComponent*> visitedComponents;
338 for (
const auto* item : nearby) {
339 const auto* component = componentForItem(item);
340 if (!component || std::ranges::contains(visitedComponents, component))
342 visitedComponents.push_back(component);
343 forEachPortAnchor(*component,
344 [&](
const auto& anchor) { updateBest(anchor.position); });
347 for (
const auto* item : nearby) {
348 const auto* segment =
350 if (!segment || !segment->getGraphicalWire()
351 || segment->getGraphicalWire()->getManager() != &
wireManager)
355 if (!
wireManager.topologyFor(segment->getUiId()).firstVertex
356 && !std::ranges::contains(registeredSegments, segment))
358 const auto points = segment->getScenePoints();
360 updateBest(snappedEdgePoint(scenePoint, a, b), segment);
367 std::vector<RoutingComponent> components;
368 for (
const auto* item : items()) {
369 const auto* component =
371 if (!component || !component->participatesInCollisions())
375 .id = component->getUiId(),
376 .bounds = component->mapToScene(component->collisionRectForWires())
380 snapshot.
ports.reserve(component->getInputPorts().size()
381 + component->getOutputPorts().size());
382 forEachPortAnchor(*component, [&](
const auto& anchor) {
383 snapshot.
ports.push_back(anchor.position);
385 components.push_back(std::move(snapshot));
388 std::vector<RoutingSegment> segments;
389 segments.reserve(
wireManager.getSegments().size());
390 for (
const auto* segment :
wireManager.getSegments()) {
391 if (!segment || segment->empty() || !segment->getGraphicalWire())
394 auto points = segment->getScenePoints();
395 const auto& topology =
wireManager.topologyFor(segment->getUiId());
396 std::vector<std::pair<uint64_t, QPointF>> vertices;
397 vertices.reserve(2 + topology.junctions.size());
398 vertices.emplace_back(topology.firstVertex, points.front());
399 vertices.emplace_back(topology.lastVertex, points.back());
400 vertices.append_range(topology.junctions);
401 segments.push_back({segment->getUiId(), segment->getGraphicalWire()->getRouteId(),
402 std::move(points), std::move(vertices)});
404 return std::make_unique<InteractiveWireRouter>(std::move(components),
411 for (
const auto& route : routes) {
416 std::vector<QPointF> local;
417 local.reserve(route.points.size());
418 for (
const QPointF point : route.points)
419 local.push_back(segment->mapFromScene(point));
420 if (local != segment->getPoints()) {
422 segment->setPoints(std::move(local));
431 const auto id = segment->
getUiId();
432 if (std::ranges::find_if(
originals, [
id](
const auto& entry) {
433 return entry.first == id;
436 edits.push_back(std::make_unique<WireManager::Edit>(
manager, segment));
446 for (
const auto* segment : segments) {
450 if (
const auto* wire = segment->getGraphicalWire())
454 const auto points = segment->getScenePoints();
456 if (points.size() < 2)
458 for (
const bool first : {
true,
false}) {
459 const QPointF endpoint = first ? points.front() : points.back();
461 const uint64_t vertex = first ? ownTopology.
firstVertex : ownTopology.lastVertex;
462 for (
const auto* other : segments) {
463 if (other == segment)
466 if (vertex && (otherTopology.firstVertex == vertex
467 || otherTopology.lastVertex == vertex
468 || std::ranges::any_of(otherTopology.junctions,
469 [vertex](
const auto& junction) { return junction.first == vertex; })))
470 contacts.push_back({segment->getUiId(), first, other->getUiId()});
473 for (
auto* item : scene.items()) {
477 for (
Port* port : component->getPorts())
478 if (component->mapToScene(port->getPosition()) == endpoint)
479 contacts.push_back({segment->getUiId(), first, 0, component, port});
488 for (
const auto& [
id, points] :
originals)
489 for (
auto* segment :
manager->getSegments())
490 if (segment->getUiId() ==
id) {
491 segment->setPoints(points);
496 for (
auto& edit :
edits)
510 const auto segments =
manager.getSegments();
511 for (
const auto&
id :
originals | std::views::keys) {
513 if (found != segments.end()
514 && ((*found)->getPoints().size() < 2
517 throw std::invalid_argument(
"A committed wire route must be orthogonal");
520 for (
const auto& edit :
edits)
527 std::vector<WireRouteChange>
changes;
528 for (
const auto& [
id, before] :
originals) {
531 if (segment && segment->getPoints() != before)
532 changes.push_back({id, before, segment->getPoints()});
540 for (
auto* item : selectedItems()) {
541 if (
auto* component =
543 component && component->participatesInCollisions()) {
544 componentDrag.initialPositions.emplace_back(component, component->pos());
545 componentDrag.validPositions.emplace_back(component, component->pos());
554 for (
const auto& component :
componentDrag.initialPositions | std::views::keys) {
555 std::vector<QPointF> ports;
556 for (
const auto* port : component->getPorts())
557 ports.push_back(component->mapToScene(port->getPosition()));
560 for (
const auto* segment : segments) {
561 const auto points = segment->getScenePoints();
562 if (points.size() < 2 || !segment->getGraphicalWire())
564 if (std::ranges::find(ports, points.front()) != ports.end()
565 || std::ranges::find(ports, points.back()) != ports.end())
566 attached.insert(segment->getGraphicalWire());
582 const auto found =
componentDrag.attachedWires.find(component);
584 if (found !=
componentDrag.attachedWires.end() && found->second.contains(wire))
595 if (std::ranges::all_of(
componentDrag.validPositions, [](
const auto& entry) {
596 return entry.first->pos() == entry.second;
599 std::vector<ComponentRouteMove> moves;
600 for (
const auto& [component, initial] :
componentDrag.initialPositions) {
601 if (component->pos() != initial)
602 moves.push_back({component->getUiId(),
603 component->mapToScene(component->collisionRectForWires())
604 .boundingRect().normalized()});
606 const auto routes =
componentDrag.router->routeComponents(moves);
610 for (
const auto& [component, position] :
componentDrag.validPositions)
611 component->setGeometryPosition(position);
616 for (
auto& [component, position] :
componentDrag.validPositions)
617 position = component->pos();
627 }
catch (
const std::invalid_argument&) {
644 for (
const auto& [component, position] :
componentDrag.initialPositions) {
645 component->setGeometryPosition(position);
646 component->setInitialPosition();
655 bool hasComponent =
false;
656 size_t wireCount = 0;
657 for (
auto* item : selectedItems()) {
661 return wireCount > 0 && (hasComponent || wireCount > 1);
667 for (
auto* item : selectedItems())
669 mixedDrag.push_back({graphical, graphical->pos(), graphical->pos()});
674 if (!component || !component->participatesInCollisions())
676 std::vector<QPointF> ports;
677 for (
const auto* port : component->getPorts())
678 ports.push_back(component->mapToScene(port->getPosition()));
680 for (
const auto* segment : segments) {
681 const auto points = segment->getScenePoints();
682 if (points.size() < 2 || !segment->getGraphicalWire())
684 if (std::ranges::find(ports, points.front()) != ports.end()
685 || std::ranges::find(ports, points.back()) != ports.end())
686 attached.insert(segment->getGraphicalWire());
689 for (
const auto* segment :
wireManager.getSegments()) {
690 const auto id = segment->getUiId();
692 if (
const auto* wire = segment->getGraphicalWire())
694 wire->getRouteId(), wire->getBus()});
702 const QPointF delta =
mixedDrag.front().item->pos()
704 const bool movedTogether = std::ranges::all_of(
mixedDrag, [delta](
const auto& entry) {
705 return entry.item->pos() - entry.validPosition == delta;
707 if (!movedTogether) {
711 entry.item->setGeometryPosition(entry.validPosition);
716 entry.validPosition = entry.item->pos();
727 std::vector<std::pair<uint64_t, QPointF>> translations;
730 translations.emplace_back(entry.item->getUiId(),
731 entry.validPosition - entry.originalPosition);
734 if (!
wireManager.commitSegmentTranslations(translations)) {
738 entry.item->setGeometryPosition(entry.originalPosition);
743 if (before.firstVertex != after.firstVertex
744 || before.lastVertex != after.lastVertex
745 || before.junctions != after.junctions
746 || before.edgeIds != after.edgeIds)
752 if (!segment || !segment->getGraphicalWire())
754 const auto* wire = segment->getGraphicalWire();
756 if (before.routeId != after.
routeId || !(before.bus == after.
bus))
757 edit.
netChanges.push_back({id, before, after});
777 entry.item->setGeometryPosition(entry.originalPosition);
786 const QPointF scenePos,
const QPointF localPos)
792 const auto& points = segment->
getPoints();
794 const bool dragEndpoint = bend && (*bend == 0 || *bend + 1 == points.size());
795 const bool dragBend = bend && *bend > 0 && *bend + 1 < points.size();
796 const auto edge = bend ? std::optional<size_t>{} : segment->
edgeIndexAt(localPos);
797 if (!dragEndpoint && !dragBend && !edge)
803 wireDrag.index = bend ? *bend : *edge;
807 wireDrag.routes.captureContacts(*
this);
821 const auto& original =
wireDrag.originalPoints;
828 if (delta.isNull()) {
835 segment->mapToScene(original[
wireDrag.index]) + delta);
838 segment->mapToScene(original[
wireDrag.index])
850 auto changes =
wireDrag.routes.changes(*
this);
852 const bool movableFirst =
wireDrag.index == 0;
856 for (
const auto& contact :
wireDrag.routes.contacts)
857 if (contact.segmentId == segment->
getUiId() && contact.first == movableFirst
858 && contact.neighborId)
859 endpointEdit.
beforeContacts.push_back({contact.neighborId, contact.segmentId,
863 const QPointF endpoint = movableFirst ? points.front() : points.back();
866 if (other == segment || other->
empty()
871 if (std::ranges::find(joiningWires, other->getGraphicalWire()) == joiningWires.end())
872 joiningWires.push_back(other->getGraphicalWire());
882 if (!changes.empty())
885 }
catch (
const std::invalid_argument&) {
890 for (
const auto& [
id, before] :
wireDrag.routes.topologyBefore) {
892 if (before.firstVertex != after.firstVertex
893 || before.lastVertex != after.lastVertex
894 || before.junctions != after.junctions
895 || before.edgeIds != after.edgeIds)
898 for (
const auto& [
id, before] :
wireDrag.routes.netBefore) {
901 if (!member || !member->getGraphicalWire())
903 const auto* wire = member->getGraphicalWire();
905 if (before.routeId != after.
routeId || !(before.bus == after.
bus))
906 endpointEdit.
netChanges.push_back({id, before, after});
913 std::move(endpointEdit)));
927 for (
const auto& change : changes) {
933 segment->setPoints(useAfter ? change.after : change.before);
941 std::span<const WireRouteChange> wires,
947 std::vector<std::pair<GraphicalItem*, QPointF>> previousPositions;
948 std::vector<std::pair<uint64_t, QPointF>> wireTranslations;
949 for (
const auto& move : moves) {
951 const QPointF target = useAfter ? move.after : move.before;
952 previousPositions.emplace_back(item, item->pos());
954 wireTranslations.emplace_back(move.uiId, target - item->pos());
955 item->setGeometryPosition(target);
956 item->setInitialPosition();
959 if (!
wireManager.commitSegmentTranslations(wireTranslations)) {
960 for (
const auto& [item, position] : previousPositions)
961 item->setGeometryPosition(position);
963 throw std::invalid_argument(
"Cannot restore moved wire topology");
978 painter->setPen(pen);
980 const qreal left = int(rect.left()) - (int(rect.left()) %
GRID_SIZE);
981 const qreal top = int(rect.top()) - (int(rect.top()) %
GRID_SIZE);
983 QVector<QPointF> points;
984 for (qreal x = left; x < rect.right(); x +=
GRID_SIZE) {
985 for (qreal y = top; y < rect.bottom(); y +=
GRID_SIZE) {
986 points.append(QPointF(x, y));
989 painter->drawPoints(points.data(), points.size());
994 const bool drawWireCreationGuides =
998 if (drawWireCreationGuides) {
999 const QPoint cursorPos =
1001 const QRect guideRect = rect.toAlignedRect();
1004 pen.setCosmetic(
true);
1005 painter->setPen(pen);
1008 QLine(cursorPos.x(), guideRect.top(), cursorPos.x(), guideRect.bottom()));
1010 QLine(guideRect.left(), cursorPos.y(), guideRect.right(), cursorPos.y()));
1013 QGraphicsScene::drawForeground(painter, rect);
1018 setSceneRect(-expansionStep, -expansionStep, 2 * expansionStep, 2 * expansionStep);
1024 const auto current = sceneRect();
1025 if (current.contains(bounds))
1028 const auto combined = current.united(bounds);
1029 const QRectF expanded(
1034 if (expanded != current)
1035 setSceneRect(expanded);
1048 || !std::ranges::contains(component->
resizeHandles(), handle))
1050 bool invertible =
false;
1051 const auto fromScene = component->sceneTransform().inverted(&invertible);
1063 fromScene.map(scenePos),
1077 const auto delta = drag.fromScene.map(scenePos) - drag.start;
1078 if (delta.isNull()) {
1079 component->applyResizeState(drag.before);
1082 auto size = drag.bounds.size();
1084 size.rwidth() -= delta.x();
1086 size.rwidth() += delta.x();
1088 size.rheight() -= delta.y();
1090 size.rheight() += delta.y();
1091 size = size.expandedTo(QSizeF(1, 1));
1093 component->resizedProperties(size, drag.handle, drag.before.properties);
1094 component->applyResizeState({drag.before.position, std::move(properties)});
1096 component->mapToParent(
resizeAnchor(component->resizeBounds(), drag.handle));
1097 component->setGeometryPosition(component->pos() + drag.anchorInParent - anchor);
1098 component->setInitialPosition();
1106 if (!component || component->resizeState() == drag.before)
1120 component->applyResizeState(drag.before);
1162 if (currentMode == newMode && !force)
1165 if (!force &&
views().size() != 1)
1166 throw std::logic_error(
"setInteractionMode: scene must have exactly one view");
1175 if (currentMode == InteractionMode::COMPONENT_PLACING_MODE)
1177 else if (newMode == InteractionMode::COMPONENT_PLACING_MODE)
1180 if (newMode == InteractionMode::SIMULATION_MODE) {
1191 if (currentMode == InteractionMode::SIMULATION_MODE)
1216 }
catch (
const std::invalid_argument& error) {
1217 QMessageBox::warning(
views().isEmpty() ?
nullptr :
views().first(),
1218 "Cannot connect wire", error.what());
1238 for (
const QGraphicsItem* item : items(scenePoint)) {
1239 const auto* component =
1244 const auto portIsAtPoint = [component, scenePoint](
const Port* port) {
1245 return component->mapToScene(port->getPosition()) == scenePoint;
1248 if (std::ranges::any_of(component->getPorts(), portIsAtPoint))
1260 constexpr qreal MARGIN =
GRID_SIZE / 2.0;
1261 std::vector<QRectF> obstacles;
1262 std::vector<QRectF> tipKeepouts;
1263 for (
auto* item : items()) {
1264 const auto* component =
1266 if (!component || !component->participatesInCollisions())
1268 obstacles.push_back(component->mapToScene(component->collisionRectForWires())
1269 .boundingRect().adjusted(-MARGIN, -MARGIN, MARGIN, MARGIN));
1272 const QPointF lastPoint =
1274 for (
const auto* segment :
wireManager.getSegments()) {
1275 const auto points = segment->getScenePoints();
1276 if (points.size() < 2)
1278 for (
const QPointF tip : {points.front(), points.back()}) {
1279 if (tip == lastPoint || tip == scenePoint)
1281 const QRectF keepout(tip - QPointF(MARGIN, MARGIN),
1282 QSizeF(2 * MARGIN, 2 * MARGIN));
1283 obstacles.push_back(keepout);
1284 tipKeepouts.push_back(keepout);
1292 if (route.size() > 1)
1293 route.erase(route.begin());
1294 for (QPointF& point : route)
1324 const QPoint globalCursorPos = QCursor::pos();
1325 const auto view =
views()[0];
1329 const QPoint centerPos = view->viewport()->rect().center();
1331 const QPoint cursorPosWithinView = view->mapFromGlobal(globalCursorPos);
1332 const bool isCursorInsideView = view->viewport()->rect().contains(cursorPosWithinView);
1333 const QPoint posForCSB = isCursorInsideView ? cursorPosWithinView : centerPos;
1335 showCSB(view->mapToScene(posForCSB));
1352 mouseEvent->accept();
1360 case InteractionMode::COMPONENT_PLACING_MODE: {
1367 case InteractionMode::WIRE_CREATION_MODE: {
1374 case InteractionMode::NORMAL_MODE:
1375 case InteractionMode::PAN_MODE:
1376 case InteractionMode::SIMULATION_MODE:
break;
1377 default:
throw std::logic_error(
"Unhandled InteractionMode in mouseMoveEvent");
1379 QGraphicsScene::mouseMoveEvent(mouseEvent);
1391 && mouseEvent->button() == Qt::LeftButton
1392 && !(mouseEvent->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier))) {
1393 const auto selection = selectedItems();
1394 if (selection.size() == 1) {
1397 if (
auto handle = component->resizeHandleAt(
1398 component->mapFromScene(mouseEvent->scenePos()));
1400 mouseEvent->accept();
1411 case InteractionMode::NORMAL_MODE:
break;
1412 case InteractionMode::COMPONENT_PLACING_MODE: {
1415 const auto rotation = placedComponent->rotation();
1427 throw std::logic_error(
1428 "componentToBeDrawn should not be null after placeComponent succeeds");
1433 case InteractionMode::PAN_MODE:
break;
1434 case InteractionMode::WIRE_CREATION_MODE: {
1443 QMessageBox::warning(
views().isEmpty() ?
nullptr :
views().first(),
1444 "Cannot connect wire",
1445 "No valid orthogonal route avoids other wire endpoints");
1451 const QPointF endpoint =
1461 case InteractionMode::SIMULATION_MODE: {
1465 const auto itemsAtPos = items(cursorPos);
1467 for (
const auto item : itemsAtPos) {
1469 io->handleSimulationClick();
1474 default:
throw std::logic_error(
"Unhandled InteractionMode in mousePressEvent");
1476 QGraphicsScene::mousePressEvent(mouseEvent);
1478 mouseEvent->button() == Qt::LeftButton) {
1482 for (
auto* item = mouseGrabberItem(); item; item = item->parentItem()) {
1497 mouseEvent->accept();
1500 uint64_t clickedId = 0;
1502 && mouseEvent->button() == Qt::LeftButton
1503 && !(mouseEvent->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier))
1504 && mouseEvent->screenPos() == mouseEvent->buttonDownScreenPos(Qt::LeftButton)) {
1505 for (
auto* item = mouseGrabberItem(); item; item = item->parentItem()) {
1508 clickedId = component->getUiId();
1513 clickedId = wire->getUiId();
1519 QGraphicsScene::mouseReleaseEvent(mouseEvent);
1523 clicked->setSelected(
true);
1530 switch (event->key()) {
1531 case Qt::Key_Escape: {
1534 if (event->modifiers() & Qt::ShiftModifier) {
1553 QGraphicsScene::keyPressEvent(event);
1575 throw std::logic_error(
"setComponentShadow: no component to draw");
1576 if (
views().size() != 1)
1577 throw std::logic_error(
"setComponentShadow: scene must have exactly one view");
1579 const auto view =
views()[0];
1580 const auto cursorPos = view->mapToScene(view->mapFromGlobal(QCursor::pos()));
1599 csb->setCompletionList(componentTypesForScene(*
this));
1603 csb->showCompleter();
1609 if (
csb->scene() ==
this)
1630 std::vector<Sample> inputSnapshots)
1637 inspectConnectionForComponents(
const std::vector<GraphicalWire*>& wires,
1638 std::span<GraphicalLogicComponent* const> components)
1641 std::vector<QPointF> endpoints;
1642 for (
const auto* wire : wires)
1643 for (
const auto* segment : wire->getSegments()) {
1644 const auto points = segment->getScenePoints();
1645 if (points.size() >= 2) {
1646 endpoints.push_back(points.front());
1647 endpoints.push_back(points.back());
1650 std::optional<size_t> width;
1651 auto collect = [&](
const GraphicalLogicComponent* component,
1652 const std::vector<Port*>& ports,
const std::vector<Bus>& buses,
1653 const bool isOutput) {
1654 for (
size_t index = 0; index < std::min(buses.size(), ports.size()); ++index) {
1655 Port* port = ports[index];
1656 const QPointF position = component->mapToScene(port->getPosition());
1658 const bool connected = std::ranges::contains(endpoints, position);
1659 const bool portAlreadyAdded = std::ranges::contains(result.
affectedPorts, port);
1660 if (!connected || portAlreadyAdded)
1668 const auto portWidth = buses[index].size();
1671 else if (*width != portWidth && result.
isValid()) {
1673 result.
error = QString(
"Port %1 requires %2 bits; this net requires %3 bits")
1674 .arg(port->getName())
1681 for (
const auto* component : components) {
1682 collect(component, component->getOutputPorts(),
1683 component->getComponent()->outputBuses(),
true);
1684 collect(component, component->getInputPorts(),
1685 component->getComponent()->inputBuses(),
false);
1698 return inspectConnectionForComponents(wires, logicComponentsInScene(*
this));
1716 QTimer::singleShot(0,
this, [
this] {
1732 const auto components = logicComponentsInScene(*
this);
1736 | std::views::transform([&components](
const std::shared_ptr<GraphicalWire>& w) {
1737 return inspectConnectionForComponents({w.get()}, components);
1739 | std::ranges::to<std::vector>();
1742 auto clearBindings = [&components] {
1743 for (
auto* component : components)
1744 component->getComponent()->clearWires();
1748 auto bind = [
this, &components] {
1749 for (
auto [index, wire] :
wireManager.wires() | SILICON::views::enumerate) {
1755 if (wire->getBusSize() != net.width)
1756 wire->setBusSize(net.width);
1758 for (
auto* component : components) {
1760 for (
const auto& [portIndex, port] :
1761 component->getOutputPorts() | SILICON::views::enumerate)
1762 if (std::ranges::find(net.affectedPorts, port) != net.affectedPorts.end())
1763 component->getComponent()->setOutput(portIndex, wire->getBus());
1764 for (
const auto& [portIndex, port] :
1765 component->getInputPorts() | SILICON::views::enumerate)
1766 if (std::ranges::find(net.affectedPorts, port) != net.affectedPorts.end()) {
1768 component->assignInputPortBus(portIndex, wire->getBus());
1769 }
catch (
const std::exception& error) {
1770 net.error = QString::fromUtf8(error.what());
1786 for (
const auto [index, wire] :
wireManager.wires() | SILICON::views::enumerate) {
1788 wire->setConnectionError(net.error);
1790 for (
auto* component : components) {
1791 for (
Port* port : component->getPorts()) {
1792 port->setInputAssignmentError(
false);
1793 port->setToolTip(port->getName());
1798 for (
Port* port : net.affectedPorts) {
1799 port->setInputAssignmentError(
true);
1800 port->setToolTip(net.error.value());
1812 component->setPos(pos);
1820 auto components = logicComponentsInScene(*
this);
1821 if (components.empty())
1828 std::shared_ptr<Circuit> authoritativeCircuit =
getCircuit();
1829 if (!authoritativeCircuit
1830 || boost::num_vertices(authoritativeCircuit->getGraph()) == 0) {
1833 authoritativeCircuit =
1834 std::make_shared<Circuit>(coreComponentsFor(components),
false);
1836 const Circuit& activeCircuit = *authoritativeCircuit;
1840 QProgressDialog progress(tr(
"Finding a clean circuit layout..."), tr(
"Use best so far"),
1842 progress.setWindowTitle(tr(
"Auto place"));
1843 progress.setWindowModality(Qt::WindowModal);
1844 progress.setAutoClose(
false);
1845 progress.setAutoReset(
false);
1846 progress.setMinimumDuration(300);
1847 progress.setValue(0);
1848 QApplication::processEvents();
1851 QApplication::processEvents();
1852 return progress.wasCanceled();
1854 options.
progress = [&progress](
const int completed,
const int total) {
1855 progress.setMaximum(total);
1856 progress.setValue(completed);
1857 QApplication::processEvents();
1860 applyAutoplacement(*
this, activeCircuit, components, options);
1867 throw std::logic_error(
"placeComponent: previous component not yet placed");
1870 if (
auto* subcircuit =
1883 if (!initialProperties.contains(
"portOrientation")) {
1884 switch (logicComponent->getComponent()->metadata().portRole) {
1896 for (
const auto& [key, value] : initialProperties)
1901 logicComponent && !initialProperties.contains(
"name"))
1902 assignDefaultComponentName(*
this, *logicComponent);
1912 const auto orientation = component.
getPropertyValue<std::string>(
"portOrientation");
1959nlohmann::ordered_json
1962 return serializer->serializeItems(sceneItems);
1969 serializer->deserialize(jsonStr, guiFactory, coreRegistry);
1972std::shared_ptr<SceneLoadPlan>
1977 return serializer->prepareDeserialize(jsonStr, guiFactory, coreRegistry);
1982 serializer->applyDeserialize(std::move(plan));
1987 const bool resolveSubcircuitMetadata)
1989 serializer->loadCircuit(std::move(
circuit), guiFactory, resolveSubcircuitMetadata);
1995 QPointF targetOrigin,
const bool isPaste)
1997 return serializer->insertSelection(payload, guiFactory, coreRegistry, targetOrigin,
2010 if (sceneItems.empty())
2018 const bool removedComponents = std::ranges::any_of(sceneItems, [](
const auto* item) {
2025 for (
auto* item : sceneItems)
2028 for (
auto* item : sceneItems)
2031 if (removedComponents)
2079 QGraphicsScene::clear();
2098 item->setOwningScene(
nullptr);
Represents a digital circuit as a directed graph of components.
Base class for all digital circuit components.
std::optional< T > getPropertyValue(std::string_view key) const
Gets a property value with type deduction.
virtual ComponentMetadata metadata() const
Gets catalog metadata for this component type.
static CircuitAutoplacement compute(const core::Circuit &circuit, std::span< GraphicalLogicComponent *const > components, const CircuitAutoplacerOptions &options={})
Computes component placements and routed wire paths for a circuit.
void selectedComponent(std::string typeName, QPointF pos)
Graphics scene for the circuit diagram editor.
bool hasWireGroupSelection() const
Returns whether the selection includes a wire and a component, or multiple wires.
void registerGraphicalItem(GraphicalItem *item)
struct SILICON::ui::DiagramScene::WireDragState wireDrag
std::shared_ptr< Circuit > circuit
Underlying logic circuit model.
void placeComponent(std::string_view typeName, bool showSearchBox=true, const PropertyMap &initialProperties={})
Begins placing a component and applies its initial properties first.
void clear(bool clearUndoStack=true, bool clearLogs=true)
const CircuitResolver * circuitResolver() const noexcept
std::map< uint64_t, WireEndpointEdit::NetState > mixedDragNetBefore
void showCSB(QPointF pos)
Shows the component search box at a position.
static constexpr int GRID_SIZE
Grid cell size in scene units.
bool itemCollisionChecksEnabled() const
WireManager wireManager
Wire manager for wire topology.
QUndoStack * getUndoStack() const
const SILICON::project::DocumentStore * documents
void clearWireShadow()
Clears the wire being drawn.
std::unique_ptr< DiagramSceneSimulationController > simulationController
Simulation lifecycle and trace management.
std::string lastOutputOrientation
void updateWirePreview(QPointF scenePoint)
Updates the route preview for the wire being drawn toward a scene position.
const ConnectionReport & currentConnectionReport()
Returns the cached connection report, refreshing it first when dirty.
GraphicalComponent * componentToBeDrawn
Component being placed (shadow).
void handleInputToggled(Bus targetBus, BusValue value, Component_weakPtr source)
Handles input toggle events from GraphicalInput components.
void loadCircuit(std::shared_ptr< Circuit > circuit, GUIComponentFactory &guiFactory, bool resolveSubcircuitMetadata=true)
void setFstTraceFile(std::optional< std::string > fileName)
Enables or disables simulation FST tracing.
void addComponent(GraphicalComponent *component, QPointF pos)
Adds a component to the scene.
bool isWireCompletionPoint(QPointF scenePoint) const
Lifecycle helper methods for interaction modes.
bool cancelCurrentInteraction()
Cancels the active transient interaction, returning to normal editing.
NetConnection inspectConnection(const std::vector< GraphicalWire * > &wires) const
Inspects the combined wire group for width and driver compatibility.
bool beginWireDrag(GraphicalWireSegment *segment, QPointF scenePos, QPointF localPos)
Starts dragging the wire handle hit at a local position.
std::unique_ptr< InteractiveWireRouter > makeInteractiveRouter() const
Creates a router snapshot from current components, routes, and electrical vertices.
std::unique_ptr< DiagramSceneSerializer > serializer
Persistence and clipboard payload handling.
WireManager & getWireManager()
void hideCSB()
Hides the component search box.
nlohmann::ordered_json serializeItems(const std::vector< QGraphicsItem * > &sceneItems) const
Serializes arbitrary scene items using the internal selection payload format.
std::vector< WireRouteChange > finishComponentDrag()
Commits the component gesture and returns its before and after wire routes.
void updateMixedDrag()
Validates mixed selection movement and retains the last valid positions.
void applyItemMoves(std::span< const ItemPositionChange > moves, std::span< const WireRouteChange > wires, bool useAfter, const WireEndpointEdit &topology={})
Applies recorded item positions and wire routes and rebuilds connectivity.
void applyDeserialize(std::shared_ptr< SceneLoadPlan > plan)
Replaces the scene contents with a prepared plan.
bool suppressNextComponentSearch
Suppresses the quick search popup for catalog-driven placement.
std::map< uint64_t, WireManager::SegmentTopology > mixedDragTopologyBefore
void applyWireRouteChanges(std::span< const WireRouteChange > changes, bool useAfter, const WireEndpointEdit &endpointEdit={})
Applies recorded wire routes and rebuilds connectivity.
void removeItems(const std::vector< QGraphicsItem * > &sceneItems)
Removes the given scene items and refreshes the logical topology.
void setDocumentStore(const SILICON::project::DocumentStore *documents) noexcept
void exitSimulationMode()
void updateComponentDrag()
Previews component moves and restores the last valid positions if routing fails.
void finishComponentResize()
void finalizeWireCreation()
InteractionMode currentInteractionMode
Current interaction mode.
std::string lastPlacedComponentType
Last placed component type for repeat placement.
void requestConnectionsRefresh()
Marks connections dirty and schedules one refresh on the event loop.
struct SILICON::ui::DiagramScene::ComponentDragState componentDrag
void keyPressEvent(QKeyEvent *event) override
Handles key presses for mode changes.
std::shared_ptr< SceneLoadPlan > prepareDeserialize(const std::string &jsonStr, GUIComponentFactory &guiFactory, const ComponentRegistry &coreRegistry)
Deserializes a scene payload into a detached plan.
bool removeSelection(const nlohmann::json &payload)
Removes items matching a serialized selection payload from the current scene.
void refreshConnections()
Rebuilds the connection report, logical bindings, and visual error markers.
void updateWireDrag(GraphicalWireSegment *segment, QPointF scenePos)
Previews the active segment drag at the given scene position.
void modeChanged(InteractionMode mode)
Emitted when the interaction mode changes.
void enterComponentPlacingMode()
std::string serialize() const
Serializes the full editor scene to JSON.
void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) override
Handles mouse movement for wire/component dragging.
void unregisterGraphicalItem(GraphicalItem *item)
struct SILICON::ui::DiagramScene::ComponentResizeTransaction componentResize
std::vector< MixedDragItem > mixedDrag
void updateSceneAfterEdit()
void cancelComponentDrag()
Restores original component positions and wire geometry.
std::string lastInputOrientation
Last user-edited orientations, kept only for this editor session.
GraphicalComponent * getComponentToBeDrawn() const
Gets the component currently being placed.
std::unordered_map< uint64_t, GraphicalItem * > itemsByUiId
O(1) lookup table for runtime graphical items by stable UI id.
void updateComponentResize(QPointF scenePos)
bool wirePreviewRouteValid
bool isDraggingComponent(const GraphicalComponent *component) const
Returns whether the component participates in an active component or mixed drag.
void applyRoutingPreview(const std::vector< RoutedSegment > &routes, RouteEditState &state)
Applies preview routes while recording original geometry in the edit state.
bool connectionRefreshScheduled
void setComponentShadow()
Shows the component shadow at cursor position.
bool isFstTracingEnabled() const
void deserialize(const std::string &jsonStr, GUIComponentFactory &guiFactory, const ComponentRegistry &coreRegistry)
Deserializes a full scene from JSON.
void initializeSceneBounds(qreal expansionStep)
const CircuitResolver * resolver
bool ioInteractionsEnabled
Whether simulation-mode IO clicks may mutate input state.
void clearComponentShadow()
Clears the component shadow.
void setItemCollisionChecksEnabled(bool enabled)
bool connectionReportDirty
nlohmann::ordered_json serializeSelection() const
Serializes the selected components and wire segments for clipboard use.
std::unordered_map< const GraphicalComponent *, std::unordered_set< const GraphicalWire * > > mixedDragAttachedWires
void cancelComponentResize()
WireEndpointEdit finishMixedDrag()
Commits a mixed selection drag and returns topology and net changes for undo.
bool refreshingConnections
GraphicalWireSegment * wireSegmentToBeDrawn
Wire segment being drawn.
void drawForeground(QPainter *painter, const QRectF &rect) override
Draws helper items on the scene foreground.
void rememberIoPlacementOrientation(const Component &component)
Remembers a user IO orientation edit for subsequent placements.
bool enterSimulationMode()
GraphicalItem * findGraphicalItemByUiId(uint64_t uiId) const
bool beginComponentResize(GraphicalComponent *component, ResizeHandle handle, QPointF scenePos)
void finishWireDrag(GraphicalWireSegment *segment)
Commits the active segment drag and records its undo command.
DiagramScene(QObject *parent=nullptr)
Constructs a diagram scene.
void logsClearRequested()
const SILICON::project::DocumentStore * documentStore() const noexcept
void exitComponentPlacingMode()
void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) override
Handles mouse press for wire drawing and component placement.
ComponentSearchBox * csb
Component search box.
ConnectionReport connectionReport
InteractionMode getInteractionMode() const
Gets the current interaction mode.
bool isResizingComponent() const
void expandSceneBounds(const QRectF &bounds)
Grows the workspace in quantized steps to include scene coordinates.
std::shared_ptr< Circuit > getCircuit() const
QPointF resolveWireTarget(QPointF scenePoint) const
Resolves a scene position to a nearby port, wire, or grid point.
InteractionMode
Operating modes for the diagram scene.
bool calculateWiresForComponents()
void cancelMixedDrag()
Restores original item positions and clears the mixed drag state.
void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) override
bool isWireAttachedToDraggedComponent(const GraphicalComponent *component, const GraphicalWire *wire) const
Returns whether a wire was attached to the component when its drag began.
void simulateEditedWaveform(qulonglong duration, std::vector< Sample > inputSnapshots)
Simulates the circuit using an edited input waveform.
PropertyMap lastPlacedComponentProperties
Initial properties used when repeating placement of the last type.
bool insertSelection(const nlohmann::json &payload, GUIComponentFactory &guiFactory, const ComponentRegistry &coreRegistry, QPointF targetOrigin, bool isPaste=false)
Inserts a clipboard selection payload into the current scene.
void drawBackground(QPainter *painter, const QRectF &rect) override
Draws the background grid.
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
void beginMixedDrag()
Captures item positions, attached wires, and topology for a mixed selection drag.
void beginComponentDrag()
Captures selected component positions, attached wires, and routing geometry.
void cancelWireDrag()
Restores original wire routes and clears the active wire drag.
void autoPlaceCircuit()
Automatically places components and reroutes wires.
void setInteractionMode(InteractionMode mode)
Sets the interaction mode.
bool isDraggingWire(const GraphicalWireSegment *segment) const
Returns whether the segment owns the active wire drag.
void setCircuitResolver(const CircuitResolver *resolver) noexcept
Factory for creating graphical circuit components.
static GUIComponentFactory & instance()
Gets the global singleton factory instance.
std::vector< std::string > availableTypes() const
Gets all available component types.
std::unique_ptr< GraphicalComponent > create(std::string_view type, QGraphicsItem *parent=nullptr) const
Creates a component by type name.
Base class for graphical circuit components.
ComponentResizeState resizeState() const
bool resizeHandlesVisible() const
virtual std::span< const ResizeHandle > resizeHandles() const
virtual QRectF resizeBounds() const
Base class for all graphical items in the diagram.
void setOwningScene(DiagramScene *scene)
Base class for logic-gate graphical components.
Graphical component wrapper for a registered subcircuit.
The visible, selectable polyline wire on the diagram scene.
GraphicalWire * getGraphicalWire() const
Gets the logical wire.
const std::vector< QPointF > & getPoints() const
Gets all points of the segment.
std::optional< size_t > edgeIndexAt(QPointF localPos) const
Finds the first edge within the grab radius of a local position.
bool empty() const
Checks if segment has only one point.
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.
Logical wire entity that groups segments sharing the same bus.
WireManager * getManager() const
Gets the wire manager.
Represents a connection point on a component.
static const QColor & getColor(theme::ColorToken token)
static ThemeEngine & instance()
void commit()
Finishes the batch, rebuilding topology and notifying at the outermost level.
void commit()
Validates the preview route and queues its topology rebuild.
const std::vector< GraphicalWireSegment * > & getSegments() const
const SegmentTopology & topologyFor(uint64_t segmentId) const
Borrows segment topology until rebuilt; missing segments return an empty topology.
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
bool orthogonalRouteCrossesObstacleInterior(const std::span< const QPointF > route, const std::span< const QRectF > obstacles)
std::unordered_map< std::string, PropertyValue, TransparentStringHash, TransparentStringEqual > PropertyMap
Map from property names to their values.
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
std::weak_ptr< Component > Component_weakPtr
std::vector< QPointF > routeOrthogonalWire(const QPointF start, const QPointF end, const std::vector< QRectF > &obstacleRects, const qreal gridSize)
bool pointOnOrthogonalRoute(const QPointF point, const std::span< const QPointF > route)
Returns whether point lies on an orthogonal polyline.
bool isOrthogonalRoute(const std::span< const QPointF > points)
Returns whether every consecutive route segment is axis-aligned.
std::vector< State > BusValue
bool resizesRight(ResizeHandle handle)
bool resizesLeft(ResizeHandle handle)
bool resizesBottom(ResizeHandle handle)
QPointF resizeAnchor(const QRectF &bounds, ResizeHandle handle)
bool resizesTop(ResizeHandle handle)
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
std::optional< std::vector< RoutedSegment > > RoutePreview
GraphLayout::PlacementMap components
Computed scene positions for participating components.
Configuration for full circuit autoplacement and wire routing.
std::function< bool()> isCancelled
Optional cooperative cancellation check, also polled during routing. A candidate finishes routing bef...
std::function< void(int completed, int total)> progress
Optional notification after each completed candidate.
int candidateCount
Maximum number of deterministic candidates. Large designs use fewer candidates and refinements to bou...
bool valid() const
Returns whether every net in the report has no connection error.
void cancel()
Cancels pending edits and restores original segment routes.
void commit(WireManager &manager)
Commits pending segment edits as a batch and rebuilds changed topology.
std::vector< WireRouteChange > changes(const DiagramScene &scene) const
Returns before and after snapshots for routes changed during the gesture.
std::vector< std::pair< uint64_t, std::vector< QPointF > > > originals
std::map< uint64_t, WireEndpointEdit::NetState > netBefore
void remember(WireManager &manager, GraphicalWireSegment *segment)
Records a segment's original route and creates its preview edit once.
void captureContacts(const DiagramScene &scene)
Captures existing endpoint contacts, topology, and net identities for the gesture.
std::vector< Contact > contacts
std::map< uint64_t, WireManager::SegmentTopology > topologyBefore
std::vector< std::unique_ptr< WireManager::Edit > > edits
bool isValid() const
Returns whether this net has no connection error.
std::optional< QString > error
std::vector< Port * > affectedPorts
std::vector< QPointF > ports
std::vector< TopologyChange > topologyChanges
ContactList afterContacts
std::vector< NetChange > netChanges
ContactList beforeContacts