Debian Codegraph @

src/GUI/SetupRootDialog.cxx

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // SetupRootDialog.cxx - part of GUI launcher using Qt5
2 //
3 // Written by James Turner, started December 2014.
4 //
5 // Copyright (C) 2014 James Turner <[email protected]>
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 #include "config.h"
22
23 #include "SetupRootDialog.hxx"
24
25 #include <condition_variable>
26 #include <mutex>
27
28 #include <QDebug>
29 #include <QDesktopServices>
30 #include <QDir>
31 #include <QFile>
32 #include <QFileDialog>
33 #include <QFileInfo>
34 #include <QMessageBox>
35 #include <QNetworkAccessManager>
36 #include <QNetworkReply>
37 #include <QNetworkRequest>
38 #include <QPointer>
39 #include <QSettings>
40 #include <QThread>
41 #include <QUrl>
42
43
44 #include "ui_SetupRootDialog.h"
45
46 #include <Main/fg_init.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Main/globals.hxx>
49 #include <Main/options.hxx>
50 #include <Viewer/WindowBuilder.hxx>
51
52 #include "DownloadTerrasyncSharedData.hxx"
53 #include "LaunchConfig.hxx"
54 #include "QtLauncher.hxx"
55 #include "SettingsWrapper.hxx"
56 #include "UpdateDownloadedFGData.hxx"
57 #include <GUI/QtDNSClient.hxx>
58 #include <Main/MultipleInstanceLock.hxx>
59 #include <Main/sentryIntegration.hxx>
60
61 #include <simgear/io/iostreams/sgstream.hxx>
62 #include <simgear/io/untar.hxx>
63 #include <simgear/misc/sg_dir.hxx>
64
65 using namespace std::chrono_literals;
66
67 const qint64 fourMB = 4 * 1024 * 1024;
68
69 namespace {
70 /**
71 * @brief Calculates a progress percentage from the current and total values.
72 *
73 * Computes (current / total) × 100 using integer math. The result is clamped
74 * to the range [0, 100] and rounded down. If @p total is zero, returns 0.
75 *
76 * @param current The current progress value (e.g. bytes downloaded).
77 * @param total The total value representing 100% completion.
78 * @return An integer percentage between 0 and 100.
79 */
80 int calculateProgressPercentage(quint64 current, quint64 total) {
81
82 constexpr int max_percent = 100;
83
84 if (total == 0) {
85 return 0;
86 }
87
88 // Compute percentage and clamp to avoid overflow or narrowing
89 const quint64 percent = std::min((current * max_percent) / total, static_cast<quint64>(max_percent));
90
91 return static_cast<int>(percent);
92 }
93 }
94
95 class InstallFGDataThread : public QThread
96 {
97 Q_OBJECT
98 public:
99 InstallFGDataThread(QObject* pr, QNetworkAccessManager* nam) : QThread(pr),
100 m_networkManager(nam),
101 m_dns(new QtDNSClient(this, "dl_fgdata"))
102 {
103 const auto rp = flightgear::Options::sharedInstance()->downloadedDataRoot();
104 // ensure we remove any existing data, since it failed validation
105 if (rp.exists()) {
106 simgear::Dir ed(rp);
107 const bool ok = ed.remove(true);
108 if (!ok) {
109 m_error = true;
110 QTimer::singleShot(1s, this, [this]() {
111 emit failed(tr("Unable to remove existing data before downloading."));
112 });
113 return;
114 }
115 }
116
117 m_downloadPath = rp.dirPath() / ("_download_data_" + std::to_string(FLIGHTGEAR_MAJOR_VERSION) + "_" + std::to_string(FLIGHTGEAR_MINOR_VERSION));
118 m_downloadPath.set_cached(false);
119
120 const auto resumeDataPath = rp.dirPath() / std::string{"_fgdata_downloading.temp"};
121 // FIXME: convert via std::filesystem::path
122 m_resumeData.setFileName(QString::fromStdString(resumeDataPath.utf8Str()));
123
124 // +1 to include the leading /
125 m_pathPrefixLength = m_downloadPath.utf8Str().length() + 1;
126
127 connect(m_dns, &QtDNSClient::finished, [this]() {
128 m_servers = m_dns->results();
129 startRequest();
130 });
131
132 connect(m_dns, &QtDNSClient::failed, [this](QString msg) {
133 qWarning() << "Failed to query download servers dynamically, falling back to download.flightgear.org";
134 m_servers.append("https://download.flightgear.org");
135 startRequest();
136 });
137
138 m_dns->makeDNSRequest();
139 }
140
141 bool willResume() const
142 {
143 // if the resume data exists and is large enough, we will attempt to resume
144 return static_cast<qint64>(m_resumeData.size()) >= fourMB;
145 }
146
147 /**
148 * @brief setup the QNetworkRequest to do a resume download, by specifying
149 * a byte-range in the HTTP request.
150 *
151 * @param req : the request to modify
152 * @return qint64 : the number of bytes of overlap we will read
153 */
154 qint64 resumeDownload(QNetworkRequest& req)
155 {
156 m_resumeData.close(); // close because we may remove
157
158 std::unique_lock g(m_mutex);
159 qint64 resumeBytes = m_resumeData.size();
160 m_resumedBytesSize = 0;
161 m_readResumeFile = false;
162
163 if (resumeBytes < fourMB) {
164 m_resumeData.remove();
165 return 0;
166 }
167
168 if (!m_resumeData.open(QIODevice::ReadOnly)) {
169 return 0;
170 }
171
172 // allow a 4MB overlap, to verify the tail end of the
173 // resume file matches what we download. This will catch weird
174 // cases like the file on the server side changed, or an out-of-sync mirror
175 resumeBytes -= fourMB;
176 m_resumedBytesSize = resumeBytes;
177
178 // seek to read out our overlap data into m_buffer
179 m_resumeData.seek(resumeBytes);
180 qInfo() << "Will resume at byte offset:" << resumeBytes;
181 m_buffer = m_resumeData.read(fourMB);
182 m_resumeData.close();
183
184 if (static_cast<qint64>(m_buffer.size()) != fourMB) {
185 qWarning() << "Failed to load existing downloaded data into the buffer";
186 m_buffer.clear();
187 m_resumeData.remove();
188 return 0;
189 }
190
191 // open the file in read-write mode
192 if (!m_resumeData.open(QIODevice::ReadWrite)) {
193 qWarning() << "Failed to open download resume file in read-write mode";
194 return 0;
195 }
196
197 req.setRawHeader("Range", QString("bytes=%1-").arg(resumeBytes).toUtf8());
198 m_readResumeFile = true;
199
200 return fourMB;
201 }
202
203 void startRequest()
204 {
205 if (isRunning()) {
206 m_error = true; // force the thread to exit
207 wait();
208 m_error = false;
209 flightgear::addSentryBreadcrumb("InstallFGDataThread: did stop running thead", "info");
210 }
211
212 // clean-up from any previous failed / abandoned request
213 if (m_downloadPath.exists()) {
214 simgear::Dir ed(m_downloadPath);
215 bool ok = ed.remove(true);
216 if (!ok) {
217 m_error = true;
218 flightgear::addSentryBreadcrumb("InstallFGDataThread: removing old download dir failed", "error");
219 emit failed(tr("Unable to remove previous download."));
220 return;
221 }
222 }
223
224 // must do this before we start any resume
225 m_haveFirstMByte = false;
226 m_extractedBytes = 0;
227 m_buffer.clear();
228
229 // SF doesn't support resuming, hard-code this for now. To be more generic we would
230 // encode this in the server data somehow.
231 if (willResume()) {
232 if (m_servers.front().contains("sourceforge")) {
233 // rotate front entry to the back; if the *only* entry is SF, we still
234 // want to use it (and forget about resuming)
235 auto s = m_servers.takeFirst();
236 m_servers.append(s);
237 }
238 }
239
240 QString templateUrl = m_servers.front() + QStringLiteral("/release-%1/FlightGear-%2-data.txz");
241 if (templateUrl.startsWith("https://sourceforge.net/")) {
242 // deal with different SF syntax
243 templateUrl += QStringLiteral("/download");
244 }
245
246 QString majorMinorVersion = QString(FLIGHTGEAR_MAJOR_MINOR_VERSION);
247 m_downloadUrl = QUrl(templateUrl.arg(majorMinorVersion).arg(FLIGHTGEAR_VERSION));
248
249 qInfo() << "Download URI:" << m_downloadUrl;
250
251 QNetworkRequest req{m_downloadUrl};
252 req.setMaximumRedirectsAllowed(5);
253 // important to get correct behaviour from SourceForge, default UA causes it not to
254 // re-direct to the actual mirror correctly.
255 req.setRawHeader("user-agent", "flightgear-installer");
256
257 // check if we can resume an existing download, returns the
258 // number of overlap bytes or zero for no resume.
259 m_resumeOverlapBytes = resumeDownload(req);
260 if (!m_readResumeFile) {
261 // if we're not resuming, empty the file and open it write-only
262 m_resumeData.open(QIODevice::WriteOnly | QIODevice::Truncate);
263 }
264
265 m_download = m_networkManager->get(req);
266 m_download->setReadBufferSize(64 * 1024 * 1024);
267
268 connect(m_download, &QNetworkReply::downloadProgress, this, &InstallFGDataThread::onDownloadProgress);
269 connect(m_download, &QNetworkReply::readyRead, this, &InstallFGDataThread::processBytes);
270 connect(m_download, &QNetworkReply::finished, this, &InstallFGDataThread::onReplyFinished);
271 connect(m_download, &QNetworkReply::metaDataChanged, this, &InstallFGDataThread::onMetaDataChanged);
272
273 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
274 connect(m_download, &QNetworkReply::errorOccurred, this, &InstallFGDataThread::onNetworkError);
275 #endif
276
277 // start our thread loop
278 start();
279 }
280
281 ~InstallFGDataThread()
282 {
283 if (!m_done) {
284 m_resumeData.close();
285 if (m_download) {
286 m_download->abort();
287 }
288 m_error = true;
289 }
290
291 if (m_download) {
292 m_download->deleteLater();
293 m_download = nullptr;
294 }
295
296 wait();
297
298 if (m_error) {
299 simgear::Dir ed(m_downloadPath);
300 ed.remove(true);
301 }
302 }
303
304 void updateProgress()
305 {
306 std::unique_lock g(m_mutex);
307 const int percent = calculateProgressPercentage(m_extractedBytes, m_totalSize);
308 std::string fullPathStr;
309 if (m_archive) {
310 fullPathStr = m_archive->mostRecentExtractedPath().utf8Str();
311 fullPathStr.erase(0, m_pathPrefixLength);
312 }
313
314 emit installProgress(QString::fromStdString(fullPathStr), percent);
315 }
316
317 void run() override
318 {
319 while (!m_error & !m_done) {
320 if (!m_archive) {
321 // reset the archive
322 m_archive.reset(new simgear::ArchiveExtractor(m_downloadPath));
323 m_archive->setRemoveTopmostDirectory(true);
324 m_archive->setCreateDirHashEntries(true);
325 }
326
327 // do the resume read first, as fast as the disk IO will allow
328 if (m_readResumeFile) {
329 QByteArray resumeBytes;
330 {
331 std::unique_lock g(m_mutex);
332 const auto bytesToRead = std::min(static_cast<qint64>(m_resumedBytesSize - m_resumeData.pos()), static_cast<qint64>(16 * 0x100000));
333 resumeBytes = m_resumeData.read(bytesToRead);
334 }
335 m_archive->extractBytes((const uint8_t*)resumeBytes.constData(), resumeBytes.size());
336 m_extractedBytes += resumeBytes.size();
337 if (m_resumeData.pos() >= static_cast<qint64>(m_resumedBytesSize)) {
338 m_readResumeFile = false;
339 flightgear::addSentryBreadcrumb("InstallFGDataThread: done reading resume bytes", "info");
340 }
341 updateProgress();
342 continue;
343 }
344
345 QByteArray localBytes;
346 {
347 std::unique_lock g(m_mutex);
348 if (m_buffer.isEmpty()) {
349 m_bufferWait.wait_for(g, 100ms);
350 }
351
352 // don't start pulling bytes out of the buffer while we
353 // are checking the resume overlap
354 if (m_resumeOverlapBytes > 0) {
355 continue;
356 }
357
358 // don't start passing bytes to the archive extractor, until we have 1MB
359 // this is necessary to avoid passing redirect/404 page bytes in, and breaking
360 // the extractor.
361 if (!m_haveFirstMByte && (m_buffer.size() < 0x100000)) {
362 continue;
363 } else {
364 m_haveFirstMByte = true;
365 }
366
367 // take at most 1MB
368 localBytes = m_buffer.left(0x100000);
369 m_buffer.remove(0, localBytes.length());
370 m_resumeData.write(localBytes);
371 }
372
373 if (!localBytes.isEmpty()) {
374 m_archive->extractBytes((const uint8_t*)localBytes.constData(), localBytes.size());
375 m_extractedBytes += localBytes.size();
376 }
377
378 updateProgress();
379
380 if (m_archive->hasError()) {
381 m_error = true;
382 // remove any resume file, since we probably have corrupted data somehow
383 m_resumeData.close();
384 m_resumeData.remove();
385 qWarning() << "Archive error, installation will terminate";
386 }
387
388 if (m_archive->isAtEndOfArchive()) {
389 // end the thread's event loop
390 m_done = true;
391 }
392 }
393
394 if (m_error) {
395 // ensure the archive is cleaned up, including any files,
396 // since we will likely attempt to remove it.
397 m_archive.reset();
398 qInfo() << "InstallFGData ending with error, deleting ArchiveExtractor";
399 } else {
400 // create marker file for future updates
401 {
402 SGPath setupInfoPath = m_downloadPath / ".setup-info";
403 sg_ofstream stream(setupInfoPath, std::ios::out | std::ios::binary);
404 stream << m_downloadUrl.toString().toStdString();
405 }
406
407 const auto finalDataPath = flightgear::Options::sharedInstance()->downloadedDataRoot();
408 SG_LOG(SG_IO, SG_INFO, "Renaming downloaded data to: " << finalDataPath);
409 bool renamedOk = m_downloadPath.rename(finalDataPath);
410 if (!renamedOk) {
411 m_error = true;
412 }
413
414 // remove the resume-data file from disk, now we succeeded.
415 m_resumeData.remove();
416 flightgear::addSentryBreadcrumb("InstallFGData finshed successfully", "info");
417
418 emit completed();
419 }
420 }
421
422 void onNetworkError(QNetworkReply::NetworkError code)
423 {
424 if (code == QNetworkReply::OperationCanceledError) {
425 // abort() is handled differently,
426 // eg when a resume fails
427 return;
428 }
429
430 SG_LOG(SG_IO, SG_WARN, "FGdata download failed, will re-try next mirror:" << code << " (" << m_download->errorString().toStdString() << ")");
431
432 // don't need to delete, onReplyFinished will also fire
433 m_servers.pop_front();
434 if (m_servers.empty()) {
435 m_error = true;
436 emit failed(m_download->errorString());
437 } else {
438 startRequest();
439 // will try a new request
440 }
441 }
442
443 void onMetaDataChanged()
444 {
445 const int status = m_download->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
446 if (m_resumeOverlapBytes > 0) {
447 if (status == 206) {
448 // we wil get the range request, excellent
449 } else if (status == 200) {
450 // full content, abandon resume
451 m_resumeOverlapBytes = 0;
452 m_buffer.clear();
453 m_resumeData.close();
454 m_resumeData.open(QIODevice::WriteOnly | QIODevice::Truncate);
455 m_readResumeFile = false;
456 qWarning() << "Server can't resume, reverting to full download";
457 }
458 }
459 }
460
461 void onDownloadProgress(quint64 got, quint64 total)
462 {
463 emit downloadProgress(got, total);
464 m_totalSize = total + m_resumedBytesSize;
465 }
466
467 void processBytes()
468 {
469 QByteArray bytes = m_download->readAll();
470 {
471 std::unique_lock g(m_mutex);
472 if (m_resumeOverlapBytes > 0) {
473 const auto bytesToCompare = std::min(m_resumeOverlapBytes, static_cast<qint64>(bytes.size()));
474 auto checkBytes = m_buffer.mid(m_buffer.size() - m_resumeOverlapBytes, bytesToCompare);
475 if (checkBytes == bytes.left(bytesToCompare)) {
476 // all good, remove from the bytes downloaded,
477 // since they are already in m_buffer
478 bytes.remove(0, bytesToCompare);
479 m_resumeOverlapBytes -= bytesToCompare;
480 } else {
481 g.unlock();
482 // remove the resume file, but don't adjust m_servers since we
483 // can re-use the same one
484 qWarning() << "Resume overlap bytes mismatch, will abandon resume and re-try";
485 m_resumeData.close();
486 m_resumeData.remove();
487 m_download->abort();
488 QTimer::singleShot(0, this, &InstallFGDataThread::startRequest);
489 return;
490 }
491
492 // if all available bytes were consumed,
493 // don't bother waking up the thread
494 if (bytes.isEmpty()) {
495 return;
496 }
497 }
498
499 m_buffer.append(bytes);
500 m_bufferWait.notify_one();
501 }
502 }
503
504 void onReplyFinished()
505 {
506 // we can't use m_download here because in the case of re-trying,
507 // we already replaced m_download with our new request.
508 QNetworkReply* r = qobject_cast<QNetworkReply*>(sender());
509 r->deleteLater();
510
511 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
512 if (r->error() != QNetworkReply::NoError) {
513 onNetworkError(r->error());
514 }
515 #endif
516 }
517
518 bool hasError() const
519 {
520 return m_error;
521 }
522 signals:
523 void extractionError(QString file, QString msg);
524
525 void installProgress(QString fileName, int percent);
526
527 void downloadProgress(quint64 cur, quint64 total);
528
529 void failed(QString message);
530
531 void completed();
532
533 private:
534 QNetworkAccessManager* m_networkManager = nullptr;
535 QtDNSClient* m_dns = nullptr;
536 QStringList m_servers;
537 std::mutex m_mutex;
538 std::condition_variable m_bufferWait;
539 QByteArray m_buffer;
540 quint64 m_totalSize = 0;
541 quint64 m_extractedBytes = 0;
542 quint64 m_resumedBytesSize = 0;
543
544 bool m_readResumeFile = false;
545 bool m_haveFirstMByte = false;
546
547 /// remaining bytes of overalp in m_buffer, that we need to receive
548 /// before we are adding fresh bytes
549 qint64 m_resumeOverlapBytes = 0;
550
551 QUrl m_downloadUrl;
552 QFile m_resumeData; // on-disk cache of downloaded TXZ, for resuming downloads
553
554 bool m_done = false;
555 QPointer<QNetworkReply> m_download;
556 SGPath m_downloadPath;
557 std::unique_ptr<simgear::ArchiveExtractor> m_archive;
558 bool m_error = false;
559 uint32_t m_pathPrefixLength = 0;
560 };
561
562 /////////////////////////////////////////////////////////////////////////////////////////////
563
564 QString SetupRootDialog::rootPathKey()
565 {
566 // return a settings key like fg-root-2018-3-0
567 return QString("fg-root-%1-%2").arg(FLIGHTGEAR_MAJOR_VERSION).arg(FLIGHTGEAR_MINOR_VERSION);
568 }
569
570 SetupRootDialog::SetupRootDialog(PromptState prompt, const SGPath& checked) :
571 QDialog(),
572 m_promptState(prompt),
573 m_checkedPath(checked)
574 {
575 auto exLock = flightgear::ExclusiveInstanceLock::instance();
576 if (exLock) {
577 exLock->updateReason("setup-fgdata");
578 }
579
580 m_ui.reset(new Ui::SetupRootDialog);
581 m_ui->setupUi(this);
582
583 connect(m_ui->browseButton, &QPushButton::clicked,
584 this, &SetupRootDialog::onBrowse);
585 connect(m_ui->downloadButton, &QPushButton::clicked,
586 this, &SetupRootDialog::onDownload);
587 connect(m_ui->changeDownloadLocation, &QPushButton::clicked,
588 this, &SetupRootDialog::onSelectDownloadDir);
589 connect(m_ui->defaultDownloadLocation, &QPushButton::clicked,
590 this, &SetupRootDialog::onUseDefaultDownloadDir);
591 connect(m_ui->buttonBox, &QDialogButtonBox::rejected,
592 this, &QDialog::reject);
593
594 auto options = flightgear::Options::sharedInstance();
595 if (options->isOptionSet("download-dir")) {
596 // if download dir is set on the command line, don't allow changing it here
597 m_ui->changeDownloadLocation->setEnabled(false);
598 m_ui->defaultDownloadLocation->hide();
599 }
600
601 m_ui->versionLabel->setText(tr("<h1>FlightGear %1</h1>").arg(FLIGHTGEAR_VERSION));
602 m_ui->bigIcon->setPixmap(QPixmap(":/app-icon-large"));
603 m_ui->contentsPages->setCurrentIndex(0);
604
605 updatePromptText();
606
607 if (prompt == NeedToUpdateDownloadedData) {
608 m_ui->downloadButton->setText(tr("Update"));
609 m_ui->changeDownloadLocation->hide();
610 m_ui->defaultDownloadLocation->hide();
611 }
612
613 m_networkManager = new QNetworkAccessManager(this);
614 m_networkManager->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
615 }
616
617 bool SetupRootDialog::runDialog(flightgear::SetupRootReason r)
618 {
619 // this code path is only used if have Qt enabled, but didn't use the launcher.
620 // in that case, we're coming from Options::setupRoot, which stores the path
621 // it checked in gloabls::get_fg_root() *before* it calls us here.
622 SetupRootDialog::PromptState prompt = ManualChoiceRequested;
623 switch (r) {
624 case flightgear::SetupRootReason::DefaultRootInvalid:
625 prompt = DefaultPathCheckFailed;
626 break;
627 case flightgear::SetupRootReason::ExplicitRootInvalid:
628 prompt = ExplicitPathCheckFailed;
629 break;
630 default:
631 break; // use 'manual choice'
632 };
633
634 return runDialog(prompt, globals->get_fg_root());
635 }
636
637 bool SetupRootDialog::runUpdateDialog(flightgear::SetupRootReason r)
638 {
639 SG_UNUSED(r);
640 return runDialog(SetupRootDialog::PromptState::NeedToUpdateDownloadedData, SGPath{});
641 }
642
643 bool SetupRootDialog::runDialog(PromptState prompt, const SGPath& checkedPath)
644 {
645 // avoid double Apple menu and other weirdness if both Qt and OSG
646 // try to initialise various Cocoa structures.
647 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
648
649 flightgear::addSentryBreadcrumb("running SetupRootDialog", "info");
650 SetupRootDialog dlg(prompt, checkedPath);
651 dlg.exec();
652 if (dlg.result() != QDialog::Accepted) {
653 flightgear::addSentryBreadcrumb("SetupRootDialog rejected", "info");
654 return false;
655 }
656
657 flightgear::addSentryBreadcrumb("SetupRootDialog accepted", "info");
658 return true;
659 }
660
661 flightgear::SetupRootResult SetupRootDialog::restoreUserSelectedRoot(SGPath& sgpath)
662 {
663 const auto readOnly = fgGetBool("/sim/fghome-readonly", false);
664 auto options = flightgear::Options::sharedInstance();
665 auto settings = flightgear::getQSettings();
666 QString path = settings.value(rootPathKey()).toString();
667 const bool ask = flightgear::checkKeyboardModifiersForSettingFGRoot();
668
669 QString downloadDir = settings.value("download-dir").toString();
670 if (!downloadDir.isEmpty()) {
671 options->setCustomDownloadDir(SGPath::fromUtf8(downloadDir.toStdString()));
672 }
673
674 if (ask || (path == QStringLiteral("!ask"))) {
675 if (readOnly) {
676 return flightgear::SetupRootResult::ExitDueToReadOnly;
677 }
678
679 bool ok = runDialog(ManualChoiceRequested, SGPath{});
680 if (!ok) {
681 return flightgear::SetupRootResult::UserExit;
682 }
683
684 sgpath = globals->get_fg_root();
685 return flightgear::SetupRootResult::UserSelected;
686 }
687
688 if (flightgear::ExclusiveInstanceLock::isLocked()) {
689 bool ok = flightgear::ExclusiveInstanceLock::showWaitDialog();
690 if (!ok) {
691 return flightgear::SetupRootResult::UserExit;
692 }
693 }
694
695 if (path.isEmpty()) {
696 if (downloadedDataExistsButStale()) {
697 if (readOnly) {
698 return flightgear::SetupRootResult::ExitDueToReadOnly;
699 }
700
701 bool ok = runDialog(NeedToUpdateDownloadedData, options->downloadedDataRoot());
702 if (!ok) {
703 return flightgear::SetupRootResult::UserExit;
704 }
705
706 // assume update worked, fall through
707 }
708
709 const auto pkgData = options->platformDefaultRoot();
710 if (flightgear::Options::isFGData(pkgData)) {
711 const auto pkgDataQt = QString::fromStdString(pkgData.utf8Str());
712 if (validateVersion(pkgDataQt)) {
713 return flightgear::SetupRootResult::UseDefault;
714 }
715
716 qWarning() << pkgDataQt << "contains FGData, but version doesn't match required:" << FLIGHTGEAR_VERSION;
717 }
718 }
719
720 // to give better feedback, we need to record which path we tried,
721 // that failed our check
722 SGPath checkedPath;
723 if (validatePath(path)) {
724 if (validateVersion(path)) {
725 sgpath = SGPath::fromUtf8(path.toStdString());
726 return flightgear::SetupRootResult::RestoredOk;
727 }
728
729 // path seemed good, but version failed, so this is the one to report
730 checkedPath = SGPath::fromUtf8(path.toStdString());
731 }
732
733 if (downloadedDataAcceptable()) {
734 return flightgear::SetupRootResult::UseDefault;
735 } else if (checkedPath.isNull()) {
736 // if the download data exists, use that as our 'location we checked'
737 SGPath r = flightgear::Options::sharedInstance()->downloadedDataRoot();
738 if (flightgear::Options::isFGData(r)) {
739 checkedPath = r;
740 }
741 }
742
743 // runDialog assumes writeable mode, so just bail out here and inform the user
744 if (readOnly) {
745 return flightgear::SetupRootResult::ExitDueToReadOnly;
746 }
747
748 // okay, we don't have an acceptable FG_DATA anywhere we can find, we
749 // have to ask the user what they want to do.
750 bool ok = false;
751 if (checkedPath.isNull()) {
752 ok = runDialog(DefaultPathCheckFailed, SGPath{});
753 } else {
754 ok = runDialog(VersionCheckFailed, checkedPath);
755 }
756
757 if (!ok) {
758 return flightgear::SetupRootResult::UserExit;
759 }
760
761 // run dialog sets fg_root, so this
762 // behaviour is safe and correct.
763 sgpath = globals->get_fg_root();
764 return flightgear::SetupRootResult::UserSelected;
765 }
766
767 void SetupRootDialog::askRootOnNextLaunch()
768 {
769 auto settings = flightgear::getQSettings();
770 // set the option to the magic marker value
771 settings.setValue(rootPathKey(), "!ask");
772 }
773
774 bool SetupRootDialog::validatePath(QString path)
775 {
776 return flightgear::Options::isFGData(SGPath::fromUtf8(path.toStdString()));
777 }
778
779 /**
780 * @brief Ensure the base pakcage at 'path' is the same or more recent than our
781 * specified base package minimum version.
782 *
783 * @param path : candidate base pakcage folder
784
785 */
786 bool SetupRootDialog::validateVersion(QString path)
787 {
788 const std::string minBasePackageVersion{FLIGHTGEAR_VERSION};
789 std::string ver = fgBasePackageVersion(SGPath::fromUtf8(path.toStdString()));
790
791 // ensure major & minor fields match exactly
792 if (simgear::strutils::compare_versions(minBasePackageVersion, ver, 2) != 0) {
793 return false;
794 }
795
796 // patch level must be higher
797 return simgear::strutils::compare_versions(minBasePackageVersion, ver) <= 0;
798 }
799
800 bool SetupRootDialog::downloadedDataAcceptable()
801 {
802 SGPath r = flightgear::Options::sharedInstance()->downloadedDataRoot();
803 QString dlRoot = QString::fromStdString(r.utf8Str());
804 return validatePath(dlRoot) && validateVersion(dlRoot);
805 }
806
807 bool SetupRootDialog::downloadedDataExistsButStale()
808 {
809 SGPath r = flightgear::Options::sharedInstance()->downloadedDataRoot();
810 QString dlRoot = QString::fromStdString(r.utf8Str());
811 if (!validatePath(dlRoot)) {
812 return false;
813 }
814
815 const std::string minBasePackageVersion{FLIGHTGEAR_VERSION};
816 std::string ver = fgBasePackageVersion(r);
817
818 // major or minor mismatch, we can't use it
819 // this 'should' be impossible given how we comput downloadedDataRoot
820 if (simgear::strutils::compare_versions(minBasePackageVersion, ver, 2) != 0) {
821 return false;
822 }
823
824 // check for suffix mismatch, then we will always update
825 const auto info = fgBasePackageInfo(r);
826 if (!info) {
827 SG_LOG(SG_IO, SG_INFO, "downloaded data missing the base_package.json file, won't attempt to update it");
828 return false;
829 }
830
831 // BUILD_SUFFIX includes a leading hypen, but the JSON info doesn't
832 std::string buildSuffix(BUILD_SUFFIX);
833 if (buildSuffix.find("-") == 0) {
834 buildSuffix.erase(0, 1); // effectively a 'pop front'
835 }
836
837 if (info && (info.value().suffix != buildSuffix)) {
838 SG_LOG(SG_IO, SG_INFO, "Base package suffix mismatch, build suffix is '" << buildSuffix << "'");
839 return true;
840 }
841
842 // update needed if the on-disk base package version is *lower* than our patch version
843 return simgear::strutils::compare_versions(ver, minBasePackageVersion) < 0;
844 }
845
846 SetupRootDialog::~SetupRootDialog() = default;
847
848 void SetupRootDialog::onBrowse()
849 {
850 m_browsedPath = QFileDialog::getExistingDirectory(this,
851 tr("Choose FlightGear data folder"));
852 if (m_browsedPath.isEmpty()) {
853 return;
854 }
855
856 if (!validatePath(m_browsedPath)) {
857 m_promptState = ChoseInvalidLocation;
858 updatePromptText();
859 return;
860 }
861
862 if (!validateVersion(m_browsedPath)) {
863 m_promptState = ChoseInvalidVersion;
864 updatePromptText();
865 return;
866 }
867
868 globals->set_fg_root(m_browsedPath.toStdString());
869
870 auto settings = flightgear::getQSettings();
871 settings.setValue(rootPathKey(), m_browsedPath);
872
873 accept(); // we're done
874 }
875
876 bool SetupRootDialog::locationIsWritable(QString path)
877 {
878 // we don't use QFileInfo::isWriteable here because of complexity around
879 // NTFS ACL checks (needs Qt 6.6 for QNtfsPermissionCheckGuard)
880 QFile f(path + "/_check_write");
881 if (!f.open(QIODevice::NewOnly | QIODevice::WriteOnly)) {
882 return false;
883 }
884 f.remove(); // closes
885 return true;
886 }
887
888 void SetupRootDialog::onSelectDownloadDir()
889 {
890 auto settings = flightgear::getQSettings();
891
892 auto dd = flightgear::Options::sharedInstance()->actualDownloadDir();
893 const auto dlp = QString::fromStdString(dd.utf8Str());
894
895 QString downloadDir = QFileDialog::getExistingDirectory(this,
896 tr("Choose location to store downloaded files."), dlp);
897 if (downloadDir.isEmpty()) {
898 return;
899 }
900
901 if (!locationIsWritable(downloadDir)) {
902 m_browsedPath = downloadDir;
903 m_promptState = ChoseInvalidDownloadLocation;
904 updatePromptText();
905 return;
906 }
907
908 m_promptState = ManualChoiceRequested;
909 settings.setValue("download-dir", downloadDir);
910 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
911 updatePromptText();
912 }
913
914 void SetupRootDialog::onUseDefaultDownloadDir()
915 {
916 auto settings = flightgear::getQSettings();
917 settings.remove("download-dir");
918 flightgear::Options::sharedInstance()->clearOption("download-dir");
919 updatePromptText();
920 }
921
922 void SetupRootDialog::onDownload()
923 {
924 // clear !ask value or custom root
925 auto settings = flightgear::getQSettings();
926 settings.remove(rootPathKey());
927
928 if (m_promptState == NeedToUpdateDownloadedData) {
929 onUpdate();
930 return;
931 }
932
933 m_promptState = DownloadingExtractingArchive;
934 m_archiveName = tr("base data package");
935 updatePromptText();
936
937 m_ui->contentsPages->setCurrentIndex(1);
938
939 auto installThread = new InstallFGDataThread(this, m_networkManager);
940 connect(installThread, &InstallFGDataThread::downloadProgress, this, [this](quint64 current, quint64 total) {
941 m_ui->downloadProgress->setValue(current);
942 m_ui->downloadProgress->setMaximum(total);
943
944 const quint64 currentMb = current / (1024 * 1024);
945 const quint64 totalMb = total / (1024 * 1024);
946
947 const int percent = calculateProgressPercentage(current, total);
948
949 m_ui->downloadText->setText(tr("Downloaded %1 of %2 MB (%3%)").arg(currentMb).arg(totalMb).arg(percent));
950 });
951
952 connect(installThread, &InstallFGDataThread::installProgress, this, [this](QString s, int percent) {
953 m_ui->installText->setText(tr("Installation %1% complete.\nExtracting %2").arg(percent).arg(s));
954 m_ui->installProgress->setValue(percent);
955 });
956
957 connect(installThread, &InstallFGDataThread::failed, this, [this](QString s) {
958 m_ui->downloadText->setText(tr("Download failed: %1").arg(s));
959 m_lastErrorMessage = s;
960 m_promptState = DownloadFailed;
961 });
962
963 connect(installThread, &InstallFGDataThread::completed, this, [this, installThread]() {
964 if (installThread->hasError()) {
965 // go back to the first page
966 m_promptState = DownloadFailed;
967 updatePromptText();
968 m_ui->contentsPages->setCurrentIndex(0);
969 } else {
970 startSharedDataDownload();
971 }
972 });
973
974 // we don't start the thread here, that happens automatically
975 }
976
977 void SetupRootDialog::startSharedDataDownload()
978 {
979 auto dlThread = new DownloadTerrasyncSharedData(this, m_networkManager);
980 connect(dlThread, &DownloadTerrasyncSharedData::downloadProgress, this, [this](quint64 current, quint64 total) {
981 m_ui->downloadProgress->setValue(current);
982 m_ui->downloadProgress->setMaximum(total);
983
984 const quint64 currentMb = current / (1024 * 1024);
985 const quint64 totalMb = total / (1024 * 1024);
986
987 const int percent = calculateProgressPercentage(current, total);
988
989 m_ui->downloadText->setText(tr("Downloading %1 of %2 MB (%3%)").arg(currentMb).arg(totalMb).arg(percent));
990 });
991
992 connect(dlThread, &DownloadTerrasyncSharedData::beginArchive, this, [this](QString s) {
993 m_archiveName = s;
994 updatePromptText();
995 });
996
997 connect(dlThread, &DownloadTerrasyncSharedData::installProgress, this, [this](QString s, int percent) {
998 m_ui->installText->setText(tr("Installation %1% complete.\nExtracting %2").arg(percent).arg(s));
999 m_ui->installProgress->setValue(percent);
1000 });
1001
1002 connect(dlThread, &DownloadTerrasyncSharedData::failed, this, [this](QString s) {
1003 accept();
1004 });
1005
1006 connect(dlThread, &DownloadTerrasyncSharedData::finished, this, [this]() {
1007 accept();
1008 });
1009
1010 dlThread->start();
1011 }
1012
1013 void SetupRootDialog::onUpdate()
1014 {
1015 m_promptState = UpdatingViaTerrasync;
1016 updatePromptText();
1017
1018 m_ui->contentsPages->setCurrentIndex(1);
1019 m_ui->installProgress->setMaximum(0); // show a 'unknown amount' progress
1020
1021 auto updateThread = new UpdateFGData(this);
1022 connect(updateThread, &UpdateFGData::downloadProgress, this, [this](quint64 cur, quint64 total) {
1023 m_ui->downloadProgress->setValue(cur);
1024 m_ui->downloadProgress->setMaximum(total);
1025
1026 const int curMb = cur / (1024 * 1024);
1027 const int totalMb = total / (1024 * 1024);
1028 const int percent = total > 0 ? ((cur * 100) / total) : 0;
1029 m_ui->downloadText->setText(tr("Downloaded %1 of %2 MB (%3%)").arg(curMb).arg(totalMb).arg(percent));
1030 });
1031
1032 connect(updateThread, &UpdateFGData::installProgress, this, [this](QString s, int percent) {
1033 m_ui->installText->setText(s);
1034 });
1035
1036 connect(updateThread, &UpdateFGData::failed, this, [this](QString s) {
1037 m_ui->downloadText->setText(tr("Update failed: %1").arg(s));
1038 });
1039
1040 connect(updateThread, &UpdateFGData::finished, this, [this]() {
1041 accept();
1042 });
1043 }
1044
1045 // void SetupRootDialog::onUseDefaults()
1046 // {
1047 // SGPath r = flightgear::Options::sharedInstance()->platformDefaultRoot();
1048 // m_browsedPath = QString::fromStdString(r.utf8Str());
1049 // globals->set_fg_root(r);
1050 // auto settings = flightgear::getQSettings();
1051 // settings.remove(rootPathKey()); // remove any setting
1052 // accept();
1053 // }
1054
1055 void SetupRootDialog::updatePromptText()
1056 {
1057 QString t;
1058 QString curRoot = QString::fromStdString(m_checkedPath.utf8Str());
1059 switch (m_promptState) {
1060 case DefaultPathCheckFailed:
1061 t = tr("FlightGear needs to download additional data files. This can be done automatically by pressing 'Download', or you can download them yourself and select their location.");
1062 break;
1063
1064 case ExplicitPathCheckFailed:
1065 t = tr("The requested location '%1' does not appear to be a valid set of data files for FlightGear").arg(curRoot);
1066 break;
1067
1068 case VersionCheckFailed:
1069 {
1070 QString curVer = QString::fromStdString(fgBasePackageVersion(m_checkedPath));
1071 t = tr("Detected incompatible version of the data files: version %1 found, but this is FlightGear %2. " \
1072 "(At location: '%3') " \
1073 "Please install or select a matching set of data files.").arg(curVer).arg(QString::fromLatin1(FLIGHTGEAR_VERSION)).arg(curRoot);
1074 break;
1075 }
1076
1077 case ManualChoiceRequested:
1078 t = tr("Please select or download a copy of the FlightGear data files.");
1079 break;
1080
1081 case ChoseInvalidLocation:
1082 t = tr("The chosen location (%1) does not appear to contain FlightGear data files. Please try another location.").arg(m_browsedPath);
1083 break;
1084
1085 case ChoseInvalidVersion:
1086 {
1087 QString curVer = QString::fromStdString(fgBasePackageVersion(m_browsedPath.toStdString()));
•1088 t = tr("The chosen location (%1) contains files for version %2, but this is FlightGear %3. " \
1089 "Please update or try another location").arg(m_browsedPath).arg(curVer).arg(QString::fromLatin1(FLIGHTGEAR_VERSION));
1090 break;
1091 }
1092
1093 case ChoseInvalidArchive:
1094 t = tr("The chosen file (%1) is not a valid compressed archive.").arg(m_browsedPath);
1095 break;
1096
1097 case ChoseInvalidDownloadLocation:
1098 t = tr("The chosen download location (%1) is not writable. Please select another location.").arg(m_browsedPath);
1099 break;
1100
1101 case DownloadingExtractingArchive:
1102 t = tr("Please wait while the data files are downloaded, extracted and verified.\nCurrent archive: %1").arg(m_archiveName);
1103 break;
1104
1105 case UpdatingViaTerrasync:
1106 t = tr("Please wait while the data files are updated and verified.");
1107 break;
1108
1109 case NeedToUpdateDownloadedData:
1110 t = tr("The data files (found at '%2') need to be updated to version %1. "
1111 "Please press 'Update', or if you prefer, manually download the correct data files and then select them.")
1112 .arg(QString::fromLatin1(FLIGHTGEAR_VERSION)).arg(curRoot);
1113 break;
1114
1115
1116 case DownloadFailed:
1117 t = tr("Automatic download of the data files has failed. Please download the files manually using the instructions at %1 (Error details: %2)")
1118 .arg("https://www.flightgear.org/download/data/")
1119 .arg(m_lastErrorMessage);
1120 break;
1121 }
1122
1123 m_ui->promptText->setText(t);
1124
1125 auto dd = flightgear::Options::sharedInstance()->actualDownloadDir();
1126 const auto dlp = QString::fromStdString(dd.utf8Str());
1127 m_ui->downloadLocationLabel->setText(tr("Data files will be downloaded to: %1").arg(dlp));
1128
1129 m_ui->defaultDownloadLocation->setEnabled(flightgear::Options::sharedInstance()->isOptionSet("download-dir"));
1130 }
1131
1132 #include "SetupRootDialog.moc"