firstrundialog.cpp 17 KB

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