36using namespace SILICON::core;
42constexpr int BUS_IO_PORT_X = 0;
45constexpr int BUS_IO_VALUE_TEXT_GAP = 8;
46constexpr int MAX_INLINE_VALUE_CHARACTERS = 18;
50constexpr std::string_view PORT_ORIENTATION_PROPERTY =
"portOrientation";
51constexpr std::string_view PORT_ORIENTATION_UP =
"UP";
52constexpr std::string_view PORT_ORIENTATION_DOWN =
"DOWN";
53constexpr std::string_view PORT_ORIENTATION_LEFT =
"LEFT";
54constexpr std::string_view PORT_ORIENTATION_RIGHT =
"RIGHT";
55constexpr std::string_view DEFAULT_PORT_ORIENTATION = PORT_ORIENTATION_DOWN;
58const QFont& getWidthFont()
60 static const QFont font(
"NovaMono", 8);
64QRectF busIoNameRect(
const QRectF&
shapeRect,
const QString& name)
67 const qreal
width = std::max<qreal>(
shapeRect.width(), metrics.horizontalAdvance(name));
68 const qreal height = metrics.height();
72QRectF busIoNameRect(
const QRectF&
shapeRect,
const QString& name,
const bool below)
74 QRectF rect = busIoNameRect(
shapeRect, name);
80int snapBusIoWidthToGrid(
const int width)
87int normalizedBusSize(
const int size)
89 return std::clamp(size, 1,
90 static_cast<int>(std::numeric_limits<unsigned short>::max()));
93QString compactValueText(QString value)
95 if (
value.size() <= MAX_INLINE_VALUE_CHARACTERS)
97 return value.left(9) + QStringLiteral(
"…") +
value.right(8);
101 const std::size_t fixedWidth = 0)
103 return compactValueText(QString::fromStdString(
formatValue(value, format, fixedWidth)));
108 const auto* diagramScene =
109 dynamic_cast<const DiagramScene*
>(item ? item->scene() :
nullptr);
112 == DiagramScene::InteractionMode::SIMULATION_MODE;
117enum class IoPortOrientation { Up, Down,
Left,
Right };
119class BusIoShape :
public QGraphicsItem {
121 BusIoShape(BusIoKind kind,
unsigned int busWidth, QGraphicsItem* parent =
nullptr)
122 : QGraphicsItem(parent), kind(kind), busWidth(busWidth)
127 QRectF boundingRect()
const override
130 return {-cachedWidth / 2.0, 0, cachedWidth, BUS_IO_HEIGHT};
133 void setBusWidth(
const unsigned int width)
135 if (busWidth == width)
137 prepareGeometryChange();
143 void setValueText(QString text)
145 if (valueText == text)
147 valueText = std::move(text);
151 void setDisplayState(
const State state)
153 displayState = state;
157 void paint(QPainter* painter,
const QStyleOptionGraphicsItem* ,
162 painter->setRenderHint(QPainter::Antialiasing,
false);
163 painter->setPen(QPen(ink, 3));
164 painter->setBrush(backgroundColor());
165 const QRectF body = boundingRect().adjusted(1.5, 1.5, -1.5, -1.5);
166 painter->drawRect(body);
168 painter->setPen(ink);
170 painter->drawText(QRectF(body.left() + BUS_IO_PADDING_X, 3,
171 body.width() - 2 * BUS_IO_PADDING_X - cachedWidthTextWidth
172 - BUS_IO_VALUE_TEXT_GAP,
174 Qt::AlignCenter, valueText);
176 painter->setFont(getWidthFont());
177 painter->drawText(QRectF(body.right() - BUS_IO_PADDING_X - cachedWidthTextWidth, 3,
178 cachedWidthTextWidth, 16),
179 Qt::AlignCenter, cachedWidthText);
183 void updateLayoutCache()
186 const QFontMetrics widthMetrics(getWidthFont());
188 cachedWidthText = QString(
"[%1]").arg(busWidth);
189 cachedWidthTextWidth = widthMetrics.horizontalAdvance(cachedWidthText);
191 const QString largestKnown =
194 : QStringLiteral(
"0xFFFFFFFF…FFFFFFFF");
195 const QString unknownBits(
static_cast<int>(std::min<unsigned int>(busWidth, 8)),
196 QLatin1Char(std::to_underlying(State::UNKNOWN)));
198 int maxAdvance = valueMetrics.horizontalAdvance(largestKnown);
199 for (
const QString& candidate :
200 {unknownBits, QStringLiteral(
"ERR"), QStringLiteral(
"BUS")}) {
201 maxAdvance = std::max(maxAdvance, valueMetrics.horizontalAdvance(candidate));
204 const int contentWidth =
205 2 * BUS_IO_PADDING_X + maxAdvance + BUS_IO_VALUE_TEXT_GAP + cachedWidthTextWidth;
206 cachedWidth = snapBusIoWidthToGrid(contentWidth);
209 QColor backgroundColor()
const
211 if (kind == BusIoKind::Input)
214 switch (displayState) {
224 unsigned int busWidth = 1;
225 QString valueText =
"0x0";
226 State displayState = State::UNKNOWN;
229 qreal cachedWidth = BUS_IO_MIN_WIDTH;
230 QString cachedWidthText;
231 int cachedWidthTextWidth = 0;
234class ConstantShape :
public QGraphicsItem {
236 QRectF boundingRect()
const override
238 return {0, 0,
static_cast<qreal
>(cachedWidth),
static_cast<qreal
>(CONSTANT_SIZE)};
241 void setValue(QString newValue)
243 if (value == newValue)
245 prepareGeometryChange();
246 value = std::move(newValue);
247 const QString label = displayValue();
256 void paint(QPainter* painter,
const QStyleOptionGraphicsItem* ,
261 painter->setRenderHint(QPainter::Antialiasing,
false);
262 painter->setPen(QPen(ink, 3));
264 painter->drawRect(boundingRect().adjusted(1.5, 1.5, -1.5, -1.5));
266 painter->setPen(ink);
268 painter->drawText(boundingRect(), Qt::AlignCenter, displayValue());
272 [[nodiscard]] QString displayValue()
const
274 return (value.size() > 1 ? QStringLiteral(
"0b") : QString()) + value.toUpper();
277 QString value = QStringLiteral(
"0");
278 int cachedWidth = CONSTANT_SIZE;
281ConstantShape* getConstantShape(QGraphicsItem* itemShape,
const char* context)
283 auto* shape =
dynamic_cast<ConstantShape*
>(itemShape);
284 Q_ASSERT_X(shape !=
nullptr, context,
"Constant item is missing its ConstantShape");
288BusIoShape* getBusIoShape(QGraphicsItem* itemShape,
const char* context)
290 auto* shape =
dynamic_cast<BusIoShape*
>(itemShape);
291 Q_ASSERT_X(shape !=
nullptr, context,
"Bus IO item is missing its BusIoShape");
295QRectF busIoNamedBounds(QGraphicsItem* itemShape,
const QString& name,
296 const QRectF& fallbackRect,
const bool nameBelow)
301 const auto* shape = getBusIoShape(itemShape,
"busIoNamedBounds");
305 return fallbackRect.united(busIoNameRect(shape->boundingRect(), name, nameBelow));
308IoPortOrientation parsePortOrientation(
const std::string_view orientation)
310 if (orientation == PORT_ORIENTATION_UP)
311 return IoPortOrientation::Up;
312 if (orientation == PORT_ORIENTATION_LEFT)
313 return IoPortOrientation::Left;
314 if (orientation == PORT_ORIENTATION_RIGHT)
315 return IoPortOrientation::Right;
316 return IoPortOrientation::Down;
319bool portNameBelongsBelowShape(
const std::string_view orientation)
321 return parsePortOrientation(orientation) == IoPortOrientation::Up;
324std::string currentPortOrientation(
const Component_ptr& component)
327 return std::string(DEFAULT_PORT_ORIENTATION);
329 return component->getPropertyValue<std::string>(PORT_ORIENTATION_PROPERTY)
330 .value_or(std::string(DEFAULT_PORT_ORIENTATION));
333QPoint ioPortPosition(
const QRectF&
shapeRect,
const IoPortOrientation orientation)
338 switch (orientation) {
339 case IoPortOrientation::Up:
341 case IoPortOrientation::Down:
343 case IoPortOrientation::Left:
345 case IoPortOrientation::Right:
351std::string_view portOrientationName(
const PortSide side)
370 new ConstantShape(), parent)
382 QPointer<GraphicalConstant> safeThis(
this);
385 "value", [safeThis, boundComponent](
const PropertyValue& value) {
386 auto component = boundComponent.lock();
388 const auto applied = constant ? constant->
setValue(std::get<BusValue>(value))
389 : std::get<BusValue>(value);
390 if (safeThis && safeThis->getComponent() == component)
391 safeThis->updateLayout(applied);
396 "size", [safeThis, boundComponent](
const PropertyValue& value) {
397 auto component = boundComponent.lock();
400 constant ? constant->
setSize(std::get<int>(value)) : std::get<int>(value);
401 if (safeThis && safeThis->getComponent() == component)
402 safeThis->updateLayout();
419 auto* shape = getConstantShape(
getItemShape(),
"GraphicalConstant::updateLayout");
423 prepareGeometryChange();
425 const QRectF bounds = shape->boundingRect();
427 {
PortPair{
"o", QPoint(
static_cast<int>(bounds.right()) + CONSTANT_PORT_EXTENSION,
428 static_cast<int>(bounds.center().y()))}});
439 QGraphicsItem* shape, QGraphicsItem* parent,
bool scanShape)
447 const auto nameProperty =
getComponent()->getProperty(
"name");
448 if (nameProperty.has_value()) {
449 if (
const auto* name = std::get_if<std::string>(&*nameProperty)) {
450 return QString::fromStdString(*name);
461 QPointer<GraphicalIO> safeThis(
this);
465 PORT_ORIENTATION_PROPERTY, [safeThis, boundComponent](
const PropertyValue& value) {
466 auto component = boundComponent.lock();
467 if (safeThis && safeThis->getComponent() == component) {
468 safeThis->prepareGeometryChange();
469 if (
const auto* orientation = std::get_if<std::string>(&value))
470 safeThis->updatePortOrientation(*orientation);
489 const QPoint position =
518 const QFontMetrics metrics(
UI_FONT);
519 const qreal width = std::max<qreal>(
shapeRect.width(), metrics.horizontalAdvance(name));
520 const qreal height = metrics.height();
523 return {x, y, width, height};
531 parsePortOrientation(portOrientationName(side)));
540 QRectF(portPosition - QPoint(1, 1), QSize(2, 2)));
548 std::string(portOrientationName(side)));
563 new
ThemedSvgItem(
":/other_components/input_off.svg"), parent)
570 prepareGeometryChange();
589 if (!isInteractiveSimulation(
this)) {
591 input->setState(state);
605 ->getPropertyValue<
BusValue>(
"startValue")
625 if (!name.isEmpty()) {
626 painter->drawText(
componentNameRect(name), Qt::AlignLeft | Qt::AlignVCenter, name);
639 return getComponent()->getOutputs()[0][0]->getCurrentState();
647 new BusIoShape(BusIoKind::
Input, 8), parent)
651 {
PortPair{
"bus", QPoint(BUS_IO_PORT_X, BUS_IO_PORT_Y)}});
665 QPointer<GraphicalBusInput> safeThis(
this);
674 safeThis->prepareGeometryChange();
679 "size", [safeThis, boundComponent](
const PropertyValue& value) {
680 const int normalizedSize = normalizedBusSize(std::get<int>(value));
681 auto component = boundComponent.lock();
683 busInput->setSize(normalizedSize);
687 if (safeThis && safeThis->getComponent() == component)
688 safeThis->setValue(safeThis->currentValue);
689 return normalizedSize;
693 "startValue", [safeThis, boundComponent](
const PropertyValue& value) {
694 const auto requestedValue = std::get<BusValue>(value);
695 const auto component = boundComponent.lock();
697 component ? component->getOutputs() :
decltype(component->getOutputs()){};
698 const auto width = outputs.empty() ? 1 : outputs[0].size();
699 if (requestedValue.empty() || std::ranges::contains(requestedValue,
State::ERROR))
700 throw std::invalid_argument(
"Bus input values must not contain ERROR");
701 const State extension =
702 requestedValue.size() == 1 && requestedValue.front() ==
State::UNKNOWN
705 const auto newValue =
710 if (safeThis && safeThis->getComponent() == component)
711 safeThis->setValue(newValue);
730 const auto width = outputs[0].size();
731 if (value.empty() || std::ranges::contains(value,
State::ERROR))
732 throw std::invalid_argument(
"Bus input values must not contain ERROR");
733 const State extension =
737 if (
auto* shape = getBusIoShape(
getItemShape(),
"GraphicalBusInput::setValue")) {
738 shape->setBusWidth(
static_cast<unsigned int>(width));
743 if (!isInteractiveSimulation(
this))
762 const size_t width = outputs[0].size();
763 const QString prompt =
764 QString(
"Set %1-bit bus value (decimal, 0x..., or 0b...)").arg(width);
766 const QPointer<GraphicalBusInput> safeThis(
this);
771 [safeThis, width](
const QString& text) {
784 "Bus Input",
"The value does not fit in the bus width.");
787 safeThis->setValue(*resized);
799 ->getPropertyValue<
BusValue>(
"startValue")
805 const auto width = outputs[0].size();
808 if (
auto* shape = getBusIoShape(
getItemShape(),
"GraphicalBusInput::applyStartValue")) {
809 shape->setBusWidth(
static_cast<unsigned int>(width));
827 const auto width =
getComponent()->getOutputs()[0].size();
829 getBusIoShape(
getItemShape(),
"GraphicalBusInput::refreshFromComponent")) {
830 shape->setBusWidth(
static_cast<unsigned int>(width));
841 if (!name.isEmpty()) {
842 if (
const auto* shape = getBusIoShape(
getItemShape(),
"GraphicalBusInput::paint")) {
844 Qt::AlignRight | Qt::AlignVCenter, name);
862 new
ThemedSvgItem(
":/other_components/output_unknown.svg"), parent)
869 prepareGeometryChange();
896 const QStyleOptionGraphicsItem* option, QWidget* widget)
900 if (!name.isEmpty()) {
901 painter->drawText(
componentNameRect(name), Qt::AlignLeft | Qt::AlignVCenter, name);
917 new BusIoShape(BusIoKind::
Output, 8), parent)
932 QPointer<GraphicalBusOutput> safeThis(
this);
938 safeThis->prepareGeometryChange();
943 "size", [safeThis, boundComponent](
const PropertyValue& value) {
944 const int normalizedSize = normalizedBusSize(std::get<int>(value));
945 auto component = boundComponent.lock();
947 busOutput->setSize(normalizedSize);
948 if (safeThis && safeThis->getComponent() == component)
949 safeThis->refreshFromComponent();
950 return normalizedSize;
964 if (
auto* shape = getBusIoShape(
getItemShape(),
"GraphicalBusOutput::setBusState")) {
965 shape->setBusWidth(
static_cast<unsigned int>(bus.
size()));
969 shape->setValueText(
"ERR");
976 const bool anyHigh = std::ranges::contains(value,
State::HIGH);
979 (bus.
size() + 3) / 4));
999 getBusIoShape(
getItemShape(),
"GraphicalBusOutput::resetSimulationState")) {
1003 :
static_cast<unsigned int>(
getComponent()->getInputs()[0].size());
1004 shape->setBusWidth(width);
1006 shape->setValueText(
1007 compactValueText(QString(width, QChar(std::to_underlying(
State::UNKNOWN)))));
1016 if (!name.isEmpty()) {
1017 if (
const auto* shape = getBusIoShape(
getItemShape(),
"GraphicalBusOutput::paint")) {
1019 Qt::AlignRight | Qt::AlignVCenter, name);
bool isInErrorState() const
BusValue getCurrentValue() const
Drives a one-bit constant used by imported hardware netlists.
BusValue setValue(const BusValue &value) const
Logical model behind the graphical bus output.
Logical model behind the graphical single-bit output.
Graphics scene for the circuit diagram editor.
static constexpr int GRID_SIZE
Grid cell size in scene units.
InteractionMode getInteractionMode() const
Gets the current interaction mode.
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
void setBusState(const Bus &bus)
Updates the display shape based on the state of the incoming bus. Handles edge cases like Error/Unkno...
void applyStartValue() override
Applies the default starting value configured in the component's properties.
void setComponent(const Component_ptr &component) override
Sets the associated logical component.
void resetSimulationState() override
Resets the visual state to its initial simulation state.
void installPropertyCallbacks()
QRectF boundingRect() const override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
void refreshFromComponent()
GraphicalBusOutput(QGraphicsItem *parent=nullptr)
std::vector< Port * > outputPorts
Output connection ports.
QGraphicsItem * getItemShape() const
Gets the component shape.
QRectF boundingRect() const override
Gets bounding rectangle with selection margin.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
Paints the component (selection outline).
std::vector< Port * > inputPorts
Input connection ports.
bool scanShape
Whether to scan shape alpha for port placement.
void setItemShape(QGraphicsItem *shape)
Sets the component shape graphics item.
void setComponent(const Component_ptr &component) override
Sets the associated logical component.
GraphicalConstant(QGraphicsItem *parent=nullptr)
QRectF componentNameRect(const QString &name) const
Returns the label rectangle for the current orientation.
bool isPortOrientationUp() const
Returns true when the IO port is currently placed above the shape.
void updatePortOrientation()
Rebuilds the single IO port based on the current orientation property.
void setComponent(const Component_ptr &component) override
Sets the associated logical component.
static const QFont UI_FONT
Shared, highly-optimized UI font for all IO components. Using an inline static font prevents allocati...
void inputToggled(Bus targetBus, BusValue value, Component_weakPtr source)
Emitted when an input component changes its state.
QString getComponentName() const
Safely retrieves the user-defined name of this component.
GraphicalIO(ItemCategory category, const Component_ptr &component, QGraphicsItem *shape, QGraphicsItem *parent=nullptr, bool scanShape=false)
Constructs a GraphicalIO item.
QRectF collisionRectForPortSide(PortSide side) const
Returns local wire-obstacle bounds for a proposed port side.
void setPortOrientation(PortSide side)
Persists and applies a cardinal port orientation.
QPoint portPositionFor(PortSide side) const
Returns the local port position for a proposed cardinal side.
void installPortOrientationCallback()
Installs the callback that moves the IO port when orientation changes.
Base class for all graphical items in the diagram.
Component_ptr getComponent() const
Gets the associated logical component.
void setPorts(const std::vector< PortPair > &busToPortInputs, const std::vector< PortPair > &busToPortOutputs) override
Sets ports and validates against component I/O.
bool isEditable
Whether the component allows property editing.
GraphicalLogicComponent(ItemCategory category, const Component_ptr &component, QGraphicsItem *shape, QGraphicsItem *parent, bool scanShape=false)
virtual void setComponent(const Component_ptr &component)
Sets the associated logical component.
Component_ptr associatedComponent
The logical component this graphical component represents.
GraphicalOutputSingle(QGraphicsItem *parent=nullptr)
void setState(State state)
Updates the visual representation based on the wire state.
void applyStartValue() override
Applies the default starting value configured in the component's properties.
static const QString & getOnShapePath()
void resetSimulationState() override
Resets the visual state to its initial simulation state.
QRectF boundingRect() const override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
static const QString & getOffShapePath()
static const QString & getUnknownShapePath()
static const QColor & getColor(theme::ColorToken token)
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::shared_ptr< Component > Component_ptr
ParsedBusValue valueFromStr(const std::string_view value)
Parse user-facing decimal, hexadecimal, octal, binary, or four-state text.
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
std::optional< BusValue > resizeParsedValue(const ParsedBusValue &parsed, const std::size_t width)
Adapts a parsed textual value to an exact destination width.
BusValue maxValueForBusWidth(const std::size_t width)
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::pair< QString, QPoint > PortPair
QRect shapeRect(const QSize &size)
BusValue normalizeBusValue(const BusValue &value, const std::size_t width, const State extension)
Resize an LSB-first value to an exact bus width.