SILICON
Loading...
Searching...
No Matches
graphicalIO.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 "graphicalIO.hpp"
19
20#include <core/simulator.hpp>
21#include <core/wireUtils.hpp>
24#include <ui/shell/theme.hpp>
26
27#include <QPointer>
28
29#include <algorithm>
30#include <cmath>
31#include <limits>
32#include <stdexcept>
33#include <utility>
34
35namespace SILICON::ui {
36using namespace SILICON::core;
37
38namespace {
39
40constexpr int BUS_IO_MIN_WIDTH = 8 * DiagramScene::GRID_SIZE;
41constexpr int BUS_IO_HEIGHT = 4 * DiagramScene::GRID_SIZE;
42constexpr int BUS_IO_PORT_X = 0;
43constexpr int BUS_IO_PORT_Y = 6 * DiagramScene::GRID_SIZE;
44constexpr int BUS_IO_PADDING_X = DiagramScene::GRID_SIZE;
45constexpr int BUS_IO_VALUE_TEXT_GAP = 8;
46constexpr int MAX_INLINE_VALUE_CHARACTERS = 18;
47constexpr int IO_PORT_EXTENSION = 2 * DiagramScene::GRID_SIZE;
48constexpr int CONSTANT_SIZE = 4 * DiagramScene::GRID_SIZE;
49constexpr int CONSTANT_PORT_EXTENSION = 2 * DiagramScene::GRID_SIZE;
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;
56
57// Re-use static fonts to prevent allocations
58const QFont& getWidthFont()
59{
60 static const QFont font("NovaMono", 8);
61 return font;
62}
63
64QRectF busIoNameRect(const QRectF& shapeRect, const QString& name)
65{
66 const QFontMetrics metrics(GraphicalIO::UI_FONT);
67 const qreal width = std::max<qreal>(shapeRect.width(), metrics.horizontalAdvance(name));
68 const qreal height = metrics.height();
69 return {shapeRect.right() - width, shapeRect.top() - height, width, height};
70}
71
72QRectF busIoNameRect(const QRectF& shapeRect, const QString& name, const bool below)
73{
74 QRectF rect = busIoNameRect(shapeRect, name);
75 if (below)
76 rect.moveTop(shapeRect.bottom());
77 return rect;
78}
79
80int snapBusIoWidthToGrid(const int width)
81{
82 return std::max(BUS_IO_MIN_WIDTH, ((width + 2 * DiagramScene::GRID_SIZE - 1)
85}
86
87int normalizedBusSize(const int size)
88{
89 return std::clamp(size, 1,
90 static_cast<int>(std::numeric_limits<unsigned short>::max()));
91}
92
93QString compactValueText(QString value)
94{
95 if (value.size() <= MAX_INLINE_VALUE_CHARACTERS)
96 return value;
97 return value.left(9) + QStringLiteral("…") + value.right(8);
98}
99
100QString compactValueText(const BusValue& value, const BusValueFormat format,
101 const std::size_t fixedWidth = 0)
102{
103 return compactValueText(QString::fromStdString(formatValue(value, format, fixedWidth)));
104}
105
106bool isInteractiveSimulation(const GraphicalItem* item)
107{
108 const auto* diagramScene =
109 dynamic_cast<const DiagramScene*>(item ? item->scene() : nullptr);
110 return diagramScene
111 && diagramScene->getInteractionMode()
112 == DiagramScene::InteractionMode::SIMULATION_MODE;
113}
114
115enum class BusIoKind { Input, Output };
116
117enum class IoPortOrientation { Up, Down, Left, Right };
118
119class BusIoShape : public QGraphicsItem {
120public:
121 BusIoShape(BusIoKind kind, unsigned int busWidth, QGraphicsItem* parent = nullptr)
122 : QGraphicsItem(parent), kind(kind), busWidth(busWidth)
123 {
124 updateLayoutCache(); // Initial cache generation
125 }
126
127 QRectF boundingRect() const override
128 {
129 // Zero-cost geometric return - no text allocation!
130 return {-cachedWidth / 2.0, 0, cachedWidth, BUS_IO_HEIGHT};
131 }
132
133 void setBusWidth(const unsigned int width)
134 {
135 if (busWidth == width)
136 return;
137 prepareGeometryChange();
138 busWidth = width;
139 updateLayoutCache(); // Calculate width ONLY when width actually changes
140 update();
141 }
142
143 void setValueText(QString text)
144 {
145 if (valueText == text)
146 return;
147 valueText = std::move(text);
148 update();
149 }
150
151 void setDisplayState(const State state)
152 {
153 displayState = state;
154 update();
155 }
156
157 void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/,
158 QWidget* /*widget*/) override
159 {
161
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);
167
168 painter->setPen(ink);
169 painter->setFont(GraphicalIO::UI_FONT);
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,
173 34),
174 Qt::AlignCenter, valueText);
175
176 painter->setFont(getWidthFont());
177 painter->drawText(QRectF(body.right() - BUS_IO_PADDING_X - cachedWidthTextWidth, 3,
178 cachedWidthTextWidth, 16),
179 Qt::AlignCenter, cachedWidthText);
180 }
181
182private:
183 void updateLayoutCache()
184 {
185 const QFontMetrics valueMetrics(GraphicalIO::UI_FONT);
186 const QFontMetrics widthMetrics(getWidthFont());
187
188 cachedWidthText = QString("[%1]").arg(busWidth);
189 cachedWidthTextWidth = widthMetrics.horizontalAdvance(cachedWidthText);
190
191 const QString largestKnown =
192 busWidth <= 64
193 ? compactValueText(maxValueForBusWidth(busWidth), BusValueFormat::Hex)
194 : QStringLiteral("0xFFFFFFFF…FFFFFFFF");
195 const QString unknownBits(static_cast<int>(std::min<unsigned int>(busWidth, 8)),
196 QLatin1Char(std::to_underlying(State::UNKNOWN)));
197
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));
202 }
203
204 const int contentWidth =
205 2 * BUS_IO_PADDING_X + maxAdvance + BUS_IO_VALUE_TEXT_GAP + cachedWidthTextWidth;
206 cachedWidth = snapBusIoWidthToGrid(contentWidth);
207 }
208
209 QColor backgroundColor() const
210 {
211 if (kind == BusIoKind::Input)
213
214 switch (displayState) {
215 case State::HIGH: return ThemeEngine::getColor(theme::ColorToken::Blue);
217 case State::UNKNOWN: return ThemeEngine::getColor(theme::ColorToken::Violet);
218 case State::ERROR: return ThemeEngine::getColor(theme::ColorToken::Error);
219 }
221 }
222
223 BusIoKind kind;
224 unsigned int busWidth = 1;
225 QString valueText = "0x0";
226 State displayState = State::UNKNOWN;
227
228 // Cached dimension metrics
229 qreal cachedWidth = BUS_IO_MIN_WIDTH;
230 QString cachedWidthText;
231 int cachedWidthTextWidth = 0;
232};
233
234class ConstantShape : public QGraphicsItem {
235public:
236 QRectF boundingRect() const override
237 {
238 return {0, 0, static_cast<qreal>(cachedWidth), static_cast<qreal>(CONSTANT_SIZE)};
239 }
240
241 void setValue(QString newValue)
242 {
243 if (value == newValue)
244 return;
245 prepareGeometryChange();
246 value = std::move(newValue);
247 const QString label = displayValue();
248 const int contentWidth = QFontMetrics(GraphicalIO::UI_FONT).horizontalAdvance(label)
250 cachedWidth = std::max(CONSTANT_SIZE, ((contentWidth + 2 * DiagramScene::GRID_SIZE - 1)
253 update();
254 }
255
256 void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/,
257 QWidget* /*widget*/) override
258 {
260
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));
265
266 painter->setPen(ink);
267 painter->setFont(GraphicalIO::UI_FONT);
268 painter->drawText(boundingRect(), Qt::AlignCenter, displayValue());
269 }
270
271private:
272 [[nodiscard]] QString displayValue() const
273 {
274 return (value.size() > 1 ? QStringLiteral("0b") : QString()) + value.toUpper();
275 }
276
277 QString value = QStringLiteral("0");
278 int cachedWidth = CONSTANT_SIZE;
279};
280
281ConstantShape* getConstantShape(QGraphicsItem* itemShape, const char* context)
282{
283 auto* shape = dynamic_cast<ConstantShape*>(itemShape);
284 Q_ASSERT_X(shape != nullptr, context, "Constant item is missing its ConstantShape");
285 return shape;
286}
287
288BusIoShape* getBusIoShape(QGraphicsItem* itemShape, const char* context)
289{
290 auto* shape = dynamic_cast<BusIoShape*>(itemShape);
291 Q_ASSERT_X(shape != nullptr, context, "Bus IO item is missing its BusIoShape");
292 return shape;
293}
294
295QRectF busIoNamedBounds(QGraphicsItem* itemShape, const QString& name,
296 const QRectF& fallbackRect, const bool nameBelow)
297{
298 if (name.isEmpty())
299 return fallbackRect;
300
301 const auto* shape = getBusIoShape(itemShape, "busIoNamedBounds");
302 if (!shape)
303 return fallbackRect;
304
305 return fallbackRect.united(busIoNameRect(shape->boundingRect(), name, nameBelow));
306}
307
308IoPortOrientation parsePortOrientation(const std::string_view orientation)
309{
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;
317}
318
319bool portNameBelongsBelowShape(const std::string_view orientation)
320{
321 return parsePortOrientation(orientation) == IoPortOrientation::Up;
322}
323
324std::string currentPortOrientation(const Component_ptr& component)
325{
326 if (!component)
327 return std::string(DEFAULT_PORT_ORIENTATION);
328
329 return component->getPropertyValue<std::string>(PORT_ORIENTATION_PROPERTY)
330 .value_or(std::string(DEFAULT_PORT_ORIENTATION));
331}
332
333QPoint ioPortPosition(const QRectF& shapeRect, const IoPortOrientation orientation)
334{
335 const int centerX = DiagramScene::snapToGrid(shapeRect.center().x());
336 const int centerY = DiagramScene::snapToGrid(shapeRect.center().y());
337
338 switch (orientation) {
339 case IoPortOrientation::Up:
340 return {centerX, DiagramScene::snapToGrid(shapeRect.top() - IO_PORT_EXTENSION)};
341 case IoPortOrientation::Down:
342 return {centerX, DiagramScene::snapToGrid(shapeRect.bottom() + IO_PORT_EXTENSION)};
343 case IoPortOrientation::Left:
344 return {DiagramScene::snapToGrid(shapeRect.left() - IO_PORT_EXTENSION), centerY};
345 case IoPortOrientation::Right:
346 return {DiagramScene::snapToGrid(shapeRect.right() + IO_PORT_EXTENSION), centerY};
347 }
348 std::unreachable();
349}
350
351std::string_view portOrientationName(const PortSide side)
352{
353 switch (side) {
354 case PortSide::UP: return PORT_ORIENTATION_UP;
355 case PortSide::DOWN: return PORT_ORIENTATION_DOWN;
356 case PortSide::LEFT: return PORT_ORIENTATION_LEFT;
357 case PortSide::RIGHT: return PORT_ORIENTATION_RIGHT;
358 }
359 std::unreachable();
360}
361
362} // namespace
363
364// --- Constant
365// -------------------------------------------------------------------------
366
368 : GraphicalLogicComponent(std::make_shared<ConstantComponent>(std::make_shared<Wire>(),
369 BusValue{State::LOW}),
370 new ConstantShape(), parent)
371{
372 isEditable = true;
374 updateLayout();
375}
376
378{
380 return;
381
382 QPointer<GraphicalConstant> safeThis(this);
383 std::weak_ptr<Component> boundComponent = associatedComponent;
384 associatedComponent->setPropertyCallback(
385 "value", [safeThis, boundComponent](const PropertyValue& value) {
386 auto component = boundComponent.lock();
387 auto* constant = dynamic_cast<ConstantComponent*>(component.get());
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);
392 return applied;
393 });
394
395 associatedComponent->setPropertyCallback(
396 "size", [safeThis, boundComponent](const PropertyValue& value) {
397 auto component = boundComponent.lock();
398 auto* constant = dynamic_cast<ConstantComponent*>(component.get());
399 const int applied =
400 constant ? constant->setSize(std::get<int>(value)) : std::get<int>(value);
401 if (safeThis && safeThis->getComponent() == component)
402 safeThis->updateLayout();
403 return applied;
404 });
405}
406
408{
410 return;
411
412 const auto value = associatedComponent->getPropertyValue<BusValue>("value").value_or(
414 updateLayout(value);
415}
416
418{
419 auto* shape = getConstantShape(getItemShape(), "GraphicalConstant::updateLayout");
420 if (!shape)
421 return;
422
423 prepareGeometryChange();
424 shape->setValue(compactValueText(value, BusValueFormat::Raw));
425 const QRectF bounds = shape->boundingRect();
426 setPorts({},
427 {PortPair{"o", QPoint(static_cast<int>(bounds.right()) + CONSTANT_PORT_EXTENSION,
428 static_cast<int>(bounds.center().y()))}});
429}
430
437
439 QGraphicsItem* shape, QGraphicsItem* parent, bool scanShape)
440 : GraphicalLogicComponent(category | ItemCategory::IO, component, shape, parent,
441 scanShape)
442{
443}
444
446{
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);
451 }
452 }
453 return {};
454}
455
457{
458 if (!associatedComponent || !associatedComponent->getProperty(PORT_ORIENTATION_PROPERTY))
459 return;
460
461 QPointer<GraphicalIO> safeThis(this);
462 std::weak_ptr<Component> boundComponent = associatedComponent;
463
464 associatedComponent->setPropertyCallback(
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);
471 }
472 return value;
473 });
474}
475
477{
479 return;
480
481 updatePortOrientation(currentPortOrientation(associatedComponent));
482}
483
484void GraphicalIO::updatePortOrientation(const std::string_view orientation)
485{
487 return;
488
489 const QPoint position =
490 ioPortPosition(getItemShape()->boundingRect(), parsePortOrientation(orientation));
491
492 if (!associatedComponent->getInputs().empty()) {
493 const QString name =
494 inputPorts.empty() ? QStringLiteral("in") : inputPorts.front()->getName();
495 GraphicalLogicComponent::setPorts({PortPair{name, position}}, {});
496 } else if (!associatedComponent->getOutputs().empty()) {
497 const QString name =
498 outputPorts.empty() ? QStringLiteral("o") : outputPorts.front()->getName();
499 GraphicalLogicComponent::setPorts({}, {PortPair{name, position}});
500 }
501 update();
502}
503
505{
507 return false;
508
509 return portNameBelongsBelowShape(currentPortOrientation(associatedComponent));
510}
511
512QRectF GraphicalIO::componentNameRect(const QString& name) const
513{
514 if (!getItemShape() || name.isEmpty())
515 return {};
516
517 const QRectF shapeRect = getItemShape()->boundingRect();
518 const QFontMetrics metrics(UI_FONT);
519 const qreal width = std::max<qreal>(shapeRect.width(), metrics.horizontalAdvance(name));
520 const qreal height = metrics.height();
521 const qreal x = shapeRect.left();
522 const qreal y = isPortOrientationUp() ? shapeRect.bottom() : shapeRect.top() - height;
523 return {x, y, width, height};
524}
525
527{
528 if (!getItemShape())
529 return {};
530 return ioPortPosition(getItemShape()->boundingRect(),
531 parsePortOrientation(portOrientationName(side)));
532}
533
535{
536 if (!getItemShape())
537 return {};
538 const QPoint portPosition = portPositionFor(side);
539 return getItemShape()->boundingRect().united(
540 QRectF(portPosition - QPoint(1, 1), QSize(2, 2)));
541}
542
544{
546 return;
547 associatedComponent->setPropertyValue(PORT_ORIENTATION_PROPERTY,
548 std::string(portOrientationName(side)));
549}
550
557
558// --- Graphical Input Single
559// -------------------------------------------------------------
560
561GraphicalInput::GraphicalInput(QGraphicsItem* parent)
562 : GraphicalIO(ItemCategory::Input, std::make_shared<DummyInputComponent>(Bus(1), "in"),
563 new ThemedSvgItem(":/other_components/input_off.svg"), parent)
564{
565 isEditable = false;
566 GraphicalLogicComponent::setPorts({}, {PortPair{"o", QPoint(20, 60)}});
568
569 associatedComponent->setPropertyCallback("name", [this](const PropertyValue& value) {
570 prepareGeometryChange();
571 return value;
572 });
573
575}
576
581
583{
584 skinState = state;
586 : getOffShapePath()));
587
588 const auto targetBus = getComponent()->getOutputs()[0];
589 if (!isInteractiveSimulation(this)) {
590 if (auto* input = dynamic_cast<DummyInputComponent*>(getComponent().get()))
591 input->setState(state);
592 }
593
594 emit inputToggled(targetBus, BusValue{state}, getComponent()->weak_from_this());
595}
596
601
603{
604 const auto startValue = getComponent()
605 ->getPropertyValue<BusValue>("startValue")
606 .value_or(BusValue{State::LOW});
607 skinState = startValue.empty() ? State::LOW : startValue.front();
609 : getOffShapePath()));
610
611 if (auto* input = dynamic_cast<DummyInputComponent*>(getComponent().get()))
612 input->setState(skinState);
613}
614
619
620void GraphicalInput::paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
621 QWidget* widget)
622{
623 painter->setFont(UI_FONT);
624 const QString name = getComponentName();
625 if (!name.isEmpty()) {
626 painter->drawText(componentNameRect(name), Qt::AlignLeft | Qt::AlignVCenter, name);
627 }
628 GraphicalLogicComponent::paint(painter, option, widget);
629}
630
632{
634 return rect.united(componentNameRect(getComponentName()));
635}
636
638{
639 return getComponent()->getOutputs()[0][0]->getCurrentState();
640}
641
642// --- Graphical Bus Input ---------------------------------------------------------------
643
646 std::make_shared<DummyBusInputComponent>(Bus(8), "bus_in"),
647 new BusIoShape(BusIoKind::Input, 8), parent)
648{
649 isEditable = false;
651 {PortPair{"bus", QPoint(BUS_IO_PORT_X, BUS_IO_PORT_Y)}});
656}
657
659{
661 return;
662
663 // safeThis guards the QGraphicsObject (this) lifetime: property callbacks may
664 // fire after the graphical item has been deleted, so we must check it before use.
665 QPointer<GraphicalBusInput> safeThis(this);
666 // boundComponent is a weak_ptr to the very same Component returned by
667 // getComponent(). It guards the component's lifetime independently and lets us
668 // detect whether the item's component was replaced between install and invocation.
669 std::weak_ptr<Component> boundComponent = associatedComponent;
670
671 associatedComponent->setPropertyCallback("name",
672 [safeThis](const PropertyValue& value) {
673 if (safeThis)
674 safeThis->prepareGeometryChange();
675 return value;
676 });
677
678 associatedComponent->setPropertyCallback(
679 "size", [safeThis, boundComponent](const PropertyValue& value) {
680 const int normalizedSize = normalizedBusSize(std::get<int>(value));
681 auto component = boundComponent.lock();
682 if (auto* busInput = dynamic_cast<DummyBusInputComponent*>(component.get()))
683 busInput->setSize(normalizedSize);
684 // safeThis->getComponent() and component point at the same object; the
685 // equality check confirms the item's component was not swapped out, and
686 // safeThis ensures the item itself is still alive before we touch it.
687 if (safeThis && safeThis->getComponent() == component)
688 safeThis->setValue(safeThis->currentValue);
689 return normalizedSize;
690 });
691
692 associatedComponent->setPropertyCallback(
693 "startValue", [safeThis, boundComponent](const PropertyValue& value) {
694 const auto requestedValue = std::get<BusValue>(value);
695 const auto component = boundComponent.lock();
696 const auto outputs =
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
704 : State::LOW;
705 const auto newValue =
706 SILICON::wireUtils::normalizeBusValue(requestedValue, width, extension);
707
708 // See the "size" callback above: safeThis guards the item, and the
709 // equality check confirms the item still owns this same component.
710 if (safeThis && safeThis->getComponent() == component)
711 safeThis->setValue(newValue);
712 return newValue;
713 });
714}
715
723
725{
726 const auto outputs = getComponent()->getOutputs();
727 if (outputs.empty())
728 return;
729
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 =
734 value.size() == 1 && value.front() == State::UNKNOWN ? State::UNKNOWN : State::LOW;
735 currentValue = SILICON::wireUtils::normalizeBusValue(value, width, extension);
736
737 if (auto* shape = getBusIoShape(getItemShape(), "GraphicalBusInput::setValue")) {
738 shape->setBusWidth(static_cast<unsigned int>(width));
739 shape->setValueText(compactValueText(currentValue, SILICON::core::BusValueFormat::Hex,
740 (width + 3) / 4));
741 }
742
743 if (!isInteractiveSimulation(this))
745 emit inputToggled(getComponent()->getOutputs()[0], currentValue,
746 getComponent()->weak_from_this());
747}
748
750{
751 if (auto* busInput = dynamic_cast<DummyBusInputComponent*>(getComponent().get())) {
752 busInput->setBusValue(currentValue);
753 }
754}
755
757{
758 const auto outputs = getComponent()->getOutputs();
759 if (outputs.empty())
760 return;
761
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);
765
766 const QPointer<GraphicalBusInput> safeThis(this);
769 QString::fromStdString(SILICON::core::formatValue(
771 [safeThis, width](const QString& text) {
772 if (!safeThis)
773 return;
774
775 const auto parsed = SILICON::core::valueFromStr(text.toStdString());
776 if (parsed.format == SILICON::core::BusValueFormat::Unknown
777 || std::ranges::contains(parsed.value, State::ERROR))
778 return;
779
780 const auto resized = SILICON::core::resizeParsedValue(parsed, width);
781 if (!resized) {
784 "Bus Input", "The value does not fit in the bus width.");
785 return;
786 }
787 safeThis->setValue(*resized);
788 });
789}
790
795
797{
798 const auto startValue = getComponent()
799 ->getPropertyValue<BusValue>("startValue")
800 .value_or(BusValue{State::LOW});
801 const auto outputs = getComponent()->getOutputs();
802 if (outputs.empty())
803 return;
804
805 const auto width = outputs[0].size();
807
808 if (auto* shape = getBusIoShape(getItemShape(), "GraphicalBusInput::applyStartValue")) {
809 shape->setBusWidth(static_cast<unsigned int>(width));
810 shape->setValueText(compactValueText(currentValue, SILICON::core::BusValueFormat::Hex,
811 (width + 3) / 4));
812 }
813
815}
816
821
823{
824 if (!getComponent() || getComponent()->getOutputs().empty())
825 return;
826
827 const auto width = getComponent()->getOutputs()[0].size();
828 if (auto* shape =
829 getBusIoShape(getItemShape(), "GraphicalBusInput::refreshFromComponent")) {
830 shape->setBusWidth(static_cast<unsigned int>(width));
831 shape->setValueText(compactValueText(currentValue, SILICON::core::BusValueFormat::Hex,
832 (width + 3) / 4));
833 }
834}
835
836void GraphicalBusInput::paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
837 QWidget* widget)
838{
839 painter->setFont(UI_FONT);
840 const QString name = getComponentName();
841 if (!name.isEmpty()) {
842 if (const auto* shape = getBusIoShape(getItemShape(), "GraphicalBusInput::paint")) {
843 painter->drawText(busIoNameRect(shape->boundingRect(), name, isPortOrientationUp()),
844 Qt::AlignRight | Qt::AlignVCenter, name);
845 }
846 }
847 GraphicalLogicComponent::paint(painter, option, widget);
848}
849
855
856// --- Graphical Output
857// ------------------------------------------------------------------
858
861 std::make_shared<DummyOutputComponent>(Bus(1), "out"),
862 new ThemedSvgItem(":/other_components/output_unknown.svg"), parent)
863{
864 isEditable = false;
865 GraphicalLogicComponent::setPorts({PortPair{"in", QPoint(20, 60)}}, {});
867
868 associatedComponent->setPropertyCallback("name", [this](const PropertyValue& value) {
869 prepareGeometryChange();
870 return value;
871 });
872}
873
875{
876 QString shapePath = getOffShapePath();
877 if (state == State::HIGH)
878 shapePath = getOnShapePath();
879 else if (state == State::UNKNOWN)
880 shapePath = getUnknownShapePath();
881
882 setItemShape(new ThemedSvgItem(shapePath));
883}
884
889
894
895void GraphicalOutputSingle::paint(QPainter* painter,
896 const QStyleOptionGraphicsItem* option, QWidget* widget)
897{
898 painter->setFont(UI_FONT);
899 const QString name = getComponentName();
900 if (!name.isEmpty()) {
901 painter->drawText(componentNameRect(name), Qt::AlignLeft | Qt::AlignVCenter, name);
902 }
903 GraphicalLogicComponent::paint(painter, option, widget);
904}
905
907{
909 return rect.united(componentNameRect(getComponentName()));
910}
911
912// --- Graphical Bus Output --------------------------------------------------------------
913
916 std::make_shared<DummyBusOutputComponent>(Bus(8), "bus_out"),
917 new BusIoShape(BusIoKind::Output, 8), parent)
918{
919 isEditable = false;
920 GraphicalLogicComponent::setPorts({PortPair{"bus", QPoint(BUS_IO_PORT_X, BUS_IO_PORT_Y)}},
921 {});
925}
926
928{
930 return;
931
932 QPointer<GraphicalBusOutput> safeThis(this);
933 std::weak_ptr<Component> boundComponent = associatedComponent;
934
935 associatedComponent->setPropertyCallback("name",
936 [safeThis](const PropertyValue& value) {
937 if (safeThis)
938 safeThis->prepareGeometryChange();
939 return value;
940 });
941
942 associatedComponent->setPropertyCallback(
943 "size", [safeThis, boundComponent](const PropertyValue& value) {
944 const int normalizedSize = normalizedBusSize(std::get<int>(value));
945 auto component = boundComponent.lock();
946 if (auto* busOutput = dynamic_cast<DummyBusOutputComponent*>(component.get()))
947 busOutput->setSize(normalizedSize);
948 if (safeThis && safeThis->getComponent() == component)
949 safeThis->refreshFromComponent();
950 return normalizedSize;
951 });
952}
953
961
963{
964 if (auto* shape = getBusIoShape(getItemShape(), "GraphicalBusOutput::setBusState")) {
965 shape->setBusWidth(static_cast<unsigned int>(bus.size()));
966
967 if (bus.isInErrorState()) {
968 shape->setDisplayState(State::ERROR);
969 shape->setValueText("ERR");
970 } else if (bus.hasUnknowns()) {
971 shape->setDisplayState(State::UNKNOWN);
972 shape->setValueText(
973 compactValueText(bus.getCurrentValue(), SILICON::core::BusValueFormat::Raw));
974 } else {
975 const auto value = bus.getCurrentValue();
976 const bool anyHigh = std::ranges::contains(value, State::HIGH);
977 shape->setDisplayState(anyHigh ? State::HIGH : State::LOW);
978 shape->setValueText(compactValueText(value, SILICON::core::BusValueFormat::Hex,
979 (bus.size() + 3) / 4));
980 }
981 }
982}
983
985{
986 if (!getComponent() || getComponent()->getInputs().empty())
987 return;
988 setBusState(getComponent()->getInputs()[0]);
989}
990
995
997{
998 if (auto* shape =
999 getBusIoShape(getItemShape(), "GraphicalBusOutput::resetSimulationState")) {
1000 const auto width =
1001 (!getComponent() || getComponent()->getInputs().empty())
1002 ? 1U
1003 : static_cast<unsigned int>(getComponent()->getInputs()[0].size());
1004 shape->setBusWidth(width);
1005 shape->setDisplayState(State::UNKNOWN);
1006 shape->setValueText(
1007 compactValueText(QString(width, QChar(std::to_underlying(State::UNKNOWN)))));
1008 }
1009}
1010
1011void GraphicalBusOutput::paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
1012 QWidget* widget)
1013{
1014 painter->setFont(UI_FONT);
1015 const QString name = getComponentName();
1016 if (!name.isEmpty()) {
1017 if (const auto* shape = getBusIoShape(getItemShape(), "GraphicalBusOutput::paint")) {
1018 painter->drawText(busIoNameRect(shape->boundingRect(), name, isPortOrientationUp()),
1019 Qt::AlignRight | Qt::AlignVCenter, name);
1020 }
1021 }
1022 GraphicalLogicComponent::paint(painter, option, widget);
1023}
1024
1030
1031} // namespace SILICON::ui
bool hasUnknowns() const
Definition wire.cpp:545
bool isInErrorState() const
Definition wire.cpp:538
BusValue getCurrentValue() const
Definition wire.cpp:530
Drives a one-bit constant used by imported hardware netlists.
Definition io.hpp:29
int setSize(int newSize)
Definition io.cpp:97
BusValue setValue(const BusValue &value) const
Definition io.cpp:110
Logical model behind the graphical bus input.
Definition io.hpp:89
Logical model behind the graphical bus output.
Definition io.hpp:129
Logical model behind the graphical single-bit input.
Definition io.hpp:67
Logical model behind the graphical single-bit output.
Definition io.hpp:112
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 applyStartValue() override
Applies the default starting value configured in the component's properties.
void editValue()
Opens a dialog prompting the user to type in a new bus value.
void setComponent(const Component_ptr &component) override
Sets the associated logical component.
void resetSimulationState() override
Resets the visual state to its initial simulation state.
GraphicalBusInput(QGraphicsItem *parent=nullptr)
void handleSimulationClick() override
Called when the user clicks on the component during a live simulation.
QRectF boundingRect() const override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
void refreshFromComponent()
Synchronizes the UI visuals with the underlying logic component's state.
void setValue(const BusValue &value)
Directly sets the numerical value of the bus.
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.
QRectF boundingRect() const override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
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.
void setState(State state)
Explicitly sets the input state and updates visuals/simulation logic.
void applyStartValue() override
Applies the default starting value configured in the component's properties.
GraphicalInput(QGraphicsItem *parent=nullptr)
static const QString & getOnShapePath()
State getState() const
Retrieves the current state of the input.
void resetSimulationState() override
Resets the visual state to its initial simulation state.
void handleSimulationClick() override
Called when the user clicks on the component during a live simulation.
QRectF boundingRect() const override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
void toggle()
Toggles the visual and logical state between HIGH and LOW.
static const QString & getOffShapePath()
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)
Definition theme.hpp:92
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
Definition wire.hpp:120
QWidget * parentWidgetForGraphicsItem(const QGraphicsItem *item)
void warning(QWidget *parent, const QString &title, const QString &text)
void getText(QWidget *parent, const QString &title, const QString &label, const QString &defaultText, TextCallback callback, QObject *context)
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)
Definition geometry.hpp:42
BusValue normalizeBusValue(const BusValue &value, const std::size_t width, const State extension)
Resize an LSB-first value to an exact bus width.
Definition wire.cpp:121