Browse Source

Refactor of AStandardPaths

- AStandardPaths now returns QDirs for robust cross-platform compatibility.
- Files are addressed as contents of these directories.
- Fixed a small bug in Reading/Writing the flightLogging/Approach setting.
Felix Turo 4 years ago
parent
commit
70d0ff0610

+ 1 - 2
main.cpp

@@ -42,8 +42,7 @@ int main(int argc, char *argv[])
     QCoreApplication::setApplicationName(APPNAME);
 
     AStandardPaths::setup();
-    AStandardPaths::scan_dirs();
-    if(!AStandardPaths::validate_dirs()){
+    if(!AStandardPaths::scan_dirs()){
         DEB << "Standard paths not valid.";
         return 1;
     }

+ 1 - 1
src/classes/adownload.cpp

@@ -28,7 +28,7 @@ ADownload::ADownload() : QObject(nullptr)
 
 ADownload::~ADownload()
 {
-
+    DEB << "Deleting ADownload Object";
 }
 
 void ADownload::setTarget(const QUrl &value)

+ 14 - 28
src/classes/astandardpaths.cpp

@@ -1,51 +1,37 @@
 #include "src/classes/astandardpaths.h"
 
-QMap<AStandardPaths::Directories, QString> AStandardPaths::directories;
+QMap<AStandardPaths::Directories, QDir> AStandardPaths::directories;
 
 void AStandardPaths::setup()
 {
     auto data_location = QStandardPaths::AppDataLocation;
     directories = { // [F]: Dir could be ambiguous since it is very similar to QDir
-        {Database, QDir::toNativeSeparators(
-         QStandardPaths::writableLocation(data_location) + '/')},
-        {Templates, QDir::toNativeSeparators(
-         QDir(QStandardPaths::writableLocation(data_location)).filePath(QStringLiteral("templates/")))},
-        {DatabaseBackup, QDir::toNativeSeparators(
-         QDir(QStandardPaths::writableLocation(data_location)).filePath(QStringLiteral("backup/")))}
+        {Database, QDir(QStandardPaths::writableLocation(data_location) + '/')},
+        {Templates, QDir(QStandardPaths::writableLocation(data_location)).filePath(
+         QStringLiteral("templates/"))},
+        {Backup, QDir(QStandardPaths::writableLocation(data_location)).filePath(
+         QStringLiteral("backup/"))}
     };
 }
 
-const QString& AStandardPaths::absPathOf(Directories loc)
+const QDir& AStandardPaths::directory(Directories loc)
 {
     return directories[loc];
 }
 
-const QMap<AStandardPaths::Directories, QString>& AStandardPaths::allPaths()
+const QMap<AStandardPaths::Directories, QDir>& AStandardPaths::allDirectories()
 {
     return directories;
 }
 
-void AStandardPaths::scan_dirs()
+bool AStandardPaths::scan_dirs()
 {
-    for(auto& dir : directories){
-        auto d = QDir(dir);
-        if(!d.exists()) {
-            d.mkpath(dir);
+    for(const auto& dir : directories){
+        if(!dir.exists()) {
+            DEB << dir << "Does not exist. Creating: " << dir.absolutePath();
+            if (!dir.mkpath(dir.absolutePath()))
+                return false;
         }
     }
-}
-
-// [F]: We could make scan_dirs return bool and return false if !exists && !mkpath
-// This function seems like it would do the same as scan_dirs
-// Validating the contents would be rather complex to accomplish and difficult to
-// maintain I believe, since the contents of these directories might change and it
-// seems out of the scope of this class to verify the directories' contents.
-bool AStandardPaths::validate_dirs()
-{
-    for(auto& dir : directories){
-        //DEB << "Validating " << dir;
-        if(false)  // determine path as valid (scan contents and parse for correctness)
-            return false;
-    }
     return true;
 }

+ 5 - 8
src/classes/astandardpaths.h

@@ -18,10 +18,10 @@ public:
     enum Directories {
         Database,
         Templates,
-        DatabaseBackup
+        Backup
     };
 private:
-    static QMap<Directories, QString> directories;
+    static QMap<Directories, QDir> directories;
 public:
     /// Initialise paths with corresponding StandardLocation paths
     static void setup();
@@ -30,14 +30,11 @@ public:
     // We should move away from getThis getThat functions.
     // I believe we can give better namings while avoiding this
     // OOP cliche of getEverything
-    static const QString& absPathOf(Directories loc);
-    static const QMap<Directories, QString>& allPaths();
+    static const QDir &directory(Directories loc);
+    static const QMap<Directories, QDir> &allDirectories();
 
     /// Ensure standard app directories exist, if not mkpath them.
-    static void scan_dirs();
-
-    /// Validate standard app directories are valid in structure and contents.
-    static bool validate_dirs();
+    static bool scan_dirs();
 };
 
 

+ 5 - 2
src/database/adatabase.cpp

@@ -81,8 +81,8 @@ ADatabase* ADatabase::instance()
 }
 
 ADatabase::ADatabase()
-    : databaseDir(QDir(AStandardPaths::absPathOf(AStandardPaths::Database))),
-      databaseFile(QFileInfo(databaseDir.filePath(QStringLiteral("logbook.db"))))
+    : databaseFile(QFileInfo(AStandardPaths::directory(AStandardPaths::Database).
+                             absoluteFilePath(QStringLiteral("logbook.db"))))
 {}
 
 /*!
@@ -103,6 +103,9 @@ bool ADatabase::connect()
     if (!QSqlDatabase::isDriverAvailable(SQLITE_DRIVER))
         return false;
 
+    if (!databaseFile.exists())
+        return false;
+
     QSqlDatabase db = QSqlDatabase::addDatabase(SQLITE_DRIVER);
     db.setDatabaseName(databaseFile.absoluteFilePath());
 

+ 2 - 1
src/database/adatabase.h

@@ -105,9 +105,10 @@ public:
     const QString sqliteVersion();
 
     ADatabaseError lastError;
-    const QDir databaseDir;
+    //const QDir databaseDir;
     const QFileInfo databaseFile;
 
+
     /*!
      * \brief Connect to the database and populate database information.
      */

+ 8 - 7
src/database/adatabasesetup.cpp

@@ -276,22 +276,22 @@ bool ADataBaseSetup::createDatabase()
 
 bool ADataBaseSetup::downloadTemplates()
 {
-    QDir template_dir(AStandardPaths::absPathOf(AStandardPaths::Templates));
+    QDir template_dir(AStandardPaths::directory(AStandardPaths::Templates));
     DEB << template_dir;
     for (const auto& table : templateTables) {
         QEventLoop loop;
         ADownload* dl = new ADownload;
         QObject::connect(dl, &ADownload::done, &loop, &QEventLoop::quit );
         dl->setTarget(QUrl(TEMPLATE_URL % table % QStringLiteral(".csv")));
-        dl->setFileName(template_dir.filePath(table % QStringLiteral(".csv")));
+        dl->setFileName(template_dir.absoluteFilePath(table % QStringLiteral(".csv")));
         dl->download();
+        dl->deleteLater();
         loop.exec(); // event loop waits for download done signal before allowing loop to continue
 
         QFileInfo downloaded_file(template_dir.filePath(table % QStringLiteral(".csv")));
         if (downloaded_file.size() == 0)
             return false; // ssl/network error
 
-        dl->deleteLater();
     }
     return true;
 }
@@ -305,11 +305,11 @@ bool ADataBaseSetup::backupOldData()
 
     auto date_string = ADateTime::toString(QDateTime::currentDateTime(),
                                            Opl::Datetime::Backup);
-    auto backup_dir = QDir(AStandardPaths::absPathOf(AStandardPaths::DatabaseBackup));
+    auto backup_dir = AStandardPaths::directory(AStandardPaths::Backup);
     auto backup_name = database_file.baseName() + "_bak_" + date_string + ".db";
     QFile file(aDB->databaseFile.absoluteFilePath());
 
-    if (!file.rename(backup_dir.absolutePath() + backup_name)) {
+    if (!file.rename(backup_dir.absoluteFilePath(backup_name))) {
         DEB << "Unable to backup old database.";
         return false;
     }
@@ -337,8 +337,9 @@ bool ADataBaseSetup::importDefaultData(bool use_local_data)
                                       + table_name + QStringLiteral(".csv"));
             error_message.append(" (local) ");
         } else {
-            data_to_commit = aReadCsv(AStandardPaths::absPathOf(AStandardPaths::Templates)
-                                      + table_name + QStringLiteral(".csv"));
+            data_to_commit = aReadCsv(AStandardPaths::directory(
+                                          AStandardPaths::Templates).absoluteFilePath(
+                                          table_name + QStringLiteral(".csv")));
             error_message.append(" (remote) ");
         }
 

