firstrundialog.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. *openPilotLog - A FOSS Pilot Logbook Application
  3. *Copyright (C) 2020-2023 Felix Turowsky
  4. *
  5. *This program is free software: you can redistribute it and/or modify
  6. *it under the terms of the GNU General Public License as published by
  7. *the Free Software Foundation, either version 3 of the License, or
  8. *(at your option) any later version.
  9. *
  10. *This program is distributed in the hope that it will be useful,
  11. *but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. *GNU General Public License for more details.
  14. *
  15. *You should have received a copy of the GNU General Public License
  16. *along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. #include "firstrundialog.h"
  19. #include "ui_firstrundialog.h"
  20. #include "src/opl.h"
  21. #include "src/database/database.h"
  22. #include "src/database/dbsummary.h"
  23. #include "src/gui/widgets/backupwidget.h"
  24. #include "src/database/row.h"
  25. #include "src/classes/downloadhelper.h"
  26. #include "src/classes/settings.h"
  27. #include "src/functions/datetime.h"
  28. #include "src/classes/style.h"
  29. #include "src/classes/md5sum.h"
  30. #include <QErrorMessage>
  31. #include <QFileDialog>
  32. #include <QKeyEvent>
  33. FirstRunDialog::FirstRunDialog(QWidget *parent) :
  34. QDialog(parent),
  35. ui(new Ui::FirstRunDialog)
  36. {
  37. ui->setupUi(this);
  38. ui->stackedWidget->setCurrentIndex(0);
  39. ui->lastnameLineEdit->setFocus();
  40. ui->previousPushButton->setEnabled(false);
  41. ui->logoLabel->setPixmap(QPixmap(OPL::Assets::LOGO));
  42. // Approach Combo Box and Function Combo Box
  43. OPL::GLOBALS->loadApproachTypes(ui->approachComboBox);
  44. OPL::GLOBALS->loadPilotFunctios(ui->functionComboBox);
  45. OPL::GLOBALS->fillViewNamesComboBox(ui->logbookViewComboBox);
  46. // Style combo box
  47. const QSignalBlocker style_blocker(ui->styleComboBox);
  48. OPL::Style::loadStylesComboBox(ui->styleComboBox);
  49. ui->styleComboBox->setCurrentText(OPL::Style::defaultStyle);
  50. // Prepare Date Edits
  51. const auto date_edits = this->findChildren<QDateEdit *>();
  52. for (const auto &date_edit : date_edits) {
  53. date_edit->setDisplayFormat(OPL::DateTime::getFormatString(OPL::DateFormat::ISODate));
  54. date_edit->setDate(QDate::currentDate());
  55. }
  56. // Debug - use ctrl + t to enable branchLineEdit to select from which git branch the templates are pulled
  57. ui->branchLineEdit->setVisible(false);
  58. }
  59. FirstRunDialog::~FirstRunDialog()
  60. {
  61. delete ui;
  62. }
  63. void FirstRunDialog::on_previousPushButton_clicked()
  64. {
  65. const int current_index = ui->stackedWidget->currentIndex();
  66. switch (current_index) {
  67. case 0:
  68. return;
  69. case 1:
  70. ui->previousPushButton->setEnabled(false);
  71. break;
  72. case 2:
  73. ui->nextPushButton->setText(tr("Next"));
  74. break;
  75. }
  76. ui->stackedWidget->setCurrentIndex(current_index - 1);
  77. }
  78. void FirstRunDialog::on_nextPushButton_clicked()
  79. {
  80. const int current_index = ui->stackedWidget->currentIndex();
  81. switch (current_index) {
  82. case 0:
  83. if(ui->firstnameLineEdit->text().isEmpty()
  84. || ui->lastnameLineEdit->text().isEmpty())
  85. {
  86. QMessageBox(QMessageBox::Information, tr("No name entered"),
  87. tr("Please enter first and last name")
  88. ).exec();
  89. return;
  90. }
  91. ui->previousPushButton->setEnabled(true);
  92. break;
  93. case 3:
  94. ui->nextPushButton->setText(tr("Done"));
  95. break;
  96. case 4:
  97. ui->nextPushButton->setDisabled(true);
  98. if(!finishSetup())
  99. QDialog::reject();
  100. else
  101. QDialog::accept();
  102. return;
  103. }
  104. ui->stackedWidget->setCurrentIndex(current_index + 1);
  105. }
  106. bool FirstRunDialog::finishSetup()
  107. {
  108. writeSettings();
  109. QFileInfo database_file(OPL::Paths::databaseFileInfo());
  110. if (database_file.exists() && database_file.size() != 0) {
  111. QMessageBox message_box(QMessageBox::Question, tr("Existing Database found"),
  112. tr("An existing database file has been detected on your system.<br>"
  113. "Would you like to create a backup of the existing database?<br><br>"
  114. "Note: if you select no, the existing database will be overwritten. This "
  115. "action is irreversible."),
  116. QMessageBox::Yes | QMessageBox::No, this);
  117. message_box.setDefaultButton(QMessageBox::Yes);
  118. if(message_box.exec() == QMessageBox::Yes) {
  119. // Create Backup
  120. const QString backup_name = BackupWidget::absoluteBackupPath();
  121. QFile old_db_file(database_file.absoluteFilePath());
  122. if (!old_db_file.copy(backup_name)) {
  123. WARN(tr("Unable to backup old database:<br>%1").arg(old_db_file.errorString()));
  124. return false;
  125. } else {
  126. INFO(tr("Backup successfully created."));
  127. }
  128. }
  129. //delete existing DB file
  130. QFile db_file(database_file.absoluteFilePath());
  131. if (!db_file.remove()) {
  132. WARN(tr("Unable to delete existing database file."));
  133. return false;
  134. }
  135. } // if database file exists
  136. if (!DB->connect()) {
  137. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed"),
  138. tr("Errors have ocurred creating the database."
  139. "Without a working database The application will not be usable.<br>"
  140. "The following error has ocurred:<br>"
  141. "Database: Unable to connect"));
  142. message_box.exec();
  143. return false;
  144. }
  145. if (!setupDatabase()) {
  146. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed"),
  147. tr("Errors have ocurred creating the database."
  148. "Without a working database The application will not be usable.<br>"
  149. "The following error has ocurred:<br>%1"
  150. ).arg(DB->lastError.text()));
  151. message_box.exec();
  152. return false;
  153. }
  154. if (!createUserEntry()) {
  155. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed"),
  156. tr("Unable to execute database query<br>"
  157. "The following error has occured:<br>%1"
  158. ).arg(DB->lastError.text()));
  159. message_box.exec();
  160. return false;
  161. }
  162. if (!writeCurrencies()) {
  163. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed"),
  164. tr("Unable to execute database query<br>"
  165. "The following error has occured:<br>%1"
  166. ).arg(DB->lastError.text()));
  167. message_box.exec();
  168. return false;
  169. }
  170. DB->disconnect(); // Connection will be re-established by MainWindow
  171. return true;
  172. }
  173. bool FirstRunDialog::downloadTemplates(QString branch_name)
  174. {
  175. // Create url string
  176. auto template_url_string = QStringLiteral("https://raw.githubusercontent.com/fiffty-50/openpilotlog/");
  177. template_url_string.append(branch_name);
  178. template_url_string.append(QLatin1String("/assets/database/templates/"));
  179. QDir template_dir(OPL::Paths::directory(OPL::Paths::Templates));
  180. QStringList template_table_names;
  181. for (const auto table : DB->getTemplateTables())
  182. template_table_names.append(OPL::GLOBALS->getDbTableName(table));
  183. // Download json files
  184. for (const auto& table_name : template_table_names) {
  185. QEventLoop loop;
  186. DownloadHelper* dl = new DownloadHelper;
  187. QObject::connect(dl, &DownloadHelper::done, &loop, &QEventLoop::quit );
  188. dl->setTarget(QUrl(template_url_string + table_name + QLatin1String(".json")));
  189. dl->setFileName(template_dir.absoluteFilePath(table_name + QLatin1String(".json")));
  190. DEB << "Downloading: " << template_url_string + table_name + QLatin1String(".json");
  191. dl->download();
  192. dl->deleteLater();
  193. loop.exec(); // event loop waits for download done signal before allowing loop to continue
  194. QFileInfo downloaded_file(template_dir.filePath(table_name + QLatin1String(".json")));
  195. if (downloaded_file.size() == 0) {
  196. LOG << "Unable to download template files (SSL / Network Error)";
  197. return false; // ssl/network error
  198. }
  199. }
  200. // Download checksum files
  201. for (const auto& table_name : template_table_names) {
  202. QEventLoop loop;
  203. DownloadHelper* dl = new DownloadHelper;
  204. QObject::connect(dl, &DownloadHelper::done, &loop, &QEventLoop::quit );
  205. dl->setTarget(QUrl(template_url_string + table_name + QLatin1String(".md5")));
  206. dl->setFileName(template_dir.absoluteFilePath(table_name + QLatin1String(".md5")));
  207. LOG << "Downloading: " << template_url_string + table_name + QLatin1String(".md5");
  208. dl->download();
  209. dl->deleteLater();
  210. loop.exec(); // event loop waits for download done signal before allowing loop to continue
  211. QFileInfo downloaded_file(template_dir.filePath(table_name + QLatin1String(".md5")));
  212. if (downloaded_file.size() == 0) {
  213. LOG << "Unable to download checksum files (SSL / Network Error)";
  214. return false; // ssl/network error
  215. }
  216. }
  217. // check downloadad files
  218. return verifyTemplates();
  219. }
  220. bool FirstRunDialog::verifyTemplates()
  221. {QStringList template_table_names;
  222. for (const auto table : DB->getTemplateTables())
  223. template_table_names.append(OPL::GLOBALS->getDbTableName(table));
  224. for (const auto &table_name : template_table_names) {
  225. const QString path = OPL::Paths::filePath(OPL::Paths::Templates, table_name);
  226. QFileInfo check_file(path + QLatin1String(".json"));
  227. Md5Sum hash(check_file);
  228. QFileInfo md5_file(path + QLatin1String(".md5"));
  229. if (!hash.compare(md5_file))
  230. return false;
  231. }
  232. return true;
  233. }
  234. void FirstRunDialog::writeSettings()
  235. {
  236. Settings::resetToDefaults();
  237. Settings::write(Settings::FlightLogging::Function, ui->functionComboBox->currentIndex());
  238. Settings::write(Settings::FlightLogging::Approach, ui->approachComboBox->currentIndex());
  239. Settings::write(Settings::FlightLogging::NightLoggingEnabled, ui->nightComboBox->currentIndex());
  240. switch (ui->nightRulesComboBox->currentIndex()) {
  241. case 0:
  242. Settings::write(Settings::FlightLogging::NightAngle, -6);
  243. break;
  244. case 1:
  245. Settings::write(Settings::FlightLogging::NightAngle, 0);
  246. break;
  247. }
  248. Settings::write(Settings::FlightLogging::LogIFR, ui->rulesComboBox->currentIndex());
  249. Settings::write(Settings::FlightLogging::FlightNumberPrefix, ui->prefixLineEdit->text());
  250. Settings::write(Settings::UserData::DisplaySelfAs, ui->aliasComboBox->currentIndex());
  251. Settings::write(Settings::Main::LogbookView, ui->logbookViewComboBox->currentIndex());
  252. Settings::write(Settings::Main::Style, ui->styleComboBox->currentText());
  253. Settings::sync();
  254. }
  255. bool FirstRunDialog::setupDatabase()
  256. {
  257. QMessageBox confirm(QMessageBox::Question, tr("Create Database"),
  258. tr("We are now going to create the database.<br>"
  259. "Would you like to download the latest database information?"
  260. "<br>(Recommended, Internet connection required)"),
  261. QMessageBox::Yes | QMessageBox::No, this);
  262. confirm.setDefaultButton(QMessageBox::No);
  263. if (confirm.exec() == QMessageBox::Yes) {
  264. useRessourceData = false;
  265. if (!downloadTemplates(ui->branchLineEdit->text())) {
  266. QMessageBox message_box(this);
  267. message_box.setText(tr("Downloading or verifying latest data has failed.<br><br>Using local data instead."));
  268. message_box.exec();
  269. useRessourceData = true; // fall back
  270. }
  271. } else {
  272. useRessourceData = true;
  273. }
  274. if(!DB->createSchema()) {
  275. WARN(tr("Database creation has been unsuccessful. The following error has ocurred:<br><br>%1<br><br>%2")
  276. .arg(FUNC_IDENT, DB->lastError.text()));
  277. return false;
  278. }
  279. if(!DB->importTemplateData(useRessourceData)) {
  280. WARN(tr("Database creation has been unsuccessful. Unable to fill template data.<br><br>%1<br><br>%2")
  281. .arg(FUNC_IDENT, DB->lastError.text()));
  282. return false;
  283. }
  284. return true;
  285. }
  286. bool FirstRunDialog::createUserEntry()
  287. {
  288. QHash<QString, QVariant> data;
  289. data.insert(OPL::Db::PILOTS_LASTNAME, ui->lastnameLineEdit->text());
  290. data.insert(OPL::Db::PILOTS_FIRSTNAME, ui->firstnameLineEdit->text());
  291. data.insert(OPL::Db::PILOTS_ALIAS, QStringLiteral("self"));
  292. data.insert(OPL::Db::PILOTS_EMPLOYEEID, ui->employeeidLineEdit->text());
  293. data.insert(OPL::Db::PILOTS_PHONE, ui->phoneLineEdit->text());
  294. data.insert(OPL::Db::PILOTS_EMAIL, ui->emailLineEdit->text());
  295. auto pilot = OPL::PilotEntry(1, data);
  296. return DB->commit(pilot);
  297. }
  298. bool FirstRunDialog::writeCurrencies()
  299. {
  300. const QMap<OPL::CurrencyName, QDateEdit*> currencies_list = {
  301. {OPL::CurrencyName::Licence, ui->currLicDateEdit},
  302. {OPL::CurrencyName::TypeRating, ui->currTrDateEdit},
  303. {OPL::CurrencyName::LineCheck, ui->currLckDateEdit},
  304. {OPL::CurrencyName::Medical, ui->currMedDateEdit},
  305. {OPL::CurrencyName::Custom1, ui->currCustom1DateEdit},
  306. {OPL::CurrencyName::Custom2, ui->currCustom2DateEdit},
  307. };
  308. const QMap<OPL::CurrencyName, Settings::UserData> settings_list = {
  309. {OPL::CurrencyName::Licence, Settings::UserData::ShowLicCurrency },
  310. {OPL::CurrencyName::TypeRating, Settings::UserData::ShowTrCurrency },
  311. {OPL::CurrencyName::LineCheck, Settings::UserData::ShowLckCurrency },
  312. {OPL::CurrencyName::Medical, Settings::UserData::ShowMedCurrency },
  313. {OPL::CurrencyName::Custom1, Settings::UserData::ShowCustom1Currency },
  314. {OPL::CurrencyName::Custom2, Settings::UserData::ShowCustom2Currency },
  315. };
  316. QDate today = QDate::currentDate();
  317. for (const auto &date_edit : currencies_list) {
  318. const auto enum_value = currencies_list.key(date_edit);
  319. // only write dates that have been edited
  320. if (date_edit->date() != today) {
  321. OPL::RowData_T row_data = {{OPL::Db::CURRENCIES_EXPIRYDATE, date_edit->date().toString(Qt::ISODate)}};
  322. if (enum_value == OPL::CurrencyName::Custom1)
  323. row_data.insert(OPL::Db::CURRENCIES_CURRENCYNAME, ui->currCustom1LineEdit->text());
  324. else if(enum_value == OPL::CurrencyName::Custom2)
  325. row_data.insert(OPL::Db::CURRENCIES_CURRENCYNAME, ui->currCustom2LineEdit->text());
  326. Settings::write(settings_list.value(enum_value), true); // Show selected currency on Home Screen
  327. OPL::CurrencyEntry entry(static_cast<int>(enum_value), row_data);
  328. if (!DB->commit(entry))
  329. return false;
  330. }
  331. }
  332. return true;
  333. }
  334. void FirstRunDialog::reject()
  335. {
  336. QMessageBox confirm(QMessageBox::Critical,
  337. tr("Setup incomplete"),
  338. tr("Without completing the initial setup "
  339. "you cannot use the application.<br><br>"
  340. "Quit anyway?"),
  341. QMessageBox::Yes | QMessageBox::No, this);
  342. confirm.setDefaultButton(QMessageBox::No);
  343. if (confirm.exec() == QMessageBox::Yes) {
  344. QDialog::reject();
  345. }
  346. }
  347. void FirstRunDialog::keyPressEvent(QKeyEvent *keyEvent)
  348. {
  349. if(keyEvent->type() == QKeyEvent::KeyPress) {
  350. if(keyEvent->matches(QKeySequence::AddTab)) {
  351. ui->branchLineEdit->setVisible(true);
  352. ui->branchLineEdit->setEnabled(true);
  353. }
  354. }
  355. }
  356. void FirstRunDialog::on_styleComboBox_currentTextChanged(const QString &new_style_setting)
  357. {
  358. if (new_style_setting == QLatin1String("Dark-Palette")) {
  359. OPL::Style::setStyle(OPL::Style::darkPalette());
  360. return;
  361. }
  362. for (const auto &style_name : OPL::Style::styles) {
  363. if (new_style_setting == style_name) {
  364. OPL::Style::setStyle(style_name);
  365. return;
  366. }
  367. }
  368. for (const auto &style_sheet : OPL::Style::styleSheets) {
  369. if (new_style_setting == style_sheet.styleSheetName) {
  370. OPL::Style::setStyle(style_sheet);
  371. return;
  372. }
  373. }
  374. }
  375. void FirstRunDialog::on_currCustom1LineEdit_editingFinished()
  376. {
  377. Settings::write(Settings::UserData::Custom1CurrencyName, ui->currCustom1LineEdit->text());
  378. }
  379. void FirstRunDialog::on_currCustom2LineEdit_editingFinished()
  380. {
  381. Settings::write(Settings::UserData::Custom2CurrencyName, ui->currCustom2LineEdit->text());
  382. }
  383. void FirstRunDialog::on_importPushButton_clicked()
  384. {
  385. QString filename = QFileDialog::getOpenFileName(
  386. this,
  387. tr("Choose backup file"),
  388. QDir::homePath(),
  389. "*.db"
  390. );
  391. if(filename.isEmpty()) { // QFileDialog has been cancelled
  392. WARN(tr("No Database has been selected."));
  393. return;
  394. }
  395. QMessageBox confirm(this);
  396. confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  397. confirm.setDefaultButton(QMessageBox::No);
  398. confirm.setIcon(QMessageBox::Question);
  399. confirm.setWindowTitle(tr("Import Database"));
  400. confirm.setText(tr("The following database will be imported:<br><br><b><tt>"
  401. "%1<br></b></tt>"
  402. "<br>Is this correct?"
  403. ).arg(OPL::DbSummary::summaryString(filename)));
  404. if (confirm.exec() == QMessageBox::Yes) {
  405. if(!DB->restoreBackup(filename)) {
  406. WARN(tr("Unable to import database file:").arg(filename));
  407. return;
  408. }
  409. INFO(tr("Database successfully imported."));
  410. QDialog::accept(); // quit the dialog as if a database was successfully created
  411. } else {
  412. return;
  413. }
  414. }