27#include <QFontMetricsF>
28#include <QGraphicsSceneHoverEvent>
29#include <QGraphicsView>
34#include <QPainterPathStroker>
44using namespace SILICON::core;
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;
60class ThemedPortLineItem :
public QGraphicsLineItem {
62 ThemedPortLineItem(
const QLineF& line, QGraphicsItem* parent)
63 : QGraphicsLineItem(line, parent)
68 void paint(QPainter* painter,
const QStyleOptionGraphicsItem* option,
69 QWidget* widget)
override
71 auto themedPen = pen();
73 painter->setPen(themedPen);
74 painter->drawLine(line());
78QFont portMarkerFont(
const QFont& baseFont)
80 QFont font(
"NovaMono");
82 font.setPointSizeF(QFontInfo(baseFont).pointSizeF());
86QRectF strokedLineRect(
const QLineF& line,
const qreal width)
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();
97QLineF portSlash(
const QLineF& line)
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));
105QRectF portNameRect(
const QLineF& line,
const QString& name,
const PortSide side,
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();
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);
127 return {point.x() -
width / 2.0,
128 point.y() - margin / 1.5 - padding.bottom() - height,
width, height};
130 return {point.x() -
width / 2.0, point.y() + margin / 1.5 + padding.top(),
133 return {point.x() + margin + padding.left(), point.y() - height / 2.0,
136 return {point.x() - margin - padding.right() -
width,
137 point.y() - height / 2.0,
width, height};
142QRectF portSizeLabelRect(
const QPointF& midpoint,
const QRectF& textRect,
146 return {midpoint.x() - textRect.width(), midpoint.y() - textRect.height() / 2.0,
147 textRect.width(), textRect.height()};
150 return {midpoint.x() - textRect.width() / 2.0, midpoint.y() - textRect.height(),
151 textRect.width(), textRect.height()};
154QRectF portNameBounds(QRectF rect,
const QString& name)
156 if (name == QStringLiteral(
"clk")) {
157 constexpr qreal halfPen = ClockIconPenWidth / 2.0;
158 rect.adjust(-halfPen, -halfPen, halfPen, halfPen);
180 const auto found = properties.find(key);
181 return found == properties.end() ? std::nullopt
182 : std::optional<PropertyValue>(found->second);
185std::optional<std::reference_wrapper<const StringPropertyOptions>>
206 throw std::invalid_argument(
"Unknown graphical property: " + std::string(key));
213 setFlag(QGraphicsItem::ItemSendsGeometryChanges);
215 setAcceptHoverEvents(
true);
216 setAcceptedMouseButtons(Qt::AllButtons);
226 prepareGeometryChange();
234 QMetaObject::invokeMethod(
236 [
this, previousBounds] {
240 if (
auto* diagram = qobject_cast<DiagramScene*>(scene()))
241 diagram->expandSceneBounds(sceneBoundingRect());
243 Qt::QueuedConnection);
249 throw std::invalid_argument(
"setItemShape: shape must not be null");
256 delete std::exchange(this->
itemShape,
nullptr);
265 const auto margin =
resizeHandles().empty() ? SelectionMargin : ResizeHitRadius + 1;
277 const auto* diagram = qobject_cast<DiagramScene*>(scene());
279 && diagram->getInteractionMode() == InteractionMode::NORMAL_MODE
280 && diagram->selectedItems().size() == 1;
287 std::optional<ResizeHandle> closest;
288 qreal nearest = std::numeric_limits<qreal>::max();
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))
296 && distance < nearest) {
311 for (
const auto& [key, value] : state.
properties)
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]);
339 GraphicalItem::hoverMoveEvent(event);
345 GraphicalItem::hoverLeaveEvent(event);
357 return childrenBoundingRect();
366 auto style =
isColliding() ? Qt::SolidLine : Qt::DotLine;
368 painter->setPen(QPen(color, SelectionPenWidth, style));
369 painter->setBrush(Qt::NoBrush);
372 painter->setPen(QPen(color, 1));
376 painter->drawRect(QRectF(center - QPointF(ResizeHandleRadius, ResizeHandleRadius),
377 QSizeF(2 * ResizeHandleRadius, 2 * ResizeHandleRadius)));
389 rect = rect.united(port->mapRectToParent(port->collisionRect()));
396 setRotation(rotation() + 90);
402 if (change == ItemRotationChange || change == ItemTransformChange) {
405 port->prepareGeometryChange();
407 if (change == ItemRotationHasChanged || change == ItemTransformHasChanged) {
419 for (
const auto* port :
getPorts()) {
421 rect = rect.united(port->line->mapRectToParent(port->line->boundingRect()));
428 GraphicalItem::mouseDoubleClickEvent(event);
432 const std::string& path)
434 auto* diagram = qobject_cast<DiagramScene*>(scene());
435 if (event->button() != Qt::LeftButton || !diagram
436 || diagram->getInteractionMode() != InteractionMode::NORMAL_MODE
437 || !diagram->getDocumentNavigator())
441 QMetaObject::invokeMethod(
444 if (
auto* diagram = qobject_cast<DiagramScene*>(scene())) {
445 if (
auto* navigator = diagram->getDocumentNavigator())
446 navigator->activateDocument(path);
449 Qt::QueuedConnection);
455 const std::vector<PortPair>& busToPortOutputs)
460 for (
const auto& [index, pair] : busToPortInputs | SILICON::views::enumerate) {
461 const auto& [name, pos] = pair;
465 auto p =
new Port(index, pos, name);
470 for (
const auto& [index, pair] : busToPortOutputs | SILICON::views::enumerate) {
471 const auto& [name, pos] = pair;
474 auto p =
new Port(index, pos, name);
478 if (
auto* diagram = qobject_cast<DiagramScene*>(scene()))
479 diagram->requestConnectionsRefresh();
484 if (
auto* diagram = qobject_cast<DiagramScene*>(scene()))
485 diagram->requestConnectionsRefresh();
486 prepareGeometryChange();
492 port->prepareGeometryChange();
493 delete std::exchange(port->line,
nullptr);
501 const QPoint initialPoint)
const
510 const int initialCoord = horizontal ? initialPoint.x() : initialPoint.y();
512 const QPoint topLeft = image.rect().topLeft();
513 const QPoint bottomRight = image.rect().bottomRight();
515 const int leftUp = horizontal ? topLeft.x() : topLeft.y();
516 const int rightDown = horizontal ? bottomRight.x() : bottomRight.y();
518 for (qreal coord = initialCoord; (direction > 0) ? coord <= rightDown : coord >= leftUp;
519 coord += direction) {
521 horizontal ? QPoint(coord, initialPoint.y()) : QPoint(initialPoint.x(), coord);
523 if (qAlpha(image.pixel(p)) != 0) {
539 throw std::logic_error(
"setPortLine: item shape not set");
544 throw std::logic_error(
"setPortLine: shape bounding rect is empty");
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");
552 shapeImage = QImage(shapeSize, QImage::Format_ARGB32);
553 shapeImage.fill(Qt::transparent);
554 QPainter painter(&shapeImage);
555 painter.setRenderHint(QPainter::Antialiasing);
558 const auto options = QStyleOptionGraphicsItem();
559 itemShape->paint(&painter, &options,
nullptr);
562 const auto portPos = port->getPosition();
563 const auto portRect =
shapeRect.toRect();
567 throw std::logic_error(
"setPortLine: port position is not outside the shape");
569 const auto [portSide, naiveProjection] =
nearestPortSide(portPos, portRect);
571 const QPoint projectionOnShape =
scanImage(shapeImage, portSide, naiveProjection);
574 prepareGeometryChange();
575 port->side = portSide;
577 port->setLine(
new ThemedPortLineItem(QLineF(portPos, projectionOnShape),
this));
580 port->setToolTip(port->name);
585 QGraphicsItem* parent)
586 : QGraphicsItem(parent)
591 this->name = std::move(
name);
596 const auto portLine =
line->line();
597 return {mapFromItem(
line, portLine.p1()), mapFromItem(
line, portLine.p2())};
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());
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);
618 if (
const auto* shape = component->getItemShape();
620 && shape->boundingRect().contains(
621 shape->mapRectFromItem(
this, horizontal.mapRect(rect))))
626 return aroundCenter(angle > 90.0 && angle <= 270.0 ? 180.0 : 0.0);
633 component->prepareSceneBoundsChange();
634 prepareGeometryChange();
644 QRectF rect = mapRectFromItem(
line,
line->boundingRect())
645 .united(strokedLineRect(portLine, PortErrorPenWidth));
649 const auto includeLabelBounds = [&](
const QFont& baseFont) {
650 const QFont markerFont = portMarkerFont(baseFont);
652 const auto labelRect =
653 portNameBounds(portNameRect(portLine,
name,
side, markerFont),
name);
654 rect = rect.united(
labelTransform(labelRect,
true).mapRect(labelRect));
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));
667 const auto views = scene() ? scene()->views() : QList<QGraphicsView*>{};
669 includeLabelBounds(QApplication::font());
671 for (
const auto* view :
views)
672 includeLabelBounds(view->viewport()->font());
680 component->prepareGeometryChange();
681 prepareGeometryChange();
682 if (
line->parentItem() != parentItem()) {
684 component->prepareGeometryChange();
687 setParentItem(
line->parentItem());
688 setZValue(
line->zValue() + 1.0);
693 const unsigned int normalizedSize = std::max(1U, newSize);
694 if (
size == normalizedSize)
698 size = normalizedSize;
701 parentItem()->update();
715void Port::paint(QPainter* painter,
const QStyleOptionGraphicsItem* option,
724 const bool isBusPort = (
size != 1);
726 const QFont markerFont = portMarkerFont(painter->font());
733 painter->setPen(QPen(portColor, PortErrorPenWidth, Qt::SolidLine));
734 painter->drawLine(portLine);
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);
746 painter->setFont(markerFont);
747 painter->setPen(QPen(portColor));
748 if (
name == QStringLiteral(
"clk")) {
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);
760 painter->drawText(labelRect, label, textOption);
762 if (inverted && !label.isEmpty()) {
763 const QFontMetricsF metrics(markerFont, painter->device());
764 const QRectF textBounds = painter->boundingRect(labelRect, label, textOption);
766 const qreal y = textBounds.top() + metrics.ascent()
767 + metrics.tightBoundingRect(label).top() - metrics.lineWidth()
769 painter->setPen(QPen(portColor, metrics.lineWidth(), Qt::SolidLine, Qt::FlatCap));
770 painter->drawLine(QLineF(textBounds.left(), y, textBounds.right(), y));
776 const QString sizeText = QString::number(
size);
777 const QFontMetricsF metrics(markerFont);
780 painter->setPen(QPen(portColor, SlashPenWidth));
781 painter->drawLine(portSlash(portLine));
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);
789 painter->setFont(markerFont);
790 painter->setPen(portColor);
791 painter->drawText(labelRect, sizeText, QTextOption(Qt::AlignCenter));
802 QPainterPath boundingPath{};
803 boundingPath.addRect(mapRectFromItem(
line,
line->boundingRect()));
805 QPainterPath subtract{};
808 return boundingPath.subtracted(subtract).boundingRect();
817 {
"position", {{
"x", pos().x()}, {
"y", pos().y()}}},
818 {
"rotation",
static_cast<int>(rotation())}};
824std::unique_ptr<GraphicalComponent>
827 std::string
type = j.value(
"type",
"");
829 throw std::runtime_error(
"GraphicalComponent deserialization: missing 'type' field");
834 throw std::runtime_error(
835 std::format(
"GraphicalComponent deserialization: unknown type '{}'",
type));
838 if (j.contains(
"position")) {
839 const auto& posJson = j[
"position"];
840 component->setPos(posJson.value(
"x", 0.0), posJson.value(
"y", 0.0));
843 if (j.contains(
"uiId"))
844 component->setUiId(j[
"uiId"].get<uint64_t>());
846 component->setRotation(j.value(
"rotation", 0.0));
847 component->loadSerializedState(j);
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
bool resizeHandlesVisible() 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
virtual QRectF resizeBounds() 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.
void prepareBoundsChange()
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.
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)
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)
QPointF resizeHandlePoint(const QRectF &bounds, ResizeHandle handle)
DiagramScene::InteractionMode InteractionMode
Alias for DiagramScene::InteractionMode.
core::PropertyMap properties