firstrundialog.cpp 17 KB

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