SILICON
Loading...
Searching...
No Matches
projectDocumentActions.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
22
23#include <algorithm>
24#include <bit>
25#include <cstddef>
26#include <format>
27#include <ranges>
28#include <stdexcept>
29#include <utility>
30#include <vector>
31
32#include <QByteArray>
33#include <QComboBox>
34#include <QDialog>
35#include <QDialogButtonBox>
36#include <QFormLayout>
37#include <QLineEdit>
38#include <QMenu>
39#include <QSpinBox>
40#include <QStringList>
41#include <QUndoStack>
42
47#include <ui/shell/icons.hpp>
51
52namespace SILICON::ui {
53using namespace SILICON::core;
54
56 SILICON::project::Document document, const QString& commandText)
57{
58 const auto path = document.getPath();
59
60 auto addDocument = [this, document] {
61 try {
62 workspace.flushActiveDocument();
63 } catch (const std::exception&) {
64 }
65 this->insertDocument(document, std::nullopt, true);
66 };
67
68 auto removeDocumentCommand = [this, path] { this->removeDocument(path); };
69 undoStack->push(
70 new CallbackUndoCommand(commandText, removeDocumentCommand, addDocument));
71}
72
74{
76 dialogParent, tr("Import Document"),
77 tr("Supported Documents (*.json *.v *.sisl *.bin);;All Files (*)"),
78 [this](const QString& fileName, const QByteArray& fileContent) {
79 try {
81 fileName.toStdString(),
82 std::string(fileContent.constData(),
83 static_cast<std::size_t>(fileContent.size())));
84
85 workspace.flushActiveDocument();
86 const auto sourcePath = session.activeDocumentPath;
87 const auto importPath = document.getPath();
88 commitDocumentChanges({std::move(document)}, sourcePath, importPath,
89 tr("Import Document"), tr("Document Import Error"));
90 } catch (const std::exception& error) {
92 dialogParent, tr("Document Import Error"),
93 tr("Failed to import the document:\n%1").arg(error.what()));
94 }
95 },
96 this);
97}
98
100{
101 const auto selection = projectTree ? projectTree->selectedDocument() : std::nullopt;
102 if (!selection)
103 return;
104
105 try {
106 if (selection->path == session.activeDocumentPath)
107 workspace.flushActiveDocument();
108
109 const auto* document = session.projectContext.documents().find(selection->path);
110 if (!document)
111 throw std::runtime_error("The selected document no longer exists");
112
113 const auto& contents = document->getContents();
115 dialogParent, tr("Export Document"),
116 QString::fromStdString(SILICON::project::documentFileName(*document)),
117 tr("All Files (*)"),
118 QByteArray(contents.data(), static_cast<qsizetype>(contents.size())));
119 } catch (const std::exception& error) {
121 dialogParent, tr("Document Export Error"),
122 tr("Failed to export the document:\n%1").arg(error.what()));
123 }
124}
125
130
132{
133 auto* dialog = new QDialog(dialogParent);
134 dialog->setAttribute(Qt::WA_DeleteOnClose);
135 dialog->setWindowTitle(tr("New Code File"));
136 dialog->setModal(true);
137
138 auto* form = new QFormLayout(dialog);
139 auto* nameEdit = new QLineEdit(tr("untitled"), dialog);
140 auto* typeBox = new QComboBox(dialog);
141 for (const auto& info : codeFilePresentations()) {
143 typeBox->addItem(QString::fromUtf8(info.displayName), static_cast<int>(info.type));
144 }
145
146 form->addRow(tr("Name"), nameEdit);
147 form->addRow(tr("File type"), typeBox);
148
149 auto* buttons =
150 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dialog);
151 form->addRow(buttons);
152 connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
153 connect(
154 buttons, &QDialogButtonBox::accepted, dialog, [this, dialog, nameEdit, typeBox] {
155 const auto index = typeBox->currentIndex();
156 if (index < 0)
157 return;
158
159 const auto type =
160 static_cast<SILICON::project::DocumentType>(typeBox->currentData().toInt());
161 const auto slug = nameEdit->text().trimmed().toStdString();
162
165 dialogParent, tr("New Code File"),
166 tr("The name must be non-empty and cannot contain path separators."));
167 return;
168 }
169 const auto path = SILICON::project::documentPathForSlug(type, slug);
170 if (session.projectContext.documents().contains(path)) {
172 tr("A code file named '%1' already exists.")
173 .arg(QString::fromStdString(path)));
174 return;
175 }
176
177 pushCreateDocumentCommand({path, ""}, tr("Create Code File"));
178 dialog->accept();
179 });
180
181 nameEdit->selectAll();
182 nameEdit->setFocus();
183 dialog->open();
184}
185
187{
188 constexpr int MAXIMUM_BINARY_SIZE = 256 * 1024 * 1024;
189
190 auto* dialog = new QDialog(dialogParent);
191 dialog->setAttribute(Qt::WA_DeleteOnClose);
192 dialog->setWindowTitle(tr("New Binary File"));
193 dialog->setModal(true);
194
195 auto* form = new QFormLayout(dialog);
196 auto* nameEdit = new QLineEdit(tr("untitled"), dialog);
197 auto* sizeEdit = new QSpinBox(dialog);
198 sizeEdit->setRange(1, MAXIMUM_BINARY_SIZE);
199 sizeEdit->setValue(256);
200 sizeEdit->setSuffix(tr(" bytes"));
201
202 form->addRow(tr("Name"), nameEdit);
203 form->addRow(tr("Size"), sizeEdit);
204
205 auto* buttons =
206 new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dialog);
207 form->addRow(buttons);
208 connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
209 connect(
210 buttons, &QDialogButtonBox::accepted, dialog, [this, dialog, nameEdit, sizeEdit] {
211 const auto slug = nameEdit->text().trimmed().toStdString();
214 dialogParent, tr("New Binary File"),
215 tr("The name must be non-empty and cannot contain path separators."));
216 return;
217 }
218
221 if (session.projectContext.documents().contains(path)) {
222 SILICON::ui::inputDialog::warning(dialogParent, tr("New Binary File"),
223 tr("A binary file named '%1' already exists.")
224 .arg(QString::fromStdString(path)));
225 return;
226 }
227
228 const auto roundedSize =
229 std::bit_ceil(static_cast<unsigned int>(sizeEdit->value()));
231 {path, std::string(static_cast<std::size_t>(roundedSize), '\0')},
232 tr("Create Binary File"));
233 dialog->accept();
234 });
235
236 nameEdit->selectAll();
237 nameEdit->setFocus();
238 dialog->open();
239}
240
242{
244 throw std::invalid_argument("createDocument requires a graphical document type");
245
246 const auto noun = documentTypeName(type);
248 dialogParent, tr("New %1").arg(noun), tr("%1 name").arg(noun), noun,
249 [this, type, noun](const QString& requestedName) {
250 const auto trimmed = requestedName.trimmed();
251 const auto displayName = trimmed.isEmpty() ? noun : trimmed;
253 session.projectContext, type, displayName);
254 const auto sceneJson = projectDocumentPolicy::emptyGraphicalDocumentJson(type);
255
256 SILICON::project::Document document(path, sceneJson);
257
258 pushCreateDocumentCommand(std::move(document), tr("Create %1").arg(noun));
259 },
260 this);
261}
262
264 QString commandText, std::vector<SILICON::project::Document> before,
265 std::string beforeActive, std::vector<SILICON::project::Document> after,
266 std::string afterActive)
267{
269 std::move(commandText),
270 [this, before = std::move(before), beforeActive = std::move(beforeActive)] {
271 this->restoreProjectDocuments(before, beforeActive);
272 },
273 [this, after = std::move(after), afterActive = std::move(afterActive)] {
274 this->restoreProjectDocuments(after, afterActive);
275 }));
276}
277
279{
280 const auto selection = projectTree ? projectTree->selectedDocument() : std::nullopt;
281 if (!selection)
282 return;
283 const auto slug = SILICON::project::documentSlugForPath(selection->path);
284 if (!slug)
285 return;
286 if (ProjectTree::itemKind(projectTree->selectedProjectItem())
288 renameArchitecture(*slug);
289 return;
290 }
291
292 const auto noun = documentTypeName(selection->type);
293 const auto title = tr("Rename %1").arg(noun);
295 dialogParent, title, tr("Name"), QString::fromStdString(*slug),
296 [this, selection = *selection, noun, title](const QString& requestedName) {
297 const auto newSlug = requestedName.trimmed().toStdString();
300 dialogParent, title,
301 tr("The name must be non-empty and cannot contain path separators."));
302 return;
303 }
304 const auto newPath =
305 SILICON::project::documentPathForSlug(selection.type, newSlug);
306 if (newPath == selection.path)
307 return;
308 if (session.projectContext.documents().contains(newPath)) {
310 dialogParent, title,
311 tr("A %1 named '%2' already exists.")
312 .arg(noun.toLower(), QString::fromStdString(newPath)));
313 return;
314 }
315
316 try {
317 workspace.flushActiveDocument();
318 const auto before = session.projectContext.documents().getDocuments();
319 const auto beforeActive = session.activeDocumentPath;
321 renamed.setDocuments(before);
322 renamed.renameDocument(selection.path, newPath);
323 const auto afterActive =
324 beforeActive == selection.path ? newPath : beforeActive;
325 pushDocumentSnapshotCommand(title, before, beforeActive,
326 renamed.documents().getDocuments(), afterActive);
327 } catch (const std::exception& error) {
329 }
330 },
331 this);
332}
333
335 const std::vector<std::string>& paths, const QString& commandText)
336{
337 try {
338 workspace.flushActiveDocument();
339 const auto before = session.projectContext.documents().getDocuments();
340 auto after = before;
341 std::erase_if(after, [&paths](const auto& document) {
342 return std::ranges::find(paths, document.getPath()) != paths.end();
343 });
344 if (after.size() == before.size())
345 return;
346
347 const auto beforeActive = session.activeDocumentPath;
348 auto afterActive = beforeActive;
349 if (std::ranges::find(paths, beforeActive) != paths.end()) {
350 const auto activeType = SILICON::project::documentTypeForPath(beforeActive);
351 const auto architecture =
352 activeType
353 && SILICON::project::categoryOf(*activeType)
356 : std::nullopt;
357 const auto prefix = architecture
359 : std::string{};
360 const auto nextComponent =
361 architecture
362 ? std::ranges::find_if(after,
363 [&](const auto& document) {
364 return document.getPath().starts_with(prefix);
365 })
366 : after.end();
367 if (nextComponent != after.end())
368 afterActive = nextComponent->getPath();
369 else if (const auto circuit = std::ranges::find_if(
370 after,
371 [](const auto& document) {
372 return document.getType() == SILICON::project::DocumentType::Circuit;
373 });
374 circuit != after.end())
375 afterActive = circuit->getPath();
376 }
377
378 pushDocumentSnapshotCommand(commandText, before, beforeActive, std::move(after),
379 afterActive);
380 } catch (const std::exception& error) {
381 SILICON::ui::inputDialog::warning(dialogParent, commandText, error.what());
382 }
383}
384
386{
387 const auto selection = projectTree ? projectTree->selectedDocument() : std::nullopt;
388 auto* item = projectTree ? projectTree->selectedProjectItem() : nullptr;
389 if (!selection || !item)
390 return;
391
394 return;
395 }
396
397 if (selection->type == SILICON::project::DocumentType::Circuit) {
398 const auto circuitCount = std::ranges::count_if(
399 session.projectContext.documents().getDocuments(), [](const auto& document) {
400 return document.getType() == SILICON::project::DocumentType::Circuit;
401 });
402 if (circuitCount <= 1)
403 return;
404 }
405
406 const auto noun = documentTypeName(selection->type);
407 const auto title = tr("Delete %1").arg(noun);
408
409 try {
410 workspace.flushActiveDocument();
411 } catch (const std::exception& e) {
413 dialogParent, title,
414 tr("Failed to save the active document before deleting it:\n%1").arg(e.what()));
415 return;
416 }
417
418 if (selection->type == SILICON::project::DocumentType::Circuit) {
419 const auto dependents =
420 session.projectContext.circuitDependencies().dependentsOf(selection->path);
421 if (!dependents.empty()) {
422 QStringList names;
423 for (const auto& dependent : dependents)
424 names.push_back(QString::fromStdString(dependent));
425
427 dialogParent, title,
428 tr("This subcircuit is still used by:\n%1").arg(names.join('\n')));
429 return;
430 }
431 }
432
434 dialogParent, title, tr("Delete %1 \"%2\"?").arg(noun.toLower(), item->text(0)),
435 [this, path = selection->path, title] {
436 const auto& store = session.projectContext.documents();
437 const auto* storedDocument = store.find(path);
438 const auto storedIndex = store.indexOf(path);
439 if (!storedDocument || !storedIndex)
440 return;
441
442 const auto document = *storedDocument;
443 const auto index = static_cast<std::ptrdiff_t>(*storedIndex);
444
445 auto removeStored = [this, path] { this->removeDocument(path); };
446 auto restoreDocument = [this, document, index] {
447 this->insertDocument(document, index, true);
448 };
449
450 undoStack->push(new CallbackUndoCommand(title, restoreDocument, removeStored));
451 },
452 this);
453}
454
456 std::vector<SILICON::project::Document> documents, const std::string& sourcePath,
457 const std::string& activatePath, const QString& commandText,
458 const QString& errorTitle)
459{
460 QStringList conflicts;
461 for (const auto& document : documents) {
462 if (session.projectContext.documents().contains(document.getPath()))
463 conflicts.push_back(QString::fromStdString(document.getPath()));
464 }
465
466 auto commit = [this, documents = std::move(documents), sourcePath, activatePath,
467 commandText, errorTitle]() mutable {
468 try {
469 const auto& store = session.projectContext.documents();
470 auto beforeDocuments = store.getDocuments();
471 auto afterDocuments = beforeDocuments;
472
473 for (auto& document : documents) {
474 const auto existing = std::ranges::find(afterDocuments, document.getPath(),
476 if (existing == afterDocuments.end())
477 afterDocuments.push_back(std::move(document));
478 else
479 *existing = std::move(document);
480 }
481
482 SILICON::project::CircuitDependencyGraph validatedDependencies;
483 validatedDependencies.rebuildFromProject(afterDocuments);
484
485 pushDocumentSnapshotCommand(commandText, std::move(beforeDocuments), sourcePath,
486 std::move(afterDocuments), activatePath);
487 } catch (const std::exception& error) {
489 dialogParent, errorTitle,
490 tr("Failed to update the project documents:\n%1").arg(error.what()));
491 }
492 };
493
494 if (!conflicts.empty()) {
496 dialogParent, tr("Replace Existing Documents"),
497 tr("The following documents already exist and will be replaced:\n\n%1")
498 .arg(conflicts.join('\n')),
499 std::move(commit), this);
500 } else {
501 commit();
502 }
503}
504
505} // namespace SILICON::ui
Runtime-only graph of Circuit-to-Circuit instantiation dependencies.
void rebuildFromProject(const std::vector< Document > &documents)
Rebuilds the graph from a full project description.
const std::vector< Document > & getDocuments() const noexcept
const std::string & getPath() const noexcept
void renameDocument(std::string_view oldPath, std::string_view newPath)
void setDocuments(std::vector< Document > documents)
const DocumentStore & documents() const noexcept
void pushCreateDocumentCommand(SILICON::project::Document document, const QString &commandText)
void insertDocument(SILICON::project::Document document, std::optional< std::ptrdiff_t > insertAt, bool activate)
void pushDocumentSnapshotCommand(QString commandText, std::vector< SILICON::project::Document > before, std::string beforeActive, std::vector< SILICON::project::Document > after, std::string afterActive)
void createDocument(SILICON::project::DocumentType type)
void commitDocumentChanges(std::vector< SILICON::project::Document > documents, const std::string &sourcePath, const std::string &activatePath, const QString &commandText, const QString &errorTitle)
void restoreProjectDocuments(const std::vector< SILICON::project::Document > &documents, const std::string &activePath)
void removeProjectDocuments(const std::vector< std::string > &paths, const QString &commandText)
static std::string architectureName(const QTreeWidgetItem *item)
static ProjectTreeItemKind itemKind(const QTreeWidgetItem *item)
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
std::string documentFileName(const Document &document)
constexpr DocumentCategory categoryOf(const DocumentType type)
std::optional< std::string > documentSlugForPath(const std::string_view path)
Document importDocument(const std::string_view sourcePath, std::string contents)
bool isValidDocumentSlug(const std::string_view slug)
std::optional< DocumentType > documentTypeForPath(const std::string_view path)
std::string architectureDirectory(const std::string_view name)
std::optional< QString > saveFileContent(QWidget *parent, const QString &caption, const QString &suggestedFileName, const QString &filter, const QByteArray &content)
void openFileContent(QWidget *parent, const QString &caption, const QString &filter, OpenContentCallback callback, QObject *context)
void question(QWidget *parent, const QString &title, const QString &text, AcceptedCallback accepted, QObject *context)
void critical(QWidget *parent, const QString &title, const QString &text)
void warning(QWidget *parent, const QString &title, const QString &text)
void getText(QWidget *parent, const QString &title, const QString &label, const QString &defaultText, TextCallback callback, QObject *context)
std::string uniqueDocumentPath(const SILICON::project::ProjectContext &context, const SILICON::project::DocumentType type, const QString &requestedName)
std::string emptyGraphicalDocumentJson(const SILICON::project::DocumentType type)
std::span< const CodeFilePresentation > codeFilePresentations()
QString documentTypeName(SILICON::project::DocumentType type)
Definition uiUtils.hpp:30