Debian Codegraph @

src/Gui/Dialogs/DlgVersionMigrator.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2025 The FreeCAD project association AISBL *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 **************************************************************************/
23
24 #include <QDesktopServices>
25 #include <QDialog>
26 #include <QMenu>
27 #include <QMessageBox>
28 #include <QOpenGLFunctions>
29 #include <QProcess>
30 #include <QThread>
31 #include <QTimer>
32 #include <QToolButton>
33 #include <QWindow>
34
35 #include <fstream>
36 #include <memory>
37 #include <set>
38 #include <string>
39 #include <ranges>
40 #include <cstdlib>
41 #include <filesystem>
42
43 #include "DlgVersionMigrator.h"
44 #include "SplitButton.h"
45
46 #include "ui_DlgVersionMigrator.h"
47
48 #include "../MainWindow.h"
49 #include <App/Application.h>
50 #include <App/ApplicationDirectories.h>
51
52 #include "QTextBrowser"
53
54
55 using namespace Gui::Dialog;
56 namespace fs = std::filesystem;
57
58 bool isCurrentVersionKnown()
59 {
60 std::set<fs::path> paths = {
61 App::Application::directories()->getUserAppDataDir(),
62 App::Application::directories()->getUserConfigPath()
63 };
64 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
65 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
66 std::string currentVersionedDirName
67 = App::ApplicationDirectories::versionStringForPath(major, minor);
68 for (auto& path : paths) {
69 if (App::Application::directories()->usingCurrentVersionConfig(path)) {
70 return true;
71 }
72 fs::path markerPath = path;
73 if (App::Application::directories()->isVersionedPath(path)) {
74 markerPath = path.parent_path();
75 }
76 markerPath /= currentVersionedDirName + ".do_not_migrate";
77 if (fs::exists(markerPath)) {
78 return true;
79 }
80 }
81 return false;
82 }
83
84 void markCurrentVersionAsDoNotMigrate()
85 {
86 std::set<fs::path> paths = {
87 App::Application::directories()->getUserAppDataDir(),
88 App::Application::directories()->getUserConfigPath()
89 };
90 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
91 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
92 std::string currentVersionedDirName
93 = App::ApplicationDirectories::versionStringForPath(major, minor);
94 for (auto& path : paths) {
95 if (App::Application::directories()->usingCurrentVersionConfig(path)) {
96 // No action to take: the migration is done, so this call doesn't need to do anything
97 continue;
98 }
99 fs::path markerPath = path;
100 if (App::Application::directories()->isVersionedPath(path)) {
101 markerPath = path.parent_path();
102 }
103 markerPath /= currentVersionedDirName + ".do_not_migrate";
104 std::ofstream markerFile(markerPath);
105 if (!markerFile.is_open()) {
106 Base::Console().error(
107 "Unable to open marker file %s\n",
108 Base::FileInfo::pathToString(markerPath).c_str()
109 );
110 continue;
111 }
112 markerFile << "Migration to version " << currentVersionedDirName << " was declined. "
113 << "To request migration again, delete this file.";
114 markerFile.close();
115 }
116 }
117
118
119 DlgVersionMigrator::DlgVersionMigrator(MainWindow* mw)
120 : QDialog(mw)
121 , mainWindow(mw)
122 , sizeCalculationWorkerThread(nullptr)
123 , ui(std::make_unique<Ui_DlgVersionMigrator>())
124 {
125 ui->setupUi(this);
126
127 auto prefGroup = App::GetApplication().GetParameterGroupByPath(
128 "User parameter:BaseApp/Preferences/Migration"
129 );
130
131 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
132 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
133
134 auto programName = QString::fromStdString(App::Application::getExecutableName());
135
136 // NOTE: All rich-text strings are generated programmatically so that translators don't have to
137 // deal with the markup. The two strings in the middle of the dialog are set in the UI file.
138
139 auto programNameString
140 = tr("Welcome to %1 %2.%3").arg(programName, QString::number(major), QString::number(minor));
141 auto welcomeString = QStringLiteral("<b>") + programNameString + QStringLiteral("</b>");
142
143 auto calculatingSizeString = QStringLiteral("<b>") + tr("Calculating size…")
144 + QStringLiteral("</b>");
145
146 auto shareConfigurationString = QStringLiteral("<a href='#shareConfiguration'>")
147 + tr("Share configuration between versions") + QStringLiteral("</a>");
148
149 setWindowTitle(programNameString);
150 #ifdef Q_OS_MACOS
151 // macOS does not show the window title on modals, so add the extra label
152 ui->welcomeLabel->setText(welcomeString);
153 #else
154 ui->welcomeLabel->hide();
155 #endif
156 ui->sizeLabel->setText(calculatingSizeString);
157
158 ui->copyButton->mainButton()->setDefault(true);
159 ui->copyButton->mainButton()->setAutoDefault(true);
160
161 ui->copyButton->mainButton()->setText(tr("Copy Configuration (Recommended)"));
162
163 connect(ui->copyButton, &SplitButton::defaultClicked, this, &DlgVersionMigrator::migrate);
164 connect(ui->helpButton, &QPushButton::clicked, this, &DlgVersionMigrator::help);
165
166 // Set up the menu actions for the two hidden options
167 connect(ui->copyButton->mainButton(), &QPushButton::clicked, this, &DlgVersionMigrator::migrate);
168
169 auto* menu = ui->copyButton->menu();
170
171 QAction* share = menu->addAction(tr("Share configuration with previous version"));
172 QAction* reset = menu->addAction(tr("Use a new default configuration"));
173
174 connect(share, &QAction::triggered, this, &DlgVersionMigrator::share);
175 connect(reset, &QAction::triggered, this, &DlgVersionMigrator::freshStart);
176 }
177
178 DlgVersionMigrator::~DlgVersionMigrator() = default;
179
180 int DlgVersionMigrator::exec()
181 {
182 // If the user is running a custom directory set, there is no migration to versioned directories
183 if (App::Application::directories()->usingCustomDirectories()) {
184 return 0;
185 }
186 if (!isCurrentVersionKnown()) {
187 calculateMigrationSize();
188 QDialog::exec();
189 if (sizeCalculationWorkerThread && sizeCalculationWorkerThread->isRunning()) {
190 sizeCalculationWorkerThread->requestInterruption();
191 }
192 }
193 return 0;
194 }
195
196
197 class DirectorySizeCalculationWorker: public QObject
198 {
199 Q_OBJECT
200
201 public:
202 void run()
203 {
204 auto dir = App::Application::directories()->getUserAppDataDir();
205 uintmax_t size = 0;
206 auto thisThread = QThread::currentThread();
207 std::error_code errorCode;
208 auto iterator = fs::recursive_directory_iterator(
209 dir,
210 fs::directory_options::skip_permission_denied,
211 errorCode
212 );
213 if (errorCode) {
214 Q_EMIT(sizeFound(0));
215 Q_EMIT(finished());
216 return;
217 }
218 for (auto it = fs::begin(iterator); it != fs::end(iterator); it.increment(errorCode)) {
219 if (errorCode) {
220 errorCode.clear();
221 continue;
222 }
223 if (thisThread->isInterruptionRequested()) {
224 Q_EMIT(cancelled());
225 Q_EMIT(finished());
226 return;
227 }
228 if (it->is_regular_file(errorCode) && !errorCode) {
229 auto fileSize = fs::file_size(it->path(), errorCode);
230 if (!errorCode) {
231 size += fileSize;
232 }
233 errorCode.clear();
234 }
235 }
236 Q_EMIT(sizeFound(size));
237 Q_EMIT(finished());
238 }
239
240 Q_SIGNALS:
241 void finished();
242
243 void sizeFound(uintmax_t _t1);
244
245 void cancelled();
246 };
247
248 PathMigrationWorker::PathMigrationWorker(std::string configDir, std::string userAppDir, int major, int minor)
249 : _configDir(std::move(configDir))
250 , _userAppDir(std::move(userAppDir))
251 , _major(major)
252 , _minor(minor)
253 {}
254
255 void PathMigrationWorker::run()
256 {
257 try {
258 App::GetApplication().GetUserParameter().SaveDocument();
259 auto result = App::Application::directories()->migrateAllPaths({_userAppDir, _configDir});
260 replaceOccurrencesInPreferences();
261 if (!result.failedPaths.empty()) {
262 writeMigrationLog(result.failedPaths);
263 QStringList skippedList;
264 for (const auto& path : result.failedPaths) {
265 skippedList.append(QString::fromStdString(Base::FileInfo::pathToString(path)));
266 }
267 Q_EMIT(completedWithWarnings(skippedList));
268 }
269 else {
270 Q_EMIT(complete());
271 }
272 }
273 catch (const Base::Exception& e) {
274 Base::Console().error("Error migrating configuration data: %s\n", e.what());
275 Q_EMIT(failed());
276 }
277 catch (const std::exception& e) {
278 Base::Console().error("Unrecognized error migrating configuration data: %s\n", e.what());
279 Q_EMIT(failed());
280 }
281 catch (...) {
282 Base::Console().error("Error migrating configuration data\n");
283 Q_EMIT(failed());
284 }
285 Q_EMIT(finished());
286 }
287
288 void PathMigrationWorker::replaceOccurrencesInPreferences()
289 {
290 std::filesystem::path prefPath = locateNewPreferences();
291 std::map<std::string, std::string> replacements = {
292 {_configDir, generateNewUserAppPathString(_configDir)},
293 {_userAppDir, generateNewUserAppPathString(_userAppDir)}
294 };
295
296 try {
297 std::ifstream prefFile(prefPath);
298 std::string contents(
299 (std::istreambuf_iterator<char>(prefFile)),
300 std::istreambuf_iterator<char>()
301 );
302
303 for (const auto& [oldString, newString] : replacements) {
304 replaceInContents(contents, oldString, newString);
305 }
306
307 std::ofstream newPrefFile(prefPath);
308 newPrefFile << contents;
309 }
310 catch (const std::exception& e) {
311 Base::Console().error("Error reading preferences file: %s\n", e.what());
312 }
313 }
314
315 std::filesystem::path PathMigrationWorker::locateNewPreferences() const
316 {
317 std::filesystem::path path(_configDir);
318 if (path.filename().empty()) {
319 // Handle the case where the path was constructed from a std::string with a trailing /
320 path = path.parent_path();
321 }
322 fs::path newPath;
323
324 if (App::Application::directories()->isVersionedPath(path)) {
325 newPath = path.parent_path()
326 / App::ApplicationDirectories::versionStringForPath(_major, _minor);
327 }
328 else {
329 newPath = path / App::ApplicationDirectories::versionStringForPath(_major, _minor);
330 }
331 newPath /= "user.cfg";
332 return newPath;
333 }
334
335 std::string PathMigrationWorker::generateNewUserAppPathString(const std::string& oldPath) const
336 {
337 std::filesystem::path newPath = Base::FileInfo::stringToPath(oldPath);
338 if (App::Application::directories()->isVersionedPath(newPath)) {
339 newPath = newPath.parent_path();
340 }
341 newPath /= App::ApplicationDirectories::versionStringForPath(_major, _minor);
342 std::string result = Base::FileInfo::pathToString(newPath);
343 if (oldPath.back() == std::filesystem::path::preferred_separator) {
344 result += std::filesystem::path::preferred_separator;
345 }
346 return result;
347 }
348
349 void PathMigrationWorker::replaceInContents(
350 std::string& contents,
351 const std::string& oldString,
352 const std::string& newString
353 )
354 {
355 if (oldString.empty()) {
356 return;
357 }
358 std::size_t pos = 0;
359 while ((pos = contents.find(oldString, pos)) != std::string::npos) {
360 contents.replace(pos, oldString.length(), newString);
361 pos += newString.length();
362 }
363 }
364
365 void PathMigrationWorker::writeMigrationLog(const std::vector<std::filesystem::path>& skippedPaths)
366 {
367 auto logName = "migration-to-"
368 + App::ApplicationDirectories::versionStringForPath(_major, _minor) + ".log";
369 auto logPath = locateNewPreferences().parent_path() / logName;
370 try {
371 std::ofstream log(logPath);
372 log << "Migration completed with " << skippedPaths.size() << " skipped file(s):\n\n";
373 for (const auto& path : skippedPaths) {
374 log << " " << Base::FileInfo::pathToString(path) << "\n";
375 }
376 log << "\nSee the FreeCAD Report View for additional details.\n";
377 }
378 catch (const std::exception& e) {
379 Base::Console().warning(
380 "Migration: could not write log to '%s': %s\n",
381 Base::FileInfo::pathToString(logPath).c_str(),
382 e.what()
383 );
384 }
385 }
386
387 void DlgVersionMigrator::calculateMigrationSize()
388 {
389 sizeCalculationWorkerThread = new QThread(mainWindow);
390 auto* worker = new DirectorySizeCalculationWorker();
391 worker->moveToThread(sizeCalculationWorkerThread);
392 connect(sizeCalculationWorkerThread, &QThread::started, worker, &DirectorySizeCalculationWorker::run);
393
394 connect(
395 worker,
396 &DirectorySizeCalculationWorker::sizeFound,
397 this,
398 &DlgVersionMigrator::showSizeOfMigration
399 );
400 connect(worker, &DirectorySizeCalculationWorker::finished, sizeCalculationWorkerThread, &QThread::quit);
401 connect(worker, &DirectorySizeCalculationWorker::finished, worker, &QObject::deleteLater);
402 connect(
403 sizeCalculationWorkerThread,
404 &QThread::finished,
405 sizeCalculationWorkerThread,
406 &QObject::deleteLater
407 );
408
409 sizeCalculationWorkerThread->start();
410 }
411
412 void DlgVersionMigrator::share()
413 {
414 markCurrentVersionAsDoNotMigrate();
415 if (sizeCalculationWorkerThread && sizeCalculationWorkerThread->isRunning()) {
416 sizeCalculationWorkerThread->requestInterruption();
417 }
418 close();
419 }
420
421 void DlgVersionMigrator::showSizeOfMigration(uintmax_t size)
422 {
423 auto sizeString = QLocale().formattedDataSize(static_cast<qint64>(size));
424 auto sizeMessage = QStringLiteral("<b>")
425 + QObject::tr("Estimated size of data to copy: %1").arg(sizeString) + QStringLiteral("</b>");
426 ui->sizeLabel->setText(sizeMessage);
427 sizeCalculationWorkerThread = nullptr; // Deleted via a previously-configured deleteLater()
428 }
429
430 void DlgVersionMigrator::migrate()
431 {
432 hide();
433 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
434 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
435 auto* workerThread = new QThread(mainWindow);
436 auto* worker = new PathMigrationWorker(
437 App::Application::getUserConfigPath(),
438 App::Application::getUserAppDataDir(),
439 major,
440 minor
441 );
442 worker->moveToThread(workerThread);
443 connect(workerThread, &QThread::started, worker, &PathMigrationWorker::run);
444 connect(worker, &PathMigrationWorker::finished, workerThread, &QThread::quit);
445 connect(worker, &PathMigrationWorker::finished, worker, &QObject::deleteLater);
446 connect(workerThread, &QThread::finished, workerThread, &QObject::deleteLater);
447
448 QStringList skippedFiles;
449 auto migrationRunning = new QMessageBox(this);
450 migrationRunning->setWindowTitle(QObject::tr("Migrating"));
451 migrationRunning->setText(QObject::tr("Migrating configuration data and addons…"));
452 migrationRunning->setStandardButtons(QMessageBox::NoButton);
453 connect(worker, &PathMigrationWorker::complete, migrationRunning, &QMessageBox::accept);
454 connect(
455 worker,
456 &PathMigrationWorker::completedWithWarnings,
457 migrationRunning,
458 [migrationRunning, &skippedFiles](QStringList paths) {
459 skippedFiles = std::move(paths);
460 migrationRunning->accept();
461 }
462 );
463 connect(worker, &PathMigrationWorker::failed, migrationRunning, &QMessageBox::reject);
464
465 workerThread->start();
466 migrationRunning->exec();
467
468 if (migrationRunning->result() == QDialog::Accepted) {
469 if (!skippedFiles.isEmpty()) {
470 // Some of these file paths might be very long, so truncate them to a reasonable
471 // (arbitrary) length of 70 chars.
472 constexpr int maxDisplayLength = 70;
473 constexpr int prefixLength = maxDisplayLength / 3;
474 constexpr int suffixLength = maxDisplayLength - prefixLength - 1; // 1 for ellipsis
475 QStringList truncated;
476 for (const auto& path : skippedFiles) {
477 if (path.length() > maxDisplayLength) {
478 truncated.append(
479 path.left(prefixLength) + QStringLiteral("…") + path.right(suffixLength)
480 );
481 }
482 else {
483 truncated.append(path);
484 }
485 }
486 auto warning = new QMessageBox(mainWindow);
487 warning->setIcon(QMessageBox::Warning);
488 warning->setWindowTitle(QObject::tr("Migration completed with warnings"));
489 auto logFileName = QStringLiteral("migration-to-")
490 + QString::fromStdString(
491 App::ApplicationDirectories::versionStringForPath(major, minor)
492 )
493 + QStringLiteral(".log");
494 warning->setText(
495 QObject::tr(
496 "%n file(s) could not be copied and were skipped. "
497 "A full list has been saved to %1 in your new configuration directory.",
498 "",
499 static_cast<int>(skippedFiles.size())
500 )
501 .arg(logFileName)
502 );
503 warning->setDetailedText(truncated.join(QStringLiteral("\n")));
504 warning->setStandardButtons(QMessageBox::Ok);
505 warning->exec();
506 }
507 restart(tr("Migration complete"));
508 }
509 else {
510 QMessageBox::critical(
511 mainWindow,
512 QObject::tr("Migration failed"),
513 QObject::tr("Migration failed. See the Report View for details.")
514 );
515 }
516 }
517
518
519 void DlgVersionMigrator::freshStart()
520 {
521 // Create the versioned directories, but don't put anything in them
522 std::set<fs::path> paths = {
523 App::Application::directories()->getUserAppDataDir(),
524 App::Application::directories()->getUserConfigPath()
525 };
526 int major = std::stoi(App::Application::Config()["BuildVersionMajor"]);
527 int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]);
528 std::string currentVersionedDirName
529 = App::ApplicationDirectories::versionStringForPath(major, minor);
530 for (auto& path : paths) {
531 if (App::Application::directories()->usingCurrentVersionConfig(path)) {
532 continue;
533 }
534 fs::path versionDir = path;
535 if (App::Application::directories()->isVersionedPath(path)) {
536 versionDir = path.parent_path();
537 }
538 versionDir /= currentVersionedDirName;
539 if (fs::exists(versionDir)) {
540 continue;
541 }
542 fs::create_directory(versionDir);
543 }
544 restart(tr("New default configuration created"));
545 }
546
547 void DlgVersionMigrator::help()
548 {
549 auto helpPage = QStringLiteral("https://wiki.freecad.org/Version_migration");
550 QDesktopServices::openUrl(QUrl(helpPage));
551 }
552
553 void DlgVersionMigrator::restart(const QString& message)
554 {
555 App::GetApplication().GetUserParameter().SaveDocument(); // Flush to disk before restarting
556 auto* restarting = new QMessageBox(this);
557 restarting->setText(message + QObject::tr(" → Restarting…"));
558 restarting->setWindowTitle(QObject::tr("Restarting"));
559 restarting->setStandardButtons(QMessageBox::NoButton);
560 auto closeNotice = [restarting]() {
561 restarting->reject();
562 };
563
564 // Insert a short delay before restart so the user can see the success message and
565 // knows it's a restart and not a crash...
566 constexpr int delayRestartMillis {2000};
567 QTimer::singleShot(delayRestartMillis, closeNotice);
568 restarting->exec();
569
570 connect(qApp, &QCoreApplication::aboutToQuit, [=] {
571 if (getMainWindow()->close()) {
572 auto args = QApplication::arguments();
573 args.removeFirst();
574 QProcess::startDetached(
575 QApplication::applicationFilePath(),
576 args,
577 QApplication::applicationDirPath()
578 );
579 }
580 });
581 QCoreApplication::exit(0);
582 _Exit(0); // No really. Die.
583 }
584
585
586 #include "DlgVersionMigrator.moc"