SILICON
Loading...
Searching...
No Matches
propertyPanel.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 "propertyPanel.hpp"
19
20#include <algorithm>
21#include <limits>
22#include <memory>
23#include <optional>
24#include <ranges>
25#include <string>
26#include <type_traits>
27#include <utility>
28#include <variant>
29#include <vector>
30
31#include <QCheckBox>
32#include <QComboBox>
33#include <QDockWidget>
34#include <QFocusEvent>
35#include <QFormLayout>
36#include <QGraphicsItem>
37#include <QLabel>
38#include <QLineEdit>
39#include <QPlainTextEdit>
40#include <QSpinBox>
41#include <QSizePolicy>
42#include <QTimer>
43#include <QWidget>
44
46
53
54namespace SILICON::ui {
55using namespace SILICON::core;
56
57namespace {
58QLabel* wrappingLabel(QString text, QWidget* parent)
59{
60 auto* label = new QLabel(std::move(text), parent);
61 label->setWordWrap(true);
62 // QFormLayout needs the label's width hint to reserve space or wrap the row.
63 label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
64 return label;
65}
66
67class DescriptionEdit : public QPlainTextEdit {
68public:
69 using QPlainTextEdit::QPlainTextEdit;
70 std::function<void()> commit;
71
72protected:
73 void focusOutEvent(QFocusEvent* event) override
74 {
75 if (commit)
76 commit();
77 QPlainTextEdit::focusOutEvent(event);
78 }
79};
80} // namespace
81
82
83PropertyPanel::PropertyPanel(QDockWidget* dock, DiagramScene* scene, ProjectTree* tree,
84 QUndoStack* history,
85 std::optional<SILICON::project::ProjectInfo>& projectInfo,
86 const QString& fileName, std::function<void()> rebuildTree)
87 : QObject(dock),
88 propertyDock(dock),
89 diagramScene(scene),
90 projectTree(tree),
91 undoStack(history),
92 currentProjectInfo(projectInfo),
93 currentFileName(fileName),
94 rebuildProjectTree(std::move(rebuildTree))
95{
97 QTimer::singleShot(0, callbacks.context(), [this] { refresh(); });
98 });
99}
100
102{
103 auto* selectedProjectItem = projectTree ? projectTree->selectedProjectItem() : nullptr;
104
105 const auto itemKind = selectedProjectItem
106 ? std::optional{ProjectTree::itemKind(selectedProjectItem)}
107 : std::nullopt;
108 const auto itemCategory = selectedProjectItem
109 ? ProjectTree::itemDocumentCategory(selectedProjectItem)
110 : std::nullopt;
111
112 std::vector<GraphicalComponent*> selectedNodes;
113 for (QGraphicsItem* item : diagramScene->selectedItems()) {
114 if (auto* component =
116 selectedNodes.push_back(component);
117 }
118
119 const bool hasProperties = !selectedNodes.empty()
120 || (itemKind != ProjectTreeItemKind::Document
121 && itemKind != ProjectTreeItemKind::Architecture);
122 propertyDock->setVisible(hasProperties);
123 if (!hasProperties)
124 return;
125
126 // 1. Assign the container immediately.
127 // QDockWidget::setWidget automatically deletes the previous widget.
128 auto* container = new QWidget();
129 // This dock shares its width with the document dock; its form must not raise the
130 // configured minimum width of the entire dock column.
131 container->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
132 auto* layout = new QFormLayout(container);
133 layout->setRowWrapPolicy(QFormLayout::WrapLongRows);
134 propertyDock->setWidget(container);
135
136 if (selectedNodes.empty()) {
137 if (!selectedProjectItem) {
138 layout->addRow(wrappingLabel(tr("Select a project, circuit, or one or more "
139 "components to view properties."),
140 container));
141 return;
142 }
143
144 if (itemKind == ProjectTreeItemKind::Section && itemCategory) {
145 const auto noun =
146 *itemCategory == SILICON::project::DocumentCategory::Diagram ? tr("circuit")
147 : *itemCategory == SILICON::project::DocumentCategory::Code ? tr("code file")
149 ? tr("architecture")
150 : tr("binary file");
151 layout->addRow(
152 wrappingLabel(tr("Select a %1 to view its properties.").arg(noun), container));
153 return;
154 }
155
156 auto* nameEdit = new QLineEdit(container);
157 auto* descriptionEdit = new DescriptionEdit(container);
158 descriptionEdit->setMinimumHeight(90);
159
160 auto pushMetadataEdit = [this](const QString& label, const std::string& oldValue,
161 const std::string& newValue,
163 if (oldValue == newValue)
164 return;
165
166 undoStack->push(
167 new MetadataEditCommand(label, oldValue, newValue,
168 callbacks.guard(std::move(apply))));
169 };
170
171 auto schedulePropertyDockRefresh = [this] {
172 QTimer::singleShot(0, callbacks.context(), [this] { refresh(); });
173 };
174
175 if (itemKind == ProjectTreeItemKind::Project) {
178
179 nameEdit->setText(QString::fromStdString(currentProjectInfo->name));
180 descriptionEdit->setPlainText(
181 QString::fromStdString(currentProjectInfo->description));
182 descriptionEdit->document()->setModified(false);
183
184 callbacks.connect(nameEdit, &QLineEdit::editingFinished,
185 [this, nameEdit, pushMetadataEdit, schedulePropertyDockRefresh] {
186 if (!currentProjectInfo || !nameEdit->isModified())
187 return;
188
189 const auto oldValue = currentProjectInfo->name;
190 const auto newValue = nameEdit->text().toStdString();
191 nameEdit->setModified(false);
192 pushMetadataEdit(
193 tr("Modify Project Name"), oldValue, newValue,
194 [this, schedulePropertyDockRefresh](const std::string& value) {
196 return;
197 currentProjectInfo->name = value;
199 schedulePropertyDockRefresh();
200 });
201 });
202 descriptionEdit->commit = callbacks.guard([this, descriptionEdit, pushMetadataEdit,
203 schedulePropertyDockRefresh] {
204 if (!currentProjectInfo || !descriptionEdit->document()->isModified())
205 return;
206
207 const auto oldValue = currentProjectInfo->description;
208 const auto newValue = descriptionEdit->toPlainText().toStdString();
209 descriptionEdit->document()->setModified(false);
210 pushMetadataEdit(tr("Modify Project Description"), oldValue, newValue,
211 [this, schedulePropertyDockRefresh](const std::string& value) {
213 return;
214 currentProjectInfo->description = value;
215 schedulePropertyDockRefresh();
216 });
217 });
218 }
219
220 layout->addRow(wrappingLabel(tr("Name"), container), nameEdit);
221 layout->addRow(wrappingLabel(tr("Description"), container), descriptionEdit);
222 return;
223 }
224
225 // 3. Intersect properties to find common configurable keys
226 auto commonProps = selectedNodes.front()->getProperties();
227
228 std::erase_if(commonProps, [&](const auto& pair) {
229 return std::ranges::any_of(selectedNodes, [&](const GraphicalComponent* node) {
230 return node->isPropertyHidden(pair.first);
231 });
232 });
233
234 for (const GraphicalComponent* node : selectedNodes | std::views::drop(1)) {
235 const auto& props = node->getProperties();
236
237 std::erase_if(commonProps, [&](const auto& pair) {
238 const auto& [key, val] = pair;
239 auto it = props.find(key);
240 return it == props.end() || it->second.index() != val.index();
241 });
242 }
243
244 if (commonProps.empty()) {
245 layout->addRow(wrappingLabel(
246 tr("No common configurable properties among selection."), container));
247 return;
248 }
249
250 // Helper lambda to apply the property to all components and handle validation
251 // exceptions
252 auto applyProperty = [this, selectedNodes](const std::string& key,
253 const PropertyValue& newVal) {
254 try {
255 auto command = std::make_unique<ModifyPropertyCommand>(key);
256
257 for (GraphicalComponent* node : selectedNodes) {
258 const auto oldValue = node->getProperty(key);
259 if (oldValue)
260 command->addPropertyChange(node, *oldValue, newVal);
261 }
262
263 if (command->isEmpty())
264 return;
265
266 // Keep ownership if redo() throws before QUndoStack accepts the command.
267 undoStack->push(command.get());
268 static_cast<void>(command.release());
269 if (key == "portOrientation") {
270 for (const auto* node : selectedNodes) {
271 if (const auto* logic = category_cast<GraphicalLogicComponent>(
273 logic && logic->getComponent())
274 diagramScene->rememberIoPlacementOrientation(*logic->getComponent());
275 }
276 }
277 } catch (const std::exception& e) {
278 SILICON::ui::inputDialog::warning(propertyDock, tr("Invalid Property"), e.what());
279 QTimer::singleShot(0, callbacks.context(), [this] { refresh(); });
280 }
281 };
282
283 // 4. Build UI for common properties
284 for (const auto& [key, initialValue] : commonProps) {
285 // Check if the value differs across the selection
286 const bool isMixed = std::ranges::any_of(
287 selectedNodes | std::views::drop(1), [&](const GraphicalComponent* node) {
288 return node->getProperty(key) != initialValue;
289 });
290
291 auto createPropertyWidget = [&]<typename T>(const T& arg) {
292 if constexpr (std::is_same_v<T, bool>) {
293 auto* checkBox = new QCheckBox(container);
294
295 if (isMixed) {
296 checkBox->setTristate(true);
297 checkBox->setCheckState(Qt::PartiallyChecked);
298 } else {
299 checkBox->setChecked(arg);
300 }
301
302 callbacks.connect(checkBox, &QCheckBox::checkStateChanged, [=](Qt::CheckState state) {
303 if (state == Qt::PartiallyChecked)
304 return;
305 checkBox->setTristate(false);
306 applyProperty(key, state == Qt::Checked);
307 });
308
309 layout->addRow(wrappingLabel(QString::fromStdString(key), container), checkBox);
310 } else if constexpr (std::is_same_v<T, int>) {
311 auto* spinBox = new PropertySpinBox(container);
312 constexpr int MIN_VAL = std::numeric_limits<int>::min();
313 constexpr int MAX_VAL = std::numeric_limits<int>::max();
314
315 spinBox->setRange(MIN_VAL, MAX_VAL);
316
317 if (isMixed) {
318 spinBox->setMixed(true, tr("Mixed values"));
319 } else {
320 spinBox->setValue(arg);
321 }
322
323 callbacks.connect(spinBox, &QSpinBox::valueChanged, [=](int val) {
324 if (val == MIN_VAL && spinBox->isMixed())
325 return;
326 spinBox->setMixed(false);
327 applyProperty(key, val);
328 });
329
330 layout->addRow(wrappingLabel(QString::fromStdString(key), container), spinBox);
331 } else if constexpr (std::is_same_v<T, std::string>) {
332 const auto stringOptions = selectedNodes.front()->getStringPropertyOptions(key);
333 if (stringOptions) {
334 auto* comboBox = new QComboBox(container);
335
336 for (const std::string& option : stringOptions->get()) {
337 comboBox->addItem(QString::fromStdString(option));
338 }
339
340 if (isMixed) {
341 comboBox->setPlaceholderText(tr("Mixed values"));
342 comboBox->setCurrentIndex(-1);
343 } else {
344 comboBox->setCurrentText(QString::fromStdString(arg));
345 }
346
347 callbacks.connect(comboBox, &QComboBox::currentTextChanged,
348 [=](const QString& text) {
349 if (text.isEmpty())
350 return;
351 applyProperty(key, text.toStdString());
352 });
353
354 layout->addRow(wrappingLabel(QString::fromStdString(key), container), comboBox);
355 return;
356 }
357
358 if (std::ranges::all_of(selectedNodes, [&key](const auto* node) {
359 return node->isMultilineProperty(key);
360 })) {
361 auto* textEdit = new DescriptionEdit(container);
362 textEdit->setMinimumHeight(90);
363 if (isMixed)
364 textEdit->setPlaceholderText(tr("Mixed values..."));
365 else
366 textEdit->setPlainText(QString::fromStdString(arg));
367 textEdit->document()->setModified(false);
368 textEdit->commit = callbacks.guard([textEdit, applyProperty, key] {
369 if (!textEdit->document()->isModified())
370 return;
371 textEdit->document()->setModified(false);
372 applyProperty(key, textEdit->toPlainText().toStdString());
373 });
374 layout->addRow(wrappingLabel(QString::fromStdString(key), container), textEdit);
375 return;
376 }
377
378 auto* lineEdit = new QLineEdit(container);
379
380 if (isMixed) {
381 lineEdit->setPlaceholderText(tr("Mixed values..."));
382 } else {
383 lineEdit->setText(QString::fromStdString(arg));
384 }
385
386 callbacks.connect(lineEdit, &QLineEdit::editingFinished, [=]() {
387 if (!lineEdit->isModified())
388 return;
389
390 applyProperty(key, lineEdit->text().toStdString());
391 lineEdit->setModified(false);
392 });
393
394 layout->addRow(wrappingLabel(QString::fromStdString(key), container), lineEdit);
395 } else if constexpr (std::is_same_v<T, BusValue>) {
396 auto* lineEdit = new QLineEdit(container);
397 if (isMixed)
398 lineEdit->setPlaceholderText(tr("Mixed values..."));
399 else
400 lineEdit->setText(QString::fromStdString(
402
403 callbacks.connect(lineEdit, &QLineEdit::editingFinished, [=, this]() {
404 if (!lineEdit->isModified())
405 return;
406 try {
407 applyProperty(
408 key, SILICON::core::busValueFromBits(lineEdit->text().toStdString()));
409 lineEdit->setModified(false);
410 } catch (const std::exception& error) {
411 SILICON::ui::inputDialog::warning(propertyDock, tr("Invalid Property"),
412 error.what());
413 }
414 });
415
416 layout->addRow(wrappingLabel(QString::fromStdString(key), container), lineEdit);
417 }
418 };
419
420 std::visit(createPropertyWidget, initialValue);
421 }
422}
423
424// --- Property SpinBox
425// ------------------------------------------------------------------
426
427PropertySpinBox::PropertySpinBox(QWidget* parent) : QSpinBox(parent)
428{
429 setButtonSymbols(NoButtons);
430}
431
432void PropertySpinBox::setMixed(const bool mixed, const QString& placeholder)
433{
434 m_isMixed = mixed;
435
436 if (mixed) {
437 lineEdit()->setPlaceholderText(placeholder);
438 setValue(minimum());
439 } else {
440 lineEdit()->setPlaceholderText("");
441 }
442}
443
445{
446 return m_isMixed;
447}
448
449QString PropertySpinBox::textFromValue(const int val) const
450{
451 return m_isMixed && val == minimum() ? QString{} : QSpinBox::textFromValue(val);
452}
453
454} // namespace SILICON::ui
Graphics scene for the circuit diagram editor.
Base class for graphical circuit components.
std::optional< PropertyValue > getProperty(std::string_view key) 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
std::function< void(const std::string &)> ApplyFn
Project document navigator used by the SILICON editor.
static ProjectTreeItemKind itemKind(const QTreeWidgetItem *item)
static std::optional< project::DocumentCategory > itemDocumentCategory(const QTreeWidgetItem *item)
std::optional< SILICON::project::ProjectInfo > & currentProjectInfo
PropertyPanel(QDockWidget *dock, DiagramScene *scene, ProjectTree *tree, QUndoStack *history, std::optional< SILICON::project::ProjectInfo > &projectInfo, const QString &fileName, std::function< void()> rebuildTree)
const QString & currentFileName
std::function< void()> rebuildProjectTree
void setMixed(bool mixed, const QString &placeholder=QString())
QString textFromValue(int val) const override
PropertySpinBox(QWidget *parent=nullptr)
std::variant< int, bool, std::string, BusValue > PropertyValue
Variant type for component properties.
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
void warning(QWidget *parent, const QString &title, const QString &text)
SILICON::project::ProjectInfo defaultProjectInfo(const QString &fileName)
TargetType * category_cast(QGraphicsItem *item, ItemCategory expectedCategory)
Definition enums.hpp:60