SILICON
Loading...
Searching...
No Matches
undoCommands.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 "undoCommands.hpp"
19
20#include <cstdint>
21#include <array>
22#include <map>
23#include <utility>
24
26
33
34namespace SILICON::ui {
35using namespace SILICON::core;
36
37namespace {
38
39 DiagramScene* itemScene(const QGraphicsItem* item)
40 {
41 if (!item || !item->scene())
42 return nullptr;
43 return qobject_cast<DiagramScene*>(item->scene());
44 }
45
46 std::string activeDocumentPath(DiagramScene* scene)
47 {
48 if (auto* navigator = scene ? scene->getDocumentNavigator() : nullptr)
49 return navigator->currentDocumentPath();
50
51 return {};
52 }
53
54 bool activateDocument(DiagramScene* scene, const std::string& documentPath)
55 {
56 if (documentPath.empty())
57 return true;
58
59 if (auto* navigator = scene ? scene->getDocumentNavigator() : nullptr)
60 return navigator->activateDocument(documentPath);
61
62 return false;
63 }
64
65 GraphicalItem* findItem(DiagramScene* scene, const uint64_t uiId)
66 {
67 if (!scene)
68 return nullptr;
69 return scene->findGraphicalItemByUiId(uiId);
70 }
71
72 GraphicalComponent* findComponent(DiagramScene* scene, const uint64_t uiId)
73 {
74 return category_cast<GraphicalComponent>(findItem(scene, uiId),
76 }
77
78} // namespace
79
81 DiagramScene* diagram, const std::vector<GraphicalWireSegment*>& segments,
82 const Operation operation, const bool skipInitialRedo, QUndoCommand* parent)
83 : QUndoCommand(parent), scene(diagram), documentPath(activeDocumentPath(diagram)),
85{
86 setText(operation == Operation::Add ? "Add Wire" : "Remove Wire");
87 for (const auto* segment : segments) {
88 if (!segment || !segment->getGraphicalWire())
89 continue;
90 snapshots.push_back({segment->getUiId(),
91 segment->getGraphicalWire()->getRouteId(),
92 segment->getGraphicalWire()->getBus(),
93 segment->pos(), segment->getPoints()});
94 }
95}
96
97void WireTopologyCommand::apply(const bool restore)
98{
99 if (!scene || !activateDocument(scene, documentPath))
100 return;
101 if (scene->getInteractionMode() != DiagramScene::InteractionMode::NORMAL_MODE)
102 scene->setInteractionMode(DiagramScene::InteractionMode::NORMAL_MODE);
103 if (!restore) {
104 std::vector<QGraphicsItem*> removed;
105 for (const auto& snapshot : snapshots)
106 if (auto* item = scene->findGraphicalItemByUiId(snapshot.uiId))
107 removed.push_back(item);
108 scene->removeItems(removed);
109 return;
110 }
111
112 auto& manager = scene->getWireManager();
113 WireManager::Batch batch(manager);
114 std::map<uint64_t, std::shared_ptr<GraphicalWire>> groups;
115 for (const auto& snapshot : snapshots)
116 for (const auto& wire : manager.wires())
117 if (wire->getRouteId() == snapshot.routeId)
118 groups[snapshot.routeId] = wire;
119 for (const auto& snapshot : snapshots) {
120 if (scene->findGraphicalItemByUiId(snapshot.uiId))
121 continue;
122 auto& wire = groups[snapshot.routeId];
123 if (!wire) {
124 wire = manager.createWire(1);
125 wire->setBus(snapshot.bus);
126 wire->restoreRouteId(snapshot.routeId);
127 }
128 auto* segment = new GraphicalWireSegment(snapshot.points.front());
129 segment->setUiId(snapshot.uiId);
130 segment->setPos(snapshot.position);
131 segment->setPoints(snapshot.points);
132 scene->addItem(segment);
133 segment->setGraphicalWire(wire.get());
134 manager.addSegment(segment, false);
135 }
136 manager.rebuildFromGeometry();
137 batch.commit();
138}
139
144
146{
147 if (skipInitialRedo) {
148 skipInitialRedo = false;
149 return;
150 }
152}
153
155 Callback redoCallback, QUndoCommand* parent)
156 : QUndoCommand(std::move(text), parent),
157 undoCallback(std::move(undoCallback)),
158 redoCallback(std::move(redoCallback))
159{
160}
161
166
171
172// --- MoveItemCommand ---
173
174void MoveItemCommand::addItemMove(GraphicalItem* item, const QPointF& oldPos,
175 const QPointF& newPos)
176{
177 if (!item)
178 return;
179 if (!scene)
180 scene = itemScene(item);
181 if (documentPath.empty())
182 documentPath = activeDocumentPath(scene);
183 moves.push_back({item->getUiId(), oldPos, newPos});
184}
185
187{
188 if (scene && activateDocument(scene, documentPath))
189 scene->applyItemMoves(moves, wireMoves, false, topologyEdit);
190}
191
193{
194 if (skipInitialRedo) {
195 skipInitialRedo = false;
196 return;
197 }
198 if (scene && activateDocument(scene, documentPath))
199 scene->applyItemMoves(moves, wireMoves, true, topologyEdit);
200}
201
202// --- EditWireRouteCommand ---
203
205 std::vector<WireRouteChange> routeChanges,
206 const WireDragKind kind,
207 WireEndpointEdit contacts,
208 QUndoCommand* parent)
209 : QUndoCommand(parent),
210 scene(itemScene(segment)),
211 documentPath(activeDocumentPath(scene)),
212 changes(std::move(routeChanges)),
213 endpointEdit(std::move(contacts))
214{
215 switch (kind) {
216 case WireDragKind::Edge: setText("Move Wire Segment"); break;
217 case WireDragKind::Endpoint: setText("Move Wire Endpoint"); break;
218 case WireDragKind::Bend: setText("Move Wire Bend"); break;
219 }
220}
221
223{
224 if (!activateDocument(scene, documentPath))
225 return;
226
227 if (scene)
228 scene->applyWireRouteChanges(changes, false, endpointEdit);
229}
230
232{
233 if (skipInitialRedo) {
234 skipInitialRedo = false;
235 return;
236 }
237
238 if (!activateDocument(scene, documentPath))
239 return;
240
241 if (scene)
242 scene->applyWireRouteChanges(changes, true, endpointEdit);
243}
244
245// --- RotateItemCommand ---
246
248 const qreal oldRotation, const qreal newRotation,
249 QUndoCommand* parent)
250 : QUndoCommand(parent),
251 scene(itemScene(component)),
252 documentPath(activeDocumentPath(scene)),
253 uiId(component ? component->getUiId() : 0),
256{
257 setText("Rotate Component");
258}
259
261{
262 if (!activateDocument(scene, documentPath))
263 return;
264
265 if (auto* component = findComponent(scene, uiId)) {
266 component->setRotation(oldRotation);
267 component->setInitialRotation();
268 component->update();
269 scene->updateSceneAfterEdit();
270 }
271}
272
274{
275 if (skipInitialRedo) {
276 skipInitialRedo = false;
277 return;
278 }
279
280 if (!activateDocument(scene, documentPath))
281 return;
282
283 if (auto* component = findComponent(scene, uiId)) {
284 component->setRotation(newRotation);
285 component->setInitialRotation();
286 component->update();
287 scene->updateSceneAfterEdit();
288 }
289}
290
291// --- ModifyPropertyCommand ---
292
296 : scene(itemScene(component)),
297 documentPath(activeDocumentPath(scene)),
298 uiId(component->getUiId()),
299 before(std::move(before)),
300 after(std::move(after))
301{
302 setText("Resize Component");
303}
304
306{
307 if (!activateDocument(scene, documentPath))
308 return;
309 if (auto* component = findComponent(scene, uiId)) {
310 scene->cancelComponentResize();
311 component->applyResizeState(state);
312 scene->updateSceneAfterEdit();
313 emit scene->componentResized();
314 }
315}
316
321
323{
324 if (std::exchange(skipInitialRedo, false))
325 return;
326 apply(after);
327}
328
329ModifyPropertyCommand::ModifyPropertyCommand(std::string key, QUndoCommand* parent)
330 : QUndoCommand(parent), key(std::move(key))
331{
332 setText("Modify Property");
333}
334
336 const PropertyValue& oldValue,
337 const PropertyValue& newValue)
338{
339 if (!component || oldValue == newValue)
340 return;
341
342 auto* scene = itemScene(component);
343 if (documentPath.empty())
344 documentPath = activeDocumentPath(scene);
345 changes.push_back({scene, component->getUiId(), oldValue, newValue});
346}
347
348void ModifyPropertyCommand::apply(const bool useNewValue)
349{
350 if (!changes.empty() && !activateDocument(changes.front().scene, documentPath))
351 return;
352
353 bool applied = false;
354 for (const auto& change : changes) {
355 if (auto* component = findComponent(change.scene, change.uiId)) {
356 component->applyProperty(key, useNewValue ? change.newValue : change.oldValue);
357 applied = true;
358 }
359 }
360
361 if (applied && changes.front().scene)
362 changes.front().scene->updateSceneAfterEdit();
363}
364
366{
367 apply(false);
368}
369
371{
372 apply(true);
373}
374
375// --- SceneSelectionCommand ---
376
378 const nlohmann::json& payload,
379 const Operation operation,
380 const bool skipInitialRedo,
381 QUndoCommand* parent)
382 : QUndoCommand(parent),
383 scene(scene),
384 documentPath(activeDocumentPath(scene)),
388{
389 setText(operation == Operation::Add ? "Add Selection" : "Remove Selection");
390}
391
392nlohmann::json SceneSelectionCommand::payload() const
393{
395}
396
397QByteArray SceneSelectionCommand::encodePayload(const nlohmann::json& payload)
398{
399 const auto bson = nlohmann::json::to_bson(payload);
400 return {reinterpret_cast<const char*>(bson.data()),
401 static_cast<QByteArray::size_type>(bson.size())};
402}
403
404nlohmann::json SceneSelectionCommand::decodePayload(const QByteArray& payload)
405{
406 const auto* ptr = reinterpret_cast<const std::uint8_t*>(payload.constData());
407 return nlohmann::json::from_bson(ptr, ptr + payload.size());
408}
409
410QPointF SceneSelectionCommand::payloadOrigin(const nlohmann::json& payload)
411{
412 if (!payload.contains("origin") || !payload["origin"].is_object())
413 return {};
414
415 return {payload["origin"].value("x", 0.0), payload["origin"].value("y", 0.0)};
416}
417
419{
420 if (!scene)
421 return;
422
423 if (!activateDocument(scene, documentPath))
424 return;
425
426 if (scene->getInteractionMode() != InteractionMode::NORMAL_MODE)
427 scene->setInteractionMode(InteractionMode::NORMAL_MODE);
428
429 const auto selectionPayload = payload();
430
431 if (operation == Operation::Add) {
432 // Undoing an insertion removes the exact serialized objects by their stable UI ids.
433 scene->removeSelection(selectionPayload);
434 return;
435 }
436
437 scene->insertSelection(selectionPayload, GUIComponentFactory::instance(),
438 ComponentRegistry::instance(), payloadOrigin(selectionPayload));
439}
440
442{
443 if (!scene)
444 return;
445
446 if (skipInitialRedo) {
447 skipInitialRedo = false;
448 return;
449 }
450
451 if (!activateDocument(scene, documentPath))
452 return;
453
454 if (scene->getInteractionMode() != InteractionMode::NORMAL_MODE)
455 scene->setInteractionMode(InteractionMode::NORMAL_MODE);
456
457 const auto selectionPayload = payload();
458
459 if (operation == Operation::Add) {
460 // Redo rebuilds the serialized selection in place without generating fresh paste
461 // ids.
462 scene->insertSelection(selectionPayload, GUIComponentFactory::instance(),
464 payloadOrigin(selectionPayload));
465 return;
466 }
467
468 scene->removeSelection(selectionPayload);
469}
471 std::string newValue, ApplyFn apply,
472 QUndoCommand* parent)
473 : QUndoCommand(std::move(text), parent),
474 oldValue(std::move(oldValue)),
475 newValue(std::move(newValue)),
476 apply(std::move(apply))
477{
478}
479
484
489
490} // namespace SILICON::ui
static ComponentRegistry & instance()
CallbackUndoCommand(QString text, Callback undoCallback, Callback redoCallback, QUndoCommand *parent=nullptr)
std::function< void()> Callback
Graphics scene for the circuit diagram editor.
void undo() override
Restores the wire routes from before the gesture.
void redo() override
Restores the gesture's final routes, skipping the first invocation.
std::vector< WireRouteChange > changes
EditWireRouteCommand(GraphicalWireSegment *segment, std::vector< WireRouteChange > changes, WireDragKind kind, WireEndpointEdit endpointEdit={}, QUndoCommand *parent=nullptr)
Captures an already applied wire gesture for undo and redo.
static GUIComponentFactory & instance()
Gets the global singleton factory instance.
Base class for graphical circuit components.
Base class for all graphical items in the diagram.
The visible, selectable polyline wire on the diagram scene.
std::function< void(const std::string &)> ApplyFn
MetadataEditCommand(QString text, std::string oldValue, std::string newValue, ApplyFn apply, QUndoCommand *parent=nullptr)
ModifyPropertyCommand(std::string key, QUndoCommand *parent=nullptr)
std::vector< PropertyChange > changes
void addPropertyChange(GraphicalComponent *component, const PropertyValue &oldValue, const PropertyValue &newValue)
std::vector< WireRouteChange > wireMoves
void addItemMove(GraphicalItem *item, const QPointF &oldPos, const QPointF &newPos)
std::vector< ItemPositionChange > moves
ResizeComponentCommand(GraphicalComponent *component, ComponentResizeState before, ComponentResizeState after)
void apply(const ComponentResizeState &state)
RotateItemCommand(GraphicalComponent *component, qreal oldRotation, qreal newRotation, QUndoCommand *parent=nullptr)
static QByteArray encodePayload(const nlohmann::json &payload)
SceneSelectionCommand(DiagramScene *scene, const nlohmann::json &payload, Operation operation, bool skipInitialRedo=false, QUndoCommand *parent=nullptr)
static nlohmann::json decodePayload(const QByteArray &payload)
static QPointF payloadOrigin(const nlohmann::json &payload)
void commit()
Finishes the batch, rebuilding topology and notifying at the outermost level.
WireTopologyCommand(DiagramScene *scene, const std::vector< GraphicalWireSegment * > &segments, Operation operation, bool skipInitialRedo=true, QUndoCommand *parent=nullptr)
Captures segments for undoing or redoing wire addition or removal.
void undo() override
Reverses the captured wire addition or removal.
std::vector< Snapshot > snapshots
void apply(bool restore)
Restores captured segments or removes them from their original document.
void redo() override
Reapplies the operation, optionally skipping the first invocation.
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60