SILICON
Loading...
Searching...
No Matches
diagramScene.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 "diagramScene.hpp"
19
20#include <algorithm>
21#include <cmath>
22#include <map>
23#include <ranges>
24#include <set>
25#include <span>
26#include <stdexcept>
27#include <string>
28#include <unordered_set>
29#include <vector>
30
31#include <QCursor>
32#include <QLineF>
33#include <QMessageBox>
34#include <QProgressDialog>
35#include <QScopedValueRollback>
36#include <QTimer>
37
38#include <logging/logger.hpp>
41
55#include <ui/shell/theme.hpp>
56
57namespace SILICON::ui {
58using namespace SILICON::core;
59
60namespace {
61
62 constexpr qreal INITIAL_SCENE_HALF_EXTENT = 60.0 * DiagramScene::GRID_SIZE;
63
64 template <typename Visitor>
65 void forEachPortAnchor(const GraphicalComponent& component, Visitor&& visit)
66 {
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());
70 visit(WireManager::PortAnchor{component.getUiId(), index, output, position});
71 }
72 };
73 collect(component.getInputPorts(), false);
74 collect(component.getOutputPorts(), true);
75 }
76
77 const GraphicalComponent* componentForItem(const QGraphicsItem* item)
78 {
79 for (; item; item = item->parentItem()) {
80 if (const auto* component =
82 return component;
83 }
84 return nullptr;
85 }
86
87 qreal gridCoordinate(const qreal coordinate)
88 {
89 return std::round(coordinate / DiagramScene::GRID_SIZE) * DiagramScene::GRID_SIZE;
90 }
91
92 QPointF snappedEdgePoint(const QPointF point, const QPointF a, const QPointF b)
93 {
94 if (a.x() == b.x()) {
95 return {a.x(), std::clamp(gridCoordinate(point.y()),
96 std::min(a.y(), b.y()), std::max(a.y(), b.y()))};
97 }
98 return {std::clamp(gridCoordinate(point.x()),
99 std::min(a.x(), b.x()), std::max(a.x(), b.x())), a.y()};
100 }
101
102} // namespace
103
104DiagramScene::DiagramScene(QObject* parent) : QGraphicsScene(parent)
105{
106 initializeSceneBounds(INITIAL_SCENE_HALF_EXTENT);
107
108 connect(this, &QGraphicsScene::selectionChanged, this, [this] {
109 if (isResizingComponent()) {
110 auto* item = findGraphicalItemByUiId(componentResize.uiId);
111 if (!item || !item->isSelected() || selectedItems().size() != 1)
113 }
114 // Existing selections also need repainting when another item hides their handles.
115 update();
116 });
117
118 connect(&ThemeEngine::instance(), &ThemeEngine::themeChanged, this, [this] {
119 // QGraphicsItem and background caches do not follow widget palette propagation.
120 invalidate(sceneRect(), QGraphicsScene::AllLayers);
121 update();
122 });
123
124 simulationController = std::make_unique<DiagramSceneSimulationController>(*this);
125 serializer = std::make_unique<DiagramSceneSerializer>(*this);
126
127 setInteractionMode(InteractionMode::NORMAL_MODE, true);
128
129 csb = new ComponentSearchBox(GUIComponentFactory::instance().availableTypes());
130 csb->setParent(this);
135 [this](std::string typeName, QPointF) { placeComponent(typeName); });
136
137 wireManager.setChangedCallback([this](const WireManager::Change change) {
138 const auto flags = static_cast<uint8_t>(change);
139 if (!(flags & (static_cast<uint8_t>(WireManager::Change::Connectivity)
140 | static_cast<uint8_t>(WireManager::Change::Electrical)))) {
141 update();
142 return;
143 }
144
145 // Outside simulation, any user wire edit invalidates the cached logical circuit.
146 // Autoplacement restores a fresh authoritative circuit after replacing all routes.
147 if (getInteractionMode() != InteractionMode::SIMULATION_MODE)
148 circuit.reset();
150 });
151
152 wireManager.setPortAnchors([this] {
153 std::vector<WireManager::PortAnchor> anchors;
154 for (auto* item : items()) {
156 if (!component)
157 continue;
158 forEachPortAnchor(*component,
159 [&](const auto& anchor) { anchors.push_back(anchor); });
160 }
161 return anchors;
162 });
163}
164
166 const SILICON::project::DocumentStore* projectDocuments) noexcept
167{
168 documents = projectDocuments;
169}
170
172{
173 return documents;
174}
175
176void DiagramScene::setCircuitResolver(const CircuitResolver* projectResolver) noexcept
177{
178 resolver = projectResolver;
179}
180
182{
183 return resolver;
184}
185
186namespace {
187
188 std::vector<std::string> componentTypesForScene(const DiagramScene& scene)
189 {
190 Q_UNUSED(scene);
192 }
193
194 std::vector<GraphicalLogicComponent*>
195 logicComponentsInScene(const QGraphicsScene& scene)
196 {
197 std::vector<GraphicalLogicComponent*> components;
198
199 for (auto* item : scene.items()) {
200 auto* component =
202 if (component && component->getComponent())
203 components.push_back(component);
204 }
205
206 return components;
207 }
208
209 void assignDefaultComponentName(const QGraphicsScene& scene,
210 GraphicalLogicComponent& component)
211 {
212 const auto defaultName =
213 component.getComponent()->getPropertyValue<std::string>("name");
214 if (!defaultName || defaultName->empty())
215 return;
216
217 std::size_t count = 1;
218 std::unordered_set<std::string, TransparentStringHash, TransparentStringEqual>
219 usedNames;
220 for (const auto* existing : logicComponentsInScene(scene)) {
221 if (existing->getTypeName() == component.getTypeName())
222 ++count;
223 if (const auto name =
224 existing->getComponent()->getPropertyValue<std::string>("name"))
225 usedNames.insert(*name);
226 }
227
228 // Derive the count from the scene so cancellation, undo, and loading need
229 // no separate counter state. Skip names retained after deletion or renaming.
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);
234 }
235
236 Component_set coreComponentsFor(std::span<GraphicalLogicComponent* const> components)
237 {
238 Component_set coreComponents;
239 for (const auto* component : components) {
240 if (component && component->getComponent())
241 coreComponents.insert(component->getComponent());
242 }
243 return coreComponents;
244 }
245
246 void applyAutoplacement(DiagramScene& scene, const Circuit& activeCircuit,
247 std::span<GraphicalLogicComponent* const> components,
248 const CircuitAutoplacerOptions& options = {})
249 {
251 try {
252 result = CircuitAutoplacer::compute(activeCircuit, components, options);
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()));
256 return;
257 }
258 if (result.cancelled)
259 return;
260 const auto& componentMap = result.components;
261 const auto& wires = result.wires;
262
263 if (componentMap.empty())
264 return;
265
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();
273 }
274 scene.setItemCollisionChecksEnabled(collisionChecksEnabled);
275
276 scene.getWireManager().replaceSegments(scene, wires);
277
278 // The routed wires were produced from activeCircuit and already carry its buses.
279 // Recalculating component buses from geometry here is both redundant and unsafe:
280 // coincident route portions near a port can make a later graphical wire overwrite
281 // that port's original assignment. Keep the logical topology authoritative and only
282 // refresh the cached circuit after applying the new geometry. DiagramScene applies
283 // the document name when accepting the replacement cache.
284 auto refreshedCircuit =
285 std::make_shared<Circuit>(coreComponentsFor(components), false);
286 scene.setCircuit(std::move(refreshedCircuit));
287 scene.update();
288 }
289
290} // namespace
291
292int DiagramScene::snapToGrid(const qreal value)
293{
294 return static_cast<int>(std::round(value / GRID_SIZE)) * GRID_SIZE;
295}
296
297QPoint DiagramScene::snapToGrid(const QPointF point)
298{
299 return {snapToGrid(point.x()), snapToGrid(point.y())};
300}
301
302QPointF DiagramScene::resolveWireTarget(const QPointF scenePoint) const
303{
304 QPointF bestPoint{gridCoordinate(scenePoint.x()), gridCoordinate(scenePoint.y())};
305 qreal bestDistance = GRID_SIZE / 2.0;
306 const QRectF query(scenePoint - QPointF(bestDistance, bestDistance),
307 QSizeF(2 * bestDistance, 2 * bestDistance));
308 // Query bounding rectangles so port children and their lines participate even
309 // when the anchors lie outside the component's collision or painted shape.
310 const auto nearby = items(query, Qt::IntersectsItemBoundingRect);
311
312 const auto& registeredSegments = wireManager.getSegments();
313 const GraphicalWireSegment* bestSegment = nullptr;
314
315 auto updateBest = [&](const QPointF candidate,
316 const GraphicalWireSegment* segment = nullptr) {
317 const qreal distance = QLineF(scenePoint, candidate).length();
318 if (distance > bestDistance)
319 return;
320 if (distance == bestDistance) {
321 // Ports win ties. Between wires, preserve registration order.
322 if (!segment || !bestSegment || segment == bestSegment)
323 return;
324 const auto first = std::ranges::find_if(registeredSegments, [&](const auto* wire) {
325 return wire == segment || wire == bestSegment;
326 });
327 if (first == registeredSegments.end() || *first != segment)
328 return;
329 }
330 bestDistance = distance;
331 bestPoint = candidate;
332 bestSegment = segment;
333 };
334
335 // A nearby port or line can belong to a component outside the query rectangle.
336 // Visit each owner once, in scene stacking order, before considering wires.
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))
341 continue;
342 visitedComponents.push_back(component);
343 forEachPortAnchor(*component,
344 [&](const auto& anchor) { updateBest(anchor.position); });
345 }
346
347 for (const auto* item : nearby) {
348 const auto* segment =
350 if (!segment || !segment->getGraphicalWire()
351 || segment->getGraphicalWire()->getManager() != &wireManager)
352 continue;
353 // Topology normally identifies registered segments. During deferred bulk
354 // registration it may be absent, so fall back to the authoritative list.
355 if (!wireManager.topologyFor(segment->getUiId()).firstVertex
356 && !std::ranges::contains(registeredSegments, segment))
357 continue;
358 const auto points = segment->getScenePoints();
359 for (const auto& [a, b] : points | SILICON::views::adjacent<2>)
360 updateBest(snappedEdgePoint(scenePoint, a, b), segment);
361 }
362 return bestPoint;
363}
364
365std::unique_ptr<InteractiveWireRouter> DiagramScene::makeInteractiveRouter() const
366{
367 std::vector<RoutingComponent> components;
368 for (const auto* item : items()) {
369 const auto* component =
371 if (!component || !component->participatesInCollisions())
372 continue;
373
374 RoutingComponent snapshot{
375 .id = component->getUiId(),
376 .bounds = component->mapToScene(component->collisionRectForWires())
377 .boundingRect()
378 .normalized(),
379 .ports = {}};
380 snapshot.ports.reserve(component->getInputPorts().size()
381 + component->getOutputPorts().size());
382 forEachPortAnchor(*component, [&](const auto& anchor) {
383 snapshot.ports.push_back(anchor.position);
384 });
385 components.push_back(std::move(snapshot));
386 }
387
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())
392 continue;
393
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)});
403 }
404 return std::make_unique<InteractiveWireRouter>(std::move(components),
405 std::move(segments), GRID_SIZE);
406}
407
408void DiagramScene::applyRoutingPreview(const std::vector<RoutedSegment>& routes,
409 RouteEditState& state)
410{
411 for (const auto& route : routes) {
414 if (!segment)
415 continue;
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()) {
421 state.remember(wireManager, segment);
422 segment->setPoints(std::move(local));
423 }
424 }
425}
426
428 GraphicalWireSegment* segment)
429{
430 this->manager = &manager;
431 const auto id = segment->getUiId();
432 if (std::ranges::find_if(originals, [id](const auto& entry) {
433 return entry.first == id;
434 }) != originals.end())
435 return;
436 edits.push_back(std::make_unique<WireManager::Edit>(manager, segment));
437 originals.emplace_back(id, segment->getPoints());
438}
439
441{
442 contacts.clear();
443 topologyBefore.clear();
444 netBefore.clear();
445 const auto segments = scene.getWireManager().getSegments();
446 for (const auto* segment : segments) {
447 topologyBefore.emplace(segment->getUiId(),
448 scene.getWireManager().topologyFor(segment->getUiId()));
449
450 if (const auto* wire = segment->getGraphicalWire())
451 netBefore.emplace(segment->getUiId(),
452 WireEndpointEdit::NetState{wire->getRouteId(), wire->getBus()});
453
454 const auto points = segment->getScenePoints();
455
456 if (points.size() < 2)
457 continue;
458 for (const bool first : {true, false}) {
459 const QPointF endpoint = first ? points.front() : points.back();
460 const auto ownTopology = scene.getWireManager().topologyFor(segment->getUiId());
461 const uint64_t vertex = first ? ownTopology.firstVertex : ownTopology.lastVertex;
462 for (const auto* other : segments) {
463 if (other == segment)
464 continue;
465 const auto otherTopology = scene.getWireManager().topologyFor(other->getUiId());
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()});
471 }
472
473 for (auto* item : scene.items()) {
475 if (!component)
476 continue;
477 for (Port* port : component->getPorts())
478 if (component->mapToScene(port->getPosition()) == endpoint)
479 contacts.push_back({segment->getUiId(), first, 0, component, port});
480 }
481 }
482 }
483}
484
486{
487 if (manager) {
488 for (const auto& [id, points] : originals)
489 for (auto* segment : manager->getSegments())
490 if (segment->getUiId() == id) {
491 segment->setPoints(points);
492 break;
493 }
494 }
495
496 for (auto& edit : edits)
497 edit->cancel();
498
499 edits.clear();
500 originals.clear();
501 topologyBefore.clear();
502 netBefore.clear();
503 manager = nullptr;
504}
505
507{
508 // All contacts are recalculated from the committed routes.
510 const auto segments = manager.getSegments();
511 for (const auto& id : originals | std::views::keys) {
512 const auto found = std::ranges::find(segments, id, &GraphicalWireSegment::getUiId);
513 if (found != segments.end()
514 && ((*found)->getPoints().size() < 2
515 || !isOrthogonalRoute((*found)->getPoints()))) {
516 cancel();
517 throw std::invalid_argument("A committed wire route must be orthogonal");
518 }
519 }
520 for (const auto& edit : edits)
521 edit->commit();
522 batch.commit();
523}
524
525std::vector<WireRouteChange> DiagramScene::RouteEditState::changes(const DiagramScene& scene) const
526{
527 std::vector<WireRouteChange> changes;
528 for (const auto& [id, before] : originals) {
529 const auto* segment = category_cast<GraphicalWireSegment>(
531 if (segment && segment->getPoints() != before)
532 changes.push_back({id, before, segment->getPoints()});
533 }
534 return changes;
535}
536
538{
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());
546 }
547 }
548
549 if (componentDrag.initialPositions.empty())
550 return;
551
552 const auto segments = wireManager.getSegments();
553
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()));
558 auto& attached = componentDrag.attachedWires[component];
559
560 for (const auto* segment : segments) {
561 const auto points = segment->getScenePoints();
562 if (points.size() < 2 || !segment->getGraphicalWire())
563 continue;
564 if (std::ranges::find(ports, points.front()) != ports.end()
565 || std::ranges::find(ports, points.back()) != ports.end())
566 attached.insert(segment->getGraphicalWire());
567 }
568 }
569
571}
572
574{
575 return (componentDrag.router && componentDrag.attachedWires.contains(component))
576 || mixedDragAttachedWires.contains(component);
577}
578
580 const GraphicalComponent* component, const GraphicalWire* wire) const
581{
582 const auto found = componentDrag.attachedWires.find(component);
583
584 if (found != componentDrag.attachedWires.end() && found->second.contains(wire))
585 return true;
586
587 const auto mixed = mixedDragAttachedWires.find(component);
588 return mixed != mixedDragAttachedWires.end() && mixed->second.contains(wire);
589}
590
592{
593 if (!componentDrag.router)
594 return;
595 if (std::ranges::all_of(componentDrag.validPositions, [](const auto& entry) {
596 return entry.first->pos() == entry.second;
597 }))
598 return;
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()});
605 }
606 const auto routes = componentDrag.router->routeComponents(moves);
607 if (!routes) {
608 const bool collisionChecks = itemCollisionChecksEnabled();
610 for (const auto& [component, position] : componentDrag.validPositions)
611 component->setGeometryPosition(position);
612 setItemCollisionChecksEnabled(collisionChecks);
613 return;
614 }
615 applyRoutingPreview(*routes, componentDrag.routes);
616 for (auto& [component, position] : componentDrag.validPositions)
617 position = component->pos();
618}
619
620std::vector<WireRouteChange> DiagramScene::finishComponentDrag()
621{
622 if (!componentDrag.router)
623 return {};
624 auto changes = componentDrag.routes.changes(*this);
625 try {
626 componentDrag.routes.commit(wireManager);
627 } catch (const std::invalid_argument&) {
629 return {};
630 }
631 componentDrag = {};
632 wireManager.refreshPortAnchors();
634 update();
635 return changes;
636}
637
639{
640 if (!componentDrag.router)
641 return;
642 const bool collisionChecks = itemCollisionChecksEnabled();
644 for (const auto& [component, position] : componentDrag.initialPositions) {
645 component->setGeometryPosition(position);
646 component->setInitialPosition();
647 }
648 setItemCollisionChecksEnabled(collisionChecks);
649 componentDrag.routes.cancel();
650 componentDrag = {};
651}
652
654{
655 bool hasComponent = false;
656 size_t wireCount = 0;
657 for (auto* item : selectedItems()) {
658 hasComponent |= category_cast<GraphicalComponent>(item, ItemCategory::Component) != nullptr;
660 }
661 return wireCount > 0 && (hasComponent || wireCount > 1);
662}
663
665{
667 for (auto* item : selectedItems())
668 if (auto* graphical = dynamic_cast<GraphicalItem*>(item))
669 mixedDrag.push_back({graphical, graphical->pos(), graphical->pos()});
670 const auto segments = wireManager.getSegments();
671 for (const auto& entry : mixedDrag) {
672 auto* component = category_cast<GraphicalComponent>(entry.item,
674 if (!component || !component->participatesInCollisions())
675 continue;
676 std::vector<QPointF> ports;
677 for (const auto* port : component->getPorts())
678 ports.push_back(component->mapToScene(port->getPosition()));
679 auto& attached = mixedDragAttachedWires[component];
680 for (const auto* segment : segments) {
681 const auto points = segment->getScenePoints();
682 if (points.size() < 2 || !segment->getGraphicalWire())
683 continue;
684 if (std::ranges::find(ports, points.front()) != ports.end()
685 || std::ranges::find(ports, points.back()) != ports.end())
686 attached.insert(segment->getGraphicalWire());
687 }
688 }
689 for (const auto* segment : wireManager.getSegments()) {
690 const auto id = segment->getUiId();
691 mixedDragTopologyBefore.emplace(id, wireManager.topologyFor(id));
692 if (const auto* wire = segment->getGraphicalWire())
694 wire->getRouteId(), wire->getBus()});
695 }
696}
697
699{
700 if (mixedDrag.empty())
701 return;
702 const QPointF delta = mixedDrag.front().item->pos()
703 - mixedDrag.front().validPosition;
704 const bool movedTogether = std::ranges::all_of(mixedDrag, [delta](const auto& entry) {
705 return entry.item->pos() - entry.validPosition == delta;
706 });
707 if (!movedTogether) {
708 const bool collisionChecks = itemCollisionChecksEnabled();
710 for (const auto& entry : mixedDrag)
711 entry.item->setGeometryPosition(entry.validPosition);
712 setItemCollisionChecksEnabled(collisionChecks);
713 return;
714 }
715 for (auto& entry : mixedDrag)
716 entry.validPosition = entry.item->pos();
717}
718
720{
721 if (mixedDrag.empty())
722 return {};
723
725 WireEndpointEdit edit;
726 if (!mixedDrag.empty()) {
727 std::vector<std::pair<uint64_t, QPointF>> translations;
728 for (const auto& entry : mixedDrag)
730 translations.emplace_back(entry.item->getUiId(),
731 entry.validPosition - entry.originalPosition);
732 edit.segmentId = entry.item->getUiId();
733 }
734 if (!wireManager.commitSegmentTranslations(translations)) {
735 const bool collisionChecks = itemCollisionChecksEnabled();
737 for (const auto& entry : mixedDrag)
738 entry.item->setGeometryPosition(entry.originalPosition);
739 setItemCollisionChecksEnabled(collisionChecks);
740 } else {
741 for (const auto& [id, before] : mixedDragTopologyBefore) {
742 const auto after = wireManager.topologyFor(id);
743 if (before.firstVertex != after.firstVertex
744 || before.lastVertex != after.lastVertex
745 || before.junctions != after.junctions
746 || before.edgeIds != after.edgeIds)
747 edit.topologyChanges.push_back({id, before, after});
748 }
749 for (const auto& [id, before] : mixedDragNetBefore) {
752 if (!segment || !segment->getGraphicalWire())
753 continue;
754 const auto* wire = segment->getGraphicalWire();
755 WireEndpointEdit::NetState after{wire->getRouteId(), wire->getBus()};
756 if (before.routeId != after.routeId || !(before.bus == after.bus))
757 edit.netChanges.push_back({id, before, after});
758 }
759 }
760 }
761 mixedDrag.clear();
764 mixedDragNetBefore.clear();
765 wireManager.refreshPortAnchors();
767 return edit;
768}
769
771{
772 if (mixedDrag.empty())
773 return;
774 const bool collisionChecks = itemCollisionChecksEnabled();
776 for (const auto& entry : mixedDrag)
777 entry.item->setGeometryPosition(entry.originalPosition);
778 setItemCollisionChecksEnabled(collisionChecks);
779 mixedDrag.clear();
782 mixedDragNetBefore.clear();
783}
784
786 const QPointF scenePos, const QPointF localPos)
787{
788 if (!segment || currentInteractionMode != InteractionMode::NORMAL_MODE ||
789 !segment->getGraphicalWire() || !segment->getGraphicalWire()->getManager())
790 return false;
792 const auto& points = segment->getPoints();
793 const auto bend = segment->pointIndexAt(localPos);
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)
798 return false;
799
800 wireDrag.segment = segment;
801 wireDrag.type = dragEndpoint ? WireDragKind::Endpoint
803 wireDrag.index = bend ? *bend : *edge;
804 wireDrag.start = snapToGrid(scenePos);
805 wireDrag.originalPoints = points;
807 wireDrag.routes.captureContacts(*this);
808 return true;
809}
810
812{
813 return wireDrag.segment == segment && wireDrag.router != nullptr;
814}
815
816void DiagramScene::updateWireDrag(GraphicalWireSegment* segment, const QPointF scenePos)
817{
818 if (!isDraggingWire(segment))
819 return;
820 QPointF delta = snapToGrid(scenePos) - wireDrag.start;
821 const auto& original = wireDrag.originalPoints;
822 if (wireDrag.type == WireDragKind::Edge) {
823 if (original[wireDrag.index].y() == original[wireDrag.index + 1].y())
824 delta.setX(0);
825 else
826 delta.setY(0);
827 }
828 if (delta.isNull()) {
829 wireDrag.routes.cancel();
830 return;
831 }
832 RoutePreview routes;
833 if (wireDrag.type == WireDragKind::Bend)
834 routes = wireDrag.router->routeWireBend(segment->getUiId(), wireDrag.index,
835 segment->mapToScene(original[wireDrag.index]) + delta);
836 else if (wireDrag.type == WireDragKind::Endpoint)
837 routes = wireDrag.router->routeWireEndpoint(segment->getUiId(), wireDrag.index,
838 segment->mapToScene(original[wireDrag.index])
839 + delta);
840 else
841 routes = wireDrag.router->routeWireEdge(segment->getUiId(), wireDrag.index, delta);
842 if (routes)
843 applyRoutingPreview(*routes, wireDrag.routes);
844}
845
847{
848 if (!isDraggingWire(segment))
849 return;
850 auto changes = wireDrag.routes.changes(*this);
851 const bool movedEndpoint = wireDrag.type == WireDragKind::Endpoint;
852 const bool movableFirst = wireDrag.index == 0;
853 WireEndpointEdit endpointEdit;
854 if (movedEndpoint) {
855 endpointEdit.segmentId = segment->getUiId();
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,
860 contact.first});
861
862 const auto points = segment->getScenePoints();
863 const QPointF endpoint = movableFirst ? points.front() : points.back();
864 std::vector<GraphicalWire*> joiningWires{segment->getGraphicalWire()};
865 for (auto* other : wireManager.getSegments()) {
866 if (other == segment || other->empty()
867 || !pointOnOrthogonalRoute(endpoint, other->getScenePoints()))
868 continue;
869 endpointEdit.afterContacts.push_back({other->getUiId(), segment->getUiId(),
870 movableFirst});
871 if (std::ranges::find(joiningWires, other->getGraphicalWire()) == joiningWires.end())
872 joiningWires.push_back(other->getGraphicalWire());
873 }
874 if (!inspectConnection(joiningWires).isValid()) {
876 return;
877 }
878 }
879 try {
881 wireDrag.routes.commit(wireManager);
882 if (!changes.empty())
883 wireManager.rebuildFromGeometry();
884 batch.commit();
885 } catch (const std::invalid_argument&) {
887 return;
888 }
889 if (movedEndpoint) {
890 for (const auto& [id, before] : wireDrag.routes.topologyBefore) {
891 const auto after = wireManager.topologyFor(id);
892 if (before.firstVertex != after.firstVertex
893 || before.lastVertex != after.lastVertex
894 || before.junctions != after.junctions
895 || before.edgeIds != after.edgeIds)
896 endpointEdit.topologyChanges.push_back({id, before, after});
897 }
898 for (const auto& [id, before] : wireDrag.routes.netBefore) {
901 if (!member || !member->getGraphicalWire())
902 continue;
903 const auto* wire = member->getGraphicalWire();
904 WireEndpointEdit::NetState after{wire->getRouteId(), wire->getBus()};
905 if (before.routeId != after.routeId || !(before.bus == after.bus))
906 endpointEdit.netChanges.push_back({id, before, after});
907 }
908 }
909 const WireDragKind kind = wireDrag.type;
910 wireDrag = {};
911 if (!changes.empty() && undoStack)
912 undoStack->push(new EditWireRouteCommand(segment, std::move(changes), kind,
913 std::move(endpointEdit)));
914}
915
917{
918 wireDrag.routes.cancel();
919 wireDrag = {};
920}
921
922void DiagramScene::applyWireRouteChanges(std::span<const WireRouteChange> changes,
923 const bool useAfter,
924 const WireEndpointEdit& endpointEdit)
925{
927 for (const auto& change : changes) {
930 if (!segment)
931 continue;
932 WireManager::Edit edit(wireManager, segment);
933 segment->setPoints(useAfter ? change.after : change.before);
934 edit.commit();
935 }
936 wireManager.rebuildFromGeometry();
937 batch.commit();
938}
939
940void DiagramScene::applyItemMoves(std::span<const ItemPositionChange> moves,
941 std::span<const WireRouteChange> wires,
942 const bool useAfter,
943 const WireEndpointEdit& topology)
944{
945 const bool collisionChecks = itemCollisionChecksEnabled();
947 std::vector<std::pair<GraphicalItem*, QPointF>> previousPositions;
948 std::vector<std::pair<uint64_t, QPointF>> wireTranslations;
949 for (const auto& move : moves) {
950 if (auto* item = findGraphicalItemByUiId(move.uiId)) {
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();
957 }
958 }
959 if (!wireManager.commitSegmentTranslations(wireTranslations)) {
960 for (const auto& [item, position] : previousPositions)
961 item->setGeometryPosition(position);
962 setItemCollisionChecksEnabled(collisionChecks);
963 throw std::invalid_argument("Cannot restore moved wire topology");
964 }
965 applyWireRouteChanges(wires, useAfter);
966 wireManager.rebuildFromGeometry();
967 wireManager.refreshPortAnchors();
969 setItemCollisionChecksEnabled(collisionChecks);
970 update();
971}
972
973void DiagramScene::drawBackground(QPainter* painter, const QRectF& rect)
974{
976
978 painter->setPen(pen);
979
980 const qreal left = int(rect.left()) - (int(rect.left()) % GRID_SIZE);
981 const qreal top = int(rect.top()) - (int(rect.top()) % GRID_SIZE);
982
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));
987 }
988 }
989 painter->drawPoints(points.data(), points.size());
990}
991
992void DiagramScene::drawForeground(QPainter* painter, const QRectF& rect)
993{
994 const bool drawWireCreationGuides =
995 currentInteractionMode == InteractionMode::WIRE_CREATION_MODE
996 && wireSegmentToBeDrawn != nullptr && wireSegmentToBeDrawn->hasShowPoints();
997
998 if (drawWireCreationGuides) {
999 const QPoint cursorPos =
1000 wireSegmentToBeDrawn->mapToScene(wireSegmentToBeDrawn->lastShowPoint()).toPoint();
1001 const QRect guideRect = rect.toAlignedRect();
1002
1004 pen.setCosmetic(true);
1005 painter->setPen(pen);
1006
1007 painter->drawLine(
1008 QLine(cursorPos.x(), guideRect.top(), cursorPos.x(), guideRect.bottom()));
1009 painter->drawLine(
1010 QLine(guideRect.left(), cursorPos.y(), guideRect.right(), cursorPos.y()));
1011 }
1012
1013 QGraphicsScene::drawForeground(painter, rect);
1014}
1015
1016void DiagramScene::initializeSceneBounds(const qreal expansionStep)
1017{
1018 setSceneRect(-expansionStep, -expansionStep, 2 * expansionStep, 2 * expansionStep);
1019 sceneExpansionStep = expansionStep;
1020}
1021
1022void DiagramScene::expandSceneBounds(const QRectF& bounds)
1023{
1024 const auto current = sceneRect();
1025 if (current.contains(bounds))
1026 return;
1027
1028 const auto combined = current.united(bounds);
1029 const QRectF expanded(
1030 QPointF(std::floor(combined.left() / sceneExpansionStep) * sceneExpansionStep,
1031 std::floor(combined.top() / sceneExpansionStep) * sceneExpansionStep),
1032 QPointF(std::ceil(combined.right() / sceneExpansionStep) * sceneExpansionStep,
1033 std::ceil(combined.bottom() / sceneExpansionStep) * sceneExpansionStep));
1034 if (expanded != current)
1035 setSceneRect(expanded);
1036}
1037
1042
1044 ResizeHandle handle, QPointF scenePos)
1045{
1046 if (!component || component->scene() != this || isResizingComponent()
1047 || !component->resizeHandlesVisible()
1048 || !std::ranges::contains(component->resizeHandles(), handle))
1049 return false;
1050 bool invertible = false;
1051 const auto fromScene = component->sceneTransform().inverted(&invertible);
1052 if (!invertible)
1053 return false;
1057 componentResize = {
1058 component->getUiId(),
1059 handle,
1060 component->resizeState(),
1061 component->resizeBounds(),
1062 fromScene,
1063 fromScene.map(scenePos),
1064 component->mapToParent(resizeAnchor(component->resizeBounds(), handle))};
1065 return true;
1066}
1067
1069{
1070 auto* component = category_cast<GraphicalComponent>(
1072 if (!component) {
1073 componentResize = {};
1074 return;
1075 }
1076 const auto& drag = componentResize;
1077 const auto delta = drag.fromScene.map(scenePos) - drag.start;
1078 if (delta.isNull()) {
1079 component->applyResizeState(drag.before);
1080 return;
1081 }
1082 auto size = drag.bounds.size();
1083 if (resizesLeft(drag.handle))
1084 size.rwidth() -= delta.x();
1085 if (resizesRight(drag.handle))
1086 size.rwidth() += delta.x();
1087 if (resizesTop(drag.handle))
1088 size.rheight() -= delta.y();
1089 if (resizesBottom(drag.handle))
1090 size.rheight() += delta.y();
1091 size = size.expandedTo(QSizeF(1, 1));
1092 auto properties =
1093 component->resizedProperties(size, drag.handle, drag.before.properties);
1094 component->applyResizeState({drag.before.position, std::move(properties)});
1095 const auto anchor =
1096 component->mapToParent(resizeAnchor(component->resizeBounds(), drag.handle));
1097 component->setGeometryPosition(component->pos() + drag.anchorInParent - anchor);
1098 component->setInitialPosition();
1099}
1100
1102{
1103 const auto drag = std::exchange(componentResize, {});
1106 if (!component || component->resizeState() == drag.before)
1107 return;
1108 if (undoStack)
1109 undoStack->push(
1110 new ResizeComponentCommand(component, drag.before, component->resizeState()));
1112 emit componentResized();
1113}
1114
1116{
1117 const auto drag = std::exchange(componentResize, {});
1118 if (auto* component = category_cast<GraphicalComponent>(
1120 component->applyResizeState(drag.before);
1121}
1122
1124{
1125 if (isResizingComponent()) {
1127 return true;
1128 }
1129 if (!mixedDrag.empty()) {
1131 return true;
1132 }
1133 if (wireDrag.router) {
1135 return true;
1136 }
1137 if (componentDrag.router) {
1139 return true;
1140 }
1141 if (currentInteractionMode == InteractionMode::NORMAL_MODE)
1142 return false;
1143
1144 // Escape completes a drawn route even when one or both tips are free. A
1145 // one-point draft has no geometry and can simply be discarded.
1149 return true; // A rejected join remains available for correction.
1150
1151 setInteractionMode(InteractionMode::NORMAL_MODE);
1152 return true;
1153}
1154
1155void DiagramScene::setInteractionMode(const InteractionMode newMode, const bool force)
1156{
1161 const auto currentMode = getInteractionMode();
1162 if (currentMode == newMode && !force)
1163 return;
1164
1165 if (!force && views().size() != 1)
1166 throw std::logic_error("setInteractionMode: scene must have exactly one view");
1167
1168 clearSelection();
1169
1170 if (wireSegmentToBeDrawn && newMode != InteractionMode::WIRE_CREATION_MODE)
1172 if (wireSegmentToBeDrawn && newMode != InteractionMode::WIRE_CREATION_MODE)
1173 return;
1174
1175 if (currentMode == InteractionMode::COMPONENT_PLACING_MODE)
1177 else if (newMode == InteractionMode::COMPONENT_PLACING_MODE)
1179
1180 if (newMode == InteractionMode::SIMULATION_MODE) {
1181 currentInteractionMode = newMode;
1182 emit modeChanged(newMode);
1183
1184 if (!enterSimulationMode()) {
1185 currentInteractionMode = InteractionMode::NORMAL_MODE;
1187 }
1188 return;
1189 }
1190
1191 if (currentMode == InteractionMode::SIMULATION_MODE)
1193
1194 currentInteractionMode = newMode;
1195 emit modeChanged(newMode);
1196 update();
1197}
1198
1200{
1201 // Only clicked points belong to the completed route; discard the red preview.
1202 wireSegmentToBeDrawn->setShowPoints({});
1203 wirePreviewRouteValid = true;
1204
1205 // Remove the wireSegment if it's invisible
1206 if (wireSegmentToBeDrawn->empty()) {
1207 removeItem(wireSegmentToBeDrawn);
1208 delete wireSegmentToBeDrawn;
1209 wireSegmentToBeDrawn = nullptr;
1210 } else {
1211 auto* finalizedSegment = wireSegmentToBeDrawn;
1212 // Always register the segment so the WireManager tracks it for junctions
1213 // and collision detection
1214 try {
1215 wireManager.addSegment(finalizedSegment);
1216 } catch (const std::invalid_argument& error) {
1217 QMessageBox::warning(views().isEmpty() ? nullptr : views().first(),
1218 "Cannot connect wire", error.what());
1219 return;
1220 }
1221
1222 if (auto* undoStack = getUndoStack()) {
1223 undoStack->push(new WireTopologyCommand(this, {finalizedSegment},
1225 }
1226 wireSegmentToBeDrawn = nullptr;
1227 }
1229}
1230
1231bool DiagramScene::isWireCompletionPoint(const QPointF scenePoint) const
1232{
1233 // Ending on an existing segment creates (or extends) a wire junction.
1234 if (wireManager.segmentAtPoint(scenePoint, wireSegmentToBeDrawn))
1235 return true;
1236
1237 // Use the same exact port positions as logical wire assignment does.
1238 for (const QGraphicsItem* item : items(scenePoint)) {
1239 const auto* component =
1241 if (!component)
1242 continue;
1243
1244 const auto portIsAtPoint = [component, scenePoint](const Port* port) {
1245 return component->mapToScene(port->getPosition()) == scenePoint;
1246 };
1247
1248 if (std::ranges::any_of(component->getPorts(), portIsAtPoint))
1249 return true;
1250 }
1251
1252 return false;
1253}
1254
1255void DiagramScene::updateWirePreview(const QPointF scenePoint)
1256{
1258 return;
1259
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())
1267 continue;
1268 obstacles.push_back(component->mapToScene(component->collisionRectForWires())
1269 .boundingRect().adjusted(-MARGIN, -MARGIN, MARGIN, MARGIN));
1270 }
1271
1272 const QPointF lastPoint =
1273 wireSegmentToBeDrawn->mapToScene(wireSegmentToBeDrawn->lastPoint());
1274 for (const auto* segment : wireManager.getSegments()) {
1275 const auto points = segment->getScenePoints();
1276 if (points.size() < 2)
1277 continue;
1278 for (const QPointF tip : {points.front(), points.back()}) {
1279 if (tip == lastPoint || tip == scenePoint)
1280 continue;
1281 const QRectF keepout(tip - QPointF(MARGIN, MARGIN),
1282 QSizeF(2 * MARGIN, 2 * MARGIN));
1283 obstacles.push_back(keepout);
1284 tipKeepouts.push_back(keepout);
1285 }
1286 }
1287 auto route = core::routeOrthogonalWire(lastPoint, scenePoint, obstacles, GRID_SIZE);
1288 wirePreviewRouteValid = !route.empty()
1289 && !orthogonalRouteCrossesObstacleInterior(route, tipKeepouts);
1291 route.clear();
1292 if (route.size() > 1)
1293 route.erase(route.begin());
1294 for (QPointF& point : route)
1295 point = QPointF(snapToGrid(point.x()), snapToGrid(point.y()));
1296 wireSegmentToBeDrawn->setShowPoints(route);
1297 update();
1298}
1299
1301{
1302 hideCSB();
1303 if (componentToBeDrawn) {
1304 removeItem(componentToBeDrawn);
1305 delete componentToBeDrawn;
1306 componentToBeDrawn = nullptr;
1307 }
1308}
1309
1311{
1312 // ALGORITHM: If the cursor is inside the view then try to place the component.
1313 // If the it's outside or the component boundingRect is colliding then
1314 // go to component placing mode and place it manually.
1315 // When the component is placed then go to component placing mode and
1316 // repeat the placing of the same component until ESC is pressed
1317 // (NORMAL_MODE)
1318
1321 return;
1322 }
1323
1324 const QPoint globalCursorPos = QCursor::pos();
1325 const auto view = views()[0];
1326 // The position for the CSB should be the position of the cursor (if the cursor is
1327 // inside the view) or the center of the view (every other case)
1328 // Get center pos
1329 const QPoint centerPos = view->viewport()->rect().center();
1330 // Get cursor pos within view
1331 const QPoint cursorPosWithinView = view->mapFromGlobal(globalCursorPos);
1332 const bool isCursorInsideView = view->viewport()->rect().contains(cursorPosWithinView);
1333 const QPoint posForCSB = isCursorInsideView ? cursorPosWithinView : centerPos;
1334
1335 showCSB(view->mapToScene(posForCSB));
1336}
1337
1339{
1340 return simulationController->enterSimulationMode();
1341}
1342
1344{
1345 simulationController->exitSimulationMode();
1346}
1347
1348void DiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent)
1349{
1350 if (isResizingComponent()) {
1351 updateComponentResize(mouseEvent->scenePos());
1352 mouseEvent->accept();
1353 return;
1354 }
1355 const QPointF cursorPos = currentInteractionMode == InteractionMode::WIRE_CREATION_MODE
1356 ? resolveWireTarget(mouseEvent->scenePos())
1357 : QPointF(DiagramScene::snapToGrid(mouseEvent->scenePos()));
1358
1359 switch (currentInteractionMode) {
1360 case InteractionMode::COMPONENT_PLACING_MODE: {
1361 if (!componentToBeDrawn)
1362 break;
1363
1364 componentToBeDrawn->setPos(cursorPos);
1365 break;
1366 }
1367 case InteractionMode::WIRE_CREATION_MODE: {
1368 // Let's wait the user to start drawing the wire
1370 break;
1371 updateWirePreview(cursorPos);
1372 break;
1373 }
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");
1378 }
1379 QGraphicsScene::mouseMoveEvent(mouseEvent);
1380 if (currentInteractionMode == InteractionMode::NORMAL_MODE) {
1381 if (!mixedDrag.empty())
1383 else
1385 }
1386}
1387
1388void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent)
1389{
1390 if (currentInteractionMode == InteractionMode::NORMAL_MODE
1391 && mouseEvent->button() == Qt::LeftButton
1392 && !(mouseEvent->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier))) {
1393 const auto selection = selectedItems();
1394 if (selection.size() == 1) {
1395 if (auto* component = category_cast<GraphicalComponent>(selection.front(),
1397 if (auto handle = component->resizeHandleAt(
1398 component->mapFromScene(mouseEvent->scenePos()));
1399 handle && beginComponentResize(component, *handle, mouseEvent->scenePos())) {
1400 mouseEvent->accept();
1401 return;
1402 }
1403 }
1404 }
1405 }
1406 const QPointF cursorPos = currentInteractionMode == InteractionMode::WIRE_CREATION_MODE
1407 ? resolveWireTarget(mouseEvent->scenePos())
1408 : QPointF(DiagramScene::snapToGrid(mouseEvent->scenePos()));
1409
1410 switch (currentInteractionMode) {
1411 case InteractionMode::NORMAL_MODE: break;
1412 case InteractionMode::COMPONENT_PLACING_MODE: {
1413 if (componentToBeDrawn) {
1414 auto* placedComponent = componentToBeDrawn;
1415 const auto rotation = placedComponent->rotation();
1416
1418
1419 if (auto* undoStack = getUndoStack()) {
1420 undoStack->push(
1421 new SceneSelectionCommand(this, serializeItems({placedComponent}),
1423 }
1424
1426 if (!componentToBeDrawn)
1427 throw std::logic_error(
1428 "componentToBeDrawn should not be null after placeComponent succeeds");
1429 componentToBeDrawn->setRotation(rotation);
1430 }
1431 break;
1432 }
1433 case InteractionMode::PAN_MODE: break;
1434 case InteractionMode::WIRE_CREATION_MODE: {
1435 if (!wireSegmentToBeDrawn) {
1436 // Let's start drawing the wire!
1438 addItem(wireSegmentToBeDrawn);
1439 updateWirePreview(cursorPos);
1440 } else {
1441 updateWirePreview(cursorPos);
1442 if (!wirePreviewRouteValid) {
1443 QMessageBox::warning(views().isEmpty() ? nullptr : views().first(),
1444 "Cannot connect wire",
1445 "No valid orthogonal route avoids other wire endpoints");
1446 break;
1447 }
1448 wireSegmentToBeDrawn->addPoints();
1449 updateWirePreview(cursorPos);
1450
1451 const QPointF endpoint =
1452 wireSegmentToBeDrawn->mapToScene(wireSegmentToBeDrawn->lastPoint());
1453
1454 // Intermediate clicks remain available for routing bends. A port or existing
1455 // wire completes the route while wire creation mode stays ready for another.
1456 if (endpoint == cursorPos && isWireCompletionPoint(endpoint))
1458 }
1459 break;
1460 }
1461 case InteractionMode::SIMULATION_MODE: {
1463 break;
1464
1465 const auto itemsAtPos = items(cursorPos);
1466
1467 for (const auto item : itemsAtPos) {
1468 if (auto* io = category_cast<GraphicalIO>(item, ItemCategory::IO))
1469 io->handleSimulationClick();
1470 }
1471
1472 break;
1473 }
1474 default: throw std::logic_error("Unhandled InteractionMode in mousePressEvent");
1475 }
1476 QGraphicsScene::mousePressEvent(mouseEvent);
1477 if (currentInteractionMode == InteractionMode::NORMAL_MODE &&
1478 mouseEvent->button() == Qt::LeftButton) {
1479 if (hasWireGroupSelection() && !wireDrag.router) {
1481 } else {
1482 for (auto* item = mouseGrabberItem(); item; item = item->parentItem()) {
1485 break;
1486 }
1487 }
1488 }
1489 }
1490}
1491
1492void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* mouseEvent)
1493{
1494 if (isResizingComponent() && mouseEvent->button() == Qt::LeftButton) {
1495 updateComponentResize(mouseEvent->scenePos());
1497 mouseEvent->accept();
1498 return;
1499 }
1500 uint64_t clickedId = 0;
1501 if (currentInteractionMode == InteractionMode::NORMAL_MODE
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()) {
1506 if (auto* component = category_cast<GraphicalComponent>(item,
1508 clickedId = component->getUiId();
1509 break;
1510 }
1511 if (auto* wire = category_cast<GraphicalWireSegment>(item,
1513 clickedId = wire->getUiId();
1514 break;
1515 }
1516 }
1517 }
1518
1519 QGraphicsScene::mouseReleaseEvent(mouseEvent);
1520 if (clickedId) {
1521 if (auto* clicked = findGraphicalItemByUiId(clickedId)) {
1522 clearSelection();
1523 clicked->setSelected(true);
1524 }
1525 }
1526}
1527
1528void DiagramScene::keyPressEvent(QKeyEvent* event)
1529{
1530 switch (event->key()) {
1531 case Qt::Key_Escape: {
1532 // Escape commits a drawn wire with free endpoints; Shift+Escape explicitly
1533 // discards its draft instead.
1534 if (event->modifiers() & Qt::ShiftModifier) {
1536 removeItem(wireSegmentToBeDrawn);
1537 delete wireSegmentToBeDrawn;
1538 wireSegmentToBeDrawn = nullptr;
1539 wirePreviewRouteValid = true;
1540 setInteractionMode(InteractionMode::NORMAL_MODE);
1541 event->accept();
1542 return;
1543 }
1544 }
1546 event->accept();
1547 return;
1548 }
1549 break;
1550 }
1551 default: break;
1552 }
1553 QGraphicsScene::keyPressEvent(event);
1554}
1555
1560
1562{
1564 return;
1565
1566 wireSegmentToBeDrawn->setInitialPosition();
1567 wireSegmentToBeDrawn->setShowPoints({});
1568 wireSegmentToBeDrawn = nullptr;
1569 update();
1570}
1571
1573{
1574 if (!componentToBeDrawn)
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");
1578
1579 const auto view = views()[0];
1580 const auto cursorPos = view->mapToScene(view->mapFromGlobal(QCursor::pos()));
1581
1582 addComponent(componentToBeDrawn, cursorPos);
1583 componentToBeDrawn->setParent(this);
1584 componentToBeDrawn->setOpacity(0.5);
1585}
1586
1588{
1589 if (!componentToBeDrawn)
1590 return;
1591 componentToBeDrawn->setOpacity(1.0);
1592 componentToBeDrawn->setInitialPosition();
1593 componentToBeDrawn = nullptr;
1595}
1596
1597void DiagramScene::showCSB(const QPointF pos)
1598{
1599 csb->setCompletionList(componentTypesForScene(*this));
1600 csb->clear();
1601 csb->setPos(pos);
1602 addItem(csb);
1603 csb->showCompleter();
1604 csb->focus();
1605}
1606
1608{
1609 if (csb->scene() == this)
1610 removeItem(csb);
1611}
1612
1614 Component_weakPtr source)
1615{
1616 simulationController->handleInputToggled(targetBus, value, source);
1617}
1618
1619void DiagramScene::setFstTraceFile(std::optional<std::string> fileName)
1620{
1621 simulationController->setFstTraceFile(std::move(fileName));
1622}
1623
1625{
1626 return simulationController->isFstTracingEnabled();
1627}
1628
1629void DiagramScene::simulateEditedWaveform(const qulonglong duration,
1630 std::vector<Sample> inputSnapshots)
1631{
1632 simulationController->simulateEditedWaveform(duration, std::move(inputSnapshots));
1633}
1634
1635namespace {
1637 inspectConnectionForComponents(const std::vector<GraphicalWire*>& wires,
1638 std::span<GraphicalLogicComponent* const> components)
1639 {
1640 NetConnection result;
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());
1648 }
1649 }
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());
1657
1658 const bool connected = std::ranges::contains(endpoints, position);
1659 const bool portAlreadyAdded = std::ranges::contains(result.affectedPorts, port);
1660 if (!connected || portAlreadyAdded)
1661 continue;
1662
1663 result.affectedPorts.push_back(port);
1664 // Input buses retain the width of their previous binding. Validate them
1665 // through assignInputPortBus() when binding the output-sized net.
1666 if (!isOutput)
1667 continue;
1668 const auto portWidth = buses[index].size();
1669 if (!width)
1670 width = portWidth;
1671 else if (*width != portWidth && result.isValid()) {
1672 // Width mismatch
1673 result.error = QString("Port %1 requires %2 bits; this net requires %3 bits")
1674 .arg(port->getName())
1675 .arg(portWidth)
1676 .arg(*width);
1677 }
1678 }
1679 };
1680
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);
1686 }
1687
1688 result.width = width.value_or(1U);
1689
1690 return result;
1691 }
1692
1693} // namespace
1694
1695NetConnection
1696DiagramScene::inspectConnection(const std::vector<GraphicalWire*>& wires) const
1697{
1698 return inspectConnectionForComponents(wires, logicComponentsInScene(*this));
1699}
1700
1707
1709{
1711 return;
1712 connectionReportDirty = true;
1714 return;
1716 QTimer::singleShot(0, this, [this] {
1720 });
1721}
1722
1724{
1725 // Prevent recursive calls
1727 return;
1728 QScopedValueRollback guard(refreshingConnections, true);
1729
1730 connectionReportDirty = false;
1731 connectionReport.nets.clear();
1732 const auto components = logicComponentsInScene(*this);
1733
1734 // clang-format off
1735 connectionReport.nets = wireManager.wires()
1736 | std::views::transform([&components](const std::shared_ptr<GraphicalWire>& w) {
1737 return inspectConnectionForComponents({w.get()}, components);
1738 })
1739 | std::ranges::to<std::vector>();
1740 //clang-format on
1741
1742 auto clearBindings = [&components] {
1743 for (auto* component : components)
1744 component->getComponent()->clearWires();
1745 };
1746
1747 // Iterates over valid nets and associates their buses with connected ports
1748 auto bind = [this, &components] {
1749 for (auto [index, wire] : wireManager.wires() | SILICON::views::enumerate) {
1750 auto& net = connectionReport.nets[index];
1751
1752 if (!net.isValid())
1753 continue;
1754
1755 if (wire->getBusSize() != net.width)
1756 wire->setBusSize(net.width);
1757
1758 for (auto* component : components) {
1759
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()) {
1767 try {
1768 component->assignInputPortBus(portIndex, wire->getBus());
1769 } catch (const std::exception& error) {
1770 net.error = QString::fromUtf8(error.what());
1771 }
1772 }
1773 }
1774 }
1775 };
1776
1777 clearBindings();
1778 bind();
1779
1780 if (!connectionReport.valid()) {
1781 // A component's assignment rule can reject a width that passed the common
1782 // width check. Rebind only the remaining valid nets after clearing partial work.
1783 clearBindings();
1784 bind();
1785 }
1786 for (const auto [index, wire] : wireManager.wires() | SILICON::views::enumerate) {
1787 const auto& net = connectionReport.nets[index];
1788 wire->setConnectionError(net.error);
1789 }
1790 for (auto* component : components) {
1791 for (Port* port : component->getPorts()) {
1792 port->setInputAssignmentError(false);
1793 port->setToolTip(port->getName());
1794 }
1795 }
1796 for (const auto& net : connectionReport.nets)
1797 if (!net.isValid())
1798 for (Port* port : net.affectedPorts) {
1799 port->setInputAssignmentError(true);
1800 port->setToolTip(net.error.value());
1801 }
1802 update();
1803}
1804
1809
1811{
1812 component->setPos(pos);
1813 addItem(component);
1814}
1815
1817{
1818 setInteractionMode(InteractionMode::NORMAL_MODE);
1819
1820 auto components = logicComponentsInScene(*this);
1821 if (components.empty())
1822 return;
1823
1824 // A deserialized circuit is the authoritative topology. Reconstructing it from the
1825 // current drawing before autoplacement can import accidental visual overlaps as real
1826 // connections. For an edited scene the cache is invalidated by updateSceneAfterEdit,
1827 // so only then derive the circuit from graphical endpoints.
1828 std::shared_ptr<Circuit> authoritativeCircuit = getCircuit();
1829 if (!authoritativeCircuit
1830 || boost::num_vertices(authoritativeCircuit->getGraph()) == 0) {
1832 return;
1833 authoritativeCircuit =
1834 std::make_shared<Circuit>(coreComponentsFor(components), false);
1835 }
1836 const Circuit& activeCircuit = *authoritativeCircuit;
1837
1839 auto* parent = views().isEmpty() ? nullptr : views().first()->window();
1840 QProgressDialog progress(tr("Finding a clean circuit layout..."), tr("Use best so far"),
1841 0, options.candidateCount, parent);
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();
1849
1850 options.isCancelled = [&progress]() {
1851 QApplication::processEvents();
1852 return progress.wasCanceled();
1853 };
1854 options.progress = [&progress](const int completed, const int total) {
1855 progress.setMaximum(total);
1856 progress.setValue(completed);
1857 QApplication::processEvents();
1858 };
1859
1860 applyAutoplacement(*this, activeCircuit, components, options);
1861}
1862
1863void DiagramScene::placeComponent(std::string_view typeName, const bool showSearchBox,
1864 const PropertyMap& initialProperties)
1865{
1867 throw std::logic_error("placeComponent: previous component not yet placed");
1868
1870 if (auto* subcircuit =
1872 subcircuit->setProjectContext(documents, resolver);
1873 }
1874 else if (auto* rom = dynamic_cast<GraphicalROM*>(componentToBeDrawn))
1875 rom->setDocumentStore(documents);
1876
1877 lastPlacedComponentType = typeName;
1878 lastPlacedComponentProperties = initialProperties;
1879 suppressNextComponentSearch = !showSearchBox;
1880
1881 if (auto* logicComponent = category_cast<GraphicalLogicComponent>(
1883 if (!initialProperties.contains("portOrientation")) {
1884 switch (logicComponent->getComponent()->metadata().portRole) {
1885 case PortRole::Input:
1886 logicComponent->applyProperty("portOrientation", lastInputOrientation);
1887 break;
1888 case PortRole::Output:
1889 logicComponent->applyProperty("portOrientation", lastOutputOrientation);
1890 break;
1891 case PortRole::None: break;
1892 }
1893 }
1894 }
1895
1896 for (const auto& [key, value] : initialProperties)
1897 componentToBeDrawn->applyProperty(key, value);
1898
1899 if (auto* logicComponent = category_cast<GraphicalLogicComponent>(
1901 logicComponent && !initialProperties.contains("name"))
1902 assignDefaultComponentName(*this, *logicComponent);
1903
1904 // TODO: IMPLEMENT COMPONENT SHADOW TO BE SHOWN WHILE DRAGGING
1905 setInteractionMode(InteractionMode::COMPONENT_PLACING_MODE);
1907 hideCSB();
1908}
1909
1911{
1912 const auto orientation = component.getPropertyValue<std::string>("portOrientation");
1913 if (!orientation)
1914 return;
1915
1916 switch (component.metadata().portRole) {
1917 case PortRole::Input: lastInputOrientation = *orientation; break;
1918 case PortRole::Output: lastOutputOrientation = *orientation; break;
1919 case PortRole::None: break;
1920 }
1921}
1922
1924{
1925 if (!item)
1926 return;
1927
1928 item->setOwningScene(this);
1929 itemsByUiId[item->getUiId()] = item;
1930}
1931
1933{
1934 if (!item)
1935 return;
1936
1937 // Direct deletion reaches here after the component's derived state is gone.
1938 if (componentResize.uiId == item->getUiId())
1939 componentResize = {};
1940
1941 if (auto it = itemsByUiId.find(item->getUiId());
1942 it != itemsByUiId.end() && it->second == item) {
1943 itemsByUiId.erase(it);
1944 }
1945
1946 item->setOwningScene(nullptr);
1947}
1948
1949std::string DiagramScene::serialize() const
1950{
1951 return serializer->serialize();
1952}
1953
1954nlohmann::ordered_json DiagramScene::serializeSelection() const
1955{
1956 return serializer->serializeSelection();
1957}
1958
1959nlohmann::ordered_json
1960DiagramScene::serializeItems(const std::vector<QGraphicsItem*>& sceneItems) const
1961{
1962 return serializer->serializeItems(sceneItems);
1963}
1964
1965void DiagramScene::deserialize(const std::string& jsonStr,
1966 GUIComponentFactory& guiFactory,
1967 const ComponentRegistry& coreRegistry)
1968{
1969 serializer->deserialize(jsonStr, guiFactory, coreRegistry);
1970}
1971
1972std::shared_ptr<SceneLoadPlan>
1973DiagramScene::prepareDeserialize(const std::string& jsonStr,
1974 GUIComponentFactory& guiFactory,
1975 const ComponentRegistry& coreRegistry)
1976{
1977 return serializer->prepareDeserialize(jsonStr, guiFactory, coreRegistry);
1978}
1979
1980void DiagramScene::applyDeserialize(std::shared_ptr<SceneLoadPlan> plan)
1981{
1982 serializer->applyDeserialize(std::move(plan));
1983}
1984
1985void DiagramScene::loadCircuit(std::shared_ptr<Circuit> circuit,
1986 GUIComponentFactory& guiFactory,
1987 const bool resolveSubcircuitMetadata)
1988{
1989 serializer->loadCircuit(std::move(circuit), guiFactory, resolveSubcircuitMetadata);
1990}
1991
1992bool DiagramScene::insertSelection(const nlohmann::json& payload,
1993 GUIComponentFactory& guiFactory,
1994 const ComponentRegistry& coreRegistry,
1995 QPointF targetOrigin, const bool isPaste)
1996{
1997 return serializer->insertSelection(payload, guiFactory, coreRegistry, targetOrigin,
1998 isPaste);
1999}
2000
2002{
2003 if (auto it = itemsByUiId.find(uiId); it != itemsByUiId.end())
2004 return it->second;
2005 return nullptr;
2006}
2007
2008void DiagramScene::removeItems(const std::vector<QGraphicsItem*>& sceneItems)
2009{
2010 if (sceneItems.empty())
2011 return;
2012
2018 const bool removedComponents = std::ranges::any_of(sceneItems, [](const auto* item) {
2020 });
2021 clearSelection();
2022
2023 // Remove everything from the scene before deleting objects so scene callbacks never
2024 // observe partially-destroyed items.
2025 for (auto* item : sceneItems)
2026 removeItem(item);
2027
2028 for (auto* item : sceneItems)
2029 delete item;
2030
2031 if (removedComponents)
2032 wireManager.refreshPortAnchors();
2034 edit.commit();
2035}
2036
2037bool DiagramScene::removeSelection(const nlohmann::json& payload)
2038{
2039 return serializer->removeSelection(payload);
2040}
2041
2043{
2044 wireManager.notifyElectricalChanged();
2045 update();
2046}
2047
2048void DiagramScene::clear(const bool clearUndoStack, const bool clearLogs)
2049{
2055 removeItem(wireSegmentToBeDrawn);
2056 delete wireSegmentToBeDrawn;
2057 wireSegmentToBeDrawn = nullptr;
2058 }
2059 setInteractionMode(InteractionMode::NORMAL_MODE);
2060
2061 if (componentToBeDrawn) {
2062 delete componentToBeDrawn;
2063 componentToBeDrawn = nullptr;
2064 }
2065
2067 delete wireSegmentToBeDrawn;
2068 wireSegmentToBeDrawn = nullptr;
2069 }
2070
2071 wireManager.clear();
2072
2073 if (clearUndoStack && getUndoStack())
2074 getUndoStack()->clear();
2075
2076 if (clearLogs)
2077 emit logsClearRequested();
2078
2079 QGraphicsScene::clear();
2080 initializeSceneBounds(INITIAL_SCENE_HALF_EXTENT);
2081 simulationController->clearWaveformTrace();
2082 connectionReport.nets.clear();
2083 connectionReportDirty = true;
2084}
2085
2087{
2092 // QGraphicsScene deletes remaining items from the base destructor. Break the back
2093 // references first so GraphicalItem teardown cannot touch DiagramScene state after
2094 // our members have already started dying.
2095 for (auto& [uiId, item] : itemsByUiId) {
2096 Q_UNUSED(uiId);
2097 if (item)
2098 item->setOwningScene(nullptr);
2099 }
2100 itemsByUiId.clear();
2101
2102 // Clean up any remaining wire segment being drawn
2104 removeItem(wireSegmentToBeDrawn);
2105 delete wireSegmentToBeDrawn;
2106 wireSegmentToBeDrawn = nullptr;
2107 }
2108
2109 // Clean up any component being drawn
2110 if (componentToBeDrawn) {
2111 removeItem(componentToBeDrawn);
2112 delete componentToBeDrawn;
2113 componentToBeDrawn = nullptr;
2114 }
2115}
2116
2117} // namespace SILICON::ui
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
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.
Definition component.cpp:54
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.
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 updateComponentDrag()
Previews component moves and restores the last valid positions if routing fails.
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.
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 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 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.
void setComponentShadow()
Shows the component shadow at cursor position.
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)
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
WireEndpointEdit finishMixedDrag()
Commits a mixed selection drag and returns topology and net changes for undo.
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.
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.
const SILICON::project::DocumentStore * documentStore() const noexcept
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.
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.
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
virtual std::span< const ResizeHandle > resizeHandles() 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)
Definition theme.hpp:92
static ThemeEngine & instance()
Definition theme.cpp:147
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
Definition wire.hpp:54
std::weak_ptr< Component > Component_weakPtr
Definition wire.hpp:52
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
Definition wire.hpp:120
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)
Definition enums.hpp:60
std::optional< std::vector< RoutedSegment > > RoutePreview
constexpr auto adjacent
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::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< TopologyChange > topologyChanges
std::vector< NetChange > netChanges