SILICON
Loading...
Searching...
No Matches
projectFileController.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 <format>
21#include <functional>
22#include <memory>
23#include <stdexcept>
24#include <utility>
25
26#include <QByteArray>
27#include <QFileDialog>
28#include <QFileInfo>
29#include <QTemporaryFile>
30
31#include <nlohmann/json.hpp>
32
33#include <core/circuit.hpp>
35
36#include <logging/logger.hpp>
37
43
45
52
53namespace SILICON::ui {
54using namespace SILICON::core;
55
56namespace {
57 const SILICON::logging::Logger uiLog("ui");
58} // namespace
59
72
74{
75 session.currentFileName = fn;
76 const QString displayFileName = QFileInfo(session.currentFileName).fileName();
77
78 if (!displayFileName.isEmpty())
79 dialogParent->setWindowTitle(QString("SILICON - %1").arg(displayFileName));
80 else
81 dialogParent->setWindowTitle("SILICON");
82}
83
85{
86 confirmSaveIfDirty([this] {
87 setFileName("");
89 this->documents.rebuildTree();
90 emit projectChanged();
91 });
92}
93
95{
96 workspace.reset();
97 session.currentProjectMetadata.reset();
98 session.currentProjectInfo =
102 document.setContents(workspace.circuitEditor().scene()->serialize());
103 session.projectContext.setDocuments({std::move(document)});
104 documents.notifyActiveDocumentActivated();
105}
106
107void ProjectFileController::loadProjectContent(const QString& fileName,
108 const QByteArray& fileContent)
109{
110 uiLog.info(std::format("Opening {}", fileName.toStdString()));
111
112 try {
113 QTemporaryFile archive;
114 if (!archive.open() || archive.write(fileContent) != fileContent.size()
115 || !archive.flush())
116 throw std::runtime_error("Cannot stage the selected project archive");
117
118 const QString archivePath = archive.fileName();
119 archive.close();
120
121 auto projectFile = SILICON::project::readProjectFile(archivePath.toStdString());
122
123 session.currentProjectMetadata = std::move(projectFile.metadata);
124 workspace.reset();
125 session.currentProjectInfo = std::move(projectFile.project);
126 session.projectContext.setDocuments(std::move(projectFile.documents));
127 const auto initialCircuit = session.firstCircuitPath();
128 if (!initialCircuit)
129 throw std::runtime_error("Project has no circuit document");
130 session.activeDocumentPath = *initialCircuit;
131
132 const auto* document =
133 session.projectContext.documents().find(session.activeDocumentPath);
134 if (!document)
135 throw std::runtime_error("Initial circuit payload is missing");
136
137 workspace.loadDocument(*document);
138 documents.notifyActiveDocumentActivated();
139 setFileName(fileName);
140 this->documents.rebuildTree();
141 emit projectChanged();
142 } catch (const nlohmann::json::exception& e) {
144 dialogParent, tr("Corrupted File"),
145 tr("The project contains invalid JSON data:\n%1").arg(e.what()));
146 } catch (const std::exception& e) {
148 dialogParent, tr("Load Error"),
149 tr("Failed to load the project:\n%1").arg(e.what()));
150 }
151}
152
154{
155 confirmSaveIfDirty([this] {
157 dialogParent, tr("Open Project"), tr("SILICON Project (*.sil);;All Files (*)"),
158 [this](const QString& fileName, const QByteArray& fileContent) {
159 loadProjectContent(fileName, fileContent);
160 },
161 this);
162 });
163}
164
166{
167 try {
168 workspace.flushActiveDocument();
169 } catch (const std::exception& e) {
171 dialogParent, tr("Save Error"),
172 tr("Failed to serialize the active circuit:\n%1").arg(e.what()));
173 return false;
174 }
175
176 QString destinationFileName = session.currentFileName;
177#ifndef __EMSCRIPTEN__
178 if (destinationFileName.isEmpty()) {
179 destinationFileName =
180 QFileDialog::getSaveFileName(dialogParent, tr("Save Project"), QString(),
181 tr("SILICON Project (*.sil);;All Files (*)"));
182 if (destinationFileName.isEmpty())
183 return false;
184 }
185#else
186 if (destinationFileName.isEmpty())
187 destinationFileName = QStringLiteral("project.sil");
188#endif
189
190 try {
191 auto metadata =
192 session.currentProjectMetadata.value_or(SILICON::project::metadataForNewFile());
193 metadata.formatVersion = SILICON::project::FORMAT_VERSION;
194 metadata.siliconVersion = SILICON_VERSION;
195 metadata.lastModify = SILICON::project::currentUtcTimestamp();
196
197 auto project = session.currentProjectInfo.value_or(SILICON::project::ProjectInfo{});
198 if (project.name.empty())
199 project.name = QFileInfo(destinationFileName).baseName().toStdString();
200 session.currentProjectInfo = project;
202 const auto documents = session.projectContext.documents().getDocuments();
204 .metadata = metadata, .project = project, .documents = documents};
205
206#ifdef __EMSCRIPTEN__
207 QTemporaryFile archive;
208 if (!archive.open())
209 throw std::runtime_error("Cannot create a temporary project archive");
210 const QString archivePath = archive.fileName();
211 archive.close();
212
213 SILICON::project::writeProjectFile(archivePath.toStdString(), projectFile);
214
215 QFile archiveFile(archivePath);
216 if (!archiveFile.open(QIODevice::ReadOnly))
217 throw std::runtime_error("Cannot read the temporary project archive");
218
219 const auto savedFileName = SILICON::ui::fileDialog::saveFileContent(
220 dialogParent, tr("Save Project"), destinationFileName,
221 tr("SILICON Project (*.sil);;All Files (*)"), archiveFile.readAll());
222 if (!savedFileName)
223 return false;
224 setFileName(*savedFileName);
225#else
226 SILICON::project::writeProjectFile(destinationFileName.toStdString(), projectFile);
227 setFileName(destinationFileName);
228#endif
229 session.currentProjectMetadata = std::move(metadata);
230 this->documents.rebuildTree();
231 undoStack.setClean();
232 workspace.resetEditorDirtyState();
233 return true;
234 } catch (const std::exception& e) {
236 dialogParent, tr("Save Error"),
237 tr("Failed to save the project:\n%1").arg(e.what()));
238 return false;
239 }
240}
241
242void ProjectFileController::confirmSaveIfDirty(std::function<void()> continuation)
243{
244 if (!workspace.hasUnsavedChanges()) {
245 continuation();
246 return;
247 }
248
250 dialogParent, tr("Unsaved Changes"),
251 tr("The current project has unsaved changes. Do you want to save them?"),
252 tr("Save"), tr("Discard"),
253 [this, continuation =
254 std::move(continuation)](const SILICON::ui::inputDialog::Choice choice) {
256 return;
258 return;
259
260 continuation();
261 },
262 this);
263}
264
265} // namespace SILICON::ui
Selects and hosts editors while preserving detached document preparation.
void confirmSaveIfDirty(std::function< void()> continuation)
void setFileName(const QString &fileName)
void loadProjectContent(const QString &fileName, const QByteArray &fileContent)
ProjectFileController(ProjectSession &session, EditorWorkspace &workspace, ProjectDocumentController &documents, QUndoStack &undoStack, QWidget *dialogParent)
std::string currentUtcTimestamp()
Returns the current UTC timestamp formatted as YYYY-MM-DDTHH\:MM\:SSZ.
constexpr int FORMAT_VERSION
Current version of the Silicon project archive schema.
ProjectFile readProjectFile(const std::filesystem::path &path)
Reads and validates a Silicon .sil project archive.
void writeProjectFile(const std::filesystem::path &path, const ProjectFile &projectFile)
Writes a Silicon .sil project archive.
ProjectMetadata metadataForNewFile()
Creates default metadata for a new project file.
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 critical(QWidget *parent, const QString &title, const QString &text)
void warningChoice(QWidget *parent, const QString &title, const QString &text, const QString &primaryText, const QString &secondaryText, ChoiceCallback callback, QObject *context)
Shows a three-way warning using caller-provided action labels.
SILICON::project::Document defaultCircuitDocument()
SILICON::project::ProjectInfo defaultProjectInfo(const QString &fileName)
void ensureProjectDocuments(SILICON::project::ProjectContext &context)
const SILICON::logging::Logger uiLog("ui")
In-memory representation of a .sil project archive.
Project-level data stored in project.json.