SILICON
Loading...
Searching...
No Matches
metadata.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 "metadata.hpp"
19
20#include <algorithm>
21#include <format>
22#include <numeric>
23#include <optional>
24#include <ranges>
25#include <stdexcept>
26#include <string_view>
27#include <unordered_map>
28#include <utility>
29
30#include <nlohmann/json.hpp>
31
32#include <core/circuit.hpp>
36
37namespace SILICON::ui {
38using namespace SILICON::core;
39
40namespace {
41
43 PortPositioning readLayoutPositioning(const nlohmann::json& graphical)
44 {
45 const auto& shape = graphical.at("shape");
46 if (const auto mode = shape.find("positioning"); mode != shape.end()) {
47 if (*mode == "automatic")
49 if (*mode == "manual")
51 throw std::invalid_argument("Invalid port positioning mode");
52 }
53 // Old graphical documents always persisted coordinates, even for defaults.
54 // Preserve them on migration; new documents explicitly choose a mode.
56 }
57
58[[nodiscard]] GraphicalSubcircuitPortMetadata parsePort(const nlohmann::json& json)
59{
60 // Port coordinates in JSON are relative to the rectangle top-left, in grid units.
61 return {.name = json.value("name", std::string()),
62 .position = gridToPixels(QPoint(json.value("x", 0), json.value("y", 0))),
63 .busSize = static_cast<unsigned int>(std::max(1, json.value("busSize", 1))),
64 .id = json.contains("id") ? deserializePortId(json.at("id")) : 0};
65}
66
67[[nodiscard]] nlohmann::json portToJson(const GraphicalSubcircuitPortMetadata& port)
68{
69 // Keep project files grid-based even though QGraphicsItems consume pixels.
70 const auto gridPosition = pixelsToGrid(port.position);
71 nlohmann::json result = {{"name", port.name},
72 {"x", gridPosition.x()},
73 {"y", gridPosition.y()},
74 {"busSize", port.busSize}};
75 if (port.id != 0)
76 result["id"] = port.id;
77 return result;
78}
79
80struct PortDefinition {
81 std::string name;
82 unsigned int busSize;
83 uint64_t id;
84};
85
86// Visual positions affect display-name suffixes only. Semantic order and widths
87// always come from the core interface, including ports that share the same wires.
88[[nodiscard]] std::vector<PortDefinition>
89portDefinitions(const std::vector<CircuitPort>& ports, const nlohmann::json& document,
90 bool inputPort)
91{
92 std::unordered_map<VertexDescriptor, QPoint> positions;
93 if (const auto visual = document.find("visual");
94 visual != document.end() && visual->is_object()) {
95 if (const auto components = visual->find("components");
96 components != visual->end() && components->is_array()) {
97 for (const auto& component : *components) {
98 const auto vertex = component.find("vertexId");
99 const auto position = component.find("position");
100 if (vertex != component.end() && vertex->is_number_integer()
101 && position != component.end() && position->is_object()) {
102 positions.emplace(vertex->get<VertexDescriptor>(),
103 QPoint(static_cast<int>(position->value("x", 0.0)),
104 static_cast<int>(position->value("y", 0.0))));
105 }
106 }
107 }
108 }
109
110 std::vector<std::size_t> visualOrder(ports.size());
111 std::iota(visualOrder.begin(), visualOrder.end(), 0);
112 auto position = [&](std::size_t index) {
113 const auto vertex = ports[index].boundaryVertex;
114 const auto it = vertex ? positions.find(*vertex) : positions.end();
115 return it == positions.end() ? QPoint{} : it->second;
116 };
117 std::ranges::stable_sort(visualOrder, [&](std::size_t lhs, std::size_t rhs) {
118 const auto a = position(lhs);
119 const auto b = position(rhs);
120 return a.y() != b.y() ? a.y() < b.y() : a.x() < b.x();
121 });
122
123 std::vector<PortDefinition> definitions(ports.size());
124 std::unordered_map<std::string, int> seenNames;
125 for (const auto index : visualOrder) {
126 const auto& port = ports[index];
127 auto name =
128 port.name.empty() ? std::string(inputPort ? "input" : "output") : port.name;
129 const int seen = seenNames[name]++;
130 if (seen != 0)
131 name = std::format("{}{}", name, seen + 1);
132 definitions[index] = {
133 .name = std::move(name),
134 .busSize = static_cast<unsigned int>(std::max<std::size_t>(1, port.bus.size())),
135 .id = port.id};
136 }
137 return definitions;
138}
139
140[[nodiscard]] std::optional<std::size_t>
141findMatchingPort(const PortDefinition& definition, std::size_t index,
142 const std::vector<GraphicalSubcircuitPortMetadata>& fallbackPorts,
143 const std::vector<bool>& usedFallback)
144{
145 const auto candidates = std::views::iota(std::size_t{0}, fallbackPorts.size());
146 auto find = [&](const auto& predicate) -> std::optional<std::size_t> {
147 const auto match = std::ranges::find_if(candidates, [&](std::size_t candidate) {
148 return !usedFallback[candidate] && predicate(fallbackPorts[candidate]);
149 });
150 if (match == candidates.end())
151 return std::nullopt;
152 return *match;
153 };
154
155 if (definition.id != 0) {
156 if (const auto match =
157 find([&](const auto& port) { return port.id == definition.id; }))
158 return match;
159 }
160
161 if (const auto match = find(
162 [&](const auto& port) { return port.id == 0 && port.name == definition.name; }))
163 return match;
164
165 if (index < fallbackPorts.size() && !usedFallback[index]
166 && fallbackPorts[index].id == 0)
167 return index;
168 return std::nullopt;
169}
170
171[[nodiscard]] std::vector<GraphicalSubcircuitPortMetadata>
172synchronizePorts(const std::vector<PortDefinition>& definitions,
173 const GraphicalSubcircuitMetadata& fallbackMetadata,
174 const GraphicalSubcircuitMetadata& metadata, bool inputPort)
175{
176 const auto& fallbackPorts =
177 inputPort ? fallbackMetadata.inputs : fallbackMetadata.outputs;
178 std::vector<GraphicalSubcircuitPortMetadata> synchronized;
179 synchronized.reserve(definitions.size());
180 std::vector<bool> usedFallback(fallbackPorts.size(), false);
181 const bool layoutChanged = metadata.widthHeight != fallbackMetadata.widthHeight
182 || definitions.size() != fallbackPorts.size();
183 for (std::size_t i = 0; i < definitions.size(); ++i) {
184 const auto& definition = definitions[i];
185 const auto match = findMatchingPort(definition, i, fallbackPorts, usedFallback);
186
187 // A reorder alone keeps each identity's pin location. Automatic positions
188 // reflow when the shape or port count changes; manual positions never reflow.
189 const bool placeAutomatically =
190 !match || (metadata.positioning == PortPositioning::Automatic && layoutChanged);
191 const QPoint position = placeAutomatically
192 ? automaticPortPosition(metadata.widthHeight, inputPort,
193 i, definitions.size())
194 : fallbackPorts[*match].position;
195 if (match)
196 usedFallback[*match] = true;
197
198 synchronized.push_back({.name = definition.name,
199 .position = position,
200 .busSize = definition.busSize,
201 .id = definition.id});
202 }
203
204 return synchronized;
205}
206
207[[nodiscard]] std::string fallbackPortName(const bool inputPort, const std::size_t index)
208{
209 const std::string base = inputPort ? "input" : "output";
210 return index == 0 ? base : std::format("{}{}", base, index + 1);
211}
212
213} // namespace
214
215QSize defaultGraphicalSubcircuitSize(std::size_t inputCount, std::size_t outputCount)
216{
217 // Leave half a port spacing above and below the taller column of ports.
218 const auto rows = std::max({std::size_t{1}, inputCount, outputCount});
219 const int size = gridToPixels(EXTERNAL_PORT_SPACING_GRID * static_cast<int>(rows));
220 return {size, size};
221}
222
223std::optional<GraphicalSubcircuitMetadata>
224parseGraphicalSubcircuitMetadata(const nlohmann::json& document)
225{
226 try {
227 if (!document.contains("graphicalComponent")
228 || !document["graphicalComponent"].is_object()) {
229 return std::nullopt;
230 }
231
232 const auto& graphical = document["graphicalComponent"];
233 const auto& shape = graphical.at("shape");
234 if (!shape.is_object() || shape.value("type", std::string()) != "rectangle")
235 return std::nullopt;
236
238 metadata.positioning = readLayoutPositioning(graphical);
239 // Existing documents with explicit dimensions retain their saved shape.
240 metadata.autoSize =
241 shape.value("autoSize", !shape.contains("width") && !shape.contains("height"));
242 metadata.widthHeight =
243 QSize(gridToPixels(
244 std::max(1, shape.value("width", GRAPHICAL_SUBCIRCUIT_DEFAULT_SIZE))),
246 std::max(1, shape.value("height", GRAPHICAL_SUBCIRCUIT_DEFAULT_SIZE))));
247
248 if (const auto inputs = graphical.find("inputs");
249 inputs != graphical.end() && inputs->is_array()) {
250 for (const auto& input : *inputs)
251 metadata.inputs.push_back(parsePort(input));
252 }
253 if (const auto outputs = graphical.find("outputs");
254 outputs != graphical.end() && outputs->is_array()) {
255 for (const auto& output : *outputs)
256 metadata.outputs.push_back(parsePort(output));
257 }
258
259 if (metadata.autoSize)
260 metadata.widthHeight =
261 defaultGraphicalSubcircuitSize(metadata.inputs.size(), metadata.outputs.size());
262
263 return metadata;
264 } catch (const std::exception&) {
265 return std::nullopt;
266 }
267}
268
269bool subcircuitHasGraphicalMetadata(std::string_view sceneJson)
270{
272 nlohmann::json::parse(sceneJson, nullptr, false))
273 .has_value();
274}
275
277 const nlohmann::json& document, const GraphicalSubcircuitMetadata& fallbackMetadata,
278 const CircuitResolver* resolver)
279{
280 try {
281 auto metadata = fallbackMetadata;
282 const auto circuit = deserializeCircuitDocument(
283 document.dump(), ComponentRegistry::instance(), resolver);
284 const auto inputs = portDefinitions(circuit.getInputPorts(), document, true);
285 const auto outputs = portDefinitions(circuit.getOutputPorts(), document, false);
286 if (metadata.autoSize) {
287 metadata.widthHeight =
288 defaultGraphicalSubcircuitSize(inputs.size(), outputs.size());
289 }
290 metadata.inputs = synchronizePorts(inputs, fallbackMetadata, metadata, true);
291 metadata.outputs = synchronizePorts(outputs, fallbackMetadata, metadata, false);
292 return metadata;
293 } catch (const std::exception&) {
294 return fallbackMetadata;
295 }
296}
297
298std::vector<GraphicalSubcircuitPortMetadata> synchronizePortsWithBuses(
299 const std::vector<GraphicalSubcircuitPortMetadata>& fallbackPorts,
300 const std::vector<Bus>& buses, const GraphicalSubcircuitMetadata& metadata,
301 const bool inputPort)
302{
303 std::vector<GraphicalSubcircuitPortMetadata> synchronized;
304 synchronized.reserve(buses.size());
305
306 for (std::size_t i = 0; i < buses.size(); ++i) {
307 const bool hasFallback = i < fallbackPorts.size();
308 synchronized.push_back(
309 {.name = hasFallback && !fallbackPorts[i].name.empty()
310 ? fallbackPorts[i].name
311 : fallbackPortName(inputPort, i),
312 .position = hasFallback && metadata.positioning == PortPositioning::Manual
313 ? fallbackPorts[i].position
314 : automaticPortPosition(metadata.widthHeight, inputPort, i,
315 buses.size()),
316 .busSize = static_cast<unsigned int>(std::max<std::size_t>(1, buses[i].size())),
317 .id = hasFallback ? fallbackPorts[i].id : 0});
318 }
319
320 return synchronized;
321}
322
323nlohmann::ordered_json
325{
326 nlohmann::json inputs = nlohmann::json::array();
327 for (const auto& port : metadata.inputs)
328 inputs.push_back(portToJson(port));
329
330 nlohmann::json outputs = nlohmann::json::array();
331 for (const auto& port : metadata.outputs)
332 outputs.push_back(portToJson(port));
333
334 return nlohmann::json{
335 {"shape",
336 {{"type", "rectangle"},
337 {"autoSize", metadata.autoSize},
338 {"positioning",
339 metadata.positioning == PortPositioning::Automatic ? "automatic" : "manual"},
340 {"width", pixelsToGrid(metadata.widthHeight.width())},
341 {"height", pixelsToGrid(metadata.widthHeight.height())}}},
342 {"inputs", std::move(inputs)},
343 {"outputs", std::move(outputs)}};
344}
345
346} // namespace SILICON::ui
static ComponentRegistry & instance()
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
Circuit deserializeCircuitDocument(const std::string_view contents, const ComponentRegistry &registry, const CircuitResolver *resolver)
uint64_t deserializePortId(const nlohmann::json &value)
boost::graph_traits< CircuitGraph >::vertex_descriptor VertexDescriptor
Descriptor type for vertices in the circuit graph.
Definition circuit.hpp:94
QSize defaultGraphicalSubcircuitSize(std::size_t inputCount, std::size_t outputCount)
Default square dimensions for the boundary port counts, in pixels.
Definition metadata.cpp:215
std::optional< GraphicalSubcircuitMetadata > parseGraphicalSubcircuitMetadata(const nlohmann::json &document)
Parses graphical subcircuit metadata from a scene document.
Definition metadata.cpp:224
constexpr int EXTERNAL_PORT_SPACING_GRID
Definition geometry.hpp:28
int pixelsToGrid(int value)
Definition grid.hpp:33
bool subcircuitHasGraphicalMetadata(std::string_view sceneJson)
Checks whether a scene document contains valid graphical metadata.
Definition metadata.cpp:269
nlohmann::ordered_json graphicalSubcircuitMetadataToJson(const GraphicalSubcircuitMetadata &metadata)
Serializes graphical metadata to the JSON shape/port object.
Definition metadata.cpp:324
int gridToPixels(int value)
Definition grid.hpp:29
GraphicalSubcircuitMetadata synchronizeGraphicalSubcircuitMetadata(const nlohmann::json &document, const GraphicalSubcircuitMetadata &fallbackMetadata, const CircuitResolver *resolver)
Reconciles saved graphical metadata with the current circuit document.
Definition metadata.cpp:276
std::vector< GraphicalSubcircuitPortMetadata > synchronizePortsWithBuses(const std::vector< GraphicalSubcircuitPortMetadata > &fallbackPorts, const std::vector< Bus > &buses, const GraphicalSubcircuitMetadata &metadata, const bool inputPort)
Reconciles metadata when a loaded subcircuit component has a different bus count than its saved graph...
Definition metadata.cpp:298
constexpr int GRAPHICAL_SUBCIRCUIT_DEFAULT_SIZE
Default subcircuit rectangle size in persisted grid units.
Definition metadata.hpp:44
QPoint automaticPortPosition(const QSize &size, bool input, std::size_t index, std::size_t count)
Definition geometry.hpp:31
Visual metadata used to render a subcircuit as a reusable component.
Definition metadata.hpp:74
std::vector< GraphicalSubcircuitPortMetadata > inputs
Input boundary ports in core interface order.
Definition metadata.hpp:83
PortPositioning positioning
One positioning mode for all input and output ports of the shape.
Definition metadata.hpp:81
std::vector< GraphicalSubcircuitPortMetadata > outputs
Output boundary ports in core interface order.
Definition metadata.hpp:85
QSize widthHeight
Rectangle dimensions in pixels.
Definition metadata.hpp:76
bool autoSize
Derive dimensions from port counts until the user edits the size.
Definition metadata.hpp:79
Visual metadata for one subcircuit boundary port.
Definition metadata.hpp:56