wiRedPanda
Logic Circuit Simulator
Loading...
Searching...
No Matches
GraphicElement.h
Go to the documentation of this file.
1// Copyright 2015 - 2026, GIBIS-UNIFESP and the wiRedPanda contributors
2// SPDX-License-Identifier: GPL-3.0-or-later
3
7
8#pragma once
9
10#include <memory>
11#include <utility>
12
13#include <QBitArray>
14#include <QGraphicsItem>
15#include <QKeySequence>
16#include <QList>
17
18#include "App/Core/Enums.h"
19#include "App/Core/ItemWithId.h"
26
29
30class GraphicElement;
31class InputPort;
32class OutputPort;
33class Port;
34class QPainter;
35class QStyleOptionGraphicsItem;
36class QSvgRenderer;
37class QWidget;
38
58class GraphicElement : public QGraphicsObject, public ItemWithId
59{
60 Q_OBJECT
61public:
62 // --- Type Info ---
63
64 enum { Type = QGraphicsItem::UserType + 3 };
65
67 int type() const override { return Type; }
68
69 // --- Lifecycle ---
70
72 explicit GraphicElement(ElementType type, QGraphicsItem *parent = nullptr);
73
75 ~GraphicElement() override;
76
77signals:
83
84public:
85 // --- External file dependencies ---
86
89 virtual QStringList externalFiles() const;
90
91 // --- Serialization ---
92
96 virtual void save(QDataStream &stream, SerializationOptions options) const;
97
102 virtual void load(QDataStream &stream, SerializationContext &context);
103
104 // --- Port Management ---
105
113 virtual void updatePortsProperties();
114
121 virtual WirelessMode wirelessMode() const;
122
128 virtual bool hasWirelessMode() const;
129
130 // --- Element Type & Identity ---
131
134
136 ElementType elementType() const;
137
138 // --- Port Access ---
139
141 InputPort *inputPort(const int index = 0) const;
142
144 OutputPort *outputPort(const int index = 0) const;
145
147 const QVector<InputPort *> &inputs() const;
148
150 const QVector<OutputPort *> &outputs() const;
151
153 QVector<Port *> allPorts() const;
154
156 int inputSize() const;
157
159 int outputSize() const;
160
161 // --- Port Size Constraints ---
162
164 int maxInputSize() const;
165
167 int minInputSize() const;
168
170 int maxOutputSize() const;
171
173 int minOutputSize() const;
174
175 // --- Labeling ---
176
178 QString label() const;
179
181 void setLabel(const QString &label);
182
184 void updateLabel();
185
187 bool hasLabel() const;
188
192 QRectF labelSceneBoundingRect() const;
193
194 // --- Embedded IC ---
195
197 virtual bool isEmbedded() const { return false; }
198
200 virtual const QString &blobName() const { static const QString empty; return empty; }
201
202 // --- Trigger Control ---
203
205 QKeySequence trigger() const;
206
208 void setTrigger(const QKeySequence &trigger);
209
211 bool hasTrigger() const;
212
213 // --- Audio Properties ---
214
216 virtual QString audio() const;
217
219 virtual void setAudio(const QString &audio);
220
222 bool hasAudio() const;
223
225 bool hasAudioBox() const;
226
228 bool hasVolume() const;
229
231 virtual float volume() const;
232
234 virtual void setVolume(float vol);
235
236 // --- Color Properties ---
237
239 virtual QString color() const;
240
242 virtual void setColor(const QString &color);
243
245 bool hasColors() const;
246
248 static int colorNameToIndex(const QString &color);
249
251 QString nextColor() const;
252
254 QString previousColor() const;
255
256 // --- Frequency & Delay ---
257
259 virtual double frequency() const;
260
262 virtual double delay() const;
263
265 bool hasFrequency() const;
266
268 bool hasDelay() const;
269
271 virtual void setFrequency(const double freq);
272
274 virtual void setDelay(const double delay);
275
281 QList<PropertyDescriptor> editableProperties() const;
282
283 // --- Appearance Management ---
284
286 bool canChangeAppearance() const;
287
293 virtual void setAppearance(const bool defaultAppearance, const QString &fileName);
294
300 void setAppearanceAt(const int index, const QString &fileName);
301
307 virtual QList<std::pair<int, QString>> appearanceStates() const;
308
310 QPixmap appearancePreviewPixmap(const int index, const QSize &size) const;
311
313 void setPixmap(const QString &pixmapPath);
314
316 void setPixmap(const int index);
317
318 // --- Truth Table ---
319
321 bool hasTruthTable() const;
322
323 // --- Rotation ---
324
326 qreal rotation() const;
327
329 void setRotation(const qreal angle);
330
333 bool rotatesGraphic() const;
334
337 void rotatePorts();
338
343 void reapplyAppearanceOrientation() { m_appearance.applyOrientation(); updateLabelOrientation(); }
344
345 // --- Flip / Mirror ---
346
348 bool isFlippedX() const { return m_orientation.isFlippedX(); }
349
351 bool isFlippedY() const { return m_orientation.isFlippedY(); }
352
354 void setFlippedX(bool flipped);
355
357 void setFlippedY(bool flipped);
358
359 // --- Geometric Properties ---
360
362 QPointF pixmapCenter() const;
363
365 QRectF boundingRect() const override;
366
367 // --- State Queries ---
368
370 bool isValid();
371
372 // --- Direct Simulation Interface ---
373
378 virtual void updateLogic();
379
387 virtual void resetSimState();
388
398 virtual void resettleCombinational() { updateLogic(); }
399
401 inline Status outputValue(const int index = 0) const { return m_sim.outputValue(index); }
402
404 qsizetype simOutputSize() const { return m_sim.outputSize(); }
405
407 inline void setOutputValue(const int index, const Status value) { m_sim.setOutputValue(index, value); }
408
410 inline void setOutputValue(const Status value) { m_sim.setOutputValue(0, value); }
411
413 void setOutputValue(const int index, const bool value) { m_sim.setOutputValue(index, value ? Status::Active : Status::Inactive); }
414
416 void setOutputValue(const bool value) { m_sim.setOutputValue(0, value ? Status::Active : Status::Inactive); }
417
419 void connectPredecessor(const int inputIndex, GraphicElement *source, const int outputPort);
420
423 bool outputChanged() const { return m_sim.outputChanged(); }
424
426 void clearOutputChanged() { m_sim.clearOutputChanged(); }
427
430 void beginDeferredCommit() { m_sim.beginDeferredCommit(); }
431
434 void commitDeferredOutputs() { m_sim.commitDeferredOutputs(); }
435
437 void initSimulationVectors(const int inputCount, const int outputCount);
438
440 virtual void loadFromDrop(const QString &fileName, const QString &contextDir);
441
442 // --- Virtual Methods ---
443
445 virtual QString genericProperties();
446
448 virtual void refresh();
449
450 // --- Qt Graphics & Display ---
451
460 void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
461
467 void retranslate();
468
469 // --- Setters (Port & Logic Configuration) ---
470
472 virtual void setInputSize(const int size);
473
475 virtual void setOutputSize(const int size);
476
478 void setInputs(const QVector<InputPort *> &inputs);
479
481 void setPortName(const QString &name);
482
484 const QVector<Status> &simInputs() const { return m_sim.inputs(); }
485
487 const QVector<Status> &simOutputs() const { return m_sim.outputs(); }
488
489 // --- Theme ---
490
492 virtual void updateTheme();
493
494protected:
495 // --- Graphics & Rendering ---
496
498 QPixmap pixmap() const;
499
506 QRectF portsBoundingRect() const;
507
516 QRectF renderBodyBounds() const;
517
522 void setLabelAnchor(const QPointF &pos);
523
526 virtual void labelContentChanged() {}
527
528 // --- Qt Event Handling ---
529
541 QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
542
550 void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
551
559 bool sceneEvent(QEvent *event) override;
560
561 // --- Capability Setters ---
562
564 void setHasColors(const bool hasColors);
565
566 // --- Port Size Constraint Setters ---
567
569 void setMaxInputSize(const int maxInputSize);
570
572 void setMinInputSize(const int minInputSize);
573
575 void setMaxOutputSize(const int maxOutputSize);
576
578 void setMinOutputSize(const int minOutputSize);
579
583
587
588 QGraphicsSimpleTextItem *m_label = new QGraphicsSimpleTextItem(this);
590
591 // --- Members: Metadata ---
592
593 QString m_titleText;
595
596 // --- Direct Simulation Helpers ---
597
609 bool simUpdateInputs() { return m_sim.updateInputs(false, m_ports.inputs()); }
610
618 bool simUpdateInputsAllowUnknown() { return m_sim.updateInputs(true, m_ports.inputs()); }
619
627 int decodeSelectValue(int offset, int count) const { return m_sim.decodeSelectValue(offset, count); }
628
629private:
630 Q_DISABLE_COPY_MOVE(GraphicElement)
631
632
635
639 friend class ElementAppearance;
640
646 void invalidateRenderCache();
647
648 // --- Port Management Helpers ---
649
652 void setPortSize(const int size, const bool isInput);
653
654 // --- Display & Interaction ---
655
662 void highlight(const bool isSelected);
663
667 void updateLabelOrientation();
668
669 // --- Members: Element Type & Identity ---
670
671 ElementGroup m_elementGroup = ElementGroup::Unknown;
672 ElementType m_elementType = ElementType::Unknown;
673
677 const ElementMetadata &m_metadata;
678
679 // --- Members: Direct Simulation ---
680
683 ElementSimState m_sim;
684
685 // --- Members: Trigger & Label ---
686
687 QKeySequence m_trigger;
688 QString m_labelText;
689
690 // --- Members: Capabilities & Display State ---
691
692 bool m_hasColors = false;
693 bool m_selected = false;
694
698 ElementOrientation m_orientation{this};
699
700 // --- Members: Port Size Constraints ---
701
702 quint64 m_minInputSize = 0;
703 quint64 m_maxInputSize = 0;
704 quint64 m_minOutputSize = 0;
705 quint64 m_maxOutputSize = 0;
706};
Owns a GraphicElement's pixmap / SVG appearance, appearance list, and selection paint.
Element metadata struct and global registry for compile-time element registration.
Owns a GraphicElement's rotation angle and flip (mirror) state.
Owns a GraphicElement's input/output port vectors and their creation/resize lifecycle.
Per-element simulation runtime state (input/output values and the connection graph).
Central enumeration types for element types, groups, and signal status.
Enums::ElementType ElementType
Definition Enums.h:107
Enums::Status Status
Definition Enums.h:106
Enums::WirelessMode WirelessMode
Definition Enums.h:109
Enums::ElementGroup ElementGroup
Definition Enums.h:108
Defines ItemWithId, the base class for all uniquely identified circuit items.
PropertyDescriptor struct for describing editable element properties.
Owns the rotation angle and flip flags of a GraphicElement, and the transform math that applies them ...
Owns the input and output Port vectors of a GraphicElement and the primitives that create,...
Owns a GraphicElement's simulation runtime state, decoupled from its graphics.
Abstract base class for all graphical circuit elements in wiRedPanda.
void setOutputValue(const bool value)
Convenience overload — converts bool to Active/Inactive for port 0.
virtual void updateLogic()
Computes this element's output values from its current inputs.
QPointF pixmapCenter() const
Returns the centre point of the element's pixmap in local coordinates.
GraphicElement(ElementType type, QGraphicsItem *parent=nullptr)
Constructs a graphic element of the given type, fetching all properties from the metadata registry.
const QVector< Status > & simInputs() const
Read-only view of the cached simulation input values.
virtual void updateTheme()
Updates the element's visual theme according to the current dark/light palette.
void setFlippedY(bool flipped)
Sets the vertical mirror state and updates the item transform.
Status outputValue(const int index=0) const
Returns the four-state signal value on simulation output port index.
QPixmap appearancePreviewPixmap(const int index, const QSize &size) const
Returns a small preview pixmap for the appearance at index (see appearanceStates()).
QString m_translatedName
Translated element name used as tooltip and port object name.
virtual WirelessMode wirelessMode() const
Returns the wireless routing mode for this element.
virtual void setFrequency(const double freq)
Sets the clock frequency to freq (overridden by clock elements).
ElementType elementType() const
Returns the type identifier for this element.
int decodeSelectValue(int offset, int count) const
Decodes count select-line statuses from simInputs() into a binary index.
void setHasColors(const bool hasColors)
Sets whether this element type supports color selection.
void setFlippedX(bool flipped)
Sets the horizontal mirror state and updates the item transform.
bool hasDelay() const
Returns true if this element type exposes a configurable clock phase delay.
void clearOutputChanged()
Clears the simulation output-changed flag.
void commitDeferredOutputs()
virtual void setColor(const QString &color)
Sets the element color to color and refreshes the pixmap.
virtual QStringList externalFiles() const
ElementAppearance m_appearance
bool hasVolume() const
Returns true if this element type supports volume control.
virtual void setAudio(const QString &audio)
Sets the audio file associated with this element to audio.
virtual void resettleCombinational()
Re-evaluates combinational outputs after the synchronous sequential commit, propagating just-committe...
int inputSize() const
Returns the current number of input ports.
QList< PropertyDescriptor > editableProperties() const
Returns the list of editable properties this element exposes in the ElementEditor.
bool hasTruthTable() const
Returns true if this element type has an editable truth table.
qsizetype simOutputSize() const
Returns the number of simulation output slots.
bool hasAudioBox() const
Returns true if this element type shows an audio selection box.
void retranslate()
Updates the translated display name, tooltip, and port object name after a locale change.
qreal rotation() const
Returns the current rotation angle of this element in degrees.
void setRotation(const qreal angle)
Rotates the element to angle degrees and updates port positions.
bool isFlippedY() const
Returns true if this element is mirrored along the Y axis (vertical flip).
QRectF portsBoundingRect() const
Returns the bounding rectangle that encompasses all child ports.
QVector< Port * > allPorts() const
Returns a combined list of all input and output ports as Port pointers.
void setLabelAnchor(const QPointF &pos)
void inlineEditRequested(GraphicElement *element)
QPixmap pixmap() const
Returns the pixmap currently displayed by this element.
bool simUpdateInputsAllowUnknown()
Like simUpdateInputs(), but allows Unknown/Error values through.
bool outputChanged() const
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
Paints the element onto the scene.
void setOutputValue(const int index, const Status value)
Sets simulation output port index to value.
QRectF renderBodyBounds() const
Footprint of a "procedural render body" (IC/Mux/Demux/TruthTable): the nominal 64x64 body unioned wit...
QString label() const
Returns the user-visible label text for this element.
int maxOutputSize() const
Returns the maximum allowed number of output ports.
virtual QList< std::pair< int, QString > > appearanceStates() const
Returns the list of editable appearance states for this element. Each pair is (appearance list index,...
virtual void load(QDataStream &stream, SerializationContext &context)
Loads the graphic element through a binary data stream.
void setTrigger(const QKeySequence &trigger)
Sets the keyboard shortcut to trigger and updates the label.
InputPort * inputPort(const int index=0) const
Returns the input port at index (default 0).
virtual bool isEmbedded() const
Returns true if this element is an embedded IC (not file-backed). Base returns false.
virtual void loadFromDrop(const QString &fileName, const QString &contextDir)
Polymorphic interface for drag-drop initialization (replaces elementType() == IC checks).
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override
Requests inline label editing on double-click.
void setAppearanceAt(const int index, const QString &fileName)
Sets a custom appearance at a specific index in the appearance list.
int minInputSize() const
Returns the minimum allowed number of input ports.
void setInputs(const QVector< InputPort * > &inputs)
Replaces the input port vector with inputs.
friend class GraphicElementSerializer
virtual QString audio() const
Returns the name of the audio file currently associated with this element.
bool hasLabel() const
Returns true if this element type supports a user-editable label.
virtual double delay() const
Returns the clock phase delay in seconds (overridden by Clock; returns 0 for other elements).
virtual void setInputSize(const int size)
Adjusts the number of input ports to size, adding or removing ports as needed.
void setOutputValue(const Status value)
Sets simulation output port 0 to value.
virtual double frequency() const
Returns the clock frequency in Hz (overridden by Clock; returns 0 for other elements).
~GraphicElement() override
Out-of-line so the unique_ptr to the forward-declared QSvgRenderer can be destroyed.
QKeySequence trigger() const
Returns the keyboard shortcut that activates this element.
friend class ElementAppearance
void setLabel(const QString &label)
Sets the label text to label and refreshes the display.
void updateLabel()
Repositions and updates the label child item to reflect current state.
virtual QString color() const
Returns the name of the color currently applied to this element.
int outputSize() const
Returns the current number of output ports.
void beginDeferredCommit()
void initSimulationVectors(const int inputCount, const int outputCount)
Allocates simulation I/O vectors with inputs inputs and outputs outputs.
QGraphicsSimpleTextItem * m_label
Child text item that displays the label and optional trigger shortcut.
void setOutputValue(const int index, const bool value)
Convenience overload — converts bool to Active/Inactive for port index.
QRectF labelSceneBoundingRect() const
void reapplyAppearanceOrientation()
void setPortName(const QString &name)
Sets the object name of all ports to name for identification.
OutputPort * outputPort(const int index=0) const
Returns the output port at index (default 0).
QString m_titleText
Translated title text shown in UI panels (from metadata).
bool hasFrequency() const
Returns true if this element type exposes a configurable clock frequency.
QString nextColor() const
Returns the name of the next color in the element's color list.
static int colorNameToIndex(const QString &color)
Maps a color name ("White","Red","Green","Blue","Purple") to indices 0–4.
bool hasColors() const
Returns true if this element type supports color selection.
ElementGroup elementGroup() const
Returns the group this element belongs to.
bool simUpdateInputs()
Snapshots each predecessor's output into the simulation input cache.
int maxInputSize() const
Returns the maximum allowed number of input ports.
virtual void save(QDataStream &stream, SerializationOptions options) const
void setMaxInputSize(const int maxInputSize)
Sets the maximum number of input ports to maxInputSize.
QPointF m_labelAnchor
The label's intended anchor point in the element's un-rotated local frame; see setLabelAnchor().
const QVector< Status > & simOutputs() const
Read-only view of the current simulation output values.
virtual void setDelay(const double delay)
Sets the clock phase delay to delay (overridden by clock elements).
void setMaxOutputSize(const int maxOutputSize)
Sets the maximum number of output ports to maxOutputSize.
void setPixmap(const QString &pixmapPath)
Loads and applies the pixmap located at pixmapPath.
bool canChangeAppearance() const
Returns true if the user is allowed to choose a custom appearance for this element.
virtual void setAppearance(const bool defaultAppearance, const QString &fileName)
Switches the element's appearance.
int minOutputSize() const
Returns the minimum allowed number of output ports.
void connectPredecessor(const int inputIndex, GraphicElement *source, const int outputPort)
Connects simulation input inputIndex to output outputPort of source element.
bool isFlippedX() const
Returns true if this element is mirrored along the X axis (horizontal flip).
ElementPorts m_ports
virtual void resetSimState()
Resets all simulation-visible state to power-on defaults.
virtual QString genericProperties()
Returns a string encoding element-specific properties for serialization or display.
bool isValid()
Returns true if the element is fully initialised and connected correctly.
int type() const override
Returns the custom type identifier for this item.
virtual void setVolume(float vol)
Sets the audio playback volume to vol (0.0–1.0).
void setMinInputSize(const int minInputSize)
Sets the minimum number of input ports to minInputSize.
QRectF boundingRect() const override
Returns the bounding rectangle of this element in local coordinates.
const QVector< OutputPort * > & outputs() const
Returns a const reference to the vector of all output ports.
virtual void labelContentChanged()
virtual bool hasWirelessMode() const
Returns true if this element supports a configurable wireless routing mode.
virtual const QString & blobName() const
Returns the blob name for embedded ICs, empty string otherwise. Base returns empty.
virtual float volume() const
Returns the audio playback volume (0.0–1.0).
virtual void setOutputSize(const int size)
Adjusts the number of output ports to size, adding or removing ports as needed.
void setMinOutputSize(const int minOutputSize)
Sets the minimum number of output ports to minOutputSize.
QString previousColor() const
Returns the name of the previous color in the element's color list.
bool hasAudio() const
Returns true if this element type supports audio output.
bool sceneEvent(QEvent *event) override
Intercepts mouse-press and mouse-release events to handle Ctrl+click.
bool rotatesGraphic() const
virtual void updatePortsProperties()
Repositions and reconfigures all ports after the port count changes.
virtual void refresh()
Forces a visual refresh of the element's pixmap and ports.
bool hasTrigger() const
Returns true if this element type supports a keyboard trigger.
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
Handles item state changes such as position, rotation, and selection.
const QVector< InputPort * > & inputs() const
Returns a const reference to the vector of all input ports.
A port that receives a signal (the destination end of a wire).
Definition Port.h:229
ItemWithId()=default
Constructs a new ItemWithId with an unassigned ID of -1.
A port that drives a signal (the source end of a wire).
Definition Port.h:261
Abstract base class for circuit element ports (connection endpoints).
Definition Port.h:39
Compile-time-registered properties for one element type.
Bundles all per-deserialization state so that load() overrides receive it through one explicit parame...
Options passed to GraphicElement::save() (and friends); the save-side counterpart of SerializationCon...