SILICON
Loading...
Searching...
No Matches
projectDocumentConversion.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
23
24#include <algorithm>
25#include <ranges>
26#include <stdexcept>
27#include <string_view>
28#include <unordered_map>
29#include <utility>
30#include <vector>
31
32#include <QAbstractItemView>
33#include <QDialog>
34#include <QDialogButtonBox>
35#include <QHeaderView>
36#include <QLabel>
37#include <QPushButton>
38#include <QSignalBlocker>
39#include <QStringList>
40#include <QTreeWidget>
41#include <QVBoxLayout>
42
47
48namespace SILICON::ui {
49namespace {
50 [[nodiscard]] std::optional<std::vector<std::string>>
51 selectConversionChoices(QWidget* parent,
52 std::vector<SILICON::conversion::ConversionChoice> choices)
53 {
54 if (choices.size() <= 1) {
55 std::vector<std::string> selected;
56 for (const auto& choice : choices)
57 selected.push_back(choice.id);
58 return selected;
59 }
60
61 std::ranges::sort(choices, [](const auto& lhs, const auto& rhs) {
62 if (lhs.dependencies.size() != rhs.dependencies.size())
63 return lhs.dependencies.size() > rhs.dependencies.size();
64 return lhs.label < rhs.label;
65 });
66
67 std::unordered_map<std::string, const SILICON::conversion::ConversionChoice*,
68 core::TransparentStringHash, core::TransparentStringEqual>
69 choicesById;
70 for (const auto& choice : choices)
71 choicesById.emplace(choice.id, &choice);
72
73 QDialog dialog(parent);
74 dialog.setWindowTitle(QObject::tr("Select Conversion Items"));
75 dialog.setModal(true);
76 dialog.resize(560, 420);
77
78 auto* layout = new QVBoxLayout(&dialog);
79 layout->addWidget(new QLabel(
80 QObject::tr("Select one or more items. Their dependencies are converted "
81 "automatically."),
82 &dialog));
83
84 auto* tree = new QTreeWidget(&dialog);
85 tree->setColumnCount(1);
86 tree->setHeaderLabels({QObject::tr("Item")});
87 tree->setRootIsDecorated(true);
88 tree->setSelectionMode(QAbstractItemView::NoSelection);
89 constexpr int EXPLICITLY_SELECTED_ROLE = Qt::UserRole;
90 constexpr int CHOICE_ID_ROLE = Qt::UserRole + 1;
91
92 const auto addDependencies = [&choicesById](this auto&& addDependencies,
93 QTreeWidgetItem* parentItem,
94 const std::string_view choiceId) -> void {
95 const auto choice = choicesById.find(choiceId);
96 if (choice == choicesById.end())
97 return;
98 for (const auto& dependency : choice->second->dependencies) {
99 auto* dependencyItem = new QTreeWidgetItem(parentItem);
100 const auto dependencyChoice = choicesById.find(dependency);
101 dependencyItem->setText(
102 0, QString::fromStdString(dependencyChoice == choicesById.end()
103 ? dependency
104 : dependencyChoice->second->label));
105 dependencyItem->setFlags(dependencyItem->flags() & ~Qt::ItemIsUserCheckable);
106 addDependencies(dependencyItem, dependency);
107 }
108 };
109
110 for (const auto& choice : choices) {
111 auto* item = new QTreeWidgetItem(tree);
112 item->setText(0, QString::fromStdString(choice.label));
113 item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
114 item->setCheckState(0, Qt::Unchecked);
115 item->setData(0, EXPLICITLY_SELECTED_ROLE, false);
116 item->setData(0, CHOICE_ID_ROLE, QString::fromStdString(choice.id));
117 addDependencies(item, choice.id);
118 }
119 tree->collapseAll();
120 tree->header()->setSectionResizeMode(0, QHeaderView::Stretch);
121 layout->addWidget(tree);
122
123 auto* buttons =
124 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
125 auto* importButton = buttons->button(QDialogButtonBox::Ok);
126 importButton->setText(QObject::tr("Import"));
127 importButton->setEnabled(false);
128 layout->addWidget(buttons);
129 QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
130 QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
131
132 QObject::connect(
133 tree, &QTreeWidget::itemChanged, &dialog,
134 [tree, importButton, &choicesById](QTreeWidgetItem* changedItem, int) {
135 const QSignalBlocker blocker(tree);
136 if (!changedItem->parent()
137 && changedItem->flags().testFlag(Qt::ItemIsEnabled)) {
138 changedItem->setData(0, EXPLICITLY_SELECTED_ROLE,
139 changedItem->checkState(0) == Qt::Checked);
140 }
141
142 std::vector<std::string> roots;
143 for (int index = 0; index < tree->topLevelItemCount(); ++index) {
144 const auto* item = tree->topLevelItem(index);
145 if (item->data(0, EXPLICITLY_SELECTED_ROLE).toBool())
146 roots.push_back(item->data(0, CHOICE_ID_ROLE).toString().toStdString());
147 }
148
149 importButton->setEnabled(!roots.empty());
150 std::vector<std::string> dependencies;
151 const auto collectDependencies =
152 [&choicesById, &dependencies](this auto&& collectDependencies,
153 const std::string_view id) -> void {
154 const auto choice = choicesById.find(id);
155 if (choice == choicesById.end())
156 return;
157 for (const auto& dependency : choice->second->dependencies) {
158 if (std::ranges::contains(dependencies, dependency))
159 continue;
160 dependencies.push_back(dependency);
161 collectDependencies(dependency);
162 }
163 };
164 for (const auto& root : roots)
165 collectDependencies(root);
166
167 for (int index = 0; index < tree->topLevelItemCount(); ++index) {
168 auto* item = tree->topLevelItem(index);
169 const auto name = item->data(0, CHOICE_ID_ROLE).toString().toStdString();
170 const bool selected = item->data(0, EXPLICITLY_SELECTED_ROLE).toBool();
171 const bool dependency = std::ranges::contains(dependencies, name);
172
173 auto flags = item->flags() | Qt::ItemIsUserCheckable;
174 flags.setFlag(Qt::ItemIsEnabled, !dependency);
175 item->setFlags(flags);
176 item->setCheckState(0, selected || dependency ? Qt::Checked : Qt::Unchecked);
177
178 auto font = item->font(0);
179 font.setBold(selected && !dependency);
180 font.setItalic(dependency);
181 item->setFont(0, font);
182 }
183 });
184
185 if (dialog.exec() != QDialog::Accepted)
186 return std::nullopt;
187
188 std::vector<std::string> roots;
189 for (int index = 0; index < tree->topLevelItemCount(); ++index) {
190 const auto* item = tree->topLevelItem(index);
191 if (item->data(0, EXPLICITLY_SELECTED_ROLE).toBool())
192 roots.push_back(item->data(0, CHOICE_ID_ROLE).toString().toStdString());
193 }
194 return roots;
195 }
196
197} // namespace
198
200{
201 const auto* source =
202 session.projectContext.documents().find(session.activeDocumentPath);
203 if (!source)
204 return;
205
206 const auto converters = documentConvertersFor(source->getType());
207 std::vector<SILICON::project::DocumentType> targets;
208 QStringList labels;
209 for (const auto* converter : converters) {
210 if (!converter->available)
211 continue;
212 targets.push_back(converter->target);
213 labels.push_back(documentTypeName(converter->target));
214 }
215
216 if (targets.empty())
217 return;
218 if (targets.size() == 1) {
219 convertActiveDocumentTo(targets.front());
220 return;
221 }
222
224 dialogParent, tr("Convert Document"), tr("Target format"), labels, 0, false,
225 [this, labels = std::move(labels),
226 targets = std::move(targets)](const QString& selected) {
227 const auto index = labels.indexOf(selected);
228 if (index >= 0 && index < static_cast<qsizetype>(targets.size()))
229 convertActiveDocumentTo(targets[static_cast<std::size_t>(index)]);
230 },
231 this);
232}
233
236{
237 try {
238 workspace.flushActiveDocument();
239 const auto sourcePath = session.activeDocumentPath;
240 const auto& store = session.projectContext.documents();
241 const auto* source = store.find(sourcePath);
242 if (!source)
243 throw std::runtime_error("The active document no longer exists");
244 if (source->getType() == SILICON::project::DocumentType::Circuit
245 && !workspace.circuitEditor().scene()->currentConnectionReport().valid())
246 throw std::runtime_error("Repair the invalid wire connections before conversion");
247
248 auto prepared = prepareDocumentConversion(
249 *source, target, store.getDocuments(),
251 auto selected = selectConversionChoices(dialogParent, prepared.choices);
252 if (!selected)
253 return;
254
255 auto result = prepared.execute(*selected);
256 const auto commandText = tr("Convert to %1").arg(documentTypeName(target));
257
258 this->commitDocumentChanges(std::move(result.documents), sourcePath,
259 result.activatePath, commandText,
260 tr("Code Conversion Error"));
261 } catch (const std::exception& error) {
263 dialogParent, tr("Code Conversion Error"),
264 tr("Failed to convert the active document:\n%1").arg(error.what()));
265 }
266}
267
268} // namespace SILICON::ui
static ComponentRegistry & instance()
void convertActiveDocumentTo(SILICON::project::DocumentType target)
void commitDocumentChanges(std::vector< SILICON::project::Document > documents, const std::string &sourcePath, const std::string &activatePath, const QString &commandText, const QString &errorTitle)
RTLIL::IdString id(const char *name)
void critical(QWidget *parent, const QString &title, const QString &text)
void getItem(QWidget *parent, const QString &title, const QString &label, const QStringList &items, int current, bool editable, TextCallback callback, QObject *context)
std::vector< const DocumentConverter * > documentConvertersFor(const DocumentType source)
PreparedDocumentConversion prepareDocumentConversion(const Document &source, const DocumentType target, const std::span< const Document > projectDocuments, const SILICON::core::ComponentRegistry &registry, const SILICON::core::CircuitResolver &resolver)
QString documentTypeName(SILICON::project::DocumentType type)
Definition uiUtils.hpp:30