SILICON
Loading...
Searching...
No Matches
componentCatalogOverlay.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
20#include <algorithm>
21#include <cmath>
22#include <optional>
23#include <ranges>
24#include <type_traits>
25#include <utility>
26
27#include <QAbstractItemView>
28#include <QApplication>
29#include <QGraphicsScene>
30#include <QGraphicsView>
31#include <QHeaderView>
32#include <QKeyEvent>
33#include <QLabel>
34#include <QLineEdit>
35#include <QPainter>
36#include <QPixmap>
37#include <QSignalBlocker>
38#include <QStringList>
39#include <QTableWidget>
40#include <QTableWidgetItem>
41#include <QVBoxLayout>
42
50#include <ui/shell/theme.hpp>
51
52namespace SILICON::ui {
53 using namespace SILICON::core;
54
55 namespace {
56
57 constexpr int CATALOG_PREVIEW_PADDING = 8;
58 constexpr int CATALOG_CATEGORY_ROW_HEIGHT = 32;
59 constexpr int CATALOG_MINIMUM_COMPONENT_ROW_HEIGHT = 32;
60 constexpr int CATALOG_NAME_COLUMN_PADDING = 28;
61
62 QPixmap componentPreviewPixmap(const ComponentCatalogOverlay::CatalogRow& rowData,
63 const SILICON::project::DocumentStore& documents,
64 const CircuitResolver* resolver)
65 {
66 auto component = GUIComponentFactory::instance().create(rowData.guiType);
67 if (auto* subcircuit = dynamic_cast<GraphicalSubcircuitComponent*>(component.get()))
68 subcircuit->setProjectContext(&documents, resolver);
69 if (!rowData.initialProperties.empty()) {
70 for (const auto& [key, value] : rowData.initialProperties)
71 component->applyProperty(key, value);
72 }
73 const QRectF bounds = component->sceneBoundingRect();
74 const QSize size(
75 static_cast<int>(std::ceil(bounds.width())) + 2 * CATALOG_PREVIEW_PADDING,
76 static_cast<int>(std::ceil(bounds.height())) + 2 * CATALOG_PREVIEW_PADDING);
77
78 QPixmap pixmap(size);
79 pixmap.fill(Qt::transparent);
80
81 QGraphicsScene previewScene;
82 previewScene.addItem(component.get());
83
84 QPainter painter(&pixmap);
85 painter.setRenderHint(QPainter::Antialiasing);
86 previewScene.render(
87 &painter,
88 QRectF(QPointF(CATALOG_PREVIEW_PADDING, CATALOG_PREVIEW_PADDING), bounds.size()),
89 bounds, Qt::KeepAspectRatio);
90 previewScene.removeItem(component.get());
91
92 return pixmap;
93 }
94
95 std::vector<ComponentCatalogOverlay::CatalogRow>
96 componentCatalogRows(const bool editingSubcircuit,
97 const SILICON::project::DocumentStore& documents)
98 {
99 Q_UNUSED(editingSubcircuit);
100
101 const auto& guiFactory = GUIComponentFactory::instance();
102 const auto& coreFactory = ComponentRegistry::instance();
103
104 std::vector<ComponentCatalogOverlay::CatalogRow> catalogRows;
105 for (const std::string& guiType : guiFactory.availableTypes()) {
106 const auto& entryMetadata = guiFactory.metadata(guiType);
107 catalogRows.push_back(
108 {.guiType = guiType,
109 .metadata = entryMetadata.graphicalMetadata
110 ? *entryMetadata.graphicalMetadata
111 : coreFactory.metadata(entryMetadata.coreType),
112 .initialProperties = {}});
113 }
114
115 for (const auto& document : documents.getDocuments()) {
116 if (document.getType() != SILICON::project::DocumentType::Circuit)
117 continue;
118 if (!subcircuitHasGraphicalMetadata(document.getContents()))
119 continue;
120
121 const auto slug = SILICON::project::documentSlugForPath(document.getPath())
122 .value_or(std::string{});
123 PropertyMap initialProperties;
124 initialProperties.emplace(std::string("slug"), PropertyValue(slug));
125 catalogRows.push_back({.guiType = std::string(SubcircuitComponent::Type),
126 .metadata = {.displayName = slug,
127 .description = "Project subcircuit",
128 .category = ComponentCategory::Subcircuits},
129 .initialProperties = std::move(initialProperties)});
130 }
131
132 std::ranges::sort(catalogRows, [](const auto& lhs, const auto& rhs) {
133 if (lhs.metadata.category != rhs.metadata.category)
134 return std::to_underlying(lhs.metadata.category)
135 < std::to_underlying(rhs.metadata.category);
136 return lhs.metadata.displayName < rhs.metadata.displayName;
137 });
138
139 return catalogRows;
140 }
141
142 } // namespace
143
146 const CircuitResolver* resolver, QWidget* parent)
147 : QWidget(parent), diagramScene(scene), documents(documents), resolver(resolver)
148 {
149 setObjectName(QStringLiteral("componentCatalogOverlay"));
150 setAutoFillBackground(true);
151
152 auto* layout = new QVBoxLayout(this);
153 layout->setContentsMargins(12, 12, 12, 12);
154
155 searchInput = new QLineEdit(this);
156 searchInput->setPlaceholderText(tr("Search components"));
157 layout->addWidget(searchInput);
158
159 table = new QTableWidget(this);
160 table->setColumnCount(3);
161 table->setHorizontalHeaderLabels(
162 {tr("Component shape"), tr("Component name"), tr("Component description")});
163 table->verticalHeader()->hide();
164 table->setSelectionBehavior(QAbstractItemView::SelectRows);
165 table->setSelectionMode(QAbstractItemView::SingleSelection);
166 table->setEditTriggers(QAbstractItemView::NoEditTriggers);
167 table->setShowGrid(false);
168 table->setTextElideMode(Qt::ElideNone);
169 table->horizontalHeader()->setStretchLastSection(true);
170 table->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
171 table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Interactive);
172
173 layout->addWidget(table);
174
175 callbacks.connect(searchInput, &QLineEdit::textChanged, [this] { rebuildRows(); });
177 // These circuit previews are snapshots, not SvgIconEngine icons. Hidden
178 // catalogs rebuild on open(); refresh only displayed rows, retaining selection.
179 if (!isVisible())
180 return;
181 for (int row = 0; row < table->rowCount(); ++row) {
182 const auto* name = table->item(row, 1);
183 auto* preview = qobject_cast<QLabel*>(table->cellWidget(row, 0));
184 if (!name || !preview)
185 continue;
186 const int index = name->data(Qt::UserRole + 1).toInt();
187 if (index >= 0 && static_cast<std::size_t>(index) < catalogRows.size())
188 preview->setPixmap(
189 componentPreviewPixmap(catalogRows[index], this->documents, this->resolver));
190 }
191 });
192 callbacks.connect(table, &QTableWidget::cellDoubleClicked,
193 [this](int row, int) { activateRow(row); });
194 callbacks.connect(table, &QTableWidget::itemActivated, [this](QTableWidgetItem* item) {
195 if (item)
196 activateRow(item->row());
197 });
198
199 catalogRows = componentCatalogRows(
200 diagramScene && diagramScene->isSubcircuitDocumentMode(), documents);
201 rebuildRows();
202 hide();
203 }
204
206 {
207 catalogRows = componentCatalogRows(
208 diagramScene && diagramScene->isSubcircuitDocumentMode(), documents);
209 QSignalBlocker blocker(searchInput);
210 searchInput->clear();
211 blocker.unblock();
212 rebuildRows();
213 show();
214 raise();
215 searchInput->setFocus(Qt::OtherFocusReason);
217 }
218
220 {
221 // Escape still dismisses the catalog if the cancel action was remapped.
222 if (event->key() == Qt::Key_Escape && event->modifiers() == Qt::NoModifier) {
223 dismiss();
224 event->accept();
225 return;
226 }
227 QWidget::keyPressEvent(event);
228 }
229
231 {
232 if (!isVisible())
233 return;
234
235 const auto* focus = QApplication::focusWidget();
236 const bool restoreFocus = !focus || focus == this || isAncestorOf(focus);
237 hide();
238
239 if (!restoreFocus || QApplication::activeModalWidget()
240 || QApplication::activePopupWidget() || !window()->isActiveWindow())
241 return;
242
243 for (auto* view : diagramScene->views()) {
244 if (view->isVisible() && view->isAncestorOf(this)) {
245 view->setFocus(Qt::OtherFocusReason);
246 break;
247 }
248 }
249 }
250
252 {
253 table->clearContents();
254 table->setRowCount(0);
255
256 const QString query = searchInput->text().trimmed();
257 const bool showCategories = query.isEmpty();
258
259 std::vector<const CatalogRow*> visibleRows;
260 visibleRows.reserve(catalogRows.size());
261
262 if (showCategories) {
263 for (const CatalogRow& row : catalogRows)
264 visibleRows.push_back(&row);
265 } else {
266 QStringList candidates;
267 std::vector<size_t> candidateRows;
268 candidates.reserve(static_cast<qsizetype>(catalogRows.size() * 4));
269 candidateRows.reserve(catalogRows.size() * 4);
270
271 for (size_t rowIndex = 0; rowIndex < catalogRows.size(); ++rowIndex) {
272 for (const QString& field : searchableFields(catalogRows[rowIndex])) {
273 candidates.append(field);
274 candidateRows.push_back(rowIndex);
275 }
276 }
277
278 std::vector<bool> selected(catalogRows.size(), false);
279 for (const auto& match :
280 SILICON::ui::componentSearchMatcher::rank(candidates, query, false)) {
281 const size_t rowIndex = candidateRows[static_cast<size_t>(match.index)];
282 if (selected[rowIndex])
283 continue;
284
285 visibleRows.push_back(&catalogRows[rowIndex]);
286 selected[rowIndex] = true;
287 }
288 }
289
290 std::optional<ComponentRegistry::ComponentCategory> currentCategory;
291 for (const CatalogRow* row : visibleRows) {
292 if (showCategories
293 && (!currentCategory || *currentCategory != row->metadata.category)) {
294 addCategoryRow(row->metadata.category);
295 currentCategory = row->metadata.category;
296 }
297 addComponentRow(*row);
298 }
299
302 }
303
304 void
306 {
307 const int row = table->rowCount();
308 table->insertRow(row);
309 table->setSpan(row, 0, 1, 3);
310 table->setRowHeight(row, CATALOG_CATEGORY_ROW_HEIGHT);
311
312 auto* item = new QTableWidgetItem(
313 QString::fromStdString(std::string(componentCategoryName(category))));
314 QFont font = item->font();
315 font.setBold(true);
316 item->setFont(font);
317 item->setFlags(Qt::NoItemFlags);
318 table->setItem(row, 0, item);
319 }
320
322 {
323 const int row = table->rowCount();
324 table->insertRow(row);
325
326 QPixmap previewPixmap = componentPreviewPixmap(rowData, documents, resolver);
327 auto* preview = new QLabel(table);
328 preview->setFixedSize(previewPixmap.size());
329 preview->setAlignment(Qt::AlignCenter);
330 preview->setPixmap(previewPixmap);
331 table->setCellWidget(row, 0, preview);
332 table->setRowHeight(
333 row, std::max(CATALOG_MINIMUM_COMPONENT_ROW_HEIGHT, previewPixmap.height()));
334
335 auto* name =
336 new QTableWidgetItem(QString::fromStdString(rowData.metadata.displayName));
337 name->setData(Qt::UserRole, QString::fromStdString(rowData.guiType));
338 name->setData(Qt::UserRole + 1, static_cast<int>(&rowData - catalogRows.data()));
339 table->setItem(row, 1, name);
340
341 auto* description =
342 new QTableWidgetItem(QString::fromStdString(rowData.metadata.description));
343 description->setData(Qt::UserRole, QString::fromStdString(rowData.guiType));
344 description->setData(Qt::UserRole + 1,
345 static_cast<int>(&rowData - catalogRows.data()));
346 table->setItem(row, 2, description);
347 }
348
350 {
351 if (row < 0)
352 return;
353
354 QTableWidgetItem* item = table->item(row, 1);
355 if (!item)
356 item = table->item(row, 2);
357 if (!item)
358 return;
359
360 const QString typeName = item->data(Qt::UserRole).toString();
361 if (typeName.isEmpty())
362 return;
363
364 const int catalogIndex = item->data(Qt::UserRole + 1).toInt();
365 const PropertyMap initialProperties =
366 catalogIndex >= 0 && catalogIndex < static_cast<int>(catalogRows.size())
367 ? catalogRows[static_cast<size_t>(catalogIndex)].initialProperties
368 : PropertyMap{};
369
370 if (diagramScene->getInteractionMode() != DiagramScene::InteractionMode::NORMAL_MODE)
371 diagramScene->setInteractionMode(DiagramScene::InteractionMode::NORMAL_MODE);
372
373 diagramScene->placeComponent(typeName.toStdString(), false, initialProperties);
374 dismiss();
375 }
376
378 {
379 for (int row = 0; row < table->rowCount(); ++row) {
380 const auto* item = table->item(row, 1);
381 if (item && !item->data(Qt::UserRole).toString().isEmpty()) {
382 table->selectRow(row);
383 return;
384 }
385 }
386 }
387
389 {
390 table->resizeColumnToContents(0);
391
392 const QFontMetrics fontMetrics(table->font());
393 int nameColumnWidth = 0;
394 if (const QTableWidgetItem* headerItem = table->horizontalHeaderItem(1))
395 nameColumnWidth = fontMetrics.horizontalAdvance(headerItem->text());
396
397 for (int row = 0; row < table->rowCount(); ++row) {
398 const QTableWidgetItem* item = table->item(row, 1);
399 if (!item)
400 continue;
401
402 nameColumnWidth =
403 std::max(nameColumnWidth, fontMetrics.horizontalAdvance(item->text()));
404 }
405
406 table->setColumnWidth(1, nameColumnWidth + CATALOG_NAME_COLUMN_PADDING);
407 }
408
410 {
411 return {QString::fromStdString(rowData.metadata.displayName),
412 QString::fromStdString(rowData.guiType),
413 QString::fromStdString(rowData.metadata.description),
414 QString::fromStdString(
415 std::string(componentCategoryName(rowData.metadata.category)))};
416 }
417
418} // namespace SILICON::ui
SILICON::core::ComponentCategory ComponentCategory
static ComponentRegistry & instance()
static constexpr std::string_view Type
const std::vector< Document > & getDocuments() const noexcept
ComponentCatalogOverlay(DiagramScene *scene, const SILICON::project::DocumentStore &documents, const CircuitResolver *resolver, QWidget *parent=nullptr)
static QStringList searchableFields(const CatalogRow &rowData)
void addComponentRow(const CatalogRow &rowData)
void keyPressEvent(QKeyEvent *event) override
void addCategoryRow(ComponentRegistry::ComponentCategory category)
const SILICON::project::DocumentStore & documents
Graphics scene for the circuit diagram editor.
static GUIComponentFactory & instance()
Gets the global singleton factory instance.
std::unique_ptr< GraphicalComponent > create(std::string_view type, QGraphicsItem *parent=nullptr) const
Creates a component by type name.
Graphical component wrapper for a registered subcircuit.
static ThemeEngine & instance()
Definition theme.cpp:147
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.
std::string_view componentCategoryName(const ComponentCategory category)
std::optional< std::string > documentSlugForPath(const std::string_view path)
std::vector< Match > rank(QStringList candidates, const QString &query, const bool includeNonMatches)
bool subcircuitHasGraphicalMetadata(std::string_view sceneJson)
Checks whether a scene document contains valid graphical metadata.
Definition metadata.cpp:269