+ 1 - 2
src/gui/dialogues/firstrundialog.cpp

@@ -6,7 +6,6 @@
 #include "src/classes/apilotentry.h"
 #include "src/classes/adownload.h"
 #include "src/classes/asettings.h"
-#include "src/classes/astandardpaths.h"
 #include "src/oplconstants.h"
 #include <QErrorMessage>
 
@@ -79,7 +78,7 @@ bool FirstRunDialog::finish()
 {
 
     ASettings::write(ASettings::FlightLogging::Function, ui->functionComboBox->currentText());
-    ASettings::write(ASettings::FlightLogging::Approach, ui->approachComboBox->currentText());
+    ASettings::write(ASettings::FlightLogging::Approach, ui->approachComboBox->currentIndex());
     ASettings::write(ASettings::FlightLogging::NightLogging, ui->nightComboBox->currentIndex());
     ASettings::write(ASettings::FlightLogging::LogIFR, ui->rulesComboBox->currentIndex());
     ASettings::write(ASettings::FlightLogging::FlightNumberPrefix, ui->prefixLineEdit->text());

+ 2 - 2
src/gui/dialogues/newflightdialog.cpp

@@ -155,7 +155,7 @@ void NewFlightDialog::readSettings()
     DEB << "Reading Settings...";
     QSettings settings;
     ui->FunctionComboBox->setCurrentText(ASettings::read(ASettings::FlightLogging::Function).toString());
-    ui->ApproachComboBox->setCurrentText(ASettings::read(ASettings::FlightLogging::Approach).toString());
+    ui->ApproachComboBox->setCurrentIndex(ASettings::read(ASettings::FlightLogging::Approach).toInt());
 
     ASettings::read(ASettings::FlightLogging::PilotFlying).toBool() ? ui->PilotFlyingCheckBox->setChecked(true)
                                                           : ui->PilotMonitoringCheckBox->setChecked(true);
@@ -189,7 +189,7 @@ void NewFlightDialog::writeSettings()
     DEB << "Writing Settings...";
 
     ASettings::write(ASettings::FlightLogging::Function, ui->FunctionComboBox->currentText());
-    ASettings::write(ASettings::FlightLogging::Approach, ui->ApproachComboBox->currentText());
+    ASettings::write(ASettings::FlightLogging::Approach, ui->ApproachComboBox->currentIndex());
     ASettings::write(ASettings::FlightLogging::PilotFlying, ui->PilotFlyingCheckBox->isChecked());
     ASettings::write(ASettings::FlightLogging::NumberTakeoffs, ui->TakeoffSpinBox->value());
     ASettings::write(ASettings::FlightLogging::NumberLandings, ui->LandingSpinBox->value());

+ 9 - 6
src/gui/widgets/debugwidget.cpp

@@ -50,7 +50,7 @@ void DebugWidget::on_resetDatabasePushButton_clicked()
     link_stub.append("/assets/database/templates/");
 
     QStringList template_tables = {"aircraft", "airports", "changelog"};
-    QDir template_dir(AStandardPaths::absPathOf(AStandardPaths::Templates));
+    QDir template_dir(AStandardPaths::directory(AStandardPaths::Templates));
     for (const auto& table : template_tables) {
         QEventLoop loop;
         ADownload* dl = new ADownload;
@@ -100,7 +100,7 @@ void DebugWidget::on_fillUserDataPushButton_clicked()
     QString linkStub = "https://raw.githubusercontent.com/fiffty-50/openpilotlog/";
     linkStub.append(ui->branchLineEdit->text());
     linkStub.append("/assets/database/templates/sample_");
-    QDir template_dir(AStandardPaths::absPathOf(AStandardPaths::Templates));
+    QDir template_dir(AStandardPaths::directory(AStandardPaths::Templates));
 
     for (const auto& table : userTables) {
         QEventLoop loop;
@@ -116,8 +116,8 @@ void DebugWidget::on_fillUserDataPushButton_clicked()
     allGood.resize(userTables.size());
 
     for (const auto& table : userTables) {
-        auto data = aReadCsv(AStandardPaths::absPathOf(AStandardPaths::Templates)
-                             + "/sample_" + table + ".csv");
+        auto data = aReadCsv(AStandardPaths::directory(AStandardPaths::Templates).absoluteFilePath(
+                             + "sample_" + table + ".csv"));
         allGood.setBit(userTables.indexOf(table), ADataBaseSetup::commitData(data, table));
     }
 
@@ -136,7 +136,7 @@ void DebugWidget::on_selectCsvPushButton_clicked()
 {
     auto fileName = QFileDialog::getOpenFileName(this,
                                                  tr("Open CSV File for import"),
-                                                 AStandardPaths::absPathOf(AStandardPaths::Templates),
+                                                 AStandardPaths::directory(AStandardPaths::Templates).absolutePath(),
                                                  tr("CSV files (*.csv)"));
     ui->importCsvLineEdit->setText(fileName);
 }
@@ -168,7 +168,10 @@ void DebugWidget::on_importCsvPushButton_clicked()
 void DebugWidget::on_debugPushButton_clicked()
 {
     // debug space
-    ASettings::write(ASettings::Setup::SetupComplete, false);
+    //ASettings::write(ASettings::Setup::SetupComplete, false);
+    ASettings::write(ASettings::FlightLogging::Approach, 5);
+    DEB << ASettings::read(ASettings::FlightLogging::Approach);
+
 }
 
 /* //Comparing two functions template