27#include <nlohmann/json.hpp>
30#include <QDialogButtonBox>
33#include <QGraphicsScene>
34#include <QGraphicsView>
38#include <QResizeEvent>
39#include <QScopedValueRollback>
40#include <QSignalBlocker>
42#include <QTableWidget>
43#include <QTableWidgetItem>
62 using namespace SILICON::core;
66 [[nodiscard]] std::vector<Bus>
67 previewBuses(
const std::vector<GraphicalSubcircuitPortMetadata>& ports)
69 std::vector<Bus> buses;
70 buses.reserve(ports.size());
71 for (
const auto& port : ports)
72 buses.emplace_back(
static_cast<unsigned short>(std::max(1U,
port.busSize)));
78 const QRect rect =
shapeRect(metadata.widthHeight);
79 const auto positionPorts = [&](
auto& ports,
bool input) {
80 for (std::size_t i = 0; i < ports.size(); ++i) {
81 auto&
port = ports[i];
82 const QPoint position =
89 positionPorts(metadata.inputs,
true);
90 positionPorts(metadata.outputs,
false);
93 class PreviewSubcircuitComponent :
public Component {
95 explicit PreviewSubcircuitComponent(
const GraphicalSubcircuitMetadata& metadata)
96 :
Component(previewBuses(metadata.inputs), previewBuses(metadata.outputs))
103 class PreviewPortItem :
public QGraphicsItem {
105 PreviewPortItem(QString label,
bool inputPort, QSize shapeSize,
106 QGraphicsItem* parent =
nullptr)
107 : QGraphicsItem(parent),
108 label(std::move(label)),
109 inputPort(inputPort),
110 m_shapeSize(shapeSize)
112 setFlag(QGraphicsItem::ItemIsMovable);
113 setFlag(QGraphicsItem::ItemSendsGeometryChanges);
114 setAcceptHoverEvents(
true);
115 setCursor(Qt::OpenHandCursor);
119 void setConstrainPosition(std::function<QPointF(
const QPointF&)> callback)
121 constrainPosition = std::move(callback);
124 void setPositionChanged(std::function<
void(
const QPointF&)> callback)
126 positionChanged = std::move(callback);
129 QRectF boundingRect()
const override
131 return markerRect().united(labelRect()).adjusted(-4, -4, 4, 4);
134 void paint(QPainter* painter,
const QStyleOptionGraphicsItem* option,
135 QWidget* widget)
override
140 const QColor portColor = inputPort
143 painter->setRenderHint(QPainter::Antialiasing);
146 painter->setBrush(hovered ? portColor.lighter(125) : portColor);
147 painter->drawEllipse(markerRect());
150 painter->setFont(QFont(
"NovaMono", 9));
151 painter->drawText(labelRect(), Qt::AlignCenter, label);
155 QVariant itemChange(GraphicsItemChange change,
const QVariant& value)
override
157 if (change == QGraphicsItem::ItemPositionChange && constrainPosition)
158 return constrainPosition(
value.toPointF());
159 if (change == QGraphicsItem::ItemPositionHasChanged && positionChanged)
160 positionChanged(pos());
161 return QGraphicsItem::itemChange(change, value);
164 void hoverEnterEvent(QGraphicsSceneHoverEvent* event)
override
168 QGraphicsItem::hoverEnterEvent(event);
171 void hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
override
175 QGraphicsItem::hoverLeaveEvent(event);
178 void mousePressEvent(QGraphicsSceneMouseEvent* event)
override
180 setCursor(Qt::ClosedHandCursor);
181 QGraphicsItem::mousePressEvent(event);
184 void mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
override
186 setCursor(Qt::OpenHandCursor);
187 QGraphicsItem::mouseReleaseEvent(event);
191 [[nodiscard]]
PortSide currentSide()
const
197 [[nodiscard]] QRectF markerRect()
const
199 constexpr qreal RADIUS = 6.0;
200 return {-RADIUS, -RADIUS, RADIUS * 2.0, RADIUS * 2.0};
203 [[nodiscard]] QRectF labelRect()
const
205 const QFontMetricsF metrics(QFont(
"NovaMono", 9));
206 const QRectF text = metrics.boundingRect(label).adjusted(-6, -3, 6, 3);
207 constexpr qreal GAP = 8.0;
209 switch (currentSide()) {
211 return {-GAP - text.width(), -text.height() / 2.0, text.width(),
214 return {GAP, -text.height() / 2.0, text.width(), text.height()};
216 return {-text.width() / 2.0, -GAP - text.height(), text.width(),
219 return {-text.width() / 2.0, GAP, text.width(), text.height()};
225 bool inputPort =
true;
227 bool hovered =
false;
228 std::function<QPointF(
const QPointF&)> constrainPosition;
229 std::function<void(
const QPointF&)> positionChanged;
232 class ShapePreviewWidget :
public QGraphicsView {
234 explicit ShapePreviewWidget(QWidget* parent =
nullptr)
235 : QGraphicsView(parent), scene(new QGraphicsScene(this))
238 setMinimumSize(460, 320);
239 setRenderHint(QPainter::Antialiasing);
240 setDragMode(QGraphicsView::NoDrag);
241 setFrameShape(QFrame::StyledPanel);
244 void setPortMovedCallback(
245 std::function<
void(
bool inputPort, std::size_t index, QPoint position)>
248 portMovedCallback = std::move(callback);
251 void setMetadata(
const GraphicalSubcircuitMetadata& metadata)
253 shapeSize = metadata.widthHeight;
257 void setPortPosition(
bool inputPort, std::size_t index,
const QPoint& position)
259 auto& visuals = inputPort ? inputVisuals : outputVisuals;
260 if (index >= visuals.size())
263 const QScopedValueRollback guard(suppressCallbacks,
true);
268 void resizeEvent(QResizeEvent* event)
override
270 QGraphicsView::resizeEvent(event);
274 void drawBackground(QPainter* painter,
const QRectF& rect)
override
276 QGraphicsView::drawBackground(painter, rect);
278 const QRectF sceneBounds = scene->sceneRect();
280 painter->setPen(gridPen);
281 for (qreal x = sceneBounds.left(); x <= sceneBounds.right();
283 painter->drawLine(QLineF(x, sceneBounds.top(), x, sceneBounds.bottom()));
285 for (qreal y = sceneBounds.top(); y <= sceneBounds.bottom();
287 painter->drawLine(QLineF(sceneBounds.left(), y, sceneBounds.right(), y));
292 void rebuild(
const GraphicalSubcircuitMetadata& metadata)
296 inputVisuals.clear();
297 outputVisuals.clear();
300 scene->setSceneRect(-gridMargin, -gridMargin, shapeSize.width() + gridMargin * 2,
301 shapeSize.height() + gridMargin * 2);
302 addComponent(metadata);
304 addPorts(metadata.inputs,
true);
305 addPorts(metadata.outputs,
false);
306 updateComponentPorts();
310 void addComponent(
const GraphicalSubcircuitMetadata& metadata)
312 component =
new GraphicalLogicComponent(
313 std::make_shared<PreviewSubcircuitComponent>(metadata),
314 new SubcircuitRectShape(shapeSize),
nullptr,
false);
315 component->setZValue(1);
316 scene->addItem(component);
319 void addPorts(
const std::vector<GraphicalSubcircuitPortMetadata>& ports,
322 auto& visuals = inputPort ? inputVisuals : outputVisuals;
323 visuals.reserve(ports.size());
325 for (std::size_t index = 0; index < ports.size(); ++index) {
326 const auto&
port = ports[index];
327 QString label = QString::fromStdString(
port.name);
329 auto* item =
new PreviewPortItem(label, inputPort, shapeSize);
330 item->setToolTip(QString::fromStdString(
port.name));
332 item->setConstrainPosition([
this](
const QPointF& position) {
335 item->setPositionChanged([
this, inputPort, index](
const QPointF& position) {
336 auto& visuals = inputPort ? inputVisuals : outputVisuals;
337 if (index >= visuals.size())
339 updateComponentPorts();
340 if (!suppressCallbacks && portMovedCallback)
341 portMovedCallback(inputPort, index, position.toPoint());
343 scene->addItem(item);
345 visuals.push_back(item);
349 std::vector<PortPair> previewPortPairs(
const std::vector<PreviewPortItem*>& visuals,
350 bool inputPort)
const
352 std::vector<PortPair> pairs;
353 pairs.reserve(visuals.size());
354 for (
const auto* item : visuals) {
355 pairs.emplace_back(item->toolTip().isEmpty()
356 ? QString(inputPort ?
"input" :
"output")
358 item->pos().toPoint());
363 void updateComponentPorts()
368 component->setPorts(previewPortPairs(inputVisuals,
true),
369 previewPortPairs(outputVisuals,
false));
374 if (!scene || scene->sceneRect().isEmpty())
376 fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
379 QGraphicsScene* scene =
nullptr;
380 GraphicalLogicComponent* component =
nullptr;
382 std::vector<PreviewPortItem*> inputVisuals;
383 std::vector<PreviewPortItem*> outputVisuals;
384 bool suppressCallbacks =
false;
385 std::function<void(
bool, std::size_t, QPoint)> portMovedCallback;
389 makePortPositionTable(
const std::vector<GraphicalSubcircuitPortMetadata>& ports,
392 auto* table =
new QTableWidget(parent);
393 table->setColumnCount(4);
394 table->setHorizontalHeaderLabels(
395 {QObject::tr(
"Name"), QObject::tr(
"X"), QObject::tr(
"Y"), QObject::tr(
"Bus")});
396 table->setRowCount(
static_cast<int>(ports.size()));
398 for (
int row = 0; row < static_cast<int>(ports.size()); ++row) {
399 const auto&
port = ports[
static_cast<std::size_t
>(row)];
400 auto* name =
new QTableWidgetItem(QString::fromStdString(
port.name));
401 name->setFlags(name->flags() & ~Qt::ItemIsEditable);
402 table->setItem(row, 0, name);
404 table->setItem(row, 1,
new QTableWidgetItem(QString::number(gridPosition.x())));
405 table->setItem(row, 2,
new QTableWidgetItem(QString::number(gridPosition.y())));
406 auto* bus =
new QTableWidgetItem(QString::number(
port.busSize));
407 bus->setFlags(bus->flags() & ~Qt::ItemIsEditable);
408 table->setItem(row, 3, bus);
410 table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
411 table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
412 table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
413 table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
417 void setPortTablePosition(QTableWidget* table,
int row,
const QPoint& position)
419 if (row < 0 || row >= table->rowCount())
422 const QSignalBlocker blocker(table);
425 table->item(row, 1)->setText(QString::number(gridPosition.x()));
426 table->item(row, 2)->setText(QString::number(gridPosition.y()));
429 void setPortTablePositions(QTableWidget* table,
430 const std::vector<GraphicalSubcircuitPortMetadata>& ports)
432 const int rowCount = std::min(table->rowCount(),
static_cast<int>(ports.size()));
433 for (
int row = 0; row < rowCount; ++row)
434 setPortTablePosition(table, row, ports[
static_cast<std::size_t
>(row)].position);
441 QUndoStack* undoStack, QWidget* parent)
448 const auto* document =
project.documents().find(path);
452 const auto json = nlohmann::json::parse(document->getContents(),
nullptr,
false);
459 auto draft = std::make_shared<GraphicalSubcircuitMetadata>(*metadata);
460 sanitizePortPositions(*draft);
462 auto* dialog =
new QDialog(parent);
463 dialog->setWindowTitle(QObject::tr(
"Edit shape"));
464 dialog->resize(860, 560);
465 auto* layout =
new QVBoxLayout(dialog);
466 auto* body =
new QHBoxLayout();
467 layout->addLayout(body);
469 auto* preview =
new ShapePreviewWidget(dialog);
470 preview->setMetadata(*draft);
471 body->addWidget(preview, 1);
473 auto* controls =
new QVBoxLayout();
474 body->addLayout(controls);
476 auto* form =
new QFormLayout();
477 controls->addLayout(form);
479 auto* width =
new QSpinBox(dialog);
480 width->setRange(1, 100);
481 width->setValue(
pixelsToGrid(draft->widthHeight.width()));
482 auto* height =
new QSpinBox(dialog);
483 height->setRange(1, 100);
484 height->setValue(
pixelsToGrid(draft->widthHeight.height()));
485 form->addRow(QObject::tr(
"Width"), width);
486 form->addRow(QObject::tr(
"Height"), height);
488 auto* inputTable = makePortPositionTable(draft->inputs, dialog);
489 auto* outputTable = makePortPositionTable(draft->outputs, dialog);
490 controls->addWidget(
new QLabel(QObject::tr(
"Inputs"), dialog));
491 controls->addWidget(inputTable);
492 controls->addWidget(
new QLabel(QObject::tr(
"Outputs"), dialog));
493 controls->addWidget(outputTable);
495 auto updatePortTables = [draft, inputTable, outputTable] {
496 setPortTablePositions(inputTable, draft->inputs);
497 setPortTablePositions(outputTable, draft->outputs);
502 auto applySize = [draft, preview, updatePortTables](
int widthGrid,
int heightGrid) {
503 draft->autoSize =
false;
505 sanitizePortPositions(*draft);
507 preview->setMetadata(*draft);
511 width, &QSpinBox::valueChanged, dialog,
512 [height, applySize](
int value) { applySize(value, height->value()); });
513 QObject::connect(height, &QSpinBox::valueChanged, dialog,
514 [width, applySize](
int value) { applySize(width->value(), value); });
516 auto applyTableEdit = [draft, preview, markManual](QTableWidget* table,
518 QTableWidgetItem* item) {
519 if (!item || (item->column() != 1 && item->column() != 2))
522 auto& ports = inputPort ? draft->inputs : draft->outputs;
523 const int row = item->row();
524 if (row < 0 || row >=
static_cast<int>(ports.size()))
527 auto& port = ports[
static_cast<std::size_t
>(row)];
529 const auto currentGridPosition =
pixelsToGrid(port.position);
532 const int requestedX = table->item(row, 1)->text().toInt(&okX);
533 const int requestedY = table->item(row, 2)->text().toInt(&okY);
535 gridToPixels(QPoint(okX ? requestedX : currentGridPosition.x(),
536 okY ? requestedY : currentGridPosition.y())),
538 setPortTablePosition(table, row, port.position);
539 preview->setPortPosition(inputPort,
static_cast<std::size_t
>(row), port.position);
542 QObject::connect(inputTable, &QTableWidget::itemChanged, dialog,
543 [inputTable, applyTableEdit](QTableWidgetItem* item) {
544 applyTableEdit(inputTable,
true, item);
546 QObject::connect(outputTable, &QTableWidget::itemChanged, dialog,
547 [outputTable, applyTableEdit](QTableWidgetItem* item) {
548 applyTableEdit(outputTable,
false, item);
551 preview->setPortMovedCallback([draft, inputTable, outputTable,
552 markManual](
bool inputPort, std::size_t index,
554 auto& ports = inputPort ? draft->inputs : draft->outputs;
555 if (index >= ports.size())
558 ports[index].position = position;
560 setPortTablePosition(inputPort ? inputTable : outputTable,
static_cast<int>(index),
565 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dialog);
566 layout->addWidget(buttons);
567 QObject::connect(buttons, &QDialogButtonBox::accepted, dialog, &QDialog::accept);
568 QObject::connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
570 dialog, &QDialog::accepted, dialog, [draft, path, undoStack, parent, &
project] {
572 const auto* currentDocument =
project.documents().find(path);
573 if (!currentDocument)
576 const auto oldSceneJson = currentDocument->getContents();
577 auto json = nlohmann::json::parse(oldSceneJson);
579 const auto newSceneJson = json.dump(2);
580 if (newSceneJson == oldSceneJson)
586 auto apply = [path, &
project](
const std::string& sceneJson) {
591 oldSceneJson, newSceneJson, std::move(apply)));
595 }
catch (
const std::exception& e) {
602 dialog->setAttribute(Qt::WA_DeleteOnClose);
static ComponentRegistry & instance()
Base class for all digital circuit components.
static constexpr std::string_view Type
static constexpr int GRID_SIZE
Grid cell size in scene units.
static QPoint snapToGrid(QPointF point)
Snaps a point to the grid.
static const QColor & getColor(theme::ColorToken token)
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::pair< PortSide, QPoint > nearestPortSide(const QPoint &pt, const QRect &rect)
Finds the nearest rectangle side for an interior or exterior point.
std::optional< GraphicalSubcircuitMetadata > parseGraphicalSubcircuitMetadata(const nlohmann::json &document)
Parses graphical subcircuit metadata from a scene document.
int pixelsToGrid(int value)
nlohmann::ordered_json graphicalSubcircuitMetadataToJson(const GraphicalSubcircuitMetadata &metadata)
Serializes graphical metadata to the JSON shape/port object.
int gridToPixels(int value)
constexpr int EXTERNAL_PORT_MARGIN_GRID
QRect shapeRect(const QSize &size)
QPoint sanitizePortPosition(const QPointF &position, const QRect &rect)
GraphicalSubcircuitMetadata synchronizeGraphicalSubcircuitMetadata(const nlohmann::json &document, const GraphicalSubcircuitMetadata &fallbackMetadata, const CircuitResolver *resolver)
Reconciles saved graphical metadata with the current circuit document.
void editGraphicalSubcircuitShape(const std::string &slug, SILICON::project::ProjectContext &project, QUndoStack *undoStack, QWidget *parent)
Opens the modal editor for a project subcircuit's graphical shape.
QPoint automaticPortPosition(const QSize &size, bool input, std::size_t index, std::size_t count)