27#include <unordered_map>
28#include <unordered_set>
32#include <QGraphicsScene>
33#include <QGraphicsSceneMouseEvent>
34#include <QGraphicsView>
45#include <nlohmann/json.hpp>
62using namespace SILICON::core;
63using namespace SILICON::waveform;
86 return !
error.has_value();
91 std::vector<NetConnection>
nets;
93 [[nodiscard]]
bool valid()
const {
94 return std::ranges::all_of(
nets, [](
const auto& net) {
return net.isValid(); });
234 void placeComponent(std::string_view typeName,
bool showSearchBox =
true,
290 std::span<const WireRouteChange> wires,
bool useAfter,
291 const WireEndpointEdit& topology = {});
297 circuit = std::move(newCircuit);
303 circuit = std::move(newCircuit);
342 [[nodiscard]] std::string
serialize()
const;
374 [[nodiscard]] nlohmann::ordered_json
375 serializeItems(
const std::vector<QGraphicsItem*>& sceneItems)
const;
415 [[nodiscard]] std::shared_ptr<SceneLoadPlan>
428 bool resolveSubcircuitMetadata =
true);
448 bool isPaste =
false);
455 void removeItems(
const std::vector<QGraphicsItem*>& sceneItems);
479 void clear(
bool clearUndoStack =
true,
bool clearLogs =
true);
541 QList<int> signalWidths);
553 void drawBackground(QPainter* painter,
const QRectF& rect)
override;
558 void drawForeground(QPainter* painter,
const QRectF& rect)
override;
583 void mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent)
override;
677 std::vector<std::pair<uint64_t, std::vector<QPointF>>>
originals;
679 std::vector<std::unique_ptr<WireManager::Edit>>
edits;
682 std::map<uint64_t, WireEndpointEdit::NetState>
netBefore;
696 std::unique_ptr<InteractiveWireRouter>
router;
721 std::unique_ptr<InteractiveWireRouter>
router;
Base class for all digital circuit components.
Handles DiagramScene persistence, clipboard payloads, and reconstruction.
Manages simulation lifecycle and waveform tracing for DiagramScene.
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.
void setUndoStack(QUndoStack *stack) noexcept
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 setIoInteractionsEnabled(bool enabled)
Enables or disables user-triggered IO interactions in simulation mode.
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()
const WireManager & getWireManager() const
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 setDocumentNavigator(DocumentNavigator *navigator) noexcept
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.
void setCircuit(std::shared_ptr< Circuit > newCircuit)
Replaces the derived topology cache.
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()
DocumentNavigator * documentNavigator
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.
void setSubcircuitDocumentMode(bool enabled)
Enables reusable-circuit boundary I/O editing for the scene.
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.
DocumentNavigator * getDocumentNavigator() const noexcept
std::unordered_map< uint64_t, GraphicalItem * > itemsByUiId
O(1) lookup table for runtime graphical items by stable UI id.
void updateComponentResize(QPointF scenePos)
void waveformTraceReset(QStringList signalNames, int inputCount, QList< int > signalWidths)
Emitted when interactive waveform signals should be rebuilt.
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.
bool isSubcircuitDocumentMode() const
Returns true when subcircuit-only graphical tools may be placed.
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
void setDocumentCircuit(std::shared_ptr< Circuit > newCircuit)
Installs an authoritative circuit.
bool beginComponentResize(GraphicalComponent *component, ResizeHandle handle, QPointF scenePos)
void finishWireDrag(GraphicalWireSegment *segment)
Commits the active segment drag and records its undo command.
bool isWireCreationInProgress() const
Returns whether a wire currently has a starting endpoint and is being routed.
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.
bool subcircuitDocumentMode
Whether reusable-circuit boundary I/O editing is enabled.
PropertyMap lastPlacedComponentProperties
Initial properties used when repeating placement of the last type.
bool isItemCollisionEnabled
Disabled while applying batch layouts that must not be rejected mid-move.
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 waveformTraceSnapshots(QList< QPair< qulonglong, std::vector< BusValue > > > snapshots)
Emitted when a completed simulation job produced multiple waveform states.
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.
Base class for graphical circuit components.
Base class for all graphical items in the diagram.
The visible, selectable polyline wire on the diagram scene.
Logical wire entity that groups segments sharing the same bus.
Represents a connection point on a component.
Scene payload deserialized ahead of time, detached from the host scene.
std::unordered_map< std::string, PropertyValue, TransparentStringHash, TransparentStringEqual > PropertyMap
Map from property names to their values.
std::weak_ptr< Component > Component_weakPtr
std::vector< State > BusValue
DiagramScene::InteractionMode InteractionMode
Alias for DiagramScene::InteractionMode.
bool valid() const
Returns whether every net in the report has no connection error.
std::vector< NetConnection > nets
std::unique_ptr< InteractiveWireRouter > router
std::vector< std::pair< GraphicalComponent *, QPointF > > initialPositions
std::unordered_map< const GraphicalComponent *, std::unordered_set< const GraphicalWire * > > attachedWires
std::vector< std::pair< GraphicalComponent *, QPointF > > validPositions
ComponentResizeState before
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
GraphicalWireSegment * segment
std::unique_ptr< InteractiveWireRouter > router
std::vector< QPointF > originalPoints
bool isValid() const
Returns whether this net has no connection error.
std::optional< QString > error
std::vector< Port * > affectedPorts