SILICON
Loading...
Searching...
No Matches
circuitEditor.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
10#include "circuitEditor.hpp"
11
12#include <cstdint>
13#include <ranges>
14#include <stdexcept>
15#include <vector>
16
17#include <QApplication>
18#include <QByteArray>
19#include <QClipboard>
20#include <QCursor>
21#include <QMimeData>
22#include <QPointF>
23#include <QTimer>
24#include <QUndoStack>
25
26#include <nlohmann/json.hpp>
27
28#include <core/circuit.hpp>
38
39namespace SILICON::ui {
40namespace {
42 constexpr char CIRCUIT_SELECTION_MIME_TYPE[] =
43 "application/vnd.silicon.circuit-selection+bson";
44
45 struct PreparedCircuit final : PreparedEditorDocument {
46 std::shared_ptr<SceneLoadPlan> plan;
47 };
48
49 bool hasClipboardItems(const nlohmann::json& payload)
50 {
51 if (!payload.contains("visual") || !payload["visual"].is_object())
52 return false;
53
54 const auto& visual = payload["visual"];
55 const bool hasComponents = visual.contains("components")
56 && visual["components"].is_array()
57 && !visual["components"].empty();
58 const bool hasWires = visual.contains("wires") && visual["wires"].is_array()
59 && !visual["wires"].empty();
60
61 return hasComponents || hasWires;
62 }
63} // namespace
64
66 EditorNotifications notifications)
68 diagramScene(std::make_unique<DiagramScene>()),
69 diagramView(std::make_unique<DiagramView>(parent))
70{
71 diagramScene->setDocumentStore(&session.projectContext.documents());
72 diagramScene->setCircuitResolver(&session.circuitResolver);
73 diagramView->setScene(diagramScene.get());
74
75 // Selection and interaction mode both decide which diagram commands apply, so the scene
76 // reports them through the workspace. The clipboard is not observed here: the workspace
77 // watches it once and this editor only answers what its own contents mean.
78 const auto reportEditState = [notifications] { notifications.editStateChanged(); };
79 const auto reportEditHistory = [notifications, reportEditState] {
80 reportEditState();
81 notifications.historyChanged();
82 };
83
84 callbacks.connect(diagramScene.get(), &DiagramScene::selectionChanged, reportEditState);
86 reportEditHistory);
87
88}
89
91
92QWidget* CircuitEditor::widget() const noexcept
93{
94 return diagramView.get();
95}
96
97std::shared_ptr<PreparedEditorDocument>
99{
100 auto prepared = std::make_shared<PreparedCircuit>();
101 prepared->plan = diagramScene->prepareDeserialize(
104 return prepared;
105}
106
108{
109 const auto* circuit = dynamic_cast<const PreparedCircuit*>(&prepared);
110 if (!circuit || !circuit->plan)
111 throw std::logic_error("Prepared circuit document has no load plan");
112 diagramScene->clear(false, false);
113 diagramScene->setSubcircuitDocumentMode(true);
114 diagramScene->applyDeserialize(circuit->plan);
115
116 // The editor can be hidden while another document type is active. Center after the
117 // workspace has made this view current, when its viewport has its final geometry.
118 QTimer::singleShot(0, diagramView.get(), &DiagramView::centerCircuit);
119}
120
121void CircuitEditor::flush(const std::string& path)
122{
123 diagramScene->cancelComponentResize();
124 auto serialized = diagramScene->serialize();
125 if (const auto* existing = session.projectContext.documents().find(path)) {
126 try {
127 auto json = nlohmann::json::parse(serialized);
128 const auto fallback =
130 nlohmann::json::parse(existing->getContents(), nullptr, false))
131 .value_or(GraphicalSubcircuitMetadata{});
132 json["graphicalComponent"] =
134 json, fallback, &session.circuitResolver));
135 serialized = json.dump(2);
136 } catch (const nlohmann::json::exception&) {
137 }
138 }
139 session.projectContext.upsertDocument({path, std::move(serialized)});
140}
141
143{
144 return projectHistory && !projectHistory->isClean();
145}
148{
149 diagramScene->clear();
150 diagramScene->setDocumentCircuit(std::make_shared<SILICON::core::Circuit>());
151 diagramScene->setSubcircuitDocumentMode(false);
152 QTimer::singleShot(0, diagramView.get(), &DiagramView::centerCircuit);
153}
155{
156 diagramScene->cancelComponentResize();
157 if (canUndo())
158 projectHistory->undo();
159}
161{
162 diagramScene->cancelComponentResize();
163 if (canRedo())
164 projectHistory->redo();
165}
167{
168 return diagramScene->getInteractionMode() != InteractionMode::SIMULATION_MODE
169 && projectHistory && projectHistory->canUndo();
170}
172{
173 return diagramScene->getInteractionMode() != InteractionMode::SIMULATION_MODE
174 && projectHistory && projectHistory->canRedo();
175}
176
178{
179 diagramScene->cancelComponentResize();
180 try {
181 const auto payload = diagramScene->serializeSelection();
182 if (!hasClipboardItems(payload))
183 return false;
184
185 const auto bson = nlohmann::json::to_bson(payload);
186 QByteArray bytes(reinterpret_cast<const char*>(bson.data()),
187 static_cast<qsizetype>(bson.size()));
188
189 auto* mimeData = new QMimeData();
190 mimeData->setData(CIRCUIT_SELECTION_MIME_TYPE, bytes);
191 QApplication::clipboard()->setMimeData(mimeData);
192
193 return true;
194 } catch (const std::exception&) {
195 return false;
196 }
197}
198
203
209
211{
212 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
213 if (!mimeData || !mimeData->hasFormat(CIRCUIT_SELECTION_MIME_TYPE))
214 return;
215
216 const QByteArray bytes = mimeData->data(CIRCUIT_SELECTION_MIME_TYPE);
217 if (bytes.isEmpty())
218 return;
219
220 try {
221 auto& guiFactory = GUIComponentFactory::instance();
222 auto& coreRegistry = ComponentRegistry::instance();
223 const auto payload = nlohmann::json::from_bson(
224 reinterpret_cast<const std::uint8_t*>(bytes.data()),
225 reinterpret_cast<const std::uint8_t*>(bytes.data() + bytes.size()));
226
227 if (diagramScene->getInteractionMode() != InteractionMode::NORMAL_MODE)
228 diagramScene->setInteractionMode(InteractionMode::NORMAL_MODE);
229
230 const QPointF targetOrigin =
231 diagramView->mapToScene(diagramView->mapFromGlobal(QCursor::pos()));
232 if (!diagramScene->insertSelection(payload, guiFactory, coreRegistry, targetOrigin,
233 true))
234 return;
235
236 if (projectHistory)
237 projectHistory->push(
238 new SceneSelectionCommand(diagramScene.get(), diagramScene->serializeSelection(),
240 } catch (const std::exception&) {
241 }
242}
243
245{
246 diagramScene->cancelComponentResize();
247 auto itemsToDelete =
248 diagramScene->selectedItems()
249 | std::views::filter([](auto* item) { return item->type() > UNKNOWN; })
250 | std::ranges::to<std::vector>();
251 if (itemsToDelete.empty())
252 return;
253
254 std::vector<GraphicalWireSegment*> wires;
255 std::vector<QGraphicsItem*> components;
256 for (auto* item : itemsToDelete) {
258 wires.push_back(wire);
259 else
260 components.push_back(item);
261 }
262 if (!wires.empty()) {
263 QUndoCommand* command = nullptr;
264 if (projectHistory) {
265 if (components.empty()) {
266 command = new WireTopologyCommand(
268 } else {
269 command = new QUndoCommand("Remove Selection");
270 new WireTopologyCommand(diagramScene.get(), wires,
272 command);
274 diagramScene->serializeItems(components),
276 true, command);
277 }
278 }
279 diagramScene->removeItems(itemsToDelete);
280 if (projectHistory && command)
281 projectHistory->push(command);
282 return;
283 }
284
285 const auto payload = diagramScene->serializeItems(itemsToDelete);
286 diagramScene->removeItems(itemsToDelete);
287 if (projectHistory)
290}
291
293{
294 if (in)
295 diagramView->zoomIn();
296 else
297 diagramView->zoomOut();
298}
299
301{
302 const auto interactionMode = diagramScene->getInteractionMode();
303 const bool normalMode = interactionMode == InteractionMode::NORMAL_MODE;
304 const auto selected = diagramScene->selectedItems();
305
306 EditorEditState state;
307 state.canCut = state.canCopy = state.canDelete = normalMode && !selected.empty();
308 state.canRotate = (normalMode && selected.size() == 1)
309 || interactionMode == InteractionMode::COMPONENT_PLACING_MODE;
310
311 const auto* clipboardData = QApplication::clipboard()->mimeData();
312 state.canPaste = normalMode && clipboardData
313 && clipboardData->hasFormat(CIRCUIT_SELECTION_MIME_TYPE);
314 return state;
315}
316
317} // namespace SILICON::ui
static ComponentRegistry & instance()
const std::string & getContents() const noexcept
std::unique_ptr< DiagramView > diagramView
std::unique_ptr< DiagramScene > diagramScene
void resetDirtyState() noexcept override
bool canUndo() const override
bool canRedo() const override
void apply(const PreparedEditorDocument &prepared) override
QWidget * widget() const noexcept override
void zoom(bool in) override
Zooms the document in (true) or out (false) by one step.
void flush(const std::string &path) override
EditorEditState editState() const override
Reports which editing commands the diagram currently accepts.
bool isDirty() const override
CircuitEditor(ProjectSession &session, QWidget *parent, EditorNotifications notifications)
std::shared_ptr< PreparedEditorDocument > prepare(const SILICON::project::Document &document) override
Graphics scene for the circuit diagram editor.
void modeChanged(InteractionMode mode)
Emitted when the interaction mode changes.
void centerCircuit()
Pans the viewport so the circuit's bounds are centered.
static GUIComponentFactory & instance()
Gets the global singleton factory instance.
std::optional< GraphicalSubcircuitMetadata > parseGraphicalSubcircuitMetadata(const nlohmann::json &document)
Parses graphical subcircuit metadata from a scene document.
Definition metadata.cpp:224
nlohmann::ordered_json graphicalSubcircuitMetadataToJson(const GraphicalSubcircuitMetadata &metadata)
Serializes graphical metadata to the JSON shape/port object.
Definition metadata.cpp:324
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60
GraphicalSubcircuitMetadata synchronizeGraphicalSubcircuitMetadata(const nlohmann::json &document, const GraphicalSubcircuitMetadata &fallbackMetadata, const CircuitResolver *resolver)
Reconciles saved graphical metadata with the current circuit document.
Definition metadata.cpp:276
Visual metadata used to render a subcircuit as a reusable component.
Definition metadata.hpp:74