SILICON
Loading...
Searching...
No Matches
diagramSceneSimulationController.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
19
20#include <algorithm>
21#include <ranges>
22
24
25#include <algorithm>
26#include <format>
27#include <string>
28
29#include <QApplication>
30#include <QGraphicsItem>
31#include <QGraphicsView>
32#include <QObject>
33#include <QProgressDialog>
34#include <QTimer>
35#include <QWidget>
36
38
39#include <core/circuit.hpp>
41#include <core/simulator.hpp>
42#include <logging/logger.hpp>
48
49namespace SILICON::ui {
50using namespace SILICON::core;
51using namespace SILICON::simulation;
52using namespace SILICON::waveform;
53using namespace SILICON::waveform::fst;
54
55namespace {
56
57constexpr ItemCategory INPUT_CATEGORY = ItemCategory::IO | ItemCategory::Input;
58constexpr ItemCategory OUTPUT_CATEGORY = ItemCategory::IO | ItemCategory::Output;
59const SILICON::logging::Logger simulationUiLog("simulation-ui");
60
61std::string componentNameOr(const Component_ptr& component, const std::string& fallback)
62{
63 if (!component)
64 return fallback;
65
66 const auto property = component->getProperty("name");
67 if (!property)
68 return fallback;
69
70 if (const auto* name = std::get_if<std::string>(&*property); name && !name->empty())
71 return *name;
72
73 return fallback;
74}
75
77settleInteractiveSimulation(SILICON::simulation::Session& simulator,
78 const Simulator::CancellationCheck& isCancelled)
79{
80 const auto result = simulator.runUntilIdle(isCancelled);
81 if (result != Simulator::RunResult::Completed)
82 return result;
83
84 // Advance one display tick after settling so successive interactive changes do not
85 // collapse into one same-timestamp waveform sample.
86 return simulator.run(1, isCancelled);
87}
88
89} // namespace
90
95
100
102{
103 if (!scene.calculateWiresForComponents())
104 return false;
105
106 // Initialize all wires to UNKNOWN state (will be overridden by connected inputs)
107 for (const auto& wire : scene.getWireManager().wires())
108 wire->clearBusState();
109
110 std::vector<GraphicalIO*> inputs;
111 std::vector<GraphicalIO*> outputs;
112 Component_set coreComps;
113
114 for (auto* item : scene.items()) {
115 if (auto* input = category_cast<GraphicalIO>(item, INPUT_CATEGORY))
116 inputs.push_back(input);
117 else if (auto* output = category_cast<GraphicalIO>(item, OUTPUT_CATEGORY))
118 outputs.push_back(output);
119
120 if (const auto* component =
122 component && component->getComponent()) {
123 coreComps.insert(component->getComponent());
124 }
125 }
126
127 // Reset visible outputs first, then inject input start values. Doing this in two
128 // phases prevents output reset from overwriting a shared bus after an input starts
129 // it.
130 for (auto* output : outputs)
131 output->resetSimulationState();
132
133 // Do this BEFORE creating the Simulator to avoid double-evaluations.
134 for (auto* input : inputs) {
135 input->applyStartValue();
136 QObject::connect(input, &GraphicalIO::inputToggled, &scene,
137 &DiagramScene::handleInputToggled, Qt::UniqueConnection);
138 }
139
140 // Initialize Circuit & Simulator frameworks.
141 scene.setCircuit(std::make_shared<Circuit>(coreComps, false));
142
143 auto trace = collectTraceConfiguration();
144 resetTrace(trace);
145 const auto circuit = scene.getCircuit();
146 const auto traceFile = fstTraceFile;
147
148 startJob([this, circuit, trace = std::move(trace), traceFile]() mutable {
149 const auto isCancelled = [this]() {
150#ifdef __EMSCRIPTEN__
151 // The web build has no worker thread, so periodically service the dialog and
152 // cancellation button while simulation runs cooperatively on the GUI thread.
153 QApplication::processEvents();
154#endif
156 };
157
158 simulator = std::make_unique<SILICON::simulation::Session>(
159 circuit, isCancelled, scene.circuitResolver());
160 configureSimulatorTrace(trace, traceFile);
161 return settleInteractiveSimulation(*simulator, isCancelled);
162 });
163
164 return true;
165}
166
168{
170
171 for (auto* item : scene.items()) {
172 if (auto* io = category_cast<GraphicalIO>(item, ItemCategory::IO)) {
173 QObject::disconnect(io, &GraphicalIO::inputToggled, &scene,
175 io->resetSimulationState();
176 }
177 }
178
179 simulator.reset();
180 scene.setCircuit(nullptr);
181
182 // Clear bus states to reset visual wire colors
183 for (const auto& wire : scene.getWireManager().wires())
184 wire->clearBusState();
185
186 scene.update();
187}
188
190 const BusValue& value,
191 Component_weakPtr source)
192{
193 if (!simulator || !isJobFinished())
194 return;
195
196 startJob([this, targetBus = std::move(targetBus), value,
197 source = std::move(source)]() mutable {
198 const auto isCancelled = [this]() {
199#ifdef __EMSCRIPTEN__
200 // Keep the synchronous WebAssembly fallback responsive at cancellation points.
201 QApplication::processEvents();
202#endif
204 };
205
206 auto result = simulator->setBus(std::move(targetBus), value, source, isCancelled);
208 return result;
209 return settleInteractiveSimulation(*simulator, isCancelled);
210 });
211}
212
214 std::optional<std::string> fileName)
215{
216 if (!isJobFinished())
217 return;
218
219 fstTraceFile = std::move(fileName);
220
221 if (!simulator || !isJobFinished())
222 return;
223
225}
226
228{
229 for (auto* item : scene.items()) {
230 auto* output = category_cast<GraphicalIO>(item, OUTPUT_CATEGORY);
231 if (!output)
232 continue;
233
234 if (auto* out = dynamic_cast<GraphicalOutputSingle*>(output)) {
235 if (!out->getComponent())
236 continue;
237
238 auto bus = out->getComponent()->getInputs()[0];
239
241 if (bus.isInErrorState())
242 s = State::ERROR;
243 else if (!bus.hasUnknowns())
244 s = std::ranges::any_of(bus.getCurrentValue(),
245 [](const State st) { return st == State::HIGH; })
247 : State::LOW;
248
249 out->setState(s);
250 } else if (auto* busOut = dynamic_cast<GraphicalBusOutput*>(output)) {
251 if (!busOut->getComponent() || busOut->getComponent()->getInputs().empty())
252 continue;
253
254 busOut->setBusState(busOut->getComponent()->getInputs()[0]);
255 }
256 }
257}
258
260{
261 scene.waveformTraceReset({}, 0, {});
262}
263
265 const qulonglong duration, std::vector<Sample> inputSnapshots)
266{
267 if (!isJobFinished())
268 return;
269
270 if (!scene.calculateWiresForComponents())
271 return;
272
273 for (const auto& wire : scene.getWireManager().wires())
274 wire->clearBusState();
275
276 std::vector<GraphicalIO*> inputs;
277 std::vector<GraphicalIO*> outputs;
278 Component_set coreComps;
279
280 for (auto* item : scene.items()) {
281 if (auto* input = category_cast<GraphicalIO>(item, INPUT_CATEGORY))
282 inputs.push_back(input);
283 else if (auto* output = category_cast<GraphicalIO>(item, OUTPUT_CATEGORY))
284 outputs.push_back(output);
285
286 if (const auto* component =
288 component && component->getComponent()) {
289 coreComps.insert(component->getComponent());
290 }
291 }
292
293 const auto byPosition = [](const auto* a, const auto* b) {
294 if (a->scenePos().y() != b->scenePos().y())
295 return a->scenePos().y() < b->scenePos().y();
296 return a->scenePos().x() < b->scenePos().x();
297 };
298
299 std::ranges::sort(inputs, byPosition);
300 std::ranges::sort(outputs, byPosition);
301
302 for (auto* output : outputs)
303 output->resetSimulationState();
304
305 std::vector<Simulator::WaveformInputDriver> inputDrivers;
306 inputDrivers.reserve(inputs.size());
307 for (auto* input : inputs) {
308 const auto component = input->getComponent();
309 if (!component || component->getOutputs().empty())
310 continue;
311 inputDrivers.push_back({component->getOutputs()[0], component->weak_from_this()});
312 }
313
314 scene.setCircuit(std::make_shared<Circuit>(coreComps, false));
315 auto trace = collectTraceConfiguration();
316 resetTrace(trace);
317 const auto circuit = scene.getCircuit();
318 const auto traceFile = fstTraceFile;
319
320 startJob([this, circuit, trace = std::move(trace), traceFile,
321 inputDrivers = std::move(inputDrivers), duration,
322 inputSnapshots = std::move(inputSnapshots)]() mutable {
323 const auto isCancelled = [this]() {
324#ifdef __EMSCRIPTEN__
325 QApplication::processEvents();
326#endif
328 };
329
330 simulator = std::make_unique<SILICON::simulation::Session>(
331 circuit, isCancelled, scene.circuitResolver());
332 configureSimulatorTrace(trace, traceFile);
333
334 return simulator->simulateWaveform(duration, inputSnapshots, inputDrivers,
335 isCancelled);
336 });
337}
338
340{
341 if (!simulator)
342 return;
343
344 auto trace = collectTraceConfiguration();
345 resetTrace(trace);
347 if (!pendingWaveformSnapshots.isEmpty()) {
348 // Trace configuration can emit an immediate snapshot outside a worker job.
349 scene.waveformTraceSnapshots(std::move(pendingWaveformSnapshots));
351 }
352}
353
355{
356 QStringList names;
357 names.reserve(static_cast<qsizetype>(trace.buses.size()));
358 for (const auto& [name, bus] : trace.buses) {
359 Q_UNUSED(bus);
360 names.push_back(QString::fromStdString(name));
361 }
362 scene.waveformTraceReset(names, trace.inputCount, trace.widths);
363}
364
366 const TraceConfiguration& trace, const std::optional<std::string>& traceFile)
367{
368 simulator->setTraceBuses(trace.buses);
369 simulator->setTraceSink([this](uint64_t time, const std::vector<BusValue>& values) {
370 // Collect snapshots on the worker instead of posting one GUI event per timestamp.
371 // finishJob() publishes the completed batch after joining the worker.
372 pendingWaveformSnapshots.emplaceBack(time, values);
373 });
374
375 if (!traceFile) {
376 simulator->setFstWriter(nullptr);
377 return;
378 }
379
380 simulator->setFstWriter(std::make_unique<CircuitWriter>(
381 *traceFile, trace.buses, CircuitWriter::Options{}));
382}
383
385{
386 if (!isJobFinished())
387 return;
388
389 // 1. Reset job state
390 setJobFinished(false);
392 jobException = nullptr;
394
395 // 2. Prepare progress dialog, polling timers, and lock the view
396 setupJobUI();
397
398 // 3. Wrap the job to handle exceptions and state completion safely
399 auto executeAndCatch = [this, job = std::move(job)]() {
400 try {
401 jobResult = job();
402 } catch (...) {
403 jobException = std::current_exception();
404 }
405 setJobFinished(true);
406 };
407
408 // 4. Dispatch the job
409#ifdef __EMSCRIPTEN__
410 // Emscripten keeps the existing non-threaded build; cancellation remains cooperative.
411 progressDialog->open();
412 executeAndCatch();
413 finishJob();
414#else
415 // Desktop simulation mutates only core objects asynchronously.
416 worker = std::jthread(std::move(executeAndCatch));
417#endif
418}
419
421{
422 for (auto* view : scene.views())
423 view->setEnabled(false);
424
425 // Create and operate all Qt objects on the GUI thread.
426 auto* parent = scene.views().isEmpty() ? nullptr : scene.views().first()->window();
427 progressDialog = new QProgressDialog(QObject::tr("Simulation is running..."),
428 QObject::tr("Cancel"), 0, 0, parent);
429 progressDialog->setWindowTitle(QObject::tr("Simulation"));
430 progressDialog->setWindowModality(Qt::WindowModal);
431 progressDialog->setAutoClose(false);
432 progressDialog->setAutoReset(false);
433
434 QObject::connect(progressDialog, &QProgressDialog::canceled, &scene,
435 [this]() { requestJobCancellation(); });
436
437 completionTimer = new QTimer(&scene);
438 completionTimer->setInterval(25);
439 QObject::connect(completionTimer, &QTimer::timeout, &scene, [this]() {
440 if (isJobFinished())
441 finishJob();
442 });
443 completionTimer->start();
444
445 dialogTimer = new QTimer(&scene);
446 dialogTimer->setSingleShot(true);
447 dialogTimer->setInterval(300);
448 QObject::connect(dialogTimer, &QTimer::timeout, &scene, [this]() {
450 progressDialog->open();
451 });
452 dialogTimer->start();
453}
454
456{
457 if (!isJobFinished())
458 return;
459
460 // Reassigning to an empty jthread implicitly joins to guarantee the worker is cleanly
461 // stopped
462#ifndef __EMSCRIPTEN__
463 worker = std::jthread{};
464#endif
465
466 if (!pendingWaveformSnapshots.isEmpty()) {
467 // Deliver one batch after the join so the viewer never observes
468 // concurrently-mutated sample data and the event loop is not flooded by individual
469 // timestamps.
470 scene.waveformTraceSnapshots(std::move(pendingWaveformSnapshots));
472 }
473
474 // Use deferred deletion to prevent access violations if events are still pending in
475 // the queue
476 if (completionTimer) {
477 completionTimer->stop();
478 completionTimer->deleteLater();
479 completionTimer = nullptr;
480 }
481 if (dialogTimer) {
482 dialogTimer->stop();
483 dialogTimer->deleteLater();
484 dialogTimer = nullptr;
485 }
486 if (progressDialog) {
487 progressDialog->close();
488 progressDialog->deleteLater();
489 progressDialog = nullptr;
490 }
491
492 for (auto* view : scene.views())
493 view->setEnabled(true);
495 scene.update();
496
497 if (!jobException)
498 return;
499
500 try {
501 std::rethrow_exception(jobException);
502 } catch (const std::exception& error) {
503 simulationUiLog.error(std::format("Simulation failed: {}", error.what()));
504 } catch (...) {
505 simulationUiLog.error("Simulation failed with an unknown error");
506 }
507 jobException = nullptr;
508}
509
511{
512 // Teardown must outlive the worker because its callbacks capture controller state.
513 if (!isJobFinished())
515
516#ifndef __EMSCRIPTEN__
517 // Assigning an empty std::jthread forces a block and automatically joins the active
518 // worker
519 worker = std::jthread{};
520#endif
521
522 setJobFinished(true);
523 finishJob();
524}
525
527{
528 return jobFinished.load(std::memory_order_acquire);
529}
530
532{
533 jobFinished.store(finished, std::memory_order_release);
534}
535
537{
538 return jobCancellationRequested.load(std::memory_order_acquire);
539}
540
542{
543 jobCancellationRequested.store(true, std::memory_order_release);
544}
545
547{
548 jobCancellationRequested.store(false, std::memory_order_release);
549}
550
553{
554 std::vector<GraphicalIO*> inputs;
555 std::vector<GraphicalIO*> outputs;
556
557 for (auto* item : scene.items()) {
558 if (auto* input = category_cast<GraphicalIO>(item, INPUT_CATEGORY)) {
559 inputs.push_back(input);
560 } else if (auto* output = category_cast<GraphicalIO>(item, OUTPUT_CATEGORY)) {
561 outputs.push_back(output);
562 }
563 }
564
565 const auto byPosition = [](const auto* a, const auto* b) {
566 if (a->scenePos().y() != b->scenePos().y())
567 return a->scenePos().y() < b->scenePos().y();
568 return a->scenePos().x() < b->scenePos().x();
569 };
570
571 std::ranges::sort(inputs, byPosition);
572 std::ranges::sort(outputs, byPosition);
573
574 TraceConfiguration trace;
575 trace.buses.reserve(inputs.size() + outputs.size());
576
577 for (const auto& [index, input] : inputs | SILICON::views::enumerate) {
578 const auto component = input->getComponent();
579 if (component && !component->getOutputs().empty()) {
580 trace.buses.emplace_back(
581 componentNameOr(component, QString("input_%1").arg(index).toStdString()),
582 component->getOutputs()[0]);
583 trace.widths.push_back(static_cast<int>(component->getOutputs()[0].size()));
584 ++trace.inputCount;
585 }
586 }
587
588 for (const auto& [index, output] : outputs | SILICON::views::enumerate) {
589 const auto component = output->getComponent();
590 if (component && !component->getInputs().empty()) {
591 trace.buses.emplace_back(
592 componentNameOr(component, QString("output_%1").arg(index).toStdString()),
593 component->getInputs()[0]);
594 trace.widths.push_back(static_cast<int>(component->getInputs()[0].size()));
595 }
596 }
597
598 return trace;
599}
600
601} // namespace SILICON::ui
Simulator::RunResult runUntilIdle(Simulator::CancellationCheck isCancelled={})
Runs pending simulation events until the runtime circuit is idle.
Simulator::RunResult run(uint64_t duration, Simulator::CancellationCheck isCancelled={})
Runs the active simulation for a bounded duration.
std::function< bool()> CancellationCheck
Framework-independent cooperative cancellation callback.
Definition simulator.hpp:89
RunResult
Outcome of a cancellable simulator operation.
Definition simulator.hpp:92
void resetTrace(const TraceConfiguration &trace)
Rebuilds the waveform viewer's signal-name configuration.
void setupJobUI()
Configures progress dialog, timers, and locks the views before a job.
std::optional< std::string > fstTraceFile
Optional output file used for live FST tracing.
void cancelAndWait()
Requests cancellation and waits for the active job before teardown.
void setFstTraceFile(std::optional< std::string > fileName)
Enables or disables FST tracing for the active simulation session.
void clearWaveformTrace()
Clears waveform state after the scene has been fully emptied.
DiagramSceneSimulationController(DiagramScene &scene)
Constructs a simulation controller bound to a scene.
void refreshGraphicalOutputs()
Refreshes the visual state of all graphical outputs from bus values.
DiagramScene & scene
Host scene that owns the graphical items and Qt signals.
void exitSimulationMode()
Leaves interactive simulation mode and clears runtime state.
Simulator::RunResult jobResult
Result produced by the latest simulation operation.
QTimer * completionTimer
GUI timer that detects job completion without blocking the event loop.
void handleInputToggled(Bus targetBus, const BusValue &value, Component_weakPtr source)
Applies a user input toggle to the running simulator.
void setJobFinished(bool finished)
Publishes whether the active job has completed.
std::unique_ptr< SILICON::simulation::Session > simulator
Runtime simulation session active only during simulation mode.
void finishJob()
Finalizes a completed job on the GUI thread.
std::exception_ptr jobException
Exception captured during a job and reported on the GUI thread.
void refreshTraceConfiguration()
Refreshes waveform, simulator, and FST tracing from one scene snapshot.
bool isJobCancellationRequested() const
Returns whether cancellation has been requested for the active job.
bool enterSimulationMode()
Enters interactive simulation mode for the scene.
void configureSimulatorTrace(const TraceConfiguration &trace, const std::optional< std::string > &traceFile)
Applies trace buses, snapshot collection, and optional FST output.
void startJob(std::function< Simulator::RunResult()> job)
Starts one cancellable simulation operation and its progress UI.
QTimer * dialogTimer
GUI timer that prevents the progress dialog flashing for short jobs.
std::atomic_bool jobCancellationRequested
Platform-agnostic thread-safe job state.
void resetJobCancellation()
Clears cancellation state before starting a job.
TraceConfiguration collectTraceConfiguration() const
Collects ordered trace buses and their input count.
QList< QPair< qulonglong, std::vector< BusValue > > > pendingWaveformSnapshots
Worker-produced snapshots delivered to the viewer as one GUI batch.
void simulateEditedWaveform(qulonglong duration, std::vector< Sample > inputSnapshots)
Runs the circuit from an edited input waveform and publishes output trace.
bool isJobFinished() const
Returns whether the active job has completed.
void requestJobCancellation()
Publishes a cancellation request for the active job.
QProgressDialog * progressDialog
Delayed cancellation dialog for long-running jobs.
~DiagramSceneSimulationController()
Destroys the controller and releases any simulator resources.
Graphics scene for the circuit diagram editor.
void handleInputToggled(Bus targetBus, BusValue value, Component_weakPtr source)
Handles input toggle events from GraphicalInput components.
Represents a multi-bit data bus display output in the UI.
void inputToggled(Bus targetBus, BusValue value, Component_weakPtr source)
Emitted when an input component changes its state.
Represents a single-bit display output in the UI (e.g., an LED indicator).
TraceWriter::Options Options
FST file metadata and hierarchy options shared with TraceWriter.
std::shared_ptr< Component > Component_ptr
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< State > BusValue
Definition wire.hpp:120
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60