firstrundialog.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 "src/database/previousexperienceentry.h"
  20. #include "ui_firstrundialog.h"
  21. #include "src/opl.h"
  22. #include "src/database/database.h"
  23. #include "src/database/dbsummary.h"
  24. #include "src/gui/widgets/backupwidget.h"
  25. #include "src/database/row.h"
  26. #include "src/classes/downloadhelper.h"
  27. #include "src/classes/settings.h"
  28. #include "src/functions/datetime.h"
  29. #include "src/classes/style.h"
  30. #include "src/classes/md5sum.h"
  31. #include <QErrorMessage>
  32. #include <QFileDialog>
  33. #include <QKeyEvent>
  34. FirstRunDialog::FirstRunDialog(QWidget *parent) :
  35. QDialog(parent),
  36. ui(new Ui::FirstRunDialog)
  37. {
  38. ui->setupUi(this);
  39. ui->stackedWidget->setCurrentIndex(0);
  40. ui->lastnameLineEdit->setFocus();
  41. ui->previousPushButton->setEnabled(false);
  42. ui->logoLabel->setPixmap(QPixmap(OPL::Assets::LOGO));
  43. // Approach Combo Box and Function Combo Box
  44. OPL::GLOBALS->loadApproachTypes(ui->approachComboBox);
  45. OPL::GLOBALS->loadPilotFunctios(ui->functionComboBox);
  46. OPL::GLOBALS->fillViewNamesComboBox(ui->logbookViewComboBox);
  47. // Style combo box
  48. const QSignalBlocker style_blocker(ui->styleComboBox);
  49. OPL::Style::loadStylesComboBox(ui->styleComboBox);
  50. ui->styleComboBox->setCurrentText(OPL::Style::defaultStyle);
  51. // Prepare Date Edits
  52. const auto date_edits = this->findChildren<QDateEdit *>();
  53. for (const auto &date_edit : date_edits) {
  54. date_edit->setDisplayFormat(OPL::DateTime::getFormatString(OPL::DateFormat::ISODate));
  55. date_edit->setDate(QDate::currentDate());
  56. }
  57. // Debug - use ctrl + t to enable branchLineEdit to select from which git branch the templates are pulled
  58. ui->branchLineEdit->setVisible(false);
  59. }
  60. FirstRunDialog::~FirstRunDialog()
  61. {
  62. delete ui;
  63. }
  64. void FirstRunDialog::on_previousPushButton_clicked()
  65. {
  66. const int current_index = ui->stackedWidget->currentIndex();
  67. switch (current_index) {
  68. case 0:
  69. return;
  70. case 1:
  71. ui->previousPushButton->setEnabled(false);
  72. break;
  73. case 2:
  74. ui->nextPushButton->setText(tr("Next"));
  75. break;
  76. }
  77. ui->stackedWidget->setCurrentIndex(current_index - 1);
  78. }
  79. void FirstRunDialog::on_nextPushButton_clicked()
  80. {
  81. const int current_index = ui->stackedWidget->currentIndex();
  82. switch (current_index) {
  83. case 0:
  84. if(ui->firstnameLineEdit->text().isEmpty()
  85. || ui->lastnameLineEdit->text().isEmpty())
  86. {
  87. QMessageBox(QMessageBox::Information, tr("No name entered"),
  88. tr("Please enter first and last name")
  89. ).exec();
  90. return;
  91. }
  92. ui->previousPushButton->setEnabled(true);
  93. break;
  94. case 3:
  95. ui->nextPushButton->setText(tr("Done"));
  96. break;
  97. case 4:
  98. ui->nextPushButton->setDisabled(true);
  99. if(!finishSetup())
  100. QDialog::reject();
  101. else
  102. QDialog::accept();
  103. return;
  104. }
  105. ui->stackedWidget->setCurrentIndex(current_index + 1);
  106. }
  107. bool FirstRunDialog::finishSetup()
  108. {
  109. writeSettings();
  110. QFileInfo database_file(OPL::Paths::databaseFileInfo());
  111. if (database_file.exists() && database_file.size() != 0) {
  112. QMessageBox message_box(QMessageBox::Question, tr("Existing Database found"),
  113. tr("An existing database file has been detected on your system.<br>"
  114. "Would you like to create a backup of the existing database?<br><br>"
  115. "Note: if you select no, the existing database will be overwritten. This "
  116. "action is irreversible."),
  117. QMessageBox::Yes | QMessageBox::No, this);
  118. message_box.setDefaultButton(QMessageBox::Yes);
  119. if(message_box.exec() == QMessageBox::Yes) {
  120. // Create Backup
  121. const QString backup_name = BackupWidget::absoluteBackupPath();
  122. QFile old_db_file(database_file.absoluteFilePath());
  123. if (!old_db_file.copy(backup_name)) {
  124. WARN(tr("Unable to backup old database:<br>%1").arg(old_db_file.errorString()));
  125. return false;
  126. } else {
  127. INFO(tr("Backup successfully created."));
  128. }
  129. }
  130. //delete existing DB file
  131. QFile db_file(database_file.absoluteFilePath());
  132. if (!db_file.remove()) {
  133. WARN(tr("Unable to delete existing database file."));
  134. return false;
  135. }
  136. } // if database file exists
  137. if (!DB->connect()) {
  138. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed (connect)"),
  139. tr("Errors have ocurred creating the database."
  140. "Without a working database The application will not be usable.<br>"
  141. "The following error has ocurred:<br>"
  142. "Database: Unable to connect"));
  143. message_box.exec();
  144. return false;
  145. }
  146. if (!setupDatabase()) {
  147. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed (create schema)"),
  148. tr("Errors have ocurred creating the database."
  149. "Without a working database The application will not be usable.<br>"
  150. "The following error has ocurred:<br>%1"
  151. ).arg(DB->lastError.text()));
  152. message_box.exec();
  153. return false;
  154. }
  155. if (!createUserEntry()) {
  156. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed (user entry)"),
  157. tr("Unable to execute database query<br>"
  158. "The following error has occured:<br>%1"
  159. ).arg(DB->lastError.text()));
  160. message_box.exec();
  161. return false;
  162. }
  163. if (!setupPreviousExperienceEntry()) {
  164. QMessageBox message_box(QMessageBox::Critical, tr("Database setup failed (previous Experience)"),
  165. tr("Unable to execute database query<br>"
  166. "The following error has occured:<br>%1"
  167. ).arg(DB->lastError.text()));
  168. message_box.exec();
  169. return false;
  170. }
  171. // non-critical error
  172. if(!writeCurrencies())
  173. LOG << "Error writing currencies during initial setup.";
  174. DB->disconnect(); // Connection will be re-established by MainWindow
  175. return true;
  176. }
  177. bool FirstRunDialog::downloadTemplates(QString branch_name)
  178. {
  179. // Create url string
  180. auto template_url_string = QStringLiteral("https://raw.githubusercontent.com/fiffty-50/openpilotlog/");
  181. template_url_string.append(branch_name);
  182. template_url_string.append(QLatin1String("/assets/database/templates/"));
  183. QDir template_dir(OPL::Paths::directory(OPL::Paths::Templates));
  184. QStringList template_table_names;
  185. for (const auto table : DB->getTemplateTables())
  186. template_table_names.append(OPL::GLOBALS->getDbTableName(table));
  187. // Download json files
  188. for (const auto& table_name : template_table_names) {
  189. QEventLoop loop;
  190. DownloadHelper* dl = new DownloadHelper;
  191. QObject::connect(dl, &DownloadHelper::done, &loop, &QEventLoop::quit );
  192. dl->setTarget(QUrl(template_url_string + table_name + QLatin1String(".json")));
  193. dl->setFileName(template_dir.absoluteFilePath(table_name + QLatin1String(".json")));
  194. DEB << "Downloading: " << template_url_string + table_name + QLatin1String(".json");
  195. dl->download();
  196. dl->deleteLater();
  197. loop.exec(); // event loop waits for download done signal before allowing loop to continue
  198. QFileInfo downloaded_file(template_dir.filePath(table_name + QLatin1String(".json")));
  199. if (downloaded_file.size() == 0) {
  200. LOG << "Unable to download template files (SSL / Network Error)";
  201. return false; // ssl/network error
  202. }
  203. }
  204. // Download checksum files
  205. for (const auto& table_name : template_table_names) {
  206. QEventLoop loop;
  207. DownloadHelper* dl = new DownloadHelper;
  208. QObject::connect(dl, &DownloadHelper::done, &loop, &QEventLoop::quit );
  209. dl->setTarget(QUrl(template_url_string + table_name + QLatin1String(".md5")));
  210. dl->setFileName(template_dir.absoluteFilePath(table_name + QLatin1String(".md5")));
  211. LOG << "Downloading: " << template_url_string + table_name + QLatin1String(".md5");
  212. dl->download();
  213. dl->deleteLater();
  214. loop.exec(); // event loop waits for download done signal before allowing loop to continue
  215. QFileInfo downloaded_file(template_dir.filePath(table_name + QLatin1String(".md5")));
  216. if (downloaded_file.size() == 0) {
  217. LOG << "Unable to download checksum files (SSL / Network Error)";
  218. return false; // ssl/network error
  219. }
  220. }
  221. // check downloadad files
  222. return verifyTemplates();
  223. }
  224. bool FirstRunDialog::verifyTemplates()
  225. {QStringList template_table_names;
  226. for (const auto table : DB->getTemplateTables())
  227. template_table_names.append(OPL::GLOBALS->getDbTableName(table));
  228. for (const auto &table_name : template_table_names) {
  229. const QString path = OPL::Paths::filePath(OPL::Paths::Templates, table_name);
  230. QFileInfo check_file(path + QLatin1String(".json"));
  231. Md5Sum hash(check_file);
  232. QFileInfo md5_file(path + QLatin1String(".md5"));
  233. if (!hash.compare(md5_file))
  234. return false;
  235. }
  236. return true;
  237. }
  238. void FirstRunDialog::writeSettings()
  239. {
  240. Settings::resetToDefaults();
  241. Settings::setPilotFunction(OPL::PilotFunction(ui->functionComboBox->currentIndex()));
  242. Settings::setApproachType(ui->approachComboBox->currentText());
  243. Settings::setNightLoggingEnabled(ui->nightComboBox->currentIndex());
  244. Settings::setLogIfr(ui->rulesComboBox->currentIndex());
  245. Settings::setFlightNumberPrefix(ui->prefixLineEdit->text());
  246. Settings::setLogbookView(OPL::LogbookView(ui->logbookViewComboBox->currentIndex()));
  247. Settings::setApplicationStyle(ui->styleComboBox->currentText());
  248. switch (ui->nightRulesComboBox->currentIndex()) {
  249. case 0:
  250. Settings::setNightAngle(-6);
  251. break;
  252. case 1:
  253. Settings::setNightAngle(0);
  254. break;
  255. }
  256. Settings::setShowSelfAs(ui->aliasComboBox->currentIndex());
  257. Settings::sync();
  258. }
  259. bool FirstRunDialog::setupDatabase()
  260. {
  261. QMessageBox confirm(QMessageBox::Question, tr("Create Database"),
  262. tr("We are now going to create the database.<br>"
  263. "Would you like to download the latest database information?"
  264. "<br>(Recommended, Internet connection required)"),
  265. QMessageBox::Yes | QMessageBox::No, this);
  266. confirm.setDefaultButton(QMessageBox::Yes);
  267. if (confirm.exec() == QMessageBox::Yes) {
  268. useRessourceData = false;
  269. if (!downloadTemplates(ui->branchLineEdit->text())) {
  270. QMessageBox message_box(this);
  271. message_box.setText(tr("Downloading or verifying latest data has failed.<br><br>Using local data instead."));
  272. message_box.exec();
  273. useRessourceData = true; // fall back
  274. }
  275. } else {
  276. useRessourceData = true;
  277. }
  278. if(!DB->createSchema()) {
  279. WARN(tr("Database creation has been unsuccessful. The following error has ocurred:<br><br>%1<br><br>%2")
  280. .arg(FUNC_IDENT, DB->lastError.text()));
  281. return false;
  282. }
  283. if(!DB->importTemplateData(useRessourceData)) {
  284. WARN(tr("Database creation has been unsuccessful. Unable to fill template data.<br><br>%1<br><br>%2")
  285. .arg(FUNC_IDENT, DB->lastError.text()));
  286. return false;
  287. }
  288. return true;
  289. }
  290. bool FirstRunDialog::createUserEntry()
  291. {
  292. OPL::RowData_T data;
  293. data.insert(OPL::PilotEntry::LASTNAME, ui->lastnameLineEdit->text());
  294. data.insert(OPL::PilotEntry::FIRSTNAME, ui->firstnameLineEdit->text());
  295. data.insert(OPL::PilotEntry::ALIAS, QStringLiteral("self"));
  296. data.insert(OPL::PilotEntry::EMPLOYEEID, ui->employeeidLineEdit->text());
  297. data.insert(OPL::PilotEntry::PHONE, ui->phoneLineEdit->text());
  298. data.insert(OPL::PilotEntry::EMAIL, ui->emailLineEdit->text());
  299. return DB->setLogbookOwner(data);
  300. }
  301. bool FirstRunDialog::setupPreviousExperienceEntry()
  302. {
  303. OPL::RowData_T prevData;
  304. prevData.insert(OPL::PreviousExperienceEntry::TBLK, 0);
  305. auto pXpEntry = OPL::PreviousExperienceEntry(1, prevData);
  306. return DB->commit(pXpEntry);
  307. }
  308. bool FirstRunDialog::writeCurrencies()
  309. {
  310. const QList<QPair<QString, QDateEdit*>> currencies = {
  311. { ui->currLicLabel->text(), ui->currLicDateEdit },
  312. { ui->currTrLabel->text(), ui->currTrDateEdit },
  313. { ui->currLckLabel->text(), ui->currLckDateEdit },
  314. { ui->currMedLabel->text(), ui->currMedDateEdit },
  315. { ui->currCustom1LineEdit->text(), ui->currCustom1DateEdit },
  316. { ui->currCustom2LineEdit->text(), ui->currCustom2DateEdit },
  317. };
  318. const QDate today = QDate::currentDate();
  319. for(const auto &pair : currencies) {
  320. // list 0-indexed, db row indexes start at 1
  321. OPL::CurrencyEntry currencyEntry = OPL::CurrencyEntry(currencies.indexOf(pair) + 1, OPL::RowData_T());
  322. currencyEntry.setName(pair.first);
  323. // only set expiry date if user has modified it
  324. const QDate date = pair.second->date();
  325. if(date != today) {
  326. int julianDay = date.toJulianDay();
  327. currencyEntry.setExpiryDate(OPL::Date(julianDay));
  328. }
  329. if(!DB->commit(currencyEntry))
  330. return false;
  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_importPushButton_clicked()
  376. {
  377. QString filename = QDir::toNativeSeparators(QFileDialog::getOpenFileName(
  378. this,
  379. tr("Choose backup file"),
  380. QDir::homePath(),
  381. "*.db"));
  382. if(filename.isEmpty()) { // QFileDialog has been cancelled
  383. WARN(tr("No Database has been selected."));
  384. return;
  385. }
  386. QMessageBox confirm(this);
  387. confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
  388. confirm.setDefaultButton(QMessageBox::No);
  389. confirm.setIcon(QMessageBox::Question);
  390. confirm.setWindowTitle(tr("Import Database"));
  391. confirm.setText(tr("The following database will be imported:<br><br><b><tt>"
  392. "%1<br></b></tt>"
  393. "<br>Is this correct?"
  394. ).arg(OPL::DbSummary::summaryString(filename)));
  395. if (confirm.exec() == QMessageBox::Yes) {
  396. if(!DB->restoreBackup(QDir::toNativeSeparators(filename))) {
  397. WARN(tr("Unable to import database file:").arg(filename));
  398. return;
  399. }
  400. INFO(tr("Database successfully imported."));
  401. QDialog::accept(); // quit the dialog as if a database was successfully created
  402. } else {
  403. return;
  404. }
  405. }