SILICON
Loading...
Searching...
No Matches
graphicalComponent.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#include <QFontInfo>
20
21#include <algorithm>
22#include <limits>
23#include <stdexcept>
24#include <utility>
25
26#include <QDialog>
27#include <QFontMetricsF>
28#include <QGraphicsSceneHoverEvent>
29#include <QGraphicsView>
30#include <QImage>
31#include <QLabel>
32#include <QMarginsF>
33#include <QPainter>
34#include <QPainterPathStroker>
35#include <QTextOption>
36
37#include <ui/shell/theme.hpp>
41
42
43namespace SILICON::ui {
44using namespace SILICON::core;
45
46namespace {
47
48constexpr qreal SelectionMargin = 4.0;
49constexpr qreal ResizeHandleRadius = 3.0;
50constexpr qreal ResizeHitRadius = 5.0;
51constexpr qreal SelectionPenWidth = 3.0;
52constexpr qreal PortPenWidth = 3.0;
53constexpr qreal PortErrorPenWidth = 4.0;
54constexpr qreal SlashLength = 12.0;
55constexpr qreal SlashPenWidth = 2.0;
56constexpr qreal ClockIconWidth = 16.0;
57constexpr qreal ClockIconHeight = 8.0;
58constexpr qreal ClockIconPenWidth = 1.5;
59
60class ThemedPortLineItem : public QGraphicsLineItem {
61public:
62 ThemedPortLineItem(const QLineF& line, QGraphicsItem* parent)
63 : QGraphicsLineItem(line, parent)
64 {
65 setPen(QPen(ThemeEngine::getColor(theme::ColorToken::Ink), PortPenWidth));
66 }
67
68 void paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
69 QWidget* widget) override
70 {
71 auto themedPen = pen();
73 painter->setPen(themedPen);
74 painter->drawLine(line());
75 }
76};
77
78QFont portMarkerFont(const QFont& baseFont)
79{
80 QFont font("NovaMono");
81 // Application fonts use pixels; pointSize() would return -1 for those fonts.
82 font.setPointSizeF(QFontInfo(baseFont).pointSizeF());
83 return font;
84}
85
86QRectF strokedLineRect(const QLineF& line, const qreal width)
87{
88 QPainterPath path;
89 path.moveTo(line.p1());
90 path.lineTo(line.p2());
91 QPainterPathStroker stroker;
92 stroker.setWidth(width);
93 stroker.setCapStyle(Qt::SquareCap);
94 return stroker.createStroke(path).boundingRect();
95}
96
97QLineF portSlash(const QLineF& line)
98{
99 QTransform transform;
100 transform.translate(line.center().x(), line.center().y());
101 transform.rotate(-line.angle() + 60.0);
102 return transform.map(QLineF(-SlashLength / 2.0, 0, SlashLength / 2.0, 0));
103}
104
105QRectF portNameRect(const QLineF& line, const QString& name, const PortSide side,
106 const QFont& font)
107{
108 constexpr qreal margin = DiagramScene::GRID_SIZE / 2.0;
109 const QFontMetricsF metrics(font);
110 const QString label = name.startsWith('!') ? name.mid(1) : name;
111 const QPointF point = line.p2();
112 const bool clock = name == QStringLiteral("clk");
113 const qreal width = clock ? ClockIconWidth : metrics.horizontalAdvance(label);
114 const qreal height = clock ? ClockIconHeight : metrics.height();
115 QMarginsF padding;
116 if (clock) {
117 // Match the visible text edge, including font padding and the icon's stroke.
118 const QRectF glyphs = metrics.tightBoundingRect(label);
119 constexpr qreal halfPen = ClockIconPenWidth / 2.0;
120 padding = QMarginsF(glyphs.left() + halfPen,
121 metrics.ascent() + glyphs.top() + halfPen,
122 metrics.horizontalAdvance(label) - glyphs.right() + halfPen,
123 metrics.height() - metrics.ascent() - glyphs.bottom() + halfPen);
124 }
125 switch (side) {
126 case PortSide::DOWN:
127 return {point.x() - width / 2.0,
128 point.y() - margin / 1.5 - padding.bottom() - height, width, height};
129 case PortSide::UP:
130 return {point.x() - width / 2.0, point.y() + margin / 1.5 + padding.top(),
131 width, height};
132 case PortSide::LEFT:
133 return {point.x() + margin + padding.left(), point.y() - height / 2.0,
134 width, height};
135 case PortSide::RIGHT:
136 return {point.x() - margin - padding.right() - width,
137 point.y() - height / 2.0, width, height};
138 }
139 std::unreachable();
140}
141
142QRectF portSizeLabelRect(const QPointF& midpoint, const QRectF& textRect,
143 const PortSide direction)
144{
145 if (direction == PortSide::UP || direction == PortSide::DOWN) {
146 return {midpoint.x() - textRect.width(), midpoint.y() - textRect.height() / 2.0,
147 textRect.width(), textRect.height()};
148 }
149
150 return {midpoint.x() - textRect.width() / 2.0, midpoint.y() - textRect.height(),
151 textRect.width(), textRect.height()};
152}
153
154QRectF portNameBounds(QRectF rect, const QString& name)
155{
156 if (name == QStringLiteral("clk")) {
157 constexpr qreal halfPen = ClockIconPenWidth / 2.0;
158 rect.adjust(-halfPen, -halfPen, halfPen, halfPen);
159 }
160 return rect;
161}
162
163} // namespace
164
165GraphicalComponent::GraphicalComponent(QGraphicsItem* shape, QGraphicsItem* parent,
166 bool scanShape)
168{
169}
170
172{
173 static const PropertyMap empty;
174 return empty;
175}
176
177std::optional<PropertyValue> GraphicalComponent::getProperty(std::string_view key) const
178{
179 const auto& properties = getProperties();
180 const auto found = properties.find(key);
181 return found == properties.end() ? std::nullopt
182 : std::optional<PropertyValue>(found->second);
183}
184
185std::optional<std::reference_wrapper<const StringPropertyOptions>>
187{
188 Q_UNUSED(key);
189 return std::nullopt;
190}
191
192bool GraphicalComponent::isMultilineProperty(std::string_view key) const
193{
194 Q_UNUSED(key);
195 return false;
196}
197
198bool GraphicalComponent::isPropertyHidden(std::string_view key) const
199{
200 return hiddenProperties.contains(key);
201}
202
203void GraphicalComponent::applyProperty(std::string_view key, const PropertyValue& value)
204{
205 Q_UNUSED(value);
206 throw std::invalid_argument("Unknown graphical property: " + std::string(key));
207}
208
210 QGraphicsItem* parent, bool scanShape)
211 : GraphicalItem(category | ItemCategory::Component, parent)
212{
213 setFlag(QGraphicsItem::ItemSendsGeometryChanges);
214
215 setAcceptHoverEvents(true);
216 setAcceptedMouseButtons(Qt::AllButtons);
217
218 if (shape)
219 setItemShape(shape);
220
221 this->scanShape = scanShape;
222}
223
225{
226 prepareGeometryChange();
227 if (!scene() || boundsUpdatePending)
228 return;
229
230 // Property callbacks can run before the new value is stored. Check once after
231 // the complete shape/port update, and ignore changes that leave bounds intact.
232 boundsUpdatePending = true;
233 const auto previousBounds = boundingRect();
234 QMetaObject::invokeMethod(
235 this,
236 [this, previousBounds] {
237 boundsUpdatePending = false;
238 if (boundingRect() == previousBounds)
239 return;
240 if (auto* diagram = qobject_cast<DiagramScene*>(scene()))
241 diagram->expandSceneBounds(sceneBoundingRect());
242 },
243 Qt::QueuedConnection);
244}
245
246void GraphicalComponent::setItemShape(QGraphicsItem* shape)
247{
248 if (!shape)
249 throw std::invalid_argument("setItemShape: shape must not be null");
250
251 if (itemShape == shape)
252 return;
253
255 if (this->itemShape)
256 delete std::exchange(this->itemShape, nullptr);
257
258 this->itemShape = shape;
259 this->itemShape->setParentItem(this);
260 update();
261}
262
264{
265 const auto margin = resizeHandles().empty() ? SelectionMargin : ResizeHitRadius + 1;
266 return boundingRectWithoutMargins().adjusted(-margin, -margin, margin, margin);
267}
268
270 const PropertyMap& initial)
271{
272 return initial;
273}
274
276{
277 const auto* diagram = qobject_cast<DiagramScene*>(scene());
278 return isSelected() && !resizeHandles().empty() && diagram
279 && diagram->getInteractionMode() == InteractionMode::NORMAL_MODE
280 && diagram->selectedItems().size() == 1;
281}
282
283std::optional<ResizeHandle> GraphicalComponent::resizeHandleAt(QPointF localPos) const
284{
286 return std::nullopt;
287 std::optional<ResizeHandle> closest;
288 qreal nearest = std::numeric_limits<qreal>::max();
289 for (auto handle : resizeHandles()) {
290 const auto center = resizeHandlePoint(resizeBounds(), handle);
291 const auto offset = localPos - center;
292 const auto distance = QPointF::dotProduct(offset, offset);
293 if (QRectF(center - QPointF(ResizeHitRadius, ResizeHitRadius),
294 QSizeF(2 * ResizeHitRadius, 2 * ResizeHitRadius))
295 .contains(localPos)
296 && distance < nearest) {
297 closest = handle;
298 nearest = distance;
299 }
300 }
301 return closest;
302}
303
308
310{
311 for (const auto& [key, value] : state.properties)
312 if (getProperty(key) != value)
313 applyProperty(key, value);
316}
317
318void GraphicalComponent::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
319{
320 if (const auto handle = resizeHandleAt(event->pos())) {
321 QPointF direction(resizesLeft(*handle) ? -1
322 : resizesRight(*handle) ? 1
323 : 0,
324 resizesTop(*handle) ? -1
325 : resizesBottom(*handle) ? 1
326 : 0);
327 auto transform = sceneTransform();
328 if (!scene()->views().empty())
329 transform *= scene()->views().front()->transform();
330 direction = transform.map(direction) - transform.map(QPointF{});
331 const auto angle = QLineF(QPointF{}, direction).angle();
332 const int sector = qRound(angle / 45.0) % 4;
333 constexpr std::array cursors{Qt::SizeHorCursor, Qt::SizeBDiagCursor,
334 Qt::SizeVerCursor, Qt::SizeFDiagCursor};
335 setCursor(cursors[sector]);
336 } else {
337 unsetCursor();
338 }
339 GraphicalItem::hoverMoveEvent(event);
340}
341
342void GraphicalComponent::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
343{
344 unsetCursor();
345 GraphicalItem::hoverLeaveEvent(event);
346}
347
349{
351 unsetCursor();
352 update();
353}
354
356{
357 return childrenBoundingRect();
358}
359
360void GraphicalComponent::paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
361 QWidget* widget)
362{
363 if (isSelected()) {
366 auto style = isColliding() ? Qt::SolidLine : Qt::DotLine;
367
368 painter->setPen(QPen(color, SelectionPenWidth, style));
369 painter->setBrush(Qt::NoBrush);
370 painter->drawRect(this->boundingRectWithoutMargins());
371 if (resizeHandlesVisible()) {
372 painter->setPen(QPen(color, 1));
374 for (auto handle : resizeHandles()) {
375 const auto center = resizeHandlePoint(resizeBounds(), handle);
376 painter->drawRect(QRectF(center - QPointF(ResizeHandleRadius, ResizeHandleRadius),
377 QSizeF(2 * ResizeHandleRadius, 2 * ResizeHandleRadius)));
378 }
379 }
380 }
381}
382
384{
385 QRectF rect = itemShape ? itemShape->mapRectToParent(itemShape->boundingRect())
386 : QRectF{};
387
388 for (const auto port : getPorts())
389 rect = rect.united(port->mapRectToParent(port->collisionRect()));
390
391 return rect;
392}
393
395{
396 setRotation(rotation() + 90);
397 update();
398}
399
400QVariant GraphicalComponent::itemChange(GraphicsItemChange change, const QVariant& value)
401{
402 if (change == ItemRotationChange || change == ItemTransformChange) {
404 for (auto* port : getPorts())
405 port->prepareGeometryChange();
406 }
407 if (change == ItemRotationHasChanged || change == ItemTransformHasChanged) {
408 for (auto* port : getPorts())
409 port->update();
410 update();
411 }
412 return GraphicalItem::itemChange(change, value);
413}
414
416{
417 QRectF rect = itemShape ? itemShape->mapRectToParent(itemShape->boundingRect())
418 : QRectF{};
419 for (const auto* port : getPorts()) {
420 if (port->line)
421 rect = rect.united(port->line->mapRectToParent(port->line->boundingRect()));
422 }
423 return rect;
424}
425
426void GraphicalComponent::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
427{
428 GraphicalItem::mouseDoubleClickEvent(event);
429}
430
431bool GraphicalComponent::openDocumentOnDoubleClick(QGraphicsSceneMouseEvent* event,
432 const std::string& path)
433{
434 auto* diagram = qobject_cast<DiagramScene*>(scene());
435 if (event->button() != Qt::LeftButton || !diagram
436 || diagram->getInteractionMode() != InteractionMode::NORMAL_MODE
437 || !diagram->getDocumentNavigator())
438 return false;
439
440 // Activating another circuit can delete this item. Wait until event dispatch ends.
441 QMetaObject::invokeMethod(
442 this,
443 [this, path] {
444 if (auto* diagram = qobject_cast<DiagramScene*>(scene())) {
445 if (auto* navigator = diagram->getDocumentNavigator())
446 navigator->activateDocument(path);
447 }
448 },
449 Qt::QueuedConnection);
450 event->accept();
451 return true;
452}
453
454void GraphicalComponent::setPorts(const std::vector<PortPair>& busToPortInputs,
455 const std::vector<PortPair>& busToPortOutputs)
456{
457 clearPorts();
458 QImage shapeImage;
459
460 for (const auto& [index, pair] : busToPortInputs | SILICON::views::enumerate) {
461 const auto& [name, pos] = pair;
462
463 // The memory is not leaked since the port address is freed by Qt Garbage collector
464 // ReSharper disable once CppDFAMemoryLeak
465 auto p = new Port(index, pos, name);
466 this->inputPorts.push_back(p);
467 this->setPortLine(p, shapeImage);
468 }
469
470 for (const auto& [index, pair] : busToPortOutputs | SILICON::views::enumerate) {
471 const auto& [name, pos] = pair;
472
473 // ReSharper disable once CppDFAMemoryLeak
474 auto p = new Port(index, pos, name);
475 this->outputPorts.push_back(p);
476 this->setPortLine(p, shapeImage);
477 }
478 if (auto* diagram = qobject_cast<DiagramScene*>(scene()))
479 diagram->requestConnectionsRefresh();
480}
481
483{
484 if (auto* diagram = qobject_cast<DiagramScene*>(scene()))
485 diagram->requestConnectionsRefresh();
486 prepareGeometryChange();
487
488 for (Port* port : getPorts()) {
489 if (!port)
490 continue;
491
492 port->prepareGeometryChange();
493 delete std::exchange(port->line, nullptr);
494 delete port;
495 }
496 inputPorts.clear();
497 outputPorts.clear();
498}
499
500QPoint GraphicalComponent::scanImage(const QImage& image, const PortSide side,
501 const QPoint initialPoint) const
502{
503 if (!this->scanShape) {
504 return initialPoint;
505 }
506
507 const bool horizontal = side == PortSide::LEFT || side == PortSide::RIGHT;
508 const int direction = (side == PortSide::LEFT || side == PortSide::UP) ? 1 : -1;
509
510 const int initialCoord = horizontal ? initialPoint.x() : initialPoint.y();
511
512 const QPoint topLeft = image.rect().topLeft();
513 const QPoint bottomRight = image.rect().bottomRight();
514
515 const int leftUp = horizontal ? topLeft.x() : topLeft.y();
516 const int rightDown = horizontal ? bottomRight.x() : bottomRight.y();
517
518 for (qreal coord = initialCoord; (direction > 0) ? coord <= rightDown : coord >= leftUp;
519 coord += direction) {
520 auto p =
521 horizontal ? QPoint(coord, initialPoint.y()) : QPoint(initialPoint.x(), coord);
522
523 if (qAlpha(image.pixel(p)) != 0) {
524 return p;
525 }
526 }
527 return initialPoint;
528}
529
531{
532 QImage shapeImage;
533 setPortLine(port, shapeImage);
534}
535
536void GraphicalComponent::setPortLine(Port* port, QImage& shapeImage)
537{
538 if (!itemShape)
539 throw std::logic_error("setPortLine: item shape not set");
540
541 // Get the shapeRect and its size
542 const auto shapeRect = itemShape->boundingRect();
543 if (shapeRect.isEmpty())
544 throw std::logic_error("setPortLine: shape bounding rect is empty");
545
546 const auto shapeSize = shapeRect.size().toSize();
547 if (shapeSize.width() <= 0 || shapeSize.height() <= 0)
548 throw std::logic_error("setPortLine: shape dimensions must be positive");
549
550 // Render once per port batch, only when alpha scanning is needed.
551 if (scanShape && shapeImage.isNull()) {
552 shapeImage = QImage(shapeSize, QImage::Format_ARGB32);
553 shapeImage.fill(Qt::transparent);
554 QPainter painter(&shapeImage);
555 painter.setRenderHint(QPainter::Antialiasing);
556 painter.translate(-shapeRect.topLeft());
557
558 const auto options = QStyleOptionGraphicsItem();
559 itemShape->paint(&painter, &options, nullptr);
560 }
561
562 const auto portPos = port->getPosition();
563 const auto portRect = shapeRect.toRect();
564 // nearestPortSide also handles interior points for editor drag sanitization,
565 // but component ports must already satisfy the exterior-position invariant.
566 if (!isPortPositionOutside(portPos, portRect))
567 throw std::logic_error("setPortLine: port position is not outside the shape");
568
569 const auto [portSide, naiveProjection] = nearestPortSide(portPos, portRect);
570
571 const QPoint projectionOnShape = scanImage(shapeImage, portSide, naiveProjection);
572
573 // Create the line from port position to the projection
574 prepareGeometryChange();
575 port->side = portSide;
576 port->printName = printPortNames;
577 port->setLine(new ThemedPortLineItem(QLineF(portPos, projectionOnShape), this));
578
579 if (!printPortNames) {
580 port->setToolTip(port->name);
581 }
582}
583
584Port::Port(const unsigned int index, const QPoint position, QString name, bool printName,
585 QGraphicsItem* parent)
586 : QGraphicsItem(parent)
587{
588 this->index = index;
589 this->position = position;
590 this->printName = printName;
591 this->name = std::move(name);
592}
593
595{
596 const auto portLine = line->line();
597 return {mapFromItem(line, portLine.p1()), mapFromItem(line, portLine.p2())};
598}
599
600QTransform Port::labelTransform(const QRectF& rect, const bool insideShape) const
601{
602 const auto aroundCenter = [&](qreal angle) {
603 QTransform transform;
604 transform.translate(rect.center().x(), rect.center().y());
605 transform.rotate(angle);
606 transform.translate(-rect.center().x(), -rect.center().y());
607 return transform;
608 };
609
610 const auto transform = sceneTransform();
611 const auto direction = transform.map(QPointF(1, 0)) - transform.map(QPointF());
612 const qreal angle = QLineF(QPointF(), direction).angle();
613 const auto horizontal = aroundCenter(angle);
614 if (!insideShape)
615 return horizontal;
616
617 if (const auto* component = dynamic_cast<const GraphicalComponent*>(parentItem())) {
618 if (const auto* shape = component->getItemShape();
619 shape
620 && shape->boundingRect().contains(
621 shape->mapRectFromItem(this, horizontal.mapRect(rect))))
622 return horizontal;
623 }
624
625 // Keep a label that would overflow aligned with the body, but never upside down.
626 return aroundCenter(angle > 90.0 && angle <= 270.0 ? 180.0 : 0.0);
627}
628
630{
631 // The parent paints its selection outline around the accumulated child bounds.
632 if (auto* component = dynamic_cast<GraphicalComponent*>(parentItem()))
633 component->prepareSceneBoundsChange();
634 prepareGeometryChange();
635}
636
637QRectF Port::boundingRect() const
638{
639 if (!line)
640 return {};
641
642 const QLineF portLine = connectionLine();
643 // Reserve the error stroke even while it is hidden, keeping bounds stable.
644 QRectF rect = mapRectFromItem(line, line->boundingRect())
645 .united(strokedLineRect(portLine, PortErrorPenWidth));
646 if (!printName && size == 1)
647 return rect;
648
649 const auto includeLabelBounds = [&](const QFont& baseFont) {
650 const QFont markerFont = portMarkerFont(baseFont);
651 if (printName) {
652 const auto labelRect =
653 portNameBounds(portNameRect(portLine, name, side, markerFont), name);
654 rect = rect.united(labelTransform(labelRect, true).mapRect(labelRect));
655 }
656 if (size != 1) {
657 const QFontMetricsF metrics(markerFont);
658 const QRectF textRect =
659 metrics.boundingRect(QString::number(size)).adjusted(-4.0, -2.0, 4.0, 2.0);
660 const auto labelRect = portSizeLabelRect(portLine.center(), textRect, side);
661 rect = rect.united(labelTransform(labelRect, false).mapRect(labelRect))
662 .united(strokedLineRect(portSlash(portLine), SlashPenWidth));
663 }
664 };
665
666 // Each view's painter inherits its viewport font. Measure those same fonts.
667 const auto views = scene() ? scene()->views() : QList<QGraphicsView*>{};
668 if (views.isEmpty())
669 includeLabelBounds(QApplication::font());
670 else
671 for (const auto* view : views)
672 includeLabelBounds(view->viewport()->font());
673
674 return rect;
675}
676
677void Port::setLine(QGraphicsLineItem* line)
678{
679 if (auto* component = dynamic_cast<GraphicalComponent*>(parentItem()))
680 component->prepareGeometryChange();
681 prepareGeometryChange();
682 if (line->parentItem() != parentItem()) {
683 if (auto* component = dynamic_cast<GraphicalComponent*>(line->parentItem()))
684 component->prepareGeometryChange();
685 }
686 this->line = line;
687 setParentItem(line->parentItem());
688 setZValue(line->zValue() + 1.0);
689}
690
691void Port::setSize(const unsigned int newSize)
692{
693 const unsigned int normalizedSize = std::max(1U, newSize);
694 if (size == normalizedSize)
695 return;
696
698 size = normalizedSize;
699 update();
700 if (parentItem())
701 parentItem()->update();
702}
703
704void Port::setInputAssignmentError(const bool failed)
705{
706 if (inputAssignmentError == failed)
707 return;
708
709 inputAssignmentError = failed;
710 update();
711 if (line)
712 line->update();
713}
714
715void Port::paint(QPainter* painter, const QStyleOptionGraphicsItem* option,
716 QWidget* widget)
717{
718 Q_UNUSED(option);
719 Q_UNUSED(widget);
720
721 if (!line)
722 return;
723
724 const bool isBusPort = (size != 1);
725 const QLineF portLine = connectionLine();
726 const QFont markerFont = portMarkerFont(painter->font());
727 const QColor portColor = inputAssignmentError
730
732 painter->save();
733 painter->setPen(QPen(portColor, PortErrorPenWidth, Qt::SolidLine));
734 painter->drawLine(portLine);
735 painter->restore();
736 }
737
738 if (printName) {
739 const bool inverted = name.startsWith('!');
740 const QString label = inverted ? name.mid(1) : name;
741 const QRectF labelRect = portNameRect(portLine, name, side, markerFont);
742 const QTextOption textOption(Qt::AlignCenter);
743
744 painter->save();
745 painter->setTransform(labelTransform(portNameBounds(labelRect, name), true), true);
746 painter->setFont(markerFont);
747 painter->setPen(QPen(portColor));
748 if (name == QStringLiteral("clk")) {
749 // A rising edge: low on the left, high on the right.
750 QPainterPath clock;
751 clock.moveTo(labelRect.left(), labelRect.bottom());
752 clock.lineTo(labelRect.center().x(), labelRect.bottom());
753 clock.lineTo(labelRect.center().x(), labelRect.top());
754 clock.lineTo(labelRect.right(), labelRect.top());
755 painter->setPen(QPen(portColor, ClockIconPenWidth, Qt::SolidLine,
756 Qt::FlatCap, Qt::MiterJoin));
757 painter->setBrush(Qt::NoBrush);
758 painter->drawPath(clock);
759 } else {
760 painter->drawText(labelRect, label, textOption);
761 }
762 if (inverted && !label.isEmpty()) {
763 const QFontMetricsF metrics(markerFont, painter->device());
764 const QRectF textBounds = painter->boundingRect(labelRect, label, textOption);
765 // Follow the visible glyph tops instead of the font's high overline position.
766 const qreal y = textBounds.top() + metrics.ascent()
767 + metrics.tightBoundingRect(label).top() - metrics.lineWidth()
768 - 4.5;
769 painter->setPen(QPen(portColor, metrics.lineWidth(), Qt::SolidLine, Qt::FlatCap));
770 painter->drawLine(QLineF(textBounds.left(), y, textBounds.right(), y));
771 }
772 painter->restore();
773 }
774
775 if (isBusPort) {
776 const QString sizeText = QString::number(size);
777 const QFontMetricsF metrics(markerFont);
778
779 painter->save();
780 painter->setPen(QPen(portColor, SlashPenWidth));
781 painter->drawLine(portSlash(portLine));
782 painter->restore();
783
784 const QRectF textRect = metrics.boundingRect(sizeText).adjusted(-4.0, -2.0, 4.0, 2.0);
785 const QRectF labelRect = portSizeLabelRect(portLine.center(), textRect, side);
786
787 painter->save();
788 painter->setTransform(labelTransform(labelRect, false), true);
789 painter->setFont(markerFont);
790 painter->setPen(portColor);
791 painter->drawText(labelRect, sizeText, QTextOption(Qt::AlignCenter));
792 painter->restore();
793 }
794}
795
797{
798 if (!line)
799 return {};
800
801 // Decorations describe the bus; they must not obstruct a wire reaching its tip.
802 QPainterPath boundingPath{};
803 boundingPath.addRect(mapRectFromItem(line, line->boundingRect()));
804
805 QPainterPath subtract{};
806 subtract.addEllipse(connectionLine().p1(), 5, 5);
807
808 return boundingPath.subtracted(subtract).boundingRect();
809}
810
812{ return "Unknown"; }
813
814nlohmann::ordered_json GraphicalComponent::serialize() const
815{
816 return {{"uiId", getUiId()},
817 {"position", {{"x", pos().x()}, {"y", pos().y()}}},
818 {"rotation", static_cast<int>(rotation())}};
819}
820
821void GraphicalComponent::loadSerializedState(const nlohmann::json& j)
822{ Q_UNUSED(j); }
823
824std::unique_ptr<GraphicalComponent>
825GraphicalComponent::deserialize(const nlohmann::json& j, GUIComponentFactory& factory)
826{
827 std::string type = j.value("type", "");
828 if (type.empty()) {
829 throw std::runtime_error("GraphicalComponent deserialization: missing 'type' field");
830 }
831
832 auto component = factory.create(type);
833 if (!component) {
834 throw std::runtime_error(
835 std::format("GraphicalComponent deserialization: unknown type '{}'", type));
836 }
837
838 if (j.contains("position")) {
839 const auto& posJson = j["position"];
840 component->setPos(posJson.value("x", 0.0), posJson.value("y", 0.0));
841 }
842
843 if (j.contains("uiId"))
844 component->setUiId(j["uiId"].get<uint64_t>());
845
846 component->setRotation(j.value("rotation", 0.0));
847 component->loadSerializedState(j);
848
849 return component;
850}
851
852} // namespace SILICON::ui
Base class for all digital circuit components.
static constexpr int GRID_SIZE
Grid cell size in scene units.
Factory for creating graphical circuit components.
std::unique_ptr< GraphicalComponent > create(std::string_view type, QGraphicsItem *parent=nullptr) const
Creates a component by type name.
QRectF getCollisionRect() const override
Gets physical body and port line bounds for drag/drop.
virtual PropertyMap resizedProperties(QSizeF size, ResizeHandle handle, const PropertyMap &initial)
ComponentResizeState resizeState() const
void setPortLine(Port *port)
Creates the connecting line from port to shape.
void clearPorts()
Removes existing input/output ports and their line items.
void rotate()
Rotates the component by 90 degrees.
void prepareSceneBoundsChange()
Prepares a geometry edit and checks its final bounds on the event loop.
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override
std::optional< PropertyValue > getProperty(std::string_view key) const
void applyResizeState(const ComponentResizeState &state)
GraphicalComponent(ItemCategory category, QGraphicsItem *shape, QGraphicsItem *parent=nullptr, bool scanShape=false)
virtual void setPorts(const std::vector< PortPair > &busToPortInputs, const std::vector< PortPair > &busToPortOutputs)
Sets input and output ports.
std::vector< Port * > outputPorts
Output connection ports.
virtual nlohmann::ordered_json serialize() const
Serializes the component to JSON.
virtual const PropertyMap & getProperties() const
Properties exposed by graphical and simulation components alike.
QRectF boundingRectWithoutMargins() const
Gets bounding rectangle without margins.
QGraphicsItem * itemShape
The visual shape item.
std::optional< ResizeHandle > resizeHandleAt(QPointF localPos) const
virtual void applyProperty(std::string_view key, const PropertyValue &value)
QPoint scanImage(const QImage &image, PortSide side, QPoint initialPoint) const
Scans image for first non-transparent pixel.
virtual std::string getTypeName() const
Gets the component type name for serialization.
std::unordered_set< std::string, TransparentStringHash, std::equal_to<> > hiddenProperties
Property names hidden from the panel, still accessible and serialized. Add names in subclasses with h...
QRectF collisionRectForWires() const
Gets the collision rectangle extended for wire connections.
void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override
bool printPortNames
Whether to print port names.
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override
Handles double-clicks not consumed by a component-specific action.
void modeChanged(InteractionMode mode) override
Called when the interaction mode changes.
virtual std::span< const ResizeHandle > resizeHandles() const
bool isPropertyHidden(std::string_view key) const
Whether a property is omitted from the properties panel.
virtual bool isMultilineProperty(std::string_view key) const
auto getPorts() const
Borrows every port, inputs first, without copying or deduplicating.
QRectF boundingRect() const override
Gets bounding rectangle with selection margin.
virtual void loadSerializedState(const nlohmann::json &j)
Loads subclass-specific serialized state.
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
Paints the component (selection outline).
virtual std::optional< std::reference_wrapper< const StringPropertyOptions > > getStringPropertyOptions(std::string_view key) const
bool openDocumentOnDoubleClick(QGraphicsSceneMouseEvent *event, const std::string &path)
Queues document navigation for a left double-click in normal mode.
static std::unique_ptr< GraphicalComponent > deserialize(const nlohmann::json &j, GUIComponentFactory &factory)
Deserializes a component from JSON using the factory.
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.
int type() const override
Returns the item type identifier.
void setInitialPosition()
Sets the initialPosition of the item to its current position (should be used when placed).
virtual void modeChanged(InteractionMode mode)
Called when the interaction mode changes.
void setGeometryPosition(QPointF position)
GraphicalItem(ItemCategory category=ItemCategory::GraphicalItem, QGraphicsItem *parent=nullptr)
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override
Handles item change events.
bool isColliding() const
Checks if the item is colliding.
bool printName
Whether to write the port name on the component.
Port(unsigned int index, QPoint position, QString name, bool printName=false, QGraphicsItem *parent=nullptr)
Constructs a port.
QTransform labelTransform(const QRectF &rect, bool insideShape) const
QGraphicsLineItem * line
Visual line connecting to component.
bool inputAssignmentError
Whether the net associated with this port has an error.
unsigned int index
Port index in the port list.
PortSide side
Direction of the connecting line from port to component.
QPoint position
Position relative to component center.
friend class GraphicalComponent
unsigned int size
Number of wires represented by this port.
QRectF collisionRect() const
Gets the collision rectangle for wire detection.
QString name
Port name.
QRectF boundingRect() const override
Gets visual bounds, including port labels and stroked markers.
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
Paints port names, bus markers, and input assignment errors.
void setInputAssignmentError(bool failed)
Marks whether this port failed input assignment during simulation setup.
QLineF connectionLine() const
void setLine(QGraphicsLineItem *line)
Sets the connecting line.
void setSize(unsigned int newSize)
Sets the port bus size.
static const QColor & getColor(theme::ColorToken token)
Definition theme.hpp:92
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
std::unordered_map< std::string, PropertyValue, TransparentStringHash, TransparentStringEqual > PropertyMap
Map from property names to their values.
bool resizesRight(ResizeHandle handle)
std::pair< PortSide, QPoint > nearestPortSide(const QPoint &pt, const QRect &rect)
Finds the nearest rectangle side for an interior or exterior point.
bool resizesLeft(ResizeHandle handle)
bool resizesBottom(ResizeHandle handle)
bool isPortPositionOutside(const QPoint &pt, const QRect &rect)
Returns whether a position lies strictly beyond a rectangle boundary.
bool resizesTop(ResizeHandle handle)
QRect shapeRect(const QSize &size)
Definition geometry.hpp:42
QPointF resizeHandlePoint(const QRectF &bounds, ResizeHandle handle)
DiagramScene::InteractionMode InteractionMode
Alias for DiagramScene::InteractionMode.