29#include <QApplication>
30#include <QGraphicsItem>
31#include <QGraphicsView>
33#include <QProgressDialog>
50using namespace SILICON::core;
51using namespace SILICON::simulation;
52using namespace SILICON::waveform;
53using namespace SILICON::waveform::fst;
59const SILICON::logging::Logger simulationUiLog(
"simulation-ui");
61std::string componentNameOr(
const Component_ptr& component,
const std::string& fallback)
66 const auto property = component->getProperty(
"name");
70 if (
const auto* name = std::get_if<std::string>(&*property); name && !name->empty())
77settleInteractiveSimulation(SILICON::simulation::Session& simulator,
81 if (result != Simulator::RunResult::Completed)
86 return simulator.
run(1, isCancelled);
103 if (!
scene.calculateWiresForComponents())
107 for (
const auto& wire :
scene.getWireManager().wires())
108 wire->clearBusState();
110 std::vector<GraphicalIO*> inputs;
111 std::vector<GraphicalIO*> outputs;
114 for (
auto* item :
scene.items()) {
116 inputs.push_back(input);
118 outputs.push_back(output);
120 if (
const auto* component =
122 component && component->getComponent()) {
123 coreComps.insert(component->getComponent());
130 for (
auto* output : outputs)
131 output->resetSimulationState();
134 for (
auto* input : inputs) {
135 input->applyStartValue();
141 scene.setCircuit(std::make_shared<Circuit>(coreComps,
false));
145 const auto circuit =
scene.getCircuit();
148 startJob([
this, circuit, trace = std::move(trace), traceFile]()
mutable {
149 const auto isCancelled = [
this]() {
153 QApplication::processEvents();
158 simulator = std::make_unique<SILICON::simulation::Session>(
159 circuit, isCancelled,
scene.circuitResolver());
161 return settleInteractiveSimulation(*
simulator, isCancelled);
171 for (
auto* item :
scene.items()) {
175 io->resetSimulationState();
180 scene.setCircuit(
nullptr);
183 for (
const auto& wire :
scene.getWireManager().wires())
184 wire->clearBusState();
196 startJob([
this, targetBus = std::move(targetBus), value,
197 source = std::move(source)]()
mutable {
198 const auto isCancelled = [
this]() {
201 QApplication::processEvents();
206 auto result =
simulator->setBus(std::move(targetBus), value, source, isCancelled);
209 return settleInteractiveSimulation(*
simulator, isCancelled);
214 std::optional<std::string> fileName)
229 for (
auto* item :
scene.items()) {
235 if (!out->getComponent())
238 auto bus = out->getComponent()->getInputs()[0];
241 if (bus.isInErrorState())
243 else if (!bus.hasUnknowns())
244 s = std::ranges::any_of(bus.getCurrentValue(),
245 [](
const State st) { return st == State::HIGH; })
251 if (!busOut->getComponent() || busOut->getComponent()->getInputs().empty())
254 busOut->setBusState(busOut->getComponent()->getInputs()[0]);
261 scene.waveformTraceReset({}, 0, {});
265 const qulonglong duration, std::vector<Sample> inputSnapshots)
270 if (!
scene.calculateWiresForComponents())
273 for (
const auto& wire :
scene.getWireManager().wires())
274 wire->clearBusState();
276 std::vector<GraphicalIO*> inputs;
277 std::vector<GraphicalIO*> outputs;
280 for (
auto* item :
scene.items()) {
282 inputs.push_back(input);
284 outputs.push_back(output);
286 if (
const auto* component =
288 component && component->getComponent()) {
289 coreComps.insert(component->getComponent());
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();
299 std::ranges::sort(inputs, byPosition);
300 std::ranges::sort(outputs, byPosition);
302 for (
auto* output : outputs)
303 output->resetSimulationState();
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())
311 inputDrivers.push_back({component->getOutputs()[0], component->weak_from_this()});
314 scene.setCircuit(std::make_shared<Circuit>(coreComps,
false));
317 const auto circuit =
scene.getCircuit();
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]() {
325 QApplication::processEvents();
330 simulator = std::make_unique<SILICON::simulation::Session>(
331 circuit, isCancelled,
scene.circuitResolver());
334 return simulator->simulateWaveform(duration, inputSnapshots, inputDrivers,
357 names.reserve(
static_cast<qsizetype
>(trace.
buses.size()));
358 for (
const auto& [name, bus] : trace.
buses) {
360 names.push_back(QString::fromStdString(name));
369 simulator->setTraceSink([
this](uint64_t time,
const std::vector<BusValue>& values) {
380 simulator->setFstWriter(std::make_unique<CircuitWriter>(
399 auto executeAndCatch = [
this, job = std::move(job)]() {
416 worker = std::jthread(std::move(executeAndCatch));
422 for (
auto* view :
scene.views())
423 view->setEnabled(
false);
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);
462#ifndef __EMSCRIPTEN__
492 for (
auto* view :
scene.views())
493 view->setEnabled(
true);
502 }
catch (
const std::exception& error) {
503 simulationUiLog.error(std::format(
"Simulation failed: {}", error.what()));
505 simulationUiLog.error(
"Simulation failed with an unknown error");
516#ifndef __EMSCRIPTEN__
528 return jobFinished.load(std::memory_order_acquire);
533 jobFinished.store(finished, std::memory_order_release);
554 std::vector<GraphicalIO*> inputs;
555 std::vector<GraphicalIO*> outputs;
557 for (
auto* item :
scene.items()) {
559 inputs.push_back(input);
561 outputs.push_back(output);
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();
571 std::ranges::sort(inputs, byPosition);
572 std::ranges::sort(outputs, byPosition);
575 trace.
buses.reserve(inputs.size() + outputs.size());
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()));
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()));
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.
RunResult
Outcome of a cancellable simulator operation.
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.
std::atomic_bool jobFinished
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.
std::jthread worker
Native worker synchronization.
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).
std::shared_ptr< Component > Component_ptr
std::set< Component_ptr, std::owner_less< Component_ptr > > Component_set
std::weak_ptr< Component > Component_weakPtr
std::vector< State > BusValue
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Ordered buses and group metadata used by waveform tracing.
std::vector< CircuitWriter::NamedBus > buses