diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..18da99f
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,55 @@
+---
+BasedOnStyle: Microsoft
+AlignEscapedNewlines: Left
+IndentWidth: 4
+
+ColumnLimit: 100
+
+# We want a space between the type and the star for pointer types.
+PointerBindsToType: false
+
+# We want to break before the operators, but not before a '='.
+BreakBeforeBinaryOperators: NonAssignment
+
+# Braces are usually attached, but not after functions or class declarations.
+BreakBeforeBraces: Custom
+BraceWrapping:
+ AfterClass: true
+ AfterCaseLabel: true
+ AfterControlStatement: true
+ AfterEnum: true
+ AfterFunction: true
+ BeforeLambdaBody: true
+ AfterNamespace: false
+ AfterObjCDeclaration: false
+ AfterStruct: true
+ AfterUnion: false
+ BeforeCatch: true
+ BeforeElse: true
+ IndentBraces: false
+ SplitEmptyFunction: true
+
+# Indent width for line continuations.
+ContinuationIndentWidth: 2
+
+# Allow indentation for preprocessing directives (if/ifdef/endif). https://reviews.llvm.org/rL312125
+IndentPPDirectives: AfterHash
+
+# Do not indent public/private/protected
+IndentAccessModifiers: false
+
+# This is needed because IndentAccessModifiers doesn't seem to work
+AccessModifierOffset: -4
+
+BreakConstructorInitializers: AfterColon
+PackConstructorInitializers: Never
+
+# Horizontally align arguments after an open bracket.
+AlignAfterOpenBracket: true
+
+SortIncludes: false
+
+InsertNewlineAtEOF: true
+
+AlignConsecutiveMacros: AcrossEmptyLines
+AlignConsecutiveAssignments: AcrossEmptyLines
diff --git a/src/app/main.cpp b/src/app/main.cpp
index 0cbf6d5..7f216cc 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -46,23 +46,29 @@ void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QS
QMutexLocker lock(&logMutex);
QString str;
- //const QString fmt = QStringLiteral("%1: %2 (%3:%4, %5)\n");
+ // const QString fmt = QStringLiteral("%1: %2 (%3:%4, %5)\n");
static const QString fmt = QStringLiteral("%1: %2\n");
- switch (type) {
+ switch (type)
+ {
case QtDebugMsg:
- str = fmt.arg(QStringLiteral("Debug"), msg); //.arg(context.file).arg(context.line).arg(context.function);
+ str = fmt.arg(QStringLiteral("Debug"),
+ msg); //.arg(context.file).arg(context.line).arg(context.function);
break;
case QtInfoMsg:
- str = fmt.arg(QStringLiteral("Info"), msg); //.arg(context.file).arg(context.line).arg(context.function);
+ str = fmt.arg(QStringLiteral("Info"),
+ msg); //.arg(context.file).arg(context.line).arg(context.function);
break;
case QtWarningMsg:
- str = fmt.arg(QStringLiteral("Warning"), msg); //.arg(context.file).arg(context.line).arg(context.function);
+ str = fmt.arg(QStringLiteral("Warning"),
+ msg); //.arg(context.file).arg(context.line).arg(context.function);
break;
case QtCriticalMsg:
- str = fmt.arg(QStringLiteral("Critical"), msg); //.arg(context.file).arg(context.line).arg(context.function);
+ str = fmt.arg(QStringLiteral("Critical"),
+ msg); //.arg(context.file).arg(context.line).arg(context.function);
break;
case QtFatalMsg:
- str = fmt.arg(QStringLiteral("Fatal"), msg); //.arg(context.file).arg(context.line).arg(context.function);
+ str = fmt.arg(QStringLiteral("Fatal"),
+ msg); //.arg(context.file).arg(context.line).arg(context.function);
}
QTextStream s(gLogFile());
@@ -73,114 +79,124 @@ void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QS
void setupLogger()
{
- //const QString path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
+ // const QString path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QString path = MeetingSession::appDataPath;
- if(qApp->arguments().contains("--test"))
- path = qApp->applicationDirPath(); //If testing use exe folder instead of AppData: see MeetingSession
+ if (qApp->arguments().contains("--test"))
+ path = qApp->applicationDirPath(); // If testing use exe folder instead of AppData:
+ // see MeetingSession
QFile *logFile = gLogFile();
logFile->setFileName(path + QStringLiteral("/logs/mrtp_log.log"));
logFile->open(QFile::WriteOnly | QFile::Append | QFile::Text);
- if(!logFile->isOpen()) //FIXME: if logFile gets too big, ask user to truncate it
+ if (!logFile->isOpen()) // FIXME: if logFile gets too big, ask user to truncate it
{
QDir dir(path);
dir.mkdir("logs");
logFile->open(QFile::WriteOnly | QFile::Append | QFile::Text);
}
- if(logFile->isOpen())
+ if (logFile->isOpen())
{
defaultHandler = qInstallMessageHandler(myMessageOutput);
}
- else {
- qDebug() << "Cannot open Log file:" << logFile->fileName() << "Error:" << logFile->errorString();
+ else
+ {
+ qDebug() << "Cannot open Log file:" << logFile->fileName()
+ << "Error:" << logFile->errorString();
}
}
int main(int argc, char *argv[])
{
#ifdef GLOBAL_TRY_CATCH
- try{
+ try
+ {
#endif
- QApplication app(argc, argv);
- QApplication::setOrganizationName(AppCompany);
- //QApplication::setApplicationName(AppProduct);
- QApplication::setApplicationDisplayName(AppDisplayName);
- QApplication::setApplicationVersion(AppVersion);
+ QApplication app(argc, argv);
+ QApplication::setOrganizationName(AppCompany);
+ // QApplication::setApplicationName(AppProduct);
+ QApplication::setApplicationDisplayName(AppDisplayName);
+ QApplication::setApplicationVersion(AppVersion);
- MeetingSession::locateAppdata();
+ MeetingSession::locateAppdata();
- setupLogger();
+ setupLogger();
- qDebug() << QApplication::applicationDisplayName()
- << "Version:" << QApplication::applicationVersion()
- << "Built:" << AppBuildDate
- << "Website: " << AppProjectWebSite;
- qDebug() << "Qt:" << QT_VERSION_STR;
- qDebug() << "Sqlite:" << sqlite3_libversion() << " DB Format: V" << FormatVersion;
- qDebug() << QDateTime::currentDateTime().toString("dd/MM/yyyy HH:mm");
+ qDebug() << QApplication::applicationDisplayName()
+ << "Version:" << QApplication::applicationVersion() << "Built:" << AppBuildDate
+ << "Website: " << AppProjectWebSite;
+ qDebug() << "Qt:" << QT_VERSION_STR;
+ qDebug() << "Sqlite:" << sqlite3_libversion() << " DB Format: V" << FormatVersion;
+ qDebug() << QDateTime::currentDateTime().toString("dd/MM/yyyy HH:mm");
- //Check SQLite thread safety
- int val = sqlite3_threadsafe();
- if(val != 1)
- {
- //Not thread safe
- qWarning() << "SQLite Library was not compiled with SQLITE_THREADSAFE=1. This may cause crashes of this application.";
- }
-
- MeetingSession meetingSession;
- utils::language::loadTranslationsFromSettings();
-
- MainWindow w;
- w.showNormal();
- w.resize(800, 600);
- w.showMaximized();
-
- if(argc > 1) //FIXME: better handling if there are extra arguments
- {
- QString fileName = app.arguments().at(1);
- qDebug() << "Trying to load:" << fileName;
- if(QFile(fileName).exists())
+ // Check SQLite thread safety
+ int val = sqlite3_threadsafe();
+ if (val != 1)
{
- w.loadFile(app.arguments().at(1));
+ // Not thread safe
+ qWarning() << "SQLite Library was not compiled with SQLITE_THREADSAFE=1. This may "
+ "cause crashes of this application.";
}
- }
- qDebug() << "Running...";
+ MeetingSession meetingSession;
+ utils::language::loadTranslationsFromSettings();
- int ret = app.exec();
- QThreadPool::globalInstance()->waitForDone(1000);
- DB_Error err = Session->closeDB();
+ MainWindow w;
+ w.showNormal();
+ w.resize(800, 600);
+ w.showMaximized();
- if(err == DB_Error::DbBusyWhenClosing || QThreadPool::globalInstance()->activeThreadCount() > 0)
- {
- qWarning() << "Error: Application closing while threadpool still running or database busy!";
- QThreadPool::globalInstance()->waitForDone(10000);
- Session->closeDB();
- }
+ if (argc > 1) // FIXME: better handling if there are extra arguments
+ {
+ QString fileName = app.arguments().at(1);
+ qDebug() << "Trying to load:" << fileName;
+ if (QFile(fileName).exists())
+ {
+ w.loadFile(app.arguments().at(1));
+ }
+ }
- return ret;
+ qDebug() << "Running...";
+ int ret = app.exec();
+ QThreadPool::globalInstance()->waitForDone(1000);
+ DB_Error err = Session->closeDB();
+
+ if (err == DB_Error::DbBusyWhenClosing
+ || QThreadPool::globalInstance()->activeThreadCount() > 0)
+ {
+ qWarning()
+ << "Error: Application closing while threadpool still running or database busy!";
+ QThreadPool::globalInstance()->waitForDone(10000);
+ Session->closeDB();
+ }
+
+ return ret;
#ifdef GLOBAL_TRY_CATCH
- }catch(const char* str)
+ }
+ catch (const char *str)
{
qDebug() << "Exception:" << str;
throw;
- }catch(const std::string& str)
+ }
+ catch (const std::string &str)
{
qDebug() << "Exception:" << str.c_str();
throw;
- }catch(sqlite3pp::database_error& e)
+ }
+ catch (sqlite3pp::database_error &e)
{
qDebug() << "Exception:" << e.what();
throw;
- }catch(std::exception& e)
+ }
+ catch (std::exception &e)
{
qDebug() << "Exception:" << e.what();
throw;
- }catch(...)
+ }
+ catch (...)
{
qDebug() << "Caught generic exception";
throw;
diff --git a/src/app/mainwindow.cpp b/src/app/mainwindow.cpp
index 4deabf8..3ab79ab 100644
--- a/src/app/mainwindow.cpp
+++ b/src/app/mainwindow.cpp
@@ -24,7 +24,6 @@
#include "viewmanager/viewmanager.h"
-
#include "jobs/jobeditor/jobpatheditor.h"
#include
@@ -52,7 +51,7 @@
#include "printing/wizard/printwizard.h"
#ifdef ENABLE_USER_QUERY
-#include "sqlconsole/sqlconsole.h"
+# include "sqlconsole/sqlconsole.h"
#endif
#include
@@ -61,10 +60,10 @@
#include "searchbox/searchresultmodel.h"
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "backgroundmanager/backgroundmanager.h"
-#include "backgroundmanager/backgroundresultpanel.h"
-#include "jobs/jobs_checker/crossing/jobcrossingchecker.h"
-#include "rollingstock/rs_checker/rscheckermanager.h"
+# include "backgroundmanager/backgroundmanager.h"
+# include "backgroundmanager/backgroundresultpanel.h"
+# include "jobs/jobs_checker/crossing/jobcrossingchecker.h"
+# include "rollingstock/rs_checker/rscheckermanager.h"
#endif // ENABLE_BACKGROUND_MANAGER
#include "propertiesdialog.h"
@@ -100,47 +99,47 @@ MainWindow::MainWindow(QWidget *parent) :
ui->setupUi(this);
ui->actionAbout->setText(tr("About %1").arg(qApp->applicationDisplayName()));
- auto viewMgr = Session->getViewManager();
+ auto viewMgr = Session->getViewManager();
viewMgr->m_mainWidget = this;
- auto graphMgr = viewMgr->getLineGraphMgr();
+ auto graphMgr = viewMgr->getLineGraphMgr();
connect(graphMgr, &LineGraphManager::jobSelected, this, &MainWindow::onJobSelected);
- //view = graphMgr->getView();
+ // view = graphMgr->getView();
view = new LineGraphWidget(this);
- //Welcome label
+ // Welcome label
welcomeLabel = new QLabel(this);
welcomeLabel->setTextFormat(Qt::RichText);
welcomeLabel->setAlignment(Qt::AlignCenter);
welcomeLabel->setFont(QFont("Arial", 15));
welcomeLabel->setObjectName("WelcomeLabel");
- //JobPathEditor dock
- jobEditor = new JobPathEditor(this);
+ // JobPathEditor dock
+ jobEditor = new JobPathEditor(this);
viewMgr->jobEditor = jobEditor;
- jobDock = new QDockWidget(tr("Job Editor"), this);
+ jobDock = new QDockWidget(tr("Job Editor"), this);
jobDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
jobDock->setWidget(jobEditor);
- jobDock->installEventFilter(this); //NOTE: see MainWindow::eventFilter() below
+ jobDock->installEventFilter(this); // NOTE: see MainWindow::eventFilter() below
addDockWidget(Qt::RightDockWidgetArea, jobDock);
ui->menuView->addAction(jobDock->toggleViewAction());
connect(jobDock->toggleViewAction(), &QAction::triggered, jobEditor, &JobPathEditor::show);
#ifdef ENABLE_BACKGROUND_MANAGER
- //Background Errors dock
+ // Background Errors dock
BackgroundResultPanel *resPanel = new BackgroundResultPanel(this);
- resPanelDock = new QDockWidget(tr("Errors"), this);
+ resPanelDock = new QDockWidget(tr("Errors"), this);
resPanelDock->setAllowedAreas(Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea);
resPanelDock->setWidget(resPanel);
- resPanelDock->installEventFilter(this); //NOTE: see eventFilter() below
+ resPanelDock->installEventFilter(this); // NOTE: see eventFilter() below
addDockWidget(Qt::BottomDockWidgetArea, resPanelDock);
ui->menuView->addAction(resPanelDock->toggleViewAction());
ui->mainToolBar->addAction(resPanelDock->toggleViewAction());
- //Add checkers FIXME: move to session?
+ // Add checkers FIXME: move to session?
JobCrossingChecker *jobCrossingChecker = new JobCrossingChecker(Session->m_Db, this);
Session->getBackgroundManager()->addChecker(jobCrossingChecker);
@@ -148,22 +147,24 @@ MainWindow::MainWindow(QWidget *parent) :
Session->getBackgroundManager()->addChecker(rsChecker);
#endif // ENABLE_BACKGROUND_MANAGER
- //Allow JobPathEditor to use all vertical space when RsErrorWidget dock is at bottom
+ // Allow JobPathEditor to use all vertical space when RsErrorWidget dock is at bottom
setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
- //Search Box
+ // Search Box
SearchResultModel *searchModel = new SearchResultModel(Session->m_Db, this);
- searchEdit = new CustomCompletionLineEdit(searchModel, this);
+ searchEdit = new CustomCompletionLineEdit(searchModel, this);
searchEdit->setMinimumWidth(300);
searchEdit->setMinimumHeight(25);
searchEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
searchEdit->setPlaceholderText(tr("Find"));
searchEdit->setClearButtonEnabled(true);
- connect(searchEdit, &CustomCompletionLineEdit::completionDone, this, &MainWindow::onJobSearchItemSelected);
- connect(searchModel, &SearchResultModel::resultsReady, this, &MainWindow::onJobSearchResultsReady);
+ connect(searchEdit, &CustomCompletionLineEdit::completionDone, this,
+ &MainWindow::onJobSearchItemSelected);
+ connect(searchModel, &SearchResultModel::resultsReady, this,
+ &MainWindow::onJobSearchResultsReady);
- QWidget* spacer = new QWidget();
+ QWidget *spacer = new QWidget();
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->mainToolBar->addWidget(spacer);
ui->mainToolBar->addWidget(searchEdit);
@@ -172,12 +173,11 @@ MainWindow::MainWindow(QWidget *parent) :
setCentralWidgetMode(CentralWidgetMode::StartPageMode);
QMenu *recentFilesMenu = new QMenu(this);
- for(int i = 0; i < MaxRecentFiles; i++)
+ for (int i = 0; i < MaxRecentFiles; i++)
{
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
- connect(recentFileActs[i], &QAction::triggered,
- this, &MainWindow::onOpenRecent);
+ connect(recentFileActs[i], &QAction::triggered, this, &MainWindow::onOpenRecent);
recentFilesMenu->addAction(recentFileActs[i]);
}
@@ -186,7 +186,7 @@ MainWindow::MainWindow(QWidget *parent) :
ui->actionOpen_Recent->setMenu(recentFilesMenu);
- //Listen to changes to display welcomeLabel or view
+ // Listen to changes to display welcomeLabel or view
connect(Session, &MeetingSession::segmentAdded, this, &MainWindow::checkLineNumber);
connect(Session, &MeetingSession::segmentRemoved, this, &MainWindow::checkLineNumber);
connect(Session, &MeetingSession::lineAdded, this, &MainWindow::checkLineNumber);
@@ -240,11 +240,13 @@ void MainWindow::setup_actions()
connect(ui->actionProperties, &QAction::triggered, this, &MainWindow::onProperties);
connect(ui->actionStations, &QAction::triggered, this, &MainWindow::onStationManager);
- connect(ui->actionRollingstockManager, &QAction::triggered, this, &MainWindow::onRollingStockManager);
+ connect(ui->actionRollingstockManager, &QAction::triggered, this,
+ &MainWindow::onRollingStockManager);
connect(ui->actionJob_Shifts, &QAction::triggered, this, &MainWindow::onShiftManager);
connect(ui->action_JobsMgr, &QAction::triggered, this, &MainWindow::onJobsManager);
connect(ui->actionRS_Session_Viewer, &QAction::triggered, this, &MainWindow::onSessionRSViewer);
- connect(ui->actionMeeting_Information, &QAction::triggered, this, &MainWindow::onMeetingInformation);
+ connect(ui->actionMeeting_Information, &QAction::triggered, this,
+ &MainWindow::onMeetingInformation);
connect(ui->actionAddJob, &QAction::triggered, this, &MainWindow::onAddJob);
connect(ui->actionRemoveJob, &QAction::triggered, this, &MainWindow::onRemoveJob);
@@ -263,16 +265,22 @@ void MainWindow::setup_actions()
connect(ui->actionExit, &QAction::triggered, this, &MainWindow::close);
- ui->actionNext_Job_Segment->setToolTip(tr("Hold shift and click to go to last job stop."));
- ui->actionPrev_Job_Segment->setToolTip(tr("Hold shift and click to go to first job stop."));
- connect(ui->actionNext_Job_Segment, &QAction::triggered, this, []()
+ ui->actionNext_Job_Segment->setToolTip(
+ tr("Hold shift and click to go to last job stop."));
+ ui->actionPrev_Job_Segment->setToolTip(
+ tr("Hold shift and click to go to first job stop."));
+ connect(ui->actionNext_Job_Segment, &QAction::triggered, this,
+ []()
{
- bool shiftPressed = QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
+ bool shiftPressed =
+ QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
Session->getViewManager()->requestJobShowPrevNextSegment(false, shiftPressed);
});
- connect(ui->actionPrev_Job_Segment, &QAction::triggered, this, []()
+ connect(ui->actionPrev_Job_Segment, &QAction::triggered, this,
+ []()
{
- bool shiftPressed = QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
+ bool shiftPressed =
+ QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
Session->getViewManager()->requestJobShowPrevNextSegment(true, shiftPressed);
});
}
@@ -284,15 +292,14 @@ void MainWindow::about()
msgBox->setWindowTitle(tr("About %1").arg(qApp->applicationDisplayName()));
const QString translatedText =
- tr(
- "%1
"
- "This program makes it easier to deal with timetables and trains.
"
- "Version: %2
"
- "Built: %3
"
- "Website: %4
")
- .arg(qApp->applicationDisplayName(), qApp->applicationVersion(),
- QDate::fromString(AppBuildDate, QLatin1String("MMM dd yyyy")).toString("dd/MM/yyyy"),
- AppProjectWebSite);
+ tr("%1
"
+ "This program makes it easier to deal with timetables and trains.
"
+ "Version: %2
"
+ "Built: %3
"
+ "Website: %4
")
+ .arg(qApp->applicationDisplayName(), qApp->applicationVersion(),
+ QDate::fromString(AppBuildDate, QLatin1String("MMM dd yyyy")).toString("dd/MM/yyyy"),
+ AppProjectWebSite);
msgBox->setTextFormat(Qt::RichText);
msgBox->setText(translatedText);
@@ -309,15 +316,14 @@ void MainWindow::onOpen()
#endif
#ifdef ENABLE_BACKGROUND_MANAGER
- if(Session->getBackgroundManager()->isRunning())
+ if (Session->getBackgroundManager()->isRunning())
{
- int ret = QMessageBox::warning(this,
- tr("Backgroung Task"),
- tr("Background task for checking rollingstock errors is still running.\n"
- "Do you want to cancel it?"),
- QMessageBox::Yes, QMessageBox::No,
- QMessageBox::Yes);
- if(ret == QMessageBox::Yes)
+ int ret = QMessageBox::warning(
+ this, tr("Backgroung Task"),
+ tr("Background task for checking rollingstock errors is still running.\n"
+ "Do you want to cancel it?"),
+ QMessageBox::Yes, QMessageBox::No, QMessageBox::Yes);
+ if (ret == QMessageBox::Yes)
Session->getBackgroundManager()->abortAllTasks();
else
return;
@@ -335,22 +341,21 @@ void MainWindow::onOpen()
filters << FileFormats::tr(FileFormats::allFiles);
dlg->setNameFilters(filters);
- if(dlg->exec() != QDialog::Accepted || !dlg)
+ if (dlg->exec() != QDialog::Accepted || !dlg)
return;
QString fileName = dlg->selectedUrls().value(0).toLocalFile();
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
RecentDirStore::setPath(directory_key::session, fileName);
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- if(!QThreadPool::globalInstance()->waitForDone(2000))
+ if (!QThreadPool::globalInstance()->waitForDone(2000))
{
- QMessageBox::warning(this,
- tr("Background Tasks"),
+ QMessageBox::warning(this, tr("Background Tasks"),
tr("Some background tasks are still running.\n"
"The file was not opened. Try again."));
QApplication::restoreOverrideCursor();
@@ -362,10 +367,10 @@ void MainWindow::onOpen()
loadFile(fileName);
}
-void MainWindow::loadFile(const QString& fileName)
+void MainWindow::loadFile(const QString &fileName)
{
DEBUG_ENTRY;
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
qDebug() << "Loading:" << fileName;
@@ -376,86 +381,91 @@ void MainWindow::loadFile(const QString& fileName)
QApplication::restoreOverrideCursor();
- if(err == DB_Error::FormatTooOld)
+ if (err == DB_Error::FormatTooOld)
{
- int but = QMessageBox::warning(this, tr("Version is old"),
- tr("This file was created by an older version of %1.\n"
- "Opening it without conversion might not work and even crash the application.\n"
- "Do you want to open it anyway?").arg(qApp->applicationDisplayName()),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
- if(but == QMessageBox::Yes)
+ int but = QMessageBox::warning(
+ this, tr("Version is old"),
+ tr("This file was created by an older version of %1.\n"
+ "Opening it without conversion might not work and even crash the application.\n"
+ "Do you want to open it anyway?")
+ .arg(qApp->applicationDisplayName()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (but == QMessageBox::Yes)
err = Session->openDB(fileName, true);
}
- else if(err == DB_Error::FormatTooNew)
+ else if (err == DB_Error::FormatTooNew)
{
- if(err == DB_Error::FormatTooOld)
+ if (err == DB_Error::FormatTooOld)
{
int but = QMessageBox::warning(this, tr("Version is too new"),
tr("This file was created by a newer version of %1.\n"
- "You should update the application first. Opening this file might not work or even crash.\n"
- "Do you want to open it anyway?").arg(qApp->applicationDisplayName()),
+ "You should update the application first. Opening "
+ "this file might not work or even crash.\n"
+ "Do you want to open it anyway?")
+ .arg(qApp->applicationDisplayName()),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
- if(but == QMessageBox::Yes)
+ if (but == QMessageBox::Yes)
err = Session->openDB(fileName, true);
}
}
- if(err == DB_Error::DbBusyWhenClosing)
+ if (err == DB_Error::DbBusyWhenClosing)
showCloseWarning();
- if(err != DB_Error::NoError)
+ if (err != DB_Error::NoError)
return;
setCurrentFile(fileName);
- //Fake we are coming from Start Page
- //Otherwise we cannot show the first line
+ // Fake we are coming from Start Page
+ // Otherwise we cannot show the first line
m_mode = CentralWidgetMode::StartPageMode;
checkLineNumber();
-
- if(!Session->checkImportRSTablesEmpty())
+ if (!Session->checkImportRSTablesEmpty())
{
- //Probably the application crashed before finishing RS importation
- //Give user choice to resume it or discard
+ // Probably the application crashed before finishing RS importation
+ // Give user choice to resume it or discard
- OwningQPointer msgBox = new QMessageBox(
- QMessageBox::Warning,
- tr("RS Import"),
- tr("There is some rollingstock import data left in this file. "
- "Probably the application has crashed!
"
- "Before deleting it would you like to resume importation?
"
- "(Sorry for the crash, would you like to contact me and share information about it?)"),
- QMessageBox::NoButton, this);
+ OwningQPointer msgBox =
+ new QMessageBox(QMessageBox::Warning, tr("RS Import"),
+ tr("There is some rollingstock import data left in this file. "
+ "Probably the application has crashed!
"
+ "Before deleting it would you like to resume importation?
"
+ "(Sorry for the crash, would you like to contact me and share "
+ "information about it?)"),
+ QMessageBox::NoButton, this);
auto resumeBut = msgBox->addButton(tr("Resume importation"), QMessageBox::YesRole);
msgBox->addButton(tr("Just delete it"), QMessageBox::NoRole);
msgBox->setDefaultButton(resumeBut);
msgBox->setTextFormat(Qt::RichText);
msgBox->exec();
- if(!msgBox)
+ if (!msgBox)
return;
- if(msgBox->clickedButton() == resumeBut)
+ if (msgBox->clickedButton() == resumeBut)
{
Session->getViewManager()->resumeRSImportation();
- }else{
+ }
+ else
+ {
Session->clearImportRSTables();
}
}
}
-void MainWindow::setCurrentFile(const QString& fileName)
+void MainWindow::setCurrentFile(const QString &fileName)
{
DEBUG_ENTRY;
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
{
- setWindowFilePath(QString()); //Reset title bar
+ setWindowFilePath(QString()); // Reset title bar
return;
}
- //Qt automatically takes care of showing stripped filename in window title
+ // Qt automatically takes care of showing stripped filename in window title
setWindowFilePath(fileName);
QStringList files = AppSettings.getRecentFiles();
@@ -472,22 +482,23 @@ void MainWindow::setCurrentFile(const QString& fileName)
QString MainWindow::strippedName(const QString &fullFileName, bool *ok)
{
QFileInfo fi(fullFileName);
- if(ok) *ok = fi.exists();
+ if (ok)
+ *ok = fi.exists();
return fi.fileName();
}
void MainWindow::updateRecentFileActions()
{
DEBUG_ENTRY;
- QStringList files = AppSettings.getRecentFiles();
+ QStringList files = AppSettings.getRecentFiles();
int numRecentFiles = qMin(files.size(), int(MaxRecentFiles));
for (int i = 0; i < numRecentFiles; i++)
{
- bool ok = true;
+ bool ok = true;
QString name = strippedName(files[i], &ok);
- if(name.isEmpty() || !ok)
+ if (name.isEmpty() || !ok)
{
files.removeAt(i);
i--;
@@ -511,8 +522,8 @@ void MainWindow::updateRecentFileActions()
void MainWindow::onOpenRecent()
{
DEBUG_ENTRY;
- QAction *act = qobject_cast(sender());
- if(!act)
+ QAction *act = qobject_cast(sender());
+ if (!act)
return;
loadFile(act->data().toString());
@@ -527,15 +538,14 @@ void MainWindow::onNew()
#endif
#ifdef ENABLE_BACKGROUND_MANAGER
- if(Session->getBackgroundManager()->isRunning())
+ if (Session->getBackgroundManager()->isRunning())
{
- int ret = QMessageBox::warning(this,
- tr("Backgroung Task"),
- tr("Background task for checking rollingstock errors is still running.\n"
- "Do you want to cancel it?"),
- QMessageBox::Yes, QMessageBox::No,
- QMessageBox::Yes);
- if(ret == QMessageBox::Yes)
+ int ret = QMessageBox::warning(
+ this, tr("Backgroung Task"),
+ tr("Background task for checking rollingstock errors is still running.\n"
+ "Do you want to cancel it?"),
+ QMessageBox::Yes, QMessageBox::No, QMessageBox::Yes);
+ if (ret == QMessageBox::Yes)
Session->getBackgroundManager()->abortAllTasks();
else
return;
@@ -553,22 +563,21 @@ void MainWindow::onNew()
filters << FileFormats::tr(FileFormats::allFiles);
dlg->setNameFilters(filters);
- if(dlg->exec() != QDialog::Accepted || !dlg)
+ if (dlg->exec() != QDialog::Accepted || !dlg)
return;
QString fileName = dlg->selectedUrls().value(0).toLocalFile();
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
RecentDirStore::setPath(directory_key::session, fileName);
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- if(!QThreadPool::globalInstance()->waitForDone(2000))
+ if (!QThreadPool::globalInstance()->waitForDone(2000))
{
- QMessageBox::warning(this,
- tr("Background Tasks"),
+ QMessageBox::warning(this, tr("Background Tasks"),
tr("Some background tasks are still running.\n"
"The new file was not created. Try again."));
QApplication::restoreOverrideCursor();
@@ -576,17 +585,17 @@ void MainWindow::onNew()
}
QFile f(fileName);
- if(f.exists())
+ if (f.exists())
f.remove();
DB_Error err = Session->createNewDB(fileName);
QApplication::restoreOverrideCursor();
- if(err == DB_Error::DbBusyWhenClosing)
+ if (err == DB_Error::DbBusyWhenClosing)
showCloseWarning();
- if(err != DB_Error::NoError)
+ if (err != DB_Error::NoError)
return;
setCurrentFile(fileName);
@@ -595,7 +604,7 @@ void MainWindow::onNew()
void MainWindow::onSave()
{
- if(!Session->getViewManager()->closeEditors())
+ if (!Session->getViewManager()->closeEditors())
return;
Session->releaseAllSavepoints();
@@ -605,7 +614,7 @@ void MainWindow::onSaveCopyAs()
{
DEBUG_ENTRY;
- if(!Session->getViewManager()->closeEditors())
+ if (!Session->getViewManager()->closeEditors())
return;
OwningQPointer dlg = new QFileDialog(this, tr("Save Session Copy"));
@@ -619,29 +628,30 @@ void MainWindow::onSaveCopyAs()
filters << FileFormats::tr(FileFormats::allFiles);
dlg->setNameFilters(filters);
- if(dlg->exec() != QDialog::Accepted || !dlg)
+ if (dlg->exec() != QDialog::Accepted || !dlg)
return;
QString fileName = dlg->selectedUrls().value(0).toLocalFile();
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
RecentDirStore::setPath(directory_key::session, fileName);
QFile f(fileName);
- if(f.exists())
+ if (f.exists())
f.remove();
database backupDB(fileName.toUtf8(), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
- int rc = Session->m_Db.backup(backupDB, [](int pageCount, int remaining, int res)
+ int rc = Session->m_Db.backup(backupDB,
+ [](int pageCount, int remaining, int res)
{
Q_UNUSED(res)
qDebug() << pageCount << "/" << remaining;
});
- if(rc != SQLITE_OK && rc != SQLITE_DONE)
+ if (rc != SQLITE_OK && rc != SQLITE_DONE)
{
QString errMsg = Session->m_Db.error_msg();
qDebug() << Session->m_Db.error_code() << errMsg;
@@ -651,7 +661,7 @@ void MainWindow::onSaveCopyAs()
void MainWindow::closeEvent(QCloseEvent *e)
{
- if(closeSession())
+ if (closeSession())
e->accept();
else
e->ignore();
@@ -659,15 +669,14 @@ void MainWindow::closeEvent(QCloseEvent *e)
void MainWindow::showCloseWarning()
{
- QMessageBox::warning(this,
- tr("Error while Closing"),
+ QMessageBox::warning(this, tr("Error while Closing"),
tr("There was an error while closing the database.\n"
"Make sure there aren't any background tasks running and try again."));
}
void MainWindow::stopCloseTimer()
{
- if(closeTimerId)
+ if (closeTimerId)
{
killTimer(closeTimerId);
closeTimerId = 0;
@@ -701,36 +710,36 @@ void MainWindow::setCentralWidgetMode(MainWindow::CentralWidgetMode mode)
#endif // ENABLE_BACKGROUND_MANAGER
welcomeLabel->setText(
- tr("There are no lines in this session
"
- ""
- "
"
- ""
- "Start by creating the railway layout for this session: | "
- "
"
- ""
- ""
- ""
- ""
- "1. | "
- "Create stations (Edit > Stations) | "
- " "
- ""
- "2. | "
- "Create railway lines (Edit > Stations > Lines Tab) | "
- " "
- ""
- "3. | "
- "Add stations to railway lines | "
- " "
- ""
- " | "
- "(Edit > Stations > Lines Tab > Edit Line) | "
- " "
- " "
- " | "
- "
"
- "
"
- "
"));
+ tr("There are no lines in this session
"
+ ""
+ "
"
+ ""
+ "Start by creating the railway layout for this session: | "
+ "
"
+ ""
+ ""
+ ""
+ ""
+ "1. | "
+ "Create stations (Edit > Stations) | "
+ " "
+ ""
+ "2. | "
+ "Create railway lines (Edit > Stations > Lines Tab) | "
+ " "
+ ""
+ "3. | "
+ "Add stations to railway lines | "
+ " "
+ ""
+ " | "
+ "(Edit > Stations > Lines Tab > Edit Line) | "
+ " "
+ " "
+ " | "
+ "
"
+ "
"
+ ""));
break;
}
case CentralWidgetMode::ViewSessionMode:
@@ -748,37 +757,39 @@ void MainWindow::setCentralWidgetMode(MainWindow::CentralWidgetMode mode)
enableDBActions(mode != CentralWidgetMode::StartPageMode);
- if(mode == CentralWidgetMode::ViewSessionMode)
+ if (mode == CentralWidgetMode::ViewSessionMode)
{
- if(centralWidget() != view)
+ if (centralWidget() != view)
{
- takeCentralWidget(); //Remove ownership from welcomeLabel
+ takeCentralWidget(); // Remove ownership from welcomeLabel
setCentralWidget(view);
view->show();
welcomeLabel->hide();
}
- //Enable Job Creation
+ // Enable Job Creation
ui->actionAddJob->setEnabled(true);
ui->actionAddJob->setToolTip(tr("Add train job"));
- //Update actions based on Job selection
- JobStopEntry selectedJob = Session->getViewManager()->getLineGraphMgr()->getCurrentSelectedJob();
+ // Update actions based on Job selection
+ JobStopEntry selectedJob =
+ Session->getViewManager()->getLineGraphMgr()->getCurrentSelectedJob();
onJobSelected(selectedJob.jobId);
}
else
{
- if(centralWidget() != welcomeLabel)
+ if (centralWidget() != welcomeLabel)
{
- takeCentralWidget(); //Remove ownership from LineGraphWidget
+ takeCentralWidget(); // Remove ownership from LineGraphWidget
setCentralWidget(welcomeLabel);
view->hide();
welcomeLabel->show();
}
- //If there aren't lines prevent from creating jobs
+ // If there aren't lines prevent from creating jobs
ui->actionAddJob->setEnabled(false);
- ui->actionAddJob->setToolTip(tr("You must create at least one railway segment before adding job to this session"));
+ ui->actionAddJob->setToolTip(
+ tr("You must create at least one railway segment before adding job to this session"));
ui->actionRemoveJob->setEnabled(false);
}
@@ -799,8 +810,8 @@ void MainWindow::onProperties()
void MainWindow::onMeetingInformation()
{
OwningQPointer dlg = new MeetingInformationDialog(this);
- int ret = dlg->exec();
- if(dlg && ret == QDialog::Accepted)
+ int ret = dlg->exec();
+ if (dlg && ret == QDialog::Accepted)
dlg->saveData();
}
@@ -808,11 +819,11 @@ bool MainWindow::closeSession()
{
DB_Error err = Session->closeDB();
- if(err == DB_Error::DbBusyWhenClosing)
+ if (err == DB_Error::DbBusyWhenClosing)
{
- if(closeTimerId)
+ if (closeTimerId)
{
- //We already tried again
+ // We already tried again
stopCloseTimer();
@@ -820,19 +831,19 @@ bool MainWindow::closeSession()
return false;
}
- //Start a timer to try again
+ // Start a timer to try again
closeTimerId = startTimer(1500);
return false;
}
stopCloseTimer();
- if(err != DB_Error::NoError && err != DB_Error::DbNotOpen)
+ if (err != DB_Error::NoError && err != DB_Error::DbNotOpen)
return false;
setCentralWidgetMode(CentralWidgetMode::StartPageMode);
- //Reset filePath to refresh title
+ // Reset filePath to refresh title
setCurrentFile(QString());
return true;
@@ -842,7 +853,7 @@ void MainWindow::enableDBActions(bool enable)
{
databaseActionGroup->setEnabled(enable);
searchEdit->setEnabled(enable);
- if(!enable)
+ if (!enable)
jobEditor->setEnabled(false);
#ifdef ENABLE_BACKGROUND_MANAGER
@@ -924,30 +935,30 @@ void MainWindow::checkLineNumber()
{
RailwaySegmentHelper helper(Session->m_Db);
- bool isLine = false;
+ bool isLine = false;
db_id graphObjId = 0;
- if(!helper.findFirstLineOrSegment(graphObjId, isLine))
+ if (!helper.findFirstLineOrSegment(graphObjId, isLine))
graphObjId = 0;
- if(graphObjId && m_mode != CentralWidgetMode::ViewSessionMode)
+ if (graphObjId && m_mode != CentralWidgetMode::ViewSessionMode)
{
- //First line was added or newly opened file -> Session has at least one line
+ // First line was added or newly opened file -> Session has at least one line
setCentralWidgetMode(CentralWidgetMode::ViewSessionMode);
- //Load first line or segment
+ // Load first line or segment
view->tryLoadGraph(graphObjId,
isLine ? LineGraphType::RailwayLine : LineGraphType::RailwaySegment);
}
- else if(graphObjId == 0 && m_mode != CentralWidgetMode::NoLinesWarningMode)
+ else if (graphObjId == 0 && m_mode != CentralWidgetMode::NoLinesWarningMode)
{
- //Last line removed -> Session has no line
+ // Last line removed -> Session has no line
setCentralWidgetMode(CentralWidgetMode::NoLinesWarningMode);
}
}
void MainWindow::timerEvent(QTimerEvent *e)
{
- if(e->timerId() == closeTimerId)
+ if (e->timerId() == closeTimerId)
{
closeSession();
return;
@@ -964,38 +975,32 @@ void MainWindow::onJobSelected(db_id jobId)
ui->actionRemoveJob->setEnabled(selected);
QString removeJobTooltip;
- if(selected)
+ if (selected)
removeJobTooltip = tr("Remove selected Job");
else
removeJobTooltip = tr("First select a Job by double click on graph or type in search box");
ui->actionRemoveJob->setToolTip(removeJobTooltip);
}
-//QT-BUG 69922: If user closes a floating dock widget, when shown again it cannot dock anymore
-//HACK: intercept dock close event and manually re-dock and hide so next time is shown it's docked
-//NOTE: calling directly 'QDockWidget::setFloating(false)' from inside 'eventFinter()' causes CRASH
-// so queue it. Cannot use 'QMetaObject::invokeMethod()' because it's not a slot.
+// QT-BUG 69922: If user closes a floating dock widget, when shown again it cannot dock anymore
+// HACK: intercept dock close event and manually re-dock and hide so next time is shown it's docked
+// NOTE: calling directly 'QDockWidget::setFloating(false)' from inside 'eventFinter()' causes CRASH
+// so queue it. Cannot use 'QMetaObject::invokeMethod()' because it's not a slot.
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
- if(watched == jobDock && event->type() == QEvent::Close)
+ if (watched == jobDock && event->type() == QEvent::Close)
{
- if(jobDock->isFloating())
+ if (jobDock->isFloating())
{
- QTimer::singleShot(0, jobDock, [this]()
- {
- jobDock->setFloating(false);
- });
+ QTimer::singleShot(0, jobDock, [this]() { jobDock->setFloating(false); });
}
}
#ifdef ENABLE_BACKGROUND_MANAGER
- else if(watched == resPanelDock && event->type() == QEvent::Close)
+ else if (watched == resPanelDock && event->type() == QEvent::Close)
{
- if(resPanelDock->isFloating())
+ if (resPanelDock->isFloating())
{
- QTimer::singleShot(0, resPanelDock, [this]()
- {
- resPanelDock->setFloating(false);
- });
+ QTimer::singleShot(0, resPanelDock, [this]() { resPanelDock->setFloating(false); });
}
}
#endif // ENABLE_BACKGROUND_MANAGER
@@ -1012,10 +1017,10 @@ void MainWindow::onJobSearchItemSelected()
{
db_id jobId = 0;
QString tmp;
- if(!searchEdit->getData(jobId, tmp))
+ if (!searchEdit->getData(jobId, tmp))
return;
- searchEdit->clear(); //Clear text
+ searchEdit->clear(); // Clear text
Session->getViewManager()->requestJobSelection(jobId, true, true);
}
diff --git a/src/app/mainwindow.h b/src/app/mainwindow.h
index 5b58260..bdd9c98 100644
--- a/src/app/mainwindow.h
+++ b/src/app/mainwindow.h
@@ -57,7 +57,7 @@ public:
void loadFile(const QString &fileName);
bool closeSession();
-
+
private slots:
void onStationManager();
@@ -140,8 +140,11 @@ private:
QActionGroup *databaseActionGroup;
- enum { MaxRecentFiles = 5 };
- QAction* recentFileActs[MaxRecentFiles];
+ enum
+ {
+ MaxRecentFiles = 5
+ };
+ QAction *recentFileActs[MaxRecentFiles];
CentralWidgetMode m_mode;
diff --git a/src/app/propertiesdialog.cpp b/src/app/propertiesdialog.cpp
index f96cc3d..72ada0f 100644
--- a/src/app/propertiesdialog.cpp
+++ b/src/app/propertiesdialog.cpp
@@ -47,7 +47,7 @@ PropertiesDialog::PropertiesDialog(QWidget *parent) :
pathReadOnlyEdit->setPlaceholderText(tr("No opened file"));
pathReadOnlyEdit->setReadOnly(true);
- //TODO: make pretty and maybe add other informations like metadata versions
+ // TODO: make pretty and maybe add other informations like metadata versions
setMinimumSize(200, 200);
}
diff --git a/src/app/scopedebug.cpp b/src/app/scopedebug.cpp
index 75528eb..85483e8 100644
--- a/src/app/scopedebug.cpp
+++ b/src/app/scopedebug.cpp
@@ -28,19 +28,20 @@ Scope::Scope(const char *fn, const char *s, const char *e) :
start(s),
end(e)
{
- qDebug().nospace().noquote()
- << start << QByteArray(" ").repeated(stackLevel) << ">>> " << func << end;
+ qDebug().nospace().noquote() << start << QByteArray(" ").repeated(stackLevel) << ">>> " << func
+ << end;
stackLevel++;
}
Scope::~Scope()
{
stackLevel--;
- qDebug().nospace().noquote()
- << start << QByteArray(" ").repeated(stackLevel) << "<<< " << func << end;
+ qDebug().nospace().noquote() << start << QByteArray(" ").repeated(stackLevel) << "<<< " << func
+ << end;
}
-ScopeTimer::ScopeTimer(const char *fn, const char *s, const char *e) :Scope(fn, s, e)
+ScopeTimer::ScopeTimer(const char *fn, const char *s, const char *e) :
+ Scope(fn, s, e)
{
timer.start();
}
diff --git a/src/app/scopedebug.h b/src/app/scopedebug.h
index 743b67e..b1c0c25 100644
--- a/src/app/scopedebug.h
+++ b/src/app/scopedebug.h
@@ -20,57 +20,52 @@
#ifndef SCOPEDEBUG_H
#define SCOPEDEBUG_H
+#define SHELL_RESET "\033[0m"
-#define SHELL_RESET "\033[0m"
-
-#define SHELL_RED "\033[031m"
-#define SHELL_GREEN "\033[032m"
-#define SHELL_YELLOW "\033[033m"
-#define SHELL_BLUE "\033[034m"
-
+#define SHELL_RED "\033[031m"
+#define SHELL_GREEN "\033[032m"
+#define SHELL_YELLOW "\033[033m"
+#define SHELL_BLUE "\033[034m"
#include
#include
#include
-//#define NO_DEBUG_CALL_TRACE
+// #define NO_DEBUG_CALL_TRACE
#ifndef NO_DEBUG_CALL_TRACE
class Scope
{
public:
- Scope(const char *fn, const char *s="", const char* e="");
+ Scope(const char *fn, const char *s = "", const char *e = "");
~Scope();
const char *func, *start, *end;
};
-
class ScopeTimer : Scope
{
public:
- ScopeTimer(const char *fn, const char *s="", const char* e="");
+ ScopeTimer(const char *fn, const char *s = "", const char *e = "");
~ScopeTimer();
QElapsedTimer timer;
};
+# define DEBUG_ENTRY_NAME(name) Scope DBG(name)
+# define DEBUG_ENTRY DEBUG_ENTRY_NAME(__PRETTY_FUNCTION__)
+# define DEBUG_COLOR_ENTRY(color) Scope DBG(__PRETTY_FUNCTION__, color, SHELL_RESET)
+# define DEBUG_IMPORTANT_ENTRY DEBUG_COLOR_ENTRY(SHELL_GREEN)
-
-# define DEBUG_ENTRY_NAME(name) Scope DBG(name)
-# define DEBUG_ENTRY DEBUG_ENTRY_NAME(__PRETTY_FUNCTION__)
-# define DEBUG_COLOR_ENTRY(color) Scope DBG(__PRETTY_FUNCTION__, color, SHELL_RESET)
-# define DEBUG_IMPORTANT_ENTRY DEBUG_COLOR_ENTRY(SHELL_GREEN)
-
-# define DEBUG_TIME_ENTRY ScopeTimer DBG(__PRETTY_FUNCTION__)
+# define DEBUG_TIME_ENTRY ScopeTimer DBG(__PRETTY_FUNCTION__)
#else
-# define DEBUG_ENTRY_NAME(name)
-# define DEBUG_ENTRY
-# define DEBUG_COLOR_ENTRY(color)
-# define DEBUG_IMPORTANT_ENTRY
-# define DEBUG_TIME_ENTRY
+# define DEBUG_ENTRY_NAME(name)
+# define DEBUG_ENTRY
+# define DEBUG_COLOR_ENTRY(color)
+# define DEBUG_IMPORTANT_ENTRY
+# define DEBUG_TIME_ENTRY
#endif // NO_DEBUG_CALLTRACE
#endif // SCOPEDEBUG_H
diff --git a/src/app/session.cpp b/src/app/session.cpp
index f41e91f..acfd1ae 100644
--- a/src/app/session.cpp
+++ b/src/app/session.cpp
@@ -29,7 +29,7 @@
#include "db_metadata/metadatamanager.h"
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "backgroundmanager/backgroundmanager.h"
+# include "backgroundmanager/backgroundmanager.h"
#endif // ENABLE_BACKGROUND_MANAGER
#include
@@ -37,7 +37,7 @@
#include
-MeetingSession* MeetingSession::session;
+MeetingSession *MeetingSession::session;
QString MeetingSession::appDataPath;
const QLocale MeetingSession::embeddedLocale = QLocale(QLocale::English, QLocale::UnitedStates);
@@ -54,13 +54,14 @@ MeetingSession::MeetingSession() :
m_Db(nullptr),
sheetExportTranslator(nullptr)
{
- session = this; //Global singleton pointer
+ session = this; // Global singleton pointer
QString settings_file;
- if(qApp->arguments().contains("test"))
+ if (qApp->arguments().contains("test"))
{
- //If testing use exe folder instead of AppData
- settings_file = QCoreApplication::applicationDirPath() + QStringLiteral("/mrtp_settings.ini");
+ // If testing use exe folder instead of AppData
+ settings_file =
+ QCoreApplication::applicationDirPath() + QStringLiteral("/mrtp_settings.ini");
}
loadSettings(settings_file);
@@ -76,7 +77,7 @@ MeetingSession::MeetingSession() :
MeetingSession::~MeetingSession()
{
- //Delete sheet export translator
+ // Delete sheet export translator
setSheetExportTranslator(nullptr, sheetExportLocale);
}
@@ -90,29 +91,29 @@ DB_Error MeetingSession::openDB(const QString &str, bool ignoreVersion)
DEBUG_ENTRY;
DB_Error err = closeDB();
- if(err != DB_Error::NoError && err != DB_Error::DbNotOpen)
+ if (err != DB_Error::NoError && err != DB_Error::DbNotOpen)
{
return err;
}
- //try{
- if(m_Db.connect(str.toUtf8(), SQLITE_OPEN_READWRITE) != SQLITE_OK)
+ // try{
+ if (m_Db.connect(str.toUtf8(), SQLITE_OPEN_READWRITE) != SQLITE_OK)
{
- //throw database_error(m_Db);
+ // throw database_error(m_Db);
qWarning() << "DB:" << m_Db.error_msg();
return DB_Error::GenericError;
}
- if(!ignoreVersion)
+ if (!ignoreVersion)
{
qint64 version = 0;
switch (metaDataMgr->getInt64(version, MetaDataKey::FormatVersionKey))
{
case MetaDataKey::Result::ValueFound:
{
- if(version < FormatVersion)
+ if (version < FormatVersion)
return DB_Error::FormatTooOld;
- else if(version > FormatVersion)
+ else if (version > FormatVersion)
return DB_Error::FormatTooNew;
break;
}
@@ -123,38 +124,38 @@ DB_Error MeetingSession::openDB(const QString &str, bool ignoreVersion)
fileName = str;
- //Enable foreign keys to ensure no invalid operation is allowed
+ // Enable foreign keys to ensure no invalid operation is allowed
m_Db.enable_foreign_keys(true);
m_Db.enable_extended_result_codes(true);
-// }catch(const char *msg)
-// {
-// QMessageBox::warning(nullptr,
-// QObject::tr("Error"),
-// QObject::tr("Error while opening file:\n%1\n'%2'")
-// .arg(str)
-// .arg(msg));
-// throw;
-// return false;
-// }
-// catch(std::exception& e)
-// {
-// QMessageBox::warning(nullptr,
-// QObject::tr("Error"),
-// QObject::tr("Error while opening file:\n%1\n'%2'")
-// .arg(str)
-// .arg(e.what()));
-// throw;
-// return false;
-// }
-// catch(...)
-// {
-// QMessageBox::warning(nullptr,
-// QObject::tr("Error"),
-// QObject::tr("Unknown error while opening file:\n%1").arg(str));
-// throw;
-// return false;
-// }
+ // }catch(const char *msg)
+ // {
+ // QMessageBox::warning(nullptr,
+ // QObject::tr("Error"),
+ // QObject::tr("Error while opening file:\n%1\n'%2'")
+ // .arg(str)
+ // .arg(msg));
+ // throw;
+ // return false;
+ // }
+ // catch(std::exception& e)
+ // {
+ // QMessageBox::warning(nullptr,
+ // QObject::tr("Error"),
+ // QObject::tr("Error while opening file:\n%1\n'%2'")
+ // .arg(str)
+ // .arg(e.what()));
+ // throw;
+ // return false;
+ // }
+ // catch(...)
+ // {
+ // QMessageBox::warning(nullptr,
+ // QObject::tr("Error"),
+ // QObject::tr("Unknown error while opening file:\n%1").arg(str));
+ // throw;
+ // return false;
+ // }
#ifdef ENABLE_BACKGROUND_MANAGER
backgroundManager->handleSessionLoaded();
@@ -167,7 +168,7 @@ DB_Error MeetingSession::closeDB()
{
DEBUG_ENTRY;
- if(!m_Db.db())
+ if (!m_Db.db())
return DB_Error::DbNotOpen;
#ifdef SEARCHBOX_MODE_ASYNC
@@ -178,27 +179,27 @@ DB_Error MeetingSession::closeDB()
backgroundManager->abortAllTasks();
#endif
- if(!viewManager->closeEditors())
- return DB_Error::EditorsStillOpened; //User wants to continue editing
+ if (!viewManager->closeEditors())
+ return DB_Error::EditorsStillOpened; // User wants to continue editing
- //Close all graphs
+ // Close all graphs
viewManager->clearAllLineGraphs();
releaseAllSavepoints();
- //Calls sqlite3_close(), not forcing closing db like sqlite3_close_v2
- //So in case the database is still used by some background task (returns SQLITE_BUSY)
- //we abort closing and return. It's like nevere having closed, database is 100% working
+ // Calls sqlite3_close(), not forcing closing db like sqlite3_close_v2
+ // So in case the database is still used by some background task (returns SQLITE_BUSY)
+ // we abort closing and return. It's like nevere having closed, database is 100% working
int rc = m_Db.disconnect();
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
qWarning() << "Err: closing db" << m_Db.error_code() << m_Db.error_msg();
- if(rc == SQLITE_BUSY)
+ if (rc == SQLITE_BUSY)
{
return DB_Error::DbBusyWhenClosing;
}
- //return false;
+ // return false;
}
#ifdef ENABLE_BACKGROUND_MANAGER
@@ -210,22 +211,24 @@ DB_Error MeetingSession::closeDB()
return DB_Error::NoError;
}
-DB_Error MeetingSession::createNewDB(const QString& file)
+DB_Error MeetingSession::createNewDB(const QString &file)
{
DEBUG_ENTRY;
DB_Error err = closeDB();
- if(err != DB_Error::NoError && err != DB_Error::DbNotOpen)
+ if (err != DB_Error::NoError && err != DB_Error::DbNotOpen)
{
return err;
}
int result = SQLITE_OK;
-#define CHECK(code) if((code) != SQLITE_OK) qWarning() << __LINE__ << (code) << m_Db.error_code() << m_Db.error_msg()
+#define CHECK(code) \
+ if ((code) != SQLITE_OK) \
+ qWarning() << __LINE__ << (code) << m_Db.error_code() << m_Db.error_msg()
result = m_Db.connect(file.toUtf8(), SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
CHECK(result);
- //See 'openDB()'
+ // See 'openDB()'
m_Db.enable_foreign_keys(true);
m_Db.enable_extended_result_codes(true);
@@ -237,7 +240,7 @@ DB_Error MeetingSession::createNewDB(const QString& file)
* if not explicitly set, it will trigger SQLITE_CONSTRAINT_FOREIGNKEY error.
*/
- //Tables
+ // Tables
result = m_Db.execute("CREATE TABLE rs_models ("
"id INTEGER,"
"name TEXT,"
@@ -278,81 +281,87 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"CHECK(length(name)>0) )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE station_tracks ("
- "id INTEGER PRIMARY KEY,"
- "station_id INTEGER NOT NULL,"
- "pos INTEGER NOT NULL,"
- "type INTEGER NOT NULL,"
- "track_length_cm INTEGER NOT NULL,"
- "platf_length_cm INTEGET NOT NULL,"
- "freight_length_cm INTEGER NOT NULL,"
- "max_axes INTEGER NOT NULL,"
- "color_rgb INTEGER,"
- "name TEXT NOT NULL,"
- "CHECK("
- " length(name)>0 AND max_axes>=2 AND track_length_cm>0"
- " AND (platf_length_cm BETWEEN 0 AND track_length_cm)"
- " AND (freight_length_cm BETWEEN 0 AND track_length_cm)"
- "),"
- "UNIQUE(station_id, pos),"
- "UNIQUE(station_id, name),"
- "FOREIGN KEY (station_id) REFERENCES stations(id) ON UPDATE CASCADE ON DELETE CASCADE )");
+ result = m_Db.execute(
+ "CREATE TABLE station_tracks ("
+ "id INTEGER PRIMARY KEY,"
+ "station_id INTEGER NOT NULL,"
+ "pos INTEGER NOT NULL,"
+ "type INTEGER NOT NULL,"
+ "track_length_cm INTEGER NOT NULL,"
+ "platf_length_cm INTEGET NOT NULL,"
+ "freight_length_cm INTEGER NOT NULL,"
+ "max_axes INTEGER NOT NULL,"
+ "color_rgb INTEGER,"
+ "name TEXT NOT NULL,"
+ "CHECK("
+ " length(name)>0 AND max_axes>=2 AND track_length_cm>0"
+ " AND (platf_length_cm BETWEEN 0 AND track_length_cm)"
+ " AND (freight_length_cm BETWEEN 0 AND track_length_cm)"
+ "),"
+ "UNIQUE(station_id, pos),"
+ "UNIQUE(station_id, name),"
+ "FOREIGN KEY (station_id) REFERENCES stations(id) ON UPDATE CASCADE ON DELETE CASCADE )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE station_gates ("
- "id INTEGER PRIMARY KEY,"
- "station_id INTEGER NOT NULL,"
- "out_track_count INTEGER NOT NULL,"
- "type INTEGER NOT NULL,"
- "def_in_platf_id INTEGER,"
- "name TEXT NOT NULL,"
- "side INTEGER NOT NULL,"
- "CHECK("
- " out_track_count>0 AND (type&(1<<0) OR type&(1<<1))"
- " AND (length(name)=1 AND name BETWEEN 'A' AND 'Z')"
- ")," //NOTE: see utils::GateType
- "FOREIGN KEY (station_id) REFERENCES stations(id) ON UPDATE CASCADE ON DELETE CASCADE,"
- "FOREIGN KEY(def_in_platf_id) REFERENCES station_tracks(id) ON UPDATE CASCADE ON DELETE SET NULL,"
- "UNIQUE(station_id,name) )");
+ result = m_Db.execute(
+ "CREATE TABLE station_gates ("
+ "id INTEGER PRIMARY KEY,"
+ "station_id INTEGER NOT NULL,"
+ "out_track_count INTEGER NOT NULL,"
+ "type INTEGER NOT NULL,"
+ "def_in_platf_id INTEGER,"
+ "name TEXT NOT NULL,"
+ "side INTEGER NOT NULL,"
+ "CHECK("
+ " out_track_count>0 AND (type&(1<<0) OR type&(1<<1))"
+ " AND (length(name)=1 AND name BETWEEN 'A' AND 'Z')"
+ ")," // NOTE: see utils::GateType
+ "FOREIGN KEY (station_id) REFERENCES stations(id) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "FOREIGN KEY(def_in_platf_id) REFERENCES station_tracks(id) ON UPDATE CASCADE ON DELETE SET "
+ "NULL,"
+ "UNIQUE(station_id,name) )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE station_gate_connections ("
- "id INTEGER PRIMARY KEY,"
- "track_id INTEGER NOT NULL,"
- "track_side INTEGER NOT NULL,"
- "gate_id INTEGER NOT NULL,"
- "gate_track INTEGER NOT NULL,"
- "UNIQUE(gate_id,track_id,track_side,gate_track),"
- "FOREIGN KEY (track_id) REFERENCES station_tracks(id) ON UPDATE CASCADE ON DELETE CASCADE,"
- "FOREIGN KEY (gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE )");
+ result = m_Db.execute(
+ "CREATE TABLE station_gate_connections ("
+ "id INTEGER PRIMARY KEY,"
+ "track_id INTEGER NOT NULL,"
+ "track_side INTEGER NOT NULL,"
+ "gate_id INTEGER NOT NULL,"
+ "gate_track INTEGER NOT NULL,"
+ "UNIQUE(gate_id,track_id,track_side,gate_track),"
+ "FOREIGN KEY (track_id) REFERENCES station_tracks(id) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "FOREIGN KEY (gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE railway_segments ("
- "id INTEGER PRIMARY KEY,"
- "in_gate_id INTEGER NOT NULL,"
- "out_gate_id INTEGER NOT NULL,"
- "name TEXT,"
- "max_speed_kmh INTEGER NOT NULL,"
- "type INTEGER NOT NULL,"
- "distance_meters INTEGER NOT NULL,"
- "UNIQUE(in_gate_id),"
- "UNIQUE(out_gate_id),"
- "FOREIGN KEY(in_gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE,"
- "FOREIGN KEY(out_gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE,"
- "CHECK(in_gate_id<>out_gate_id AND"
- " max_speed_kmh>=10 AND"
- " distance_meters>=100 AND"
- " length(name)>0) )");
+ result = m_Db.execute(
+ "CREATE TABLE railway_segments ("
+ "id INTEGER PRIMARY KEY,"
+ "in_gate_id INTEGER NOT NULL,"
+ "out_gate_id INTEGER NOT NULL,"
+ "name TEXT,"
+ "max_speed_kmh INTEGER NOT NULL,"
+ "type INTEGER NOT NULL,"
+ "distance_meters INTEGER NOT NULL,"
+ "UNIQUE(in_gate_id),"
+ "UNIQUE(out_gate_id),"
+ "FOREIGN KEY(in_gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "FOREIGN KEY(out_gate_id) REFERENCES station_gates(id) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "CHECK(in_gate_id<>out_gate_id AND"
+ " max_speed_kmh>=10 AND"
+ " distance_meters>=100 AND"
+ " length(name)>0) )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE railway_connections ("
- "id INTEGER PRIMARY KEY,"
- "seg_id INTEGER NOT NULL,"
- "in_track INTEGER NOT NULL,"
- "out_track INTEGER NOT NULL,"
- "UNIQUE(seg_id,in_track),"
- "UNIQUE(seg_id,out_track),"
- "FOREIGN KEY(seg_id) REFERENCES railway_segments(id) ON UPDATE CASCADE ON DELETE RESTRICT )");
+ result = m_Db.execute(
+ "CREATE TABLE railway_connections ("
+ "id INTEGER PRIMARY KEY,"
+ "seg_id INTEGER NOT NULL,"
+ "in_track INTEGER NOT NULL,"
+ "out_track INTEGER NOT NULL,"
+ "UNIQUE(seg_id,in_track),"
+ "UNIQUE(seg_id,out_track),"
+ "FOREIGN KEY(seg_id) REFERENCES railway_segments(id) ON UPDATE CASCADE ON DELETE RESTRICT )");
CHECK(result);
result = m_Db.execute("CREATE TABLE lines ("
@@ -361,17 +370,18 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"start_meters INTEGER NOT NULL DEFAULT 0 )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE line_segments ("
- "id INTEGER PRIMARY KEY,"
- "line_id INTEGER NOT NULL,"
- "seg_id INTEGER NOT NULL,"
- "direction INTEGER NOT NULL,"
- "pos INTEGER NOT NULL,"
- "FOREIGN KEY(line_id) REFERENCES lines(id) ON UPDATE CASCADE ON DELETE CASCADE,"
- "FOREIGN KEY(seg_id) REFERENCES railway_segments(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
- "UNIQUE(line_id, seg_id)"
- "UNIQUE(line_id, pos)"
- "CHECK(pos<100) )"); //Allow up to 100 segments for each line
+ result = m_Db.execute(
+ "CREATE TABLE line_segments ("
+ "id INTEGER PRIMARY KEY,"
+ "line_id INTEGER NOT NULL,"
+ "seg_id INTEGER NOT NULL,"
+ "direction INTEGER NOT NULL,"
+ "pos INTEGER NOT NULL,"
+ "FOREIGN KEY(line_id) REFERENCES lines(id) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "FOREIGN KEY(seg_id) REFERENCES railway_segments(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
+ "UNIQUE(line_id, seg_id)"
+ "UNIQUE(line_id, pos)"
+ "CHECK(pos<100) )"); // Allow up to 100 segments for each line
CHECK(result);
result = m_Db.execute("CREATE TABLE jobshifts ("
@@ -379,34 +389,39 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"name TEXT UNIQUE NOT NULL)");
CHECK(result);
- result = m_Db.execute("CREATE TABLE jobs ("
- "id INTEGER PRIMARY KEY,"
- "category INTEGER NOT NULL DEFAULT 0,"
- "shift_id INTEGER,"
- "FOREIGN KEY(shift_id) REFERENCES jobshifts(id) ON UPDATE CASCADE ON DELETE RESTRICT)");
+ result = m_Db.execute(
+ "CREATE TABLE jobs ("
+ "id INTEGER PRIMARY KEY,"
+ "category INTEGER NOT NULL DEFAULT 0,"
+ "shift_id INTEGER,"
+ "FOREIGN KEY(shift_id) REFERENCES jobshifts(id) ON UPDATE CASCADE ON DELETE RESTRICT)");
CHECK(result);
- result = m_Db.execute("CREATE TABLE stops ("
- "id INTEGER PRIMARY KEY,"
- "job_id INTEGER NOT NULL,"
- "station_id INTEGER,"
- "arrival INTEGER NOT NULL,"
- "departure INTEGER NOT NULL,"
- "type INTEGER NOT NULL,"
- "description TEXT,"
+ result = m_Db.execute(
+ "CREATE TABLE stops ("
+ "id INTEGER PRIMARY KEY,"
+ "job_id INTEGER NOT NULL,"
+ "station_id INTEGER,"
+ "arrival INTEGER NOT NULL,"
+ "departure INTEGER NOT NULL,"
+ "type INTEGER NOT NULL,"
+ "description TEXT,"
- "in_gate_conn INTEGER,"
- "out_gate_conn INTEGER,"
- "next_segment_conn_id INTEGER,"
+ "in_gate_conn INTEGER,"
+ "out_gate_conn INTEGER,"
+ "next_segment_conn_id INTEGER,"
- "CHECK(arrival<=departure),"
- "UNIQUE(job_id,arrival),"
- "UNIQUE(job_id,departure),"
- "FOREIGN KEY(job_id) REFERENCES jobs(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
- "FOREIGN KEY(station_id) REFERENCES stations(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
- "FOREIGN KEY(in_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
- "FOREIGN KEY(out_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
- "FOREIGN KEY(next_segment_conn_id) REFERENCES railway_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT )");
+ "CHECK(arrival<=departure),"
+ "UNIQUE(job_id,arrival),"
+ "UNIQUE(job_id,departure),"
+ "FOREIGN KEY(job_id) REFERENCES jobs(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
+ "FOREIGN KEY(station_id) REFERENCES stations(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
+ "FOREIGN KEY(in_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT,"
+ "FOREIGN KEY(out_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT,"
+ "FOREIGN KEY(next_segment_conn_id) REFERENCES railway_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT )");
CHECK(result);
result = m_Db.execute("CREATE TABLE coupling ("
@@ -420,41 +435,47 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"UNIQUE(stop_id,rs_id))");
CHECK(result);
- //Create also backup tables to save old stops and couplings before editing a job and restore them if user cancels the edits.
- //NOTE: the structure of the table must be the same, remember to update theese if updating stops or couplings
+ // Create also backup tables to save old stops and couplings before editing a job and restore
+ // them if user cancels the edits. NOTE: the structure of the table must be the same, remember
+ // to update theese if updating stops or couplings
- result = m_Db.execute("CREATE TABLE old_stops ("
- "id INTEGER PRIMARY KEY,"
- "job_id INTEGER NOT NULL,"
- "station_id INTEGER,"
- "arrival INTEGER NOT NULL,"
- "departure INTEGER NOT NULL,"
- "type INTEGER NOT NULL,"
- "description TEXT,"
+ result = m_Db.execute(
+ "CREATE TABLE old_stops ("
+ "id INTEGER PRIMARY KEY,"
+ "job_id INTEGER NOT NULL,"
+ "station_id INTEGER,"
+ "arrival INTEGER NOT NULL,"
+ "departure INTEGER NOT NULL,"
+ "type INTEGER NOT NULL,"
+ "description TEXT,"
- "in_gate_conn INTEGER,"
- "out_gate_conn INTEGER,"
- "next_segment_conn_id INTEGER,"
+ "in_gate_conn INTEGER,"
+ "out_gate_conn INTEGER,"
+ "next_segment_conn_id INTEGER,"
- "CHECK(arrival<=departure),"
- "UNIQUE(job_id,arrival),"
- "UNIQUE(job_id,departure),"
- "FOREIGN KEY(job_id) REFERENCES jobs(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
- "FOREIGN KEY(station_id) REFERENCES stations(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
- "FOREIGN KEY(in_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
- "FOREIGN KEY(out_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT,"
- "FOREIGN KEY(next_segment_conn_id) REFERENCES railway_connections(id) ON UPDATE CASCADE ON DELETE RESTRICT )");
+ "CHECK(arrival<=departure),"
+ "UNIQUE(job_id,arrival),"
+ "UNIQUE(job_id,departure),"
+ "FOREIGN KEY(job_id) REFERENCES jobs(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
+ "FOREIGN KEY(station_id) REFERENCES stations(id) ON DELETE RESTRICT ON UPDATE CASCADE,"
+ "FOREIGN KEY(in_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT,"
+ "FOREIGN KEY(out_gate_conn) REFERENCES station_gate_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT,"
+ "FOREIGN KEY(next_segment_conn_id) REFERENCES railway_connections(id) ON UPDATE CASCADE ON "
+ "DELETE RESTRICT )");
CHECK(result);
- result = m_Db.execute("CREATE TABLE old_coupling ("
- "id INTEGER PRIMARY KEY,"
- "stop_id INTEGER,"
- "rs_id INTEGER,"
- "operation INTEGER NOT NULL DEFAULT 0,"
+ result =
+ m_Db.execute("CREATE TABLE old_coupling ("
+ "id INTEGER PRIMARY KEY,"
+ "stop_id INTEGER,"
+ "rs_id INTEGER,"
+ "operation INTEGER NOT NULL DEFAULT 0,"
- "FOREIGN KEY(stop_id) REFERENCES old_stops(id) ON DELETE CASCADE," //Old stops
- "FOREIGN KEY(rs_id) REFERENCES rs_list(id) ON DELETE RESTRICT,"
- "UNIQUE(stop_id,rs_id))");
+ "FOREIGN KEY(stop_id) REFERENCES old_stops(id) ON DELETE CASCADE," // Old stops
+ "FOREIGN KEY(rs_id) REFERENCES rs_list(id) ON DELETE RESTRICT,"
+ "UNIQUE(stop_id,rs_id))");
CHECK(result);
result = m_Db.execute("CREATE TABLE imported_rs_owners ("
@@ -465,7 +486,8 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"match_existing_id INTEGER,"
"sheet_idx INTEGER,"
"PRIMARY KEY(id),"
- "FOREIGN KEY(match_existing_id) REFERENCES rs_owners(id) ON UPDATE RESTRICT ON DELETE RESTRICT)");
+ "FOREIGN KEY(match_existing_id) REFERENCES rs_owners(id) ON UPDATE "
+ "RESTRICT ON DELETE RESTRICT)");
CHECK(result);
result = m_Db.execute("CREATE TABLE imported_rs_models ("
@@ -480,7 +502,8 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"type INTEGER,"
"sub_type INTEGER,"
"PRIMARY KEY(id),"
- "FOREIGN KEY(match_existing_id) REFERENCES rs_models(id) ON UPDATE RESTRICT ON DELETE RESTRICT)");
+ "FOREIGN KEY(match_existing_id) REFERENCES rs_models(id) ON UPDATE "
+ "RESTRICT ON DELETE RESTRICT)");
CHECK(result);
result = m_Db.execute("CREATE TABLE imported_rs_list ("
@@ -491,8 +514,10 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"number INTEGER,"
"new_number INTEGER,"
"PRIMARY KEY(id),"
- "FOREIGN KEY(model_id) REFERENCES imported_rs_models(id) ON UPDATE RESTRICT ON DELETE RESTRICT,"
- "FOREIGN KEY(owner_id) REFERENCES imported_rs_owners(id) ON UPDATE RESTRICT ON DELETE RESTRICT)");
+ "FOREIGN KEY(model_id) REFERENCES imported_rs_models(id) ON UPDATE "
+ "RESTRICT ON DELETE RESTRICT,"
+ "FOREIGN KEY(owner_id) REFERENCES imported_rs_owners(id) ON UPDATE "
+ "RESTRICT ON DELETE RESTRICT)");
CHECK(result);
result = m_Db.execute("CREATE TABLE metadata ("
@@ -500,50 +525,56 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"val BLOB)");
CHECK(result);
- //Triggers
+ // Triggers
- //Prevent multiple segments on same station gate
- result = m_Db.execute("CREATE TRIGGER multiple_gate_segments\n"
- "BEFORE INSERT ON railway_segments\n"
- "BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM railway_segments WHERE in_gate_id=NEW.out_gate_id OR out_gate_id=NEW.in_gate_id;"
- "END");
+ // Prevent multiple segments on same station gate
+ result =
+ m_Db.execute("CREATE TRIGGER multiple_gate_segments\n"
+ "BEFORE INSERT ON railway_segments\n"
+ "BEGIN\n"
+ "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM railway_segments "
+ "WHERE in_gate_id=NEW.out_gate_id OR out_gate_id=NEW.in_gate_id;"
+ "END");
CHECK(result);
result = m_Db.execute("CREATE TRIGGER multiple_gate_segments_update_in\n"
"BEFORE UPDATE OF in_gate_id ON railway_segments\n"
"BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM railway_segments WHERE out_gate_id=NEW.in_gate_id;"
+ "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM "
+ "railway_segments WHERE out_gate_id=NEW.in_gate_id;"
"END");
CHECK(result);
result = m_Db.execute("CREATE TRIGGER multiple_gate_segments_update_out\n"
"BEFORE UPDATE OF out_gate_id ON railway_segments\n"
"BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM railway_segments WHERE in_gate_id=NEW.out_gate_id;"
+ "SELECT RAISE(ABORT, 'Cannot connect same gate twice') FROM "
+ "railway_segments WHERE in_gate_id=NEW.out_gate_id;"
"END");
CHECK(result);
- //Prevent connecting a track to a gate of a different station
- result = m_Db.execute("CREATE TRIGGER gate_conn_different_station\n"
- "BEFORE INSERT ON station_gate_connections\n"
- "BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot connect platform of a different station') FROM station_tracks t"
- " JOIN station_gates g ON g.id=NEW.gate_id"
- " WHERE t.id=NEW.track_id AND t.station_id<>g.station_id;"
- "END");
+ // Prevent connecting a track to a gate of a different station
+ result = m_Db.execute(
+ "CREATE TRIGGER gate_conn_different_station\n"
+ "BEFORE INSERT ON station_gate_connections\n"
+ "BEGIN\n"
+ "SELECT RAISE(ABORT, 'Cannot connect platform of a different station') FROM station_tracks t"
+ " JOIN station_gates g ON g.id=NEW.gate_id"
+ " WHERE t.id=NEW.track_id AND t.station_id<>g.station_id;"
+ "END");
CHECK(result);
- result = m_Db.execute("CREATE TRIGGER gate_conn_different_station_update\n"
- "BEFORE UPDATE OF track_id,gate_id ON station_gate_connections\n"
- "BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot connect platform of a different station') FROM station_tracks t"
- " JOIN station_gates g ON g.id=NEW.gate_id"
- " WHERE t.id=NEW.track_id AND t.station_id<>g.station_id;"
- "END");
+ result = m_Db.execute(
+ "CREATE TRIGGER gate_conn_different_station_update\n"
+ "BEFORE UPDATE OF track_id,gate_id ON station_gate_connections\n"
+ "BEGIN\n"
+ "SELECT RAISE(ABORT, 'Cannot connect platform of a different station') FROM station_tracks t"
+ " JOIN station_gates g ON g.id=NEW.gate_id"
+ " WHERE t.id=NEW.track_id AND t.station_id<>g.station_id;"
+ "END");
CHECK(result);
- //FIXME: Remote possibility of updating 'station_id' of track or gate.
+ // FIXME: Remote possibility of updating 'station_id' of track or gate.
- //Prevent connecting gate track out of bound
+ // Prevent connecting gate track out of bound
result = m_Db.execute("CREATE TRIGGER gate_conn_gate_track_bound\n"
"BEFORE INSERT ON station_gate_connections\n"
"BEGIN\n"
@@ -563,18 +594,20 @@ DB_Error MeetingSession::createNewDB(const QString& file)
result = m_Db.execute("CREATE TRIGGER gate_out_track_bound_update\n"
"BEFORE UPDATE OF out_track_count ON station_gates\n"
"BEGIN\n"
- "SELECT RAISE(ABORT, 'Cannot remove gate tracks. Platforms connected.') FROM station_gate_connections c"
+ "SELECT RAISE(ABORT, 'Cannot remove gate tracks. Platforms connected.') "
+ "FROM station_gate_connections c"
" WHERE c.gate_id=NEW.id AND NEW.out_track_count<=c.gate_track;"
"END");
CHECK(result);
- //Prevent setting gate default track to a track which is not connected to it
+ // Prevent setting gate default track to a track which is not connected to it
result = m_Db.execute("CREATE TRIGGER gate_def_platf_not_connected\n"
"BEFORE INSERT ON station_gates\n"
"BEGIN\n"
"SELECT RAISE(ABORT, 'Platform not connected to this gate') WHERE"
" NEW.def_in_platf_id NOT NULL AND NOT EXISTS ("
- " SELECT 1 FROM station_gate_connections WHERE track_id=NEW.def_in_platf_id AND gate_id=NEW.id"
+ " SELECT 1 FROM station_gate_connections WHERE "
+ "track_id=NEW.def_in_platf_id AND gate_id=NEW.id"
");"
"END");
CHECK(result);
@@ -584,13 +617,13 @@ DB_Error MeetingSession::createNewDB(const QString& file)
"BEGIN\n"
"SELECT RAISE(ABORT, 'Platform not connected to this gate') WHERE"
" NEW.def_in_platf_id NOT NULL AND NOT EXISTS ("
- " SELECT 1 FROM station_gate_connections WHERE track_id=NEW.def_in_platf_id AND gate_id=NEW.id"
+ " SELECT 1 FROM station_gate_connections WHERE "
+ "track_id=NEW.def_in_platf_id AND gate_id=NEW.id"
");"
"END");
CHECK(result);
-//FIXME: if setting default gate track but then delete track connection -> invalid state
-
+ // FIXME: if setting default gate track but then delete track connection -> invalid state
#undef CHECK
@@ -605,25 +638,25 @@ DB_Error MeetingSession::createNewDB(const QString& file)
* Theese tables are used during RS importation and are cleared when the process
* completes or gets canceled by the user
* If they are not empty it might be because the application crashed before clearing theese tables
-*/
+ */
bool MeetingSession::checkImportRSTablesEmpty()
{
query q(m_Db, "SELECT COUNT(1) FROM imported_rs_list");
q.step();
int count = q.getRows().get(0);
- if(count)
+ if (count)
return false;
q.prepare("SELECT COUNT(1) FROM imported_rs_models");
q.step();
count = q.getRows().get(0);
- if(count)
+ if (count)
return false;
q.prepare("SELECT COUNT(1) FROM imported_rs_owners");
q.step();
count = q.getRows().get(0);
- if(count)
+ if (count)
return false;
return true;
}
@@ -631,15 +664,15 @@ bool MeetingSession::checkImportRSTablesEmpty()
bool MeetingSession::clearImportRSTables()
{
command cmd(m_Db, "DELETE FROM imported_rs_list");
- if(cmd.execute() != SQLITE_OK)
+ if (cmd.execute() != SQLITE_OK)
return false;
cmd.prepare("DELETE FROM imported_rs_models");
- if(cmd.execute() != SQLITE_OK)
+ if (cmd.execute() != SQLITE_OK)
return false;
cmd.prepare("DELETE FROM imported_rs_owners");
- if(cmd.execute() != SQLITE_OK)
+ if (cmd.execute() != SQLITE_OK)
return false;
return true;
@@ -647,15 +680,15 @@ bool MeetingSession::clearImportRSTables()
bool MeetingSession::setSavepoint(const QString &pointname)
{
- if(!m_Db.db())
+ if (!m_Db.db())
return false;
- if(savepointList.contains(pointname))
+ if (savepointList.contains(pointname))
return true;
QString sql = QStringLiteral("SAVEPOINT %1;");
- if(m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
+ if (m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
{
qDebug() << m_Db.error_msg();
return false;
@@ -667,15 +700,15 @@ bool MeetingSession::setSavepoint(const QString &pointname)
bool MeetingSession::releaseSavepoint(const QString &pointname)
{
- if(!m_Db.db())
+ if (!m_Db.db())
return false;
- if(!savepointList.contains(pointname))
+ if (!savepointList.contains(pointname))
return true;
QString sql = QStringLiteral("RELEASE %1;");
- if(m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
+ if (m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
{
qDebug() << m_Db.error_msg();
return false;
@@ -689,15 +722,15 @@ bool MeetingSession::releaseSavepoint(const QString &pointname)
bool MeetingSession::revertToSavepoint(const QString &pointname)
{
- if(!m_Db.db())
+ if (!m_Db.db())
return false;
- if(!savepointList.contains(pointname))
+ if (!savepointList.contains(pointname))
return false;
QString sql = QStringLiteral("ROLLBACK TO SAVEPOINT %1;");
- if(m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
+ if (m_Db.execute(sql.arg(pointname).toUtf8()) != SQLITE_OK)
{
qDebug() << m_Db.error_msg();
return false;
@@ -711,17 +744,17 @@ bool MeetingSession::revertToSavepoint(const QString &pointname)
bool MeetingSession::releaseAllSavepoints()
{
- if(!m_Db.db())
+ if (!m_Db.db())
return false;
- for(const QString& point : qAsConst(savepointList))
+ for (const QString &point : qAsConst(savepointList))
{
- if(!releaseSavepoint(point))
+ if (!releaseSavepoint(point))
return false;
}
// When still in a transaction, commit that too
- if(sqlite3_get_autocommit(m_Db.db()) == 0)
+ if (sqlite3_get_autocommit(m_Db.db()) == 0)
m_Db.execute("COMMIT;");
return true;
@@ -729,9 +762,9 @@ bool MeetingSession::releaseAllSavepoints()
bool MeetingSession::revertAll()
{
- for(const QString& point : qAsConst(savepointList))
+ for (const QString &point : qAsConst(savepointList))
{
- if(!revertToSavepoint(point))
+ if (!revertToSavepoint(point))
return false;
}
return true;
@@ -739,59 +772,59 @@ bool MeetingSession::revertAll()
QColor MeetingSession::colorForCat(JobCategory cat)
{
- QColor col = settings.getCategoryColor(int(cat)); //TODO: maybe session-specific
- if(col.isValid())
+ QColor col = settings.getCategoryColor(int(cat)); // TODO: maybe session-specific
+ if (col.isValid())
return col;
- return QColor(Qt::gray); //Error
+ return QColor(Qt::gray); // Error
}
void MeetingSession::locateAppdata()
{
appDataPath = QStringLiteral("%1/%2/%3")
- .arg(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation),
- AppCompany, AppProductShort);
+ .arg(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation),
+ AppCompany, AppProductShort);
appDataPath = QDir::cleanPath(appDataPath);
qDebug() << appDataPath;
}
void MeetingSession::setSheetExportTranslator(QTranslator *translator, const QLocale &loc)
{
- //NOTE: if Sheet Language is of Application Language then set a nullptr translator
- //If translator is valid use it
- //If translator is nullptr and language is default English locale, use hardcoded strings
- //If translator is nullptr and language is different from English, use default translations
+ // NOTE: if Sheet Language is of Application Language then set a nullptr translator
+ // If translator is valid use it
+ // If translator is nullptr and language is default English locale, use hardcoded strings
+ // If translator is nullptr and language is different from English, use default translations
- if(sheetExportTranslator && sheetExportTranslator != translator)
+ if (sheetExportTranslator && sheetExportTranslator != translator)
delete sheetExportTranslator;
sheetExportTranslator = translator;
- sheetExportLocale = loc;
+ sheetExportLocale = loc;
}
-void MeetingSession::loadSettings(const QString& settings_file)
+void MeetingSession::loadSettings(const QString &settings_file)
{
DEBUG_ENTRY;
- if(settings_file.isEmpty())
+ if (settings_file.isEmpty())
settings.loadSettings(appDataPath + QStringLiteral("/mrtp_settings.ini"));
else
settings.loadSettings(settings_file);
- hourOffset = settings.getHourOffset();
- stationOffset = settings.getStationOffset();
- horizOffset = settings.getHorizontalOffset();
- vertOffset = settings.getVerticalOffset();
- platformOffset = settings.getPlatformOffset();
+ hourOffset = settings.getHourOffset();
+ stationOffset = settings.getStationOffset();
+ horizOffset = settings.getHorizontalOffset();
+ vertOffset = settings.getVerticalOffset();
+ platformOffset = settings.getPlatformOffset();
- jobLineWidth = settings.getJobLineWidth();
+ jobLineWidth = settings.getJobLineWidth();
originalAppLocale = settings.getLanguage();
- //Default initialize to same value of application language
+ // Default initialize to same value of application language
setSheetExportTranslator(nullptr, originalAppLocale);
}
#ifdef ENABLE_BACKGROUND_MANAGER
-BackgroundManager* MeetingSession::getBackgroundManager() const
+BackgroundManager *MeetingSession::getBackgroundManager() const
{
return backgroundManager.get();
}
diff --git a/src/app/session.h b/src/app/session.h
index 5adf74d..82d9bbc 100644
--- a/src/app/session.h
+++ b/src/app/session.h
@@ -33,7 +33,6 @@ using namespace sqlite3pp;
#include
-
class ViewManager;
class MetaDataManager;
@@ -65,53 +64,60 @@ class MeetingSession : public QObject
Q_OBJECT
private:
- static MeetingSession* session;
+ static MeetingSession *session;
+
public:
MeetingSession();
~MeetingSession();
- static MeetingSession* Get();
+ static MeetingSession *Get();
- inline ViewManager* getViewManager() { return viewManager.get(); }
+ inline ViewManager *getViewManager()
+ {
+ return viewManager.get();
+ }
- inline MetaDataManager* getMetaDataManager() { return metaDataMgr.get(); }
+ inline MetaDataManager *getMetaDataManager()
+ {
+ return metaDataMgr.get();
+ }
#ifdef ENABLE_BACKGROUND_MANAGER
BackgroundManager *getBackgroundManager() const;
#endif
signals:
- //Shifts
+ // Shifts
void shiftAdded(db_id shiftId);
void shiftRemoved(db_id shiftId);
void shiftNameChanged(db_id shiftId);
- //A job was added/removed/modified belonging to this shift
+ // A job was added/removed/modified belonging to this shift
void shiftJobsChanged(db_id shiftId, db_id jobId);
- //Rollingstock
+ // Rollingstock
void rollingstockRemoved(db_id rsId);
void rollingStockPlanChanged(QSet rsIds);
void rollingStockModified(db_id rsId);
- //Jobs
+ // Jobs
void jobAdded(db_id jobId);
- void jobChanged(db_id jobId, db_id oldJobId); //Updated id/category/stops
+ void jobChanged(db_id jobId, db_id oldJobId); // Updated id/category/stops
void jobRemoved(db_id jobId);
- //Stations
+ // Stations
void stationNameChanged(db_id stationId);
- void stationJobsPlanChanged(const QSet& stationIds);
- void stationTrackPlanChanged(const QSet& stationIds);
+ void stationJobsPlanChanged(const QSet &stationIds);
+ void stationTrackPlanChanged(const QSet &stationIds);
void stationRemoved(db_id stationId);
- //Segments
+ // Segments
void segmentAdded(db_id segmentId);
void segmentNameChanged(db_id segmentId);
void segmentStationsChanged(db_id segmentId);
void segmentRemoved(db_id segmentId);
- //Lines
+ // Lines
void lineAdded(db_id lineId);
void lineNameChanged(db_id lineId);
void lineSegmentsChanged(db_id lineId);
@@ -126,45 +132,48 @@ private:
std::unique_ptr backgroundManager;
#endif
-//Settings TODO: remove
+ // Settings TODO: remove
public:
void loadSettings(const QString &settings_file);
MRTPSettings settings;
- int hourOffset;
- int stationOffset;
- qreal platformOffset;
+ int hourOffset;
+ int stationOffset;
+ qreal platformOffset;
- int horizOffset;
- int vertOffset;
+ int horizOffset;
+ int vertOffset;
int jobLineWidth;
-//Database
+ // Database
public:
database m_Db;
-//Job Categories:
+ // Job Categories:
public:
QColor colorForCat(JobCategory cat);
-//Savepoints TODO: seem unused
+ // Savepoints TODO: seem unused
public:
- inline bool getDBDirty() { return !savepointList.isEmpty(); }
+ inline bool getDBDirty()
+ {
+ return !savepointList.isEmpty();
+ }
- bool setSavepoint(const QString& pointname = "RESTOREPOINT");
- bool releaseSavepoint(const QString& pointname = "RESTOREPOINT");
- bool revertToSavepoint(const QString& pointname = "RESTOREPOINT");
+ bool setSavepoint(const QString &pointname = "RESTOREPOINT");
+ bool releaseSavepoint(const QString &pointname = "RESTOREPOINT");
+ bool revertToSavepoint(const QString &pointname = "RESTOREPOINT");
bool releaseAllSavepoints();
bool revertAll();
QStringList savepointList;
-//DB
+ // DB
public:
DB_Error createNewDB(const QString &file);
- DB_Error openDB(const QString& str, bool ignoreVersion);
+ DB_Error openDB(const QString &str, bool ignoreVersion);
DB_Error closeDB();
bool checkImportRSTablesEmpty();
@@ -172,7 +181,7 @@ public:
QString fileName;
-//AppData
+ // AppData
public:
static void locateAppdata();
static QString appDataPath;
@@ -228,14 +237,25 @@ public:
*/
static const QLocale embeddedLocale;
- void setSheetExportTranslator(QTranslator *translator, const QLocale& loc);
+ void setSheetExportTranslator(QTranslator *translator, const QLocale &loc);
- inline QTranslator *getSheetExportTranslator() const { return sheetExportTranslator; }
- inline QLocale getSheetExportLocale() const { return sheetExportLocale; }
- inline QLocale getAppLanguage() const { return originalAppLocale; }
+ inline QTranslator *getSheetExportTranslator() const
+ {
+ return sheetExportTranslator;
+ }
+
+ inline QLocale getSheetExportLocale() const
+ {
+ return sheetExportLocale;
+ }
+
+ inline QLocale getAppLanguage() const
+ {
+ return originalAppLocale;
+ }
};
-#define Session MeetingSession::Get()
+#define Session MeetingSession::Get()
#define AppSettings Session->settings
diff --git a/src/backgroundmanager/backgroundmanager.cpp b/src/backgroundmanager/backgroundmanager.cpp
index 41dc0d7..18ad7a2 100644
--- a/src/backgroundmanager/backgroundmanager.cpp
+++ b/src/backgroundmanager/backgroundmanager.cpp
@@ -20,25 +20,23 @@
#include "backgroundmanager.h"
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "backgroundmanager/ibackgroundchecker.h"
+# include "backgroundmanager/ibackgroundchecker.h"
-#include
-#include
+# include
+# include
BackgroundManager::BackgroundManager(QObject *parent) :
QObject(parent)
{
-
}
BackgroundManager::~BackgroundManager()
{
-
}
void BackgroundManager::handleSessionLoaded()
{
- for(IBackgroundChecker *mgr : qAsConst(checkers))
+ for (IBackgroundChecker *mgr : qAsConst(checkers))
mgr->startWorker();
}
@@ -46,19 +44,19 @@ void BackgroundManager::abortAllTasks()
{
emit abortTrivialTasks();
- for(IBackgroundChecker *mgr : qAsConst(checkers))
+ for (IBackgroundChecker *mgr : qAsConst(checkers))
mgr->abortTasks();
}
bool BackgroundManager::isRunning()
{
bool running = QThreadPool::globalInstance()->activeThreadCount() > 0;
- if(running)
+ if (running)
return true;
- for(IBackgroundChecker *mgr : qAsConst(checkers))
+ for (IBackgroundChecker *mgr : qAsConst(checkers))
{
- if(mgr->isRunning())
+ if (mgr->isRunning())
return true;
}
@@ -69,10 +67,8 @@ void BackgroundManager::addChecker(IBackgroundChecker *mgr)
{
checkers.append(mgr);
- connect(mgr, &IBackgroundChecker::destroyed, this, [this](QObject *self)
- {
- removeChecker(static_cast(self));
- });
+ connect(mgr, &IBackgroundChecker::destroyed, this,
+ [this](QObject *self) { removeChecker(static_cast(self)); });
emit checkerAdded(mgr);
}
@@ -86,7 +82,7 @@ void BackgroundManager::removeChecker(IBackgroundChecker *mgr)
void BackgroundManager::clearResults()
{
- for(IBackgroundChecker *mgr : qAsConst(checkers))
+ for (IBackgroundChecker *mgr : qAsConst(checkers))
{
mgr->clearModel();
}
diff --git a/src/backgroundmanager/backgroundmanager.h b/src/backgroundmanager/backgroundmanager.h
index ec47e3e..e5ee7d7 100644
--- a/src/backgroundmanager/backgroundmanager.h
+++ b/src/backgroundmanager/backgroundmanager.h
@@ -22,12 +22,12 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include
-#include
+# include
+# include
class IBackgroundChecker;
-//TODO: show a progress bar for all task like Qt Creator does
+// TODO: show a progress bar for all task like Qt Creator does
class BackgroundManager : public QObject
{
Q_OBJECT
diff --git a/src/backgroundmanager/backgroundresultpanel.cpp b/src/backgroundmanager/backgroundresultpanel.cpp
index e53ed5a..f616f29 100644
--- a/src/backgroundmanager/backgroundresultpanel.cpp
+++ b/src/backgroundmanager/backgroundresultpanel.cpp
@@ -19,13 +19,13 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "backgroundresultpanel.h"
+# include "backgroundresultpanel.h"
-#include "backgroundmanager/ibackgroundchecker.h"
-#include "backgroundresultwidget.h"
+# include "backgroundmanager/ibackgroundchecker.h"
+# include "backgroundresultwidget.h"
-#include "app/session.h"
-#include "backgroundmanager.h"
+# include "app/session.h"
+# include "backgroundmanager.h"
BackgroundResultPanel::BackgroundResultPanel(QWidget *parent) :
QTabWidget(parent)
@@ -34,7 +34,7 @@ BackgroundResultPanel::BackgroundResultPanel(QWidget *parent) :
connect(bkMgr, &BackgroundManager::checkerAdded, this, &BackgroundResultPanel::addChecker);
connect(bkMgr, &BackgroundManager::checkerRemoved, this, &BackgroundResultPanel::removeChecker);
- for(auto mgr : bkMgr->checkers)
+ for (auto mgr : bkMgr->checkers)
addChecker(mgr);
}
@@ -46,10 +46,10 @@ void BackgroundResultPanel::addChecker(IBackgroundChecker *mgr)
void BackgroundResultPanel::removeChecker(IBackgroundChecker *mgr)
{
- for(int i = 0; i < count(); i++)
+ for (int i = 0; i < count(); i++)
{
BackgroundResultWidget *w = static_cast(widget(i));
- if(w->mgr == mgr)
+ if (w->mgr == mgr)
{
removeTab(i);
delete w;
diff --git a/src/backgroundmanager/backgroundresultpanel.h b/src/backgroundmanager/backgroundresultpanel.h
index b1e23bd..f487601 100644
--- a/src/backgroundmanager/backgroundresultpanel.h
+++ b/src/backgroundmanager/backgroundresultpanel.h
@@ -22,7 +22,7 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include
+# include
class IBackgroundChecker;
diff --git a/src/backgroundmanager/backgroundresultwidget.cpp b/src/backgroundmanager/backgroundresultwidget.cpp
index e68c0e6..60a0f4a 100644
--- a/src/backgroundmanager/backgroundresultwidget.cpp
+++ b/src/backgroundmanager/backgroundresultwidget.cpp
@@ -19,21 +19,20 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "ibackgroundchecker.h"
-#include "backgroundresultwidget.h"
+# include "ibackgroundchecker.h"
+# include "backgroundresultwidget.h"
-#include
-#include
-#include
-#include
+# include
+# include
+# include
+# include
-#include
+# include
-#include
-#include
-
-#include
+# include
+# include
+# include
BackgroundResultWidget::BackgroundResultWidget(IBackgroundChecker *mgr_, QWidget *parent) :
QWidget(parent),
@@ -45,8 +44,8 @@ BackgroundResultWidget::BackgroundResultWidget(IBackgroundChecker *mgr_, QWidget
view->setSelectionBehavior(QTreeView::SelectRows);
progressBar = new QProgressBar;
- startBut = new QPushButton(tr("Start"));
- stopBut = new QPushButton(tr("Stop"));
+ startBut = new QPushButton(tr("Start"));
+ stopBut = new QPushButton(tr("Stop"));
startBut->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
stopBut->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
@@ -68,7 +67,8 @@ BackgroundResultWidget::BackgroundResultWidget(IBackgroundChecker *mgr_, QWidget
connect(stopBut, &QPushButton::clicked, this, &BackgroundResultWidget::stopTask);
view->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(view, &QTreeView::customContextMenuRequested, this, &BackgroundResultWidget::showContextMenu);
+ connect(view, &QTreeView::customContextMenuRequested, this,
+ &BackgroundResultWidget::showContextMenu);
setWindowTitle(tr("Error Results"));
@@ -79,11 +79,11 @@ void BackgroundResultWidget::startTask()
{
progressBar->setValue(0);
- if(mgr->startWorker())
+ if (mgr->startWorker())
{
- if(timerId)
+ if (timerId)
{
- killTimer(timerId); //Stop progressBar from hiding in 1 second
+ killTimer(timerId); // Stop progressBar from hiding in 1 second
timerId = 0;
}
}
@@ -105,14 +105,14 @@ void BackgroundResultWidget::taskFinished()
{
progressBar->setValue(progressBar->maximum());
- if(timerId)
+ if (timerId)
killTimer(timerId);
- timerId = startTimer(1000); //Hide progressBar after 1 second
+ timerId = startTimer(1000); // Hide progressBar after 1 second
}
void BackgroundResultWidget::timerEvent(QTimerEvent *e)
{
- if(e->timerId() == timerId)
+ if (e->timerId() == timerId)
{
killTimer(timerId);
timerId = 0;
@@ -120,10 +120,10 @@ void BackgroundResultWidget::timerEvent(QTimerEvent *e)
}
}
-void BackgroundResultWidget::showContextMenu(const QPoint& pos)
+void BackgroundResultWidget::showContextMenu(const QPoint &pos)
{
QModelIndex idx = view->indexAt(pos);
- if(!idx.isValid())
+ if (!idx.isValid())
return;
mgr->showContextMenu(this, view->viewport()->mapToGlobal(pos), idx);
diff --git a/src/backgroundmanager/backgroundresultwidget.h b/src/backgroundmanager/backgroundresultwidget.h
index 826cbb0..3a6084a 100644
--- a/src/backgroundmanager/backgroundresultwidget.h
+++ b/src/backgroundmanager/backgroundresultwidget.h
@@ -22,7 +22,7 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include
+# include
class QTreeView;
class QProgressBar;
diff --git a/src/backgroundmanager/ibackgroundchecker.cpp b/src/backgroundmanager/ibackgroundchecker.cpp
index 3167860..247da4b 100644
--- a/src/backgroundmanager/ibackgroundchecker.cpp
+++ b/src/backgroundmanager/ibackgroundchecker.cpp
@@ -19,25 +19,23 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include "ibackgroundchecker.h"
+# include "ibackgroundchecker.h"
-#include
-#include "utils/thread/iquittabletask.h"
-#include "utils/thread/taskprogressevent.h"
-
-#include "sqlite3pp/sqlite3pp.h"
+# include
+# include "utils/thread/iquittabletask.h"
+# include "utils/thread/taskprogressevent.h"
+# include "sqlite3pp/sqlite3pp.h"
IBackgroundChecker::IBackgroundChecker(sqlite3pp::database &db, QObject *parent) :
QObject(parent),
mDb(db)
{
-
}
bool IBackgroundChecker::event(QEvent *e)
{
- if(e->type() == TaskProgressEvent::_Type)
+ if (e->type() == TaskProgressEvent::_Type)
{
e->setAccepted(true);
@@ -46,14 +44,14 @@ bool IBackgroundChecker::event(QEvent *e)
return true;
}
- else if(e->type() == eventType)
+ else if (e->type() == eventType)
{
e->setAccepted(true);
GenericTaskEvent *ev = static_cast(e);
- if(m_mainWorker && ev->task == m_mainWorker)
+ if (m_mainWorker && ev->task == m_mainWorker)
{
- if(!m_mainWorker->wasStopped())
+ if (!m_mainWorker->wasStopped())
{
setErrors(ev, false);
}
@@ -66,10 +64,10 @@ bool IBackgroundChecker::event(QEvent *e)
else
{
int idx = m_workers.indexOf(ev->task);
- if(idx != -1)
+ if (idx != -1)
{
m_workers.removeAt(idx);
- if(!ev->task->wasStopped())
+ if (!ev->task->wasStopped())
setErrors(ev, true);
delete ev->task;
@@ -84,19 +82,19 @@ bool IBackgroundChecker::event(QEvent *e)
bool IBackgroundChecker::startWorker()
{
- if(m_mainWorker)
+ if (m_mainWorker)
return false;
- if(!mDb.db())
+ if (!mDb.db())
return false;
m_mainWorker = createMainWorker();
QThreadPool::globalInstance()->start(m_mainWorker);
- for(auto task = m_workers.begin(); task != m_workers.end(); task++)
+ for (auto task = m_workers.begin(); task != m_workers.end(); task++)
{
- if(QThreadPool::globalInstance()->tryTake(*task))
+ if (QThreadPool::globalInstance()->tryTake(*task))
{
IQuittableTask *ptr = *task;
m_workers.erase(task);
@@ -113,12 +111,12 @@ bool IBackgroundChecker::startWorker()
void IBackgroundChecker::abortTasks()
{
- if(m_mainWorker)
+ if (m_mainWorker)
{
m_mainWorker->stop();
}
- for(IQuittableTask *task : qAsConst(m_workers))
+ for (IQuittableTask *task : qAsConst(m_workers))
{
task->stop();
}
@@ -126,7 +124,7 @@ void IBackgroundChecker::abortTasks()
void IBackgroundChecker::sessionLoadedHandler()
{
- //no-op
+ // no-op
}
void IBackgroundChecker::addSubTask(IQuittableTask *task)
diff --git a/src/backgroundmanager/ibackgroundchecker.h b/src/backgroundmanager/ibackgroundchecker.h
index 572834b..765a868 100644
--- a/src/backgroundmanager/ibackgroundchecker.h
+++ b/src/backgroundmanager/ibackgroundchecker.h
@@ -22,8 +22,8 @@
#ifdef ENABLE_BACKGROUND_MANAGER
-#include
-#include
+# include
+# include
class QAbstractItemModel;
class QModelIndex;
@@ -47,13 +47,20 @@ public:
bool startWorker();
void abortTasks();
- inline bool isRunning() const { return m_mainWorker || m_workers.size() > 0; }
+ inline bool isRunning() const
+ {
+ return m_mainWorker || m_workers.size() > 0;
+ }
- inline QAbstractItemModel *getModel() const { return errorsModel; };
+ inline QAbstractItemModel *getModel() const
+ {
+ return errorsModel;
+ };
- virtual QString getName() const = 0;
- virtual void clearModel() = 0;
- virtual void showContextMenu(QWidget *panel, const QPoint& globalPos, const QModelIndex& idx) const = 0;
+ virtual QString getName() const = 0;
+ virtual void clearModel() = 0;
+ virtual void showContextMenu(QWidget *panel, const QPoint &globalPos,
+ const QModelIndex &idx) const = 0;
virtual void sessionLoadedHandler();
@@ -64,13 +71,13 @@ signals:
protected:
void addSubTask(IQuittableTask *task);
- virtual IQuittableTask *createMainWorker() = 0;
+ virtual IQuittableTask *createMainWorker() = 0;
virtual void setErrors(QEvent *e, bool merge) = 0;
protected:
sqlite3pp::database &mDb;
QAbstractItemModel *errorsModel = nullptr;
- int eventType = 0;
+ int eventType = 0;
private:
IQuittableTask *m_mainWorker = nullptr;
diff --git a/src/db_metadata/imagemetadata.cpp b/src/db_metadata/imagemetadata.cpp
index 15558ab..f58f61a 100644
--- a/src/db_metadata/imagemetadata.cpp
+++ b/src/db_metadata/imagemetadata.cpp
@@ -23,8 +23,7 @@
#include
-namespace ImageMetaData
-{
+namespace ImageMetaData {
constexpr char sql_get_key_id[] = "SELECT rowid FROM metadata WHERE name=? AND val NOT NULL";
@@ -35,7 +34,6 @@ ImageBlobDevice::ImageBlobDevice(sqlite3 *db, QObject *parent) :
mDb(db),
mBlob(nullptr)
{
-
}
ImageBlobDevice::~ImageBlobDevice()
@@ -45,40 +43,40 @@ ImageBlobDevice::~ImageBlobDevice()
void ImageBlobDevice::setBlobInfo(const QByteArray &table, const QByteArray &column, qint64 rowId)
{
- mRowId = rowId;
- mTable = table;
+ mRowId = rowId;
+ mTable = table;
mColumn = column;
}
bool ImageBlobDevice::reserveSizeAndReset(qint64 len)
{
- //NOTE: this will discard any previous content
+ // NOTE: this will discard any previous content
- //Close previous BLOB handle
- if(mBlob)
+ // Close previous BLOB handle
+ if (mBlob)
close();
- //Create SQL statement
- QByteArray sql = "UPDATE " + mTable + " SET " + mColumn + "=? WHERE rowId=?";
+ // Create SQL statement
+ QByteArray sql = "UPDATE " + mTable + " SET " + mColumn + "=? WHERE rowId=?";
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb, sql.constData(), sql.size(), &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc = sqlite3_prepare_v2(mDb, sql.constData(), sql.size(), &stmt, nullptr);
+ if (rc != SQLITE_OK)
{
qWarning() << "ImageBlobDevice::reserveSizeAndReset cannot prepare:" << sqlite3_errmsg(mDb);
setErrorString(tr("Cannot query database"));
return false;
}
- //Reserve BLOB memory
+ // Reserve BLOB memory
rc = sqlite3_bind_zeroblob64(stmt, 1, len);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return false;
}
rc = sqlite3_bind_int64(stmt, 2, mRowId);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return false;
@@ -88,30 +86,30 @@ bool ImageBlobDevice::reserveSizeAndReset(qint64 len)
sqlite3_finalize(stmt);
- if(rc != SQLITE_OK && rc != SQLITE_DONE)
+ if (rc != SQLITE_OK && rc != SQLITE_DONE)
{
qWarning() << "ImageBlobDevice::reserveSizeAndReset cannot step:" << sqlite3_errmsg(mDb);
setErrorString(tr("Cannot create BLOB"));
return false;
}
- //Open new BLOB handle
+ // Open new BLOB handle
return open(QIODevice::ReadWrite);
}
bool ImageBlobDevice::open(QIODevice::OpenMode mode)
{
- if(isOpen())
+ if (isOpen())
{
- qWarning().nospace() << "ImageBlobDevice::open Device already open "
- << '(' << mTable << '.' << mColumn << ')';
+ qWarning().nospace() << "ImageBlobDevice::open Device already open " << '(' << mTable << '.'
+ << mColumn << ')';
return false;
}
- mode |= QIODevice::ReadOnly; //Always enable reading
- int rc = sqlite3_blob_open(mDb, "main", mTable.constData(), mColumn.constData(),
- mRowId, (mode & QIODevice::WriteOnly) != 0, &mBlob);
- if(rc != SQLITE_OK || !mBlob)
+ mode |= QIODevice::ReadOnly; // Always enable reading
+ int rc = sqlite3_blob_open(mDb, "main", mTable.constData(), mColumn.constData(), mRowId,
+ (mode & QIODevice::WriteOnly) != 0, &mBlob);
+ if (rc != SQLITE_OK || !mBlob)
{
mBlob = nullptr;
setErrorString(sqlite3_errmsg(mDb));
@@ -127,7 +125,7 @@ bool ImageBlobDevice::open(QIODevice::OpenMode mode)
void ImageBlobDevice::close()
{
- if(mBlob)
+ if (mBlob)
{
sqlite3_blob_close(mBlob);
mBlob = nullptr;
@@ -144,21 +142,21 @@ qint64 ImageBlobDevice::size() const
qint64 ImageBlobDevice::writeData(const char *data, qint64 len)
{
- if(!mBlob)
+ if (!mBlob)
return -1;
int offset = int(pos());
- if(len + offset >= mSize)
+ if (len + offset >= mSize)
len = mSize - offset;
- if(!len)
+ if (!len)
return -1;
int rc = sqlite3_blob_write(mBlob, data, int(len), offset);
- if(rc == SQLITE_OK)
+ if (rc == SQLITE_OK)
return len;
- if(rc == SQLITE_READONLY)
+ if (rc == SQLITE_READONLY)
return -1;
setErrorString(sqlite3_errmsg(mDb));
@@ -167,45 +165,46 @@ qint64 ImageBlobDevice::writeData(const char *data, qint64 len)
qint64 ImageBlobDevice::readData(char *data, qint64 maxlen)
{
- if(!mBlob)
+ if (!mBlob)
return -1;
int offset = int(pos());
- if(maxlen + offset >= mSize)
+ if (maxlen + offset >= mSize)
maxlen = mSize - offset;
- if(!maxlen)
+ if (!maxlen)
return -1;
int rc = sqlite3_blob_read(mBlob, data, int(maxlen), offset);
- if(rc == SQLITE_OK)
+ if (rc == SQLITE_OK)
return maxlen;
setErrorString(sqlite3_errmsg(mDb));
return -1;
}
-ImageBlobDevice* getImage(sqlite3pp::database& db, const MetaDataManager::Key &key)
+ImageBlobDevice *getImage(sqlite3pp::database &db, const MetaDataManager::Key &key)
{
- if(!db.db())
+ if (!db.db())
return nullptr;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(db.db(), sql_get_key_id, sizeof (sql_get_key_id) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc =
+ sqlite3_prepare_v2(db.db(), sql_get_key_id, sizeof(sql_get_key_id) - 1, &stmt, nullptr);
+ if (rc != SQLITE_OK)
return nullptr;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return nullptr;
}
- rc = sqlite3_step(stmt);
+ rc = sqlite3_step(stmt);
qint64 rowId = 0;
- if(rc != SQLITE_ROW)
+ if (rc != SQLITE_ROW)
{
sqlite3_finalize(stmt);
return nullptr;
@@ -214,7 +213,7 @@ ImageBlobDevice* getImage(sqlite3pp::database& db, const MetaDataManager::Key &k
rowId = sqlite3_column_int64(stmt, 0);
sqlite3_finalize(stmt);
- if(!rowId)
+ if (!rowId)
return nullptr;
ImageBlobDevice *dev = new ImageBlobDevice(db.db());
@@ -222,11 +221,11 @@ ImageBlobDevice* getImage(sqlite3pp::database& db, const MetaDataManager::Key &k
return dev;
}
-void setImage(sqlite3pp::database& db, const MetaDataManager::Key &key, const void *data, int size)
+void setImage(sqlite3pp::database &db, const MetaDataManager::Key &key, const void *data, int size)
{
sqlite3pp::command cmd(db, "REPLACE INTO metadata(name, val) VALUES(?, ?)");
sqlite3_bind_text(cmd.stmt(), 1, key.str, key.len, SQLITE_STATIC);
- if(data)
+ if (data)
sqlite3_bind_blob(cmd.stmt(), 2, data, size, SQLITE_STATIC);
else
sqlite3_bind_null(cmd.stmt(), 2);
diff --git a/src/db_metadata/imagemetadata.h b/src/db_metadata/imagemetadata.h
index 41b7487..eceaa57 100644
--- a/src/db_metadata/imagemetadata.h
+++ b/src/db_metadata/imagemetadata.h
@@ -27,10 +27,9 @@
typedef struct sqlite3 sqlite3;
typedef struct sqlite3_blob sqlite3_blob;
-namespace ImageMetaData
-{
+namespace ImageMetaData {
-//TODO: move to utils
+// TODO: move to utils
class ImageBlobDevice : public QIODevice
{
Q_OBJECT
@@ -38,7 +37,7 @@ public:
ImageBlobDevice(sqlite3 *db, QObject *parent = nullptr);
~ImageBlobDevice() override;
- void setBlobInfo(const QByteArray& table, const QByteArray& column, qint64 rowId);
+ void setBlobInfo(const QByteArray &table, const QByteArray &column, qint64 rowId);
bool reserveSizeAndReset(qint64 len);
@@ -61,8 +60,8 @@ private:
QByteArray mColumn;
};
-ImageBlobDevice *getImage(sqlite3pp::database& db, const MetaDataManager::Key& key);
-void setImage(sqlite3pp::database& db, const MetaDataManager::Key &key, const void *data, int size);
+ImageBlobDevice *getImage(sqlite3pp::database &db, const MetaDataManager::Key &key);
+void setImage(sqlite3pp::database &db, const MetaDataManager::Key &key, const void *data, int size);
} // namespace ImageMetaData
diff --git a/src/db_metadata/meetinginformationdialog.cpp b/src/db_metadata/meetinginformationdialog.cpp
index 1aab591..32cfa6a 100644
--- a/src/db_metadata/meetinginformationdialog.cpp
+++ b/src/db_metadata/meetinginformationdialog.cpp
@@ -47,28 +47,34 @@ MeetingInformationDialog::MeetingInformationDialog(QWidget *parent) :
ui->setupUi(this);
connect(ui->viewPictureBut, &QPushButton::clicked, this, &MeetingInformationDialog::showImage);
- connect(ui->importPictureBut, &QPushButton::clicked, this, &MeetingInformationDialog::importImage);
- connect(ui->removePictureBut, &QPushButton::clicked, this, &MeetingInformationDialog::removeImage);
- connect(ui->resetHeaderBut, &QPushButton::clicked, this, &MeetingInformationDialog::toggleHeader);
- connect(ui->resetFooterBut, &QPushButton::clicked, this, &MeetingInformationDialog::toggleFooter);
- connect(ui->startDate, &QDateEdit::dateChanged, this, &MeetingInformationDialog::updateMinumumDate);
+ connect(ui->importPictureBut, &QPushButton::clicked, this,
+ &MeetingInformationDialog::importImage);
+ connect(ui->removePictureBut, &QPushButton::clicked, this,
+ &MeetingInformationDialog::removeImage);
+ connect(ui->resetHeaderBut, &QPushButton::clicked, this,
+ &MeetingInformationDialog::toggleHeader);
+ connect(ui->resetFooterBut, &QPushButton::clicked, this,
+ &MeetingInformationDialog::toggleFooter);
+ connect(ui->startDate, &QDateEdit::dateChanged, this,
+ &MeetingInformationDialog::updateMinumumDate);
QSizePolicy sp = ui->headerEdit->sizePolicy();
sp.setRetainSizeWhenHidden(true);
ui->headerEdit->setSizePolicy(sp);
ui->footerEdit->setSizePolicy(sp);
- //Use similar font to the actual font used in sheet export
+ // Use similar font to the actual font used in sheet export
QFont font;
font.setBold(true);
font.setPointSize(18);
ui->descrEdit->document()->setDefaultFont(font);
- if(!loadData())
+ if (!loadData())
{
QMessageBox::warning(this, tr("Database Error"),
tr("This database doesn't support metadata.\n"
- "Make sure it was created by a recent version of the application and was not manipulated."));
+ "Make sure it was created by a recent version of the application "
+ "and was not manipulated."));
setDisabled(true);
}
}
@@ -82,7 +88,7 @@ bool MeetingInformationDialog::loadData()
{
MetaDataManager *meta = Session->getMetaDataManager();
- qint64 tmp = 0;
+ qint64 tmp = 0;
QDate date;
switch (meta->getInt64(tmp, MetaDataKey::MeetingStartDate))
@@ -93,7 +99,7 @@ bool MeetingInformationDialog::loadData()
break;
}
case MetaDataKey::Result::NoMetaDataTable:
- return false; //Database has no well-formed metadata
+ return false; // Database has no well-formed metadata
default:
date = QDate::currentDate();
}
@@ -126,7 +132,7 @@ bool MeetingInformationDialog::loadData()
text.clear();
meta->getString(text, MetaDataKey::MeetingDescription);
ui->descrEdit->setPlainText(text);
- //Align all text to center
+ // Align all text to center
QTextCursor c = ui->descrEdit->textCursor();
c.select(QTextCursor::Document);
QTextBlockFormat fmt;
@@ -145,11 +151,12 @@ bool MeetingInformationDialog::loadData()
return true;
}
-void MeetingInformationDialog::setSheetText(QLineEdit *lineEdit, QPushButton *but, const QString& text, bool isNull)
+void MeetingInformationDialog::setSheetText(QLineEdit *lineEdit, QPushButton *but,
+ const QString &text, bool isNull)
{
lineEdit->setVisible(!isNull);
- if(isNull)
+ if (isNull)
{
but->setText(tr("Set custom text"));
lineEdit->setText(QString());
@@ -170,15 +177,18 @@ void MeetingInformationDialog::saveData()
meta->setInt64(ui->showDatesBox->isChecked() ? 1 : 0, false, MetaDataKey::MeetingShowDates);
meta->setString(ui->locationEdit->text().simplified(), false, MetaDataKey::MeetingLocation);
- meta->setString(ui->associationEdit->text().simplified(), false, MetaDataKey::MeetingHostAssociation);
+ meta->setString(ui->associationEdit->text().simplified(), false,
+ MetaDataKey::MeetingHostAssociation);
meta->setString(ui->descrEdit->toPlainText(), false, MetaDataKey::MeetingDescription);
- meta->setString(ui->headerEdit->text().simplified(), headerIsNull, MetaDataKey::SheetHeaderText);
- meta->setString(ui->footerEdit->text().simplified(), footerIsNull, MetaDataKey::SheetFooterText);
+ meta->setString(ui->headerEdit->text().simplified(), headerIsNull,
+ MetaDataKey::SheetHeaderText);
+ meta->setString(ui->footerEdit->text().simplified(), footerIsNull,
+ MetaDataKey::SheetFooterText);
- if(needsToSaveImg)
+ if (needsToSaveImg)
{
- if(img.isNull())
+ if (img.isNull())
{
ImageMetaData::setImage(Session->m_Db, MetaDataKey::MeetingLogoPicture, nullptr, 0);
}
@@ -189,10 +199,13 @@ void MeetingInformationDialog::saveData()
buf.open(QIODevice::WriteOnly);
QImageWriter writer(&buf, "PNG");
- if(writer.canWrite() && writer.write(img))
+ if (writer.canWrite() && writer.write(img))
+ {
+ ImageMetaData::setImage(Session->m_Db, MetaDataKey::MeetingLogoPicture, arr.data(),
+ arr.size());
+ }
+ else
{
- ImageMetaData::setImage(Session->m_Db, MetaDataKey::MeetingLogoPicture, arr.data(), arr.size());
- }else{
qDebug() << "MeetingInformationDialog: error saving image," << writer.errorString();
}
}
@@ -203,25 +216,28 @@ void MeetingInformationDialog::showImage()
{
OwningQPointer dlg = new ImageViewer(this);
- if(img.isNull() && !needsToSaveImg)
+ if (img.isNull() && !needsToSaveImg)
{
std::unique_ptr imageIO;
imageIO.reset(ImageMetaData::getImage(Session->m_Db, MetaDataKey::MeetingLogoPicture));
- if(imageIO && imageIO->open(QIODevice::ReadOnly))
+ if (imageIO && imageIO->open(QIODevice::ReadOnly))
{
QImageReader reader(imageIO.get());
- if(reader.canRead())
+ if (reader.canRead())
{
- img = reader.read(); //ERRORMSG: handle errors, show to user
+ img = reader.read(); // ERRORMSG: handle errors, show to user
}
- if(img.isNull())
+ if (img.isNull())
{
- qDebug() << "MeetingInformationDialog: error loading image," << reader.errorString();
+ qDebug() << "MeetingInformationDialog: error loading image,"
+ << reader.errorString();
}
imageIO->close();
- }else{
+ }
+ else
+ {
qDebug() << "MeetingInformationDialog: error query image," << Session->m_Db.error_msg();
}
}
@@ -230,15 +246,15 @@ void MeetingInformationDialog::showImage()
dlg->exec();
- if(!needsToSaveImg)
- img = QImage(); //Cleanup to free memory
+ if (!needsToSaveImg)
+ img = QImage(); // Cleanup to free memory
}
void MeetingInformationDialog::importImage()
{
const QLatin1String meeting_image_key = QLatin1String("meeting_image_key");
- OwningQPointer dlg = new QFileDialog(this, tr("Import image"));
+ OwningQPointer dlg = new QFileDialog(this, tr("Import image"));
dlg->setFileMode(QFileDialog::ExistingFile);
dlg->setAcceptMode(QFileDialog::AcceptOpen);
dlg->setDirectory(RecentDirStore::getDir(meeting_image_key, RecentDirStore::Images));
@@ -246,28 +262,28 @@ void MeetingInformationDialog::importImage()
QList mimes = QImageReader::supportedMimeTypes();
QStringList filters;
filters.reserve(mimes.size() + 1);
- for(const QByteArray &ba : mimes)
+ for (const QByteArray &ba : mimes)
filters.append(QString::fromUtf8(ba));
filters << "application/octet-stream"; // will show "All files (*)"
dlg->setMimeTypeFilters(filters);
- if(dlg->exec() != QDialog::Accepted || !dlg)
+ if (dlg->exec() != QDialog::Accepted || !dlg)
return;
QString fileName = dlg->selectedUrls().value(0).toLocalFile();
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
RecentDirStore::setPath(meeting_image_key, fileName);
QImageReader reader(fileName);
reader.setQuality(100);
- if(reader.canRead())
+ if (reader.canRead())
{
QImage image = reader.read();
- if(image.isNull())
+ if (image.isNull())
{
QMessageBox::warning(this, tr("Importing error"),
tr("The image format is not supported or the file is corrupted."));
@@ -275,7 +291,7 @@ void MeetingInformationDialog::importImage()
return;
}
- img = image;
+ img = image;
needsToSaveImg = true;
}
}
@@ -284,10 +300,10 @@ void MeetingInformationDialog::removeImage()
{
int ret = QMessageBox::question(this, tr("Remove image?"),
tr("Are you sure to remove the image logo?"));
- if(ret != QMessageBox::Yes)
+ if (ret != QMessageBox::Yes)
return;
- img = QImage(); //Cleanup to free memory
+ img = QImage(); // Cleanup to free memory
needsToSaveImg = true;
}
diff --git a/src/db_metadata/metadatamanager.cpp b/src/db_metadata/metadatamanager.cpp
index 1a85313..9172ba4 100644
--- a/src/db_metadata/metadatamanager.cpp
+++ b/src/db_metadata/metadatamanager.cpp
@@ -21,29 +21,29 @@
#include
-constexpr char sql_get_metadata[] = "SELECT val FROM metadata WHERE name=?";
+constexpr char sql_get_metadata[] = "SELECT val FROM metadata WHERE name=?";
constexpr char sql_has_metadata_key[] = "SELECT 1 FROM metadata WHERE name=? AND val NOT NULL";
-constexpr char sql_set_metadata[] = "REPLACE INTO metadata(name, val) VALUES(?, ?)";
+constexpr char sql_set_metadata[] = "REPLACE INTO metadata(name, val) VALUES(?, ?)";
MetaDataManager::MetaDataManager(sqlite3pp::database &db) :
mDb(db)
{
-
}
MetaDataKey::Result MetaDataManager::hasKey(const MetaDataManager::Key &key)
{
MetaDataKey::Result result = MetaDataKey::Result::NoMetaDataTable;
- if(!mDb.db())
+ if (!mDb.db())
return result;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb.db(), sql_has_metadata_key, sizeof (sql_has_metadata_key) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc = sqlite3_prepare_v2(mDb.db(), sql_has_metadata_key, sizeof(sql_has_metadata_key) - 1,
+ &stmt, nullptr);
+ if (rc != SQLITE_OK)
return result;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -51,11 +51,11 @@ MetaDataKey::Result MetaDataManager::hasKey(const MetaDataManager::Key &key)
rc = sqlite3_step(stmt);
- if(rc == SQLITE_ROW)
+ if (rc == SQLITE_ROW)
{
result = MetaDataKey::Result::ValueFound;
}
- else if(rc == SQLITE_OK || rc == SQLITE_DONE)
+ else if (rc == SQLITE_OK || rc == SQLITE_DONE)
{
result = MetaDataKey::Result::ValueNotFound;
}
@@ -68,19 +68,20 @@ MetaDataKey::Result MetaDataManager::hasKey(const MetaDataManager::Key &key)
return result;
}
-MetaDataKey::Result MetaDataManager::getInt64(qint64 &out, const Key& key)
+MetaDataKey::Result MetaDataManager::getInt64(qint64 &out, const Key &key)
{
MetaDataKey::Result result = MetaDataKey::Result::NoMetaDataTable;
- if(!mDb.db())
+ if (!mDb.db())
return result;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb.db(), sql_get_metadata, sizeof (sql_get_metadata) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc =
+ sqlite3_prepare_v2(mDb.db(), sql_get_metadata, sizeof(sql_get_metadata) - 1, &stmt, nullptr);
+ if (rc != SQLITE_OK)
return result;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -88,19 +89,19 @@ MetaDataKey::Result MetaDataManager::getInt64(qint64 &out, const Key& key)
rc = sqlite3_step(stmt);
- if(rc == SQLITE_ROW)
+ if (rc == SQLITE_ROW)
{
- if(sqlite3_column_type(stmt, 0) == SQLITE_NULL)
+ if (sqlite3_column_type(stmt, 0) == SQLITE_NULL)
{
result = MetaDataKey::Result::ValueIsNull;
}
else
{
result = MetaDataKey::Result::ValueFound;
- out = sqlite3_column_int64(stmt, 0);
+ out = sqlite3_column_int64(stmt, 0);
}
}
- else if(rc == SQLITE_OK || rc == SQLITE_DONE)
+ else if (rc == SQLITE_OK || rc == SQLITE_DONE)
{
result = MetaDataKey::Result::ValueNotFound;
}
@@ -113,29 +114,30 @@ MetaDataKey::Result MetaDataManager::getInt64(qint64 &out, const Key& key)
return result;
}
-MetaDataKey::Result MetaDataManager::setInt64(qint64 in, bool setToNull, const Key& key)
+MetaDataKey::Result MetaDataManager::setInt64(qint64 in, bool setToNull, const Key &key)
{
MetaDataKey::Result result = MetaDataKey::Result::NoMetaDataTable;
- if(!mDb.db())
+ if (!mDb.db())
return result;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb.db(), sql_set_metadata, sizeof (sql_set_metadata) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc =
+ sqlite3_prepare_v2(mDb.db(), sql_set_metadata, sizeof(sql_set_metadata) - 1, &stmt, nullptr);
+ if (rc != SQLITE_OK)
return result;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
}
- if(setToNull)
+ if (setToNull)
rc = sqlite3_bind_null(stmt, 2);
else
rc = sqlite3_bind_int64(stmt, 2, in);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -143,7 +145,7 @@ MetaDataKey::Result MetaDataManager::setInt64(qint64 in, bool setToNull, const K
rc = sqlite3_step(stmt);
- if(rc == SQLITE_OK || rc == SQLITE_DONE)
+ if (rc == SQLITE_OK || rc == SQLITE_DONE)
{
result = MetaDataKey::Result::ValueFound;
}
@@ -156,19 +158,20 @@ MetaDataKey::Result MetaDataManager::setInt64(qint64 in, bool setToNull, const K
return result;
}
-MetaDataKey::Result MetaDataManager::getString(QString &out, const Key& key)
+MetaDataKey::Result MetaDataManager::getString(QString &out, const Key &key)
{
MetaDataKey::Result result = MetaDataKey::Result::NoMetaDataTable;
- if(!mDb.db())
+ if (!mDb.db())
return result;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb.db(), sql_get_metadata, sizeof (sql_get_metadata) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc =
+ sqlite3_prepare_v2(mDb.db(), sql_get_metadata, sizeof(sql_get_metadata) - 1, &stmt, nullptr);
+ if (rc != SQLITE_OK)
return result;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -176,21 +179,21 @@ MetaDataKey::Result MetaDataManager::getString(QString &out, const Key& key)
rc = sqlite3_step(stmt);
- if(rc == SQLITE_ROW)
+ if (rc == SQLITE_ROW)
{
- if(sqlite3_column_type(stmt, 0) == SQLITE_NULL)
+ if (sqlite3_column_type(stmt, 0) == SQLITE_NULL)
{
result = MetaDataKey::Result::ValueIsNull;
}
else
{
- result = MetaDataKey::Result::ValueFound;
- const int len = sqlite3_column_bytes(stmt, 0);
- const char *text = reinterpret_cast(sqlite3_column_text(stmt, 0));
- out = QString::fromUtf8(text, len);
+ result = MetaDataKey::Result::ValueFound;
+ const int len = sqlite3_column_bytes(stmt, 0);
+ const char *text = reinterpret_cast(sqlite3_column_text(stmt, 0));
+ out = QString::fromUtf8(text, len);
}
}
- else if(rc == SQLITE_OK || rc == SQLITE_DONE)
+ else if (rc == SQLITE_OK || rc == SQLITE_DONE)
{
result = MetaDataKey::Result::ValueNotFound;
}
@@ -203,19 +206,20 @@ MetaDataKey::Result MetaDataManager::getString(QString &out, const Key& key)
return result;
}
-MetaDataKey::Result MetaDataManager::setString(const QString& in, bool setToNull, const Key& key)
+MetaDataKey::Result MetaDataManager::setString(const QString &in, bool setToNull, const Key &key)
{
MetaDataKey::Result result = MetaDataKey::Result::NoMetaDataTable;
- if(!mDb.db())
+ if (!mDb.db())
return result;
sqlite3_stmt *stmt = nullptr;
- int rc = sqlite3_prepare_v2(mDb.db(), sql_set_metadata, sizeof (sql_set_metadata) - 1, &stmt, nullptr);
- if(rc != SQLITE_OK)
+ int rc =
+ sqlite3_prepare_v2(mDb.db(), sql_set_metadata, sizeof(sql_set_metadata) - 1, &stmt, nullptr);
+ if (rc != SQLITE_OK)
return result;
rc = sqlite3_bind_text(stmt, 1, key.str, key.len, SQLITE_STATIC);
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -223,13 +227,13 @@ MetaDataKey::Result MetaDataManager::setString(const QString& in, bool setToNull
QByteArray arr = in.toUtf8();
- if(setToNull)
+ if (setToNull)
rc = sqlite3_bind_null(stmt, 2);
else
{
rc = sqlite3_bind_text(stmt, 2, arr.data(), arr.size(), SQLITE_STATIC);
}
- if(rc != SQLITE_OK)
+ if (rc != SQLITE_OK)
{
sqlite3_finalize(stmt);
return result;
@@ -237,7 +241,7 @@ MetaDataKey::Result MetaDataManager::setString(const QString& in, bool setToNull
rc = sqlite3_step(stmt);
- if(rc == SQLITE_OK || rc == SQLITE_DONE)
+ if (rc == SQLITE_OK || rc == SQLITE_DONE)
{
result = MetaDataKey::Result::ValueFound;
}
diff --git a/src/db_metadata/metadatamanager.h b/src/db_metadata/metadatamanager.h
index f9dd397..3b91272 100644
--- a/src/db_metadata/metadatamanager.h
+++ b/src/db_metadata/metadatamanager.h
@@ -27,42 +27,46 @@ namespace sqlite3pp {
class database;
}
-namespace MetaDataKey
-{
+namespace MetaDataKey {
enum Result
{
ValueFound = 0,
ValueIsNull,
ValueNotFound,
- NoMetaDataTable, //Format is too old, 'metadata' table is not present
+ NoMetaDataTable, // Format is too old, 'metadata' table is not present
NResults
};
-//BEGING Key constants TODO: maybe make static or extern to avoid duplication
+// BEGING Key constants TODO: maybe make static or extern to avoid duplication
-//Database
-constexpr char FormatVersionKey[] = "format_version"; //INTEGER: version, NOTE: FormatVersion is aleady used by info.h constants
-constexpr char ApplicationString[] = "application_str"; //STRING: application version string 'maj.min.patch'
+// Database
+constexpr char FormatVersionKey[] =
+ "format_version"; // INTEGER: version, NOTE: FormatVersion is aleady used by info.h constants
+constexpr char ApplicationString[] =
+ "application_str"; // STRING: application version string 'maj.min.patch'
-//Meeting
-constexpr char MeetingShowDates[] = "meeting_show_dates"; //INTEGER: 1 shows dates, 0 hides them
-constexpr char MeetingStartDate[] = "meeting_start_date"; //INTEGER: Start date in Julian Day integer
-constexpr char MeetingEndDate[] = "meeting_end_date"; //INTEGER: End date in Juliand Day integer
-constexpr char MeetingLocation[] = "meeting_location"; //STRING: city name
-constexpr char MeetingDescription[] = "meeting_descr"; //STRING: brief description of the meeting
-constexpr char MeetingHostAssociation[] = "meeting_host"; //STRING: name of association that is hosting the meeting
-constexpr char MeetingLogoPicture[] = "meeting_logo"; //BLOB: PNG alpha image, usually hosting association logo
+// Meeting
+constexpr char MeetingShowDates[] = "meeting_show_dates"; // INTEGER: 1 shows dates, 0 hides them
+constexpr char MeetingStartDate[] =
+ "meeting_start_date"; // INTEGER: Start date in Julian Day integer
+constexpr char MeetingEndDate[] = "meeting_end_date"; // INTEGER: End date in Juliand Day integer
+constexpr char MeetingLocation[] = "meeting_location"; // STRING: city name
+constexpr char MeetingDescription[] = "meeting_descr"; // STRING: brief description of the meeting
+constexpr char MeetingHostAssociation[] =
+ "meeting_host"; // STRING: name of association that is hosting the meeting
+constexpr char MeetingLogoPicture[] =
+ "meeting_logo"; // BLOB: PNG alpha image, usually hosting association logo
-//ODT Export Sheet
-constexpr char SheetHeaderText[] = "sheet_header"; //STRING: sheet header text
-constexpr char SheetFooterText[] = "sheet_footer"; //STRING: sheet footer text
+// ODT Export Sheet
+constexpr char SheetHeaderText[] = "sheet_header"; // STRING: sheet header text
+constexpr char SheetFooterText[] = "sheet_footer"; // STRING: sheet footer text
-//Jobs
-#define METADATA_MAKE_RS_KEY(category) ("job_default_stop_" ## #category)
+// Jobs
+#define METADATA_MAKE_RS_KEY(category) ("job_default_stop_"## #category)
-//END Key constants
-}
+// END Key constants
+} // namespace MetaDataKey
class MetaDataManager
{
@@ -71,16 +75,20 @@ public:
struct Key
{
- template
- constexpr inline Key(const char (&val)[N]) :str(val), len(N - 1) {}
+ template
+ constexpr inline Key(const char (&val)[N]) :
+ str(val),
+ len(N - 1)
+ {
+ }
const char *str;
const int len;
};
- MetaDataKey::Result hasKey(const Key& key);
+ MetaDataKey::Result hasKey(const Key &key);
- MetaDataKey::Result getInt64(qint64 &out, const Key& key);
+ MetaDataKey::Result getInt64(qint64 &out, const Key &key);
MetaDataKey::Result setInt64(qint64 in, bool setToNull, const Key &key);
MetaDataKey::Result getString(QString &out, const Key &key);
diff --git a/src/graph/CMakeLists.txt b/src/graph/CMakeLists.txt
index 9befb9f..3336a33 100644
--- a/src/graph/CMakeLists.txt
+++ b/src/graph/CMakeLists.txt
@@ -1,9 +1,4 @@
-add_subdirectory(model)
-add_subdirectory(view)
+add_subdirectory(model) add_subdirectory(view)
-set(MR_TIMETABLE_PLANNER_SOURCES
- ${MR_TIMETABLE_PLANNER_SOURCES}
- graph/linegraphtypes.h
- graph/linegraphtypes.cpp
- PARENT_SCOPE
-)
+ set(MR_TIMETABLE_PLANNER_SOURCES ${MR_TIMETABLE_PLANNER_SOURCES} graph / linegraphtypes.h graph
+ / linegraphtypes.cpp PARENT_SCOPE)
diff --git a/src/graph/linegraphtypes.cpp b/src/graph/linegraphtypes.cpp
index 387c6a1..bb7c1f8 100644
--- a/src/graph/linegraphtypes.cpp
+++ b/src/graph/linegraphtypes.cpp
@@ -28,16 +28,14 @@ public:
static const char *texts[];
};
-const char *LineGraphTypeNames::texts[] = {
- QT_TRANSLATE_NOOP("LineGraphTypeNames", "No Graph"),
- QT_TRANSLATE_NOOP("LineGraphTypeNames", "Station"),
- QT_TRANSLATE_NOOP("LineGraphTypeNames", "Segment"),
- QT_TRANSLATE_NOOP("LineGraphTypeNames", "Line")
-};
+const char *LineGraphTypeNames::texts[] = {QT_TRANSLATE_NOOP("LineGraphTypeNames", "No Graph"),
+ QT_TRANSLATE_NOOP("LineGraphTypeNames", "Station"),
+ QT_TRANSLATE_NOOP("LineGraphTypeNames", "Segment"),
+ QT_TRANSLATE_NOOP("LineGraphTypeNames", "Line")};
QString utils::getLineGraphTypeName(LineGraphType type)
{
- if(type >= LineGraphType::NTypes)
+ if (type >= LineGraphType::NTypes)
return QString();
return LineGraphTypeNames::tr(LineGraphTypeNames::texts[int(type)]);
}
diff --git a/src/graph/linegraphtypes.h b/src/graph/linegraphtypes.h
index 565b36b..4e0f21e 100644
--- a/src/graph/linegraphtypes.h
+++ b/src/graph/linegraphtypes.h
@@ -27,10 +27,10 @@
*/
enum class LineGraphType
{
- NoGraph = 0, //!< No content displayed
- SingleStation, //!< Show a single station
+ NoGraph = 0, //!< No content displayed
+ SingleStation, //!< Show a single station
RailwaySegment, //!< Show two adjacent stations and the segment in between
- RailwayLine, //!< Show a complete railway line (multiple adjacent segments)
+ RailwayLine, //!< Show a complete railway line (multiple adjacent segments)
NTypes
};
diff --git a/src/graph/model/linegraphmanager.cpp b/src/graph/model/linegraphmanager.cpp
index 250b732..7c1e5ea 100644
--- a/src/graph/model/linegraphmanager.cpp
+++ b/src/graph/model/linegraphmanager.cpp
@@ -41,34 +41,41 @@ LineGraphManager::LineGraphManager(QObject *parent) :
m_hasScheduledUpdate(false)
{
auto session = Session;
- //Stations
- connect(session, &MeetingSession::stationNameChanged, this, &LineGraphManager::onStationNameChanged);
- connect(session, &MeetingSession::stationJobsPlanChanged, this, &LineGraphManager::onStationJobPlanChanged);
- connect(session, &MeetingSession::stationTrackPlanChanged, this, &LineGraphManager::onStationTrackPlanChanged);
+ // Stations
+ connect(session, &MeetingSession::stationNameChanged, this,
+ &LineGraphManager::onStationNameChanged);
+ connect(session, &MeetingSession::stationJobsPlanChanged, this,
+ &LineGraphManager::onStationJobPlanChanged);
+ connect(session, &MeetingSession::stationTrackPlanChanged, this,
+ &LineGraphManager::onStationTrackPlanChanged);
connect(session, &MeetingSession::stationRemoved, this, &LineGraphManager::onStationRemoved);
- //Segments
- connect(session, &MeetingSession::segmentNameChanged, this, &LineGraphManager::onSegmentNameChanged);
- connect(session, &MeetingSession::segmentStationsChanged, this, &LineGraphManager::onSegmentStationsChanged);
+ // Segments
+ connect(session, &MeetingSession::segmentNameChanged, this,
+ &LineGraphManager::onSegmentNameChanged);
+ connect(session, &MeetingSession::segmentStationsChanged, this,
+ &LineGraphManager::onSegmentStationsChanged);
connect(session, &MeetingSession::segmentRemoved, this, &LineGraphManager::onSegmentRemoved);
- //Lines
+ // Lines
connect(session, &MeetingSession::lineNameChanged, this, &LineGraphManager::onLineNameChanged);
- connect(session, &MeetingSession::lineSegmentsChanged, this, &LineGraphManager::onLineSegmentsChanged);
+ connect(session, &MeetingSession::lineSegmentsChanged, this,
+ &LineGraphManager::onLineSegmentsChanged);
connect(session, &MeetingSession::lineRemoved, this, &LineGraphManager::onLineRemoved);
- //Jobs
+ // Jobs
connect(session, &MeetingSession::jobChanged, this, &LineGraphManager::onJobChanged);
connect(session, &MeetingSession::jobRemoved, this, &LineGraphManager::onJobRemoved);
- //Settings
- connect(&AppSettings, &MRTPSettings::jobGraphOptionsChanged, this, &LineGraphManager::updateGraphOptions);
+ // Settings
+ connect(&AppSettings, &MRTPSettings::jobGraphOptionsChanged, this,
+ &LineGraphManager::updateGraphOptions);
m_followJobOnGraphChange = AppSettings.getFollowSelectionOnGraphChange();
}
bool LineGraphManager::event(QEvent *ev)
{
- if(ev->type() == QEvent::Type(CustomEvents::LineGraphManagerUpdate))
+ if (ev->type() == QEvent::Type(CustomEvents::LineGraphManagerUpdate))
{
ev->accept();
processPendingUpdates();
@@ -88,13 +95,13 @@ void LineGraphManager::registerScene(LineGraphScene *scene)
connect(scene, &LineGraphScene::sceneActivated, this, &LineGraphManager::setActiveScene);
connect(scene, &LineGraphScene::jobSelected, this, &LineGraphManager::onJobSelected);
- if(m_followJobOnGraphChange)
+ if (m_followJobOnGraphChange)
connect(scene, &LineGraphScene::graphChanged, this, &LineGraphManager::onGraphChanged);
- if(scenes.count() == 1)
+ if (scenes.count() == 1)
{
- //This is the first scene registered
- //activate it so we have an active scene even if user does't activate one
+ // This is the first scene registered
+ // activate it so we have an active scene even if user does't activate one
setActiveScene(scene);
}
}
@@ -109,17 +116,17 @@ void LineGraphManager::unregisterScene(LineGraphScene *scene)
disconnect(scene, &LineGraphScene::sceneActivated, this, &LineGraphManager::setActiveScene);
disconnect(scene, &LineGraphScene::jobSelected, this, &LineGraphManager::onJobSelected);
- if(m_followJobOnGraphChange)
+ if (m_followJobOnGraphChange)
disconnect(scene, &LineGraphScene::graphChanged, this, &LineGraphManager::onGraphChanged);
- //Reset active scene if it is unregistered
- if(activeScene == scene)
+ // Reset active scene if it is unregistered
+ if (activeScene == scene)
setActiveScene(nullptr);
}
void LineGraphManager::clearAllGraphs()
{
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
scene->loadGraph(0, LineGraphType::NoGraph, true);
}
@@ -127,9 +134,9 @@ void LineGraphManager::clearAllGraphs()
void LineGraphManager::clearGraphsOfObject(db_id objectId, LineGraphType type)
{
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->getGraphObjectId() == objectId && scene->getGraphType() == type)
+ if (scene->getGraphObjectId() == objectId && scene->getGraphType() == type)
scene->loadGraph(0, LineGraphType::NoGraph);
}
}
@@ -137,61 +144,60 @@ void LineGraphManager::clearGraphsOfObject(db_id objectId, LineGraphType type)
JobStopEntry LineGraphManager::getCurrentSelectedJob() const
{
JobStopEntry selectedJob;
- if(activeScene)
+ if (activeScene)
selectedJob = activeScene->getSelectedJob();
return selectedJob;
}
void LineGraphManager::scheduleUpdate()
{
- if(m_hasScheduledUpdate)
- return; //Already scheduled
+ if (m_hasScheduledUpdate)
+ return; // Already scheduled
- //Mark as scheduled and post event to ourself
+ // Mark as scheduled and post event to ourself
m_hasScheduledUpdate = true;
- QCoreApplication::postEvent(this,
- new QEvent(QEvent::Type(CustomEvents::LineGraphManagerUpdate)),
- Qt::HighEventPriority);
+ QCoreApplication::postEvent(
+ this, new QEvent(QEvent::Type(CustomEvents::LineGraphManagerUpdate)), Qt::HighEventPriority);
}
void LineGraphManager::processPendingUpdates()
{
constexpr int MAX_UPDATE_TIME_MS = 1000;
- //Clear update flag before updating in case one operation triggers update
+ // Clear update flag before updating in case one operation triggers update
m_hasScheduledUpdate = false;
QElapsedTimer timer;
timer.start();
- for(LineGraphScene *scene : qAsConst(scenes))
- {
- if(timer.elapsed() > MAX_UPDATE_TIME_MS)
+ for (LineGraphScene *scene : qAsConst(scenes))
+ {
+ if (timer.elapsed() > MAX_UPDATE_TIME_MS)
{
- //It's taking to long, schedule a second update batch to finish
+ // It's taking to long, schedule a second update batch to finish
scheduleUpdate();
break;
}
- if(scene->pendingUpdate.testFlag(PendingUpdate::NothingToDo))
- continue; //Skip
+ if (scene->pendingUpdate.testFlag(PendingUpdate::NothingToDo))
+ continue; // Skip
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
{
scene->reload();
}
else
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::ReloadJobs))
+ if (scene->pendingUpdate.testFlag(PendingUpdate::ReloadJobs))
{
scene->reloadJobs();
}
- if(scene->pendingUpdate.testFlag(PendingUpdate::ReloadStationNames))
+ if (scene->pendingUpdate.testFlag(PendingUpdate::ReloadStationNames))
{
scene->updateStationNames();
}
- //Manually cleare pending update and trigger redraw
+ // Manually cleare pending update and trigger redraw
scene->pendingUpdate = PendingUpdate::NothingToDo;
emit scene->redrawGraph();
}
@@ -202,28 +208,28 @@ void LineGraphManager::setActiveScene(IGraphScene *scene)
{
LineGraphScene *lineScene = qobject_cast(scene);
- if(lineScene)
+ if (lineScene)
{
- if(activeScene == lineScene)
+ if (activeScene == lineScene)
return;
- //NOTE: Only registere scenes can become active
- //Otherwise we cannot track if scene got destroyed and reset active scene.
- if(!scenes.contains(lineScene))
+ // NOTE: Only registere scenes can become active
+ // Otherwise we cannot track if scene got destroyed and reset active scene.
+ if (!scenes.contains(lineScene))
return;
}
- else if(!scenes.isEmpty())
+ else if (!scenes.isEmpty())
{
- //Activate first registered scene because previous one was unregistered
+ // Activate first registered scene because previous one was unregistered
lineScene = scenes.first();
}
activeScene = lineScene;
emit activeSceneChanged(activeScene);
- //Triegger selection update or clear it
+ // Triegger selection update or clear it
JobStopEntry selectedJob;
- if(activeScene)
+ if (activeScene)
{
selectedJob = activeScene->getSelectedJob();
}
@@ -239,58 +245,60 @@ void LineGraphManager::onSceneDestroyed(QObject *obj)
void LineGraphManager::onGraphChanged(int /*graphType_*/, db_id graphObjId, LineGraphScene *scene)
{
- if(!m_followJobOnGraphChange || !scenes.contains(scene))
+ if (!m_followJobOnGraphChange || !scenes.contains(scene))
{
qWarning() << "LineGraphManager: should not receive graph change for scene" << scene;
return;
}
- if(!graphObjId || scene->getGraphType() == LineGraphType::NoGraph)
- return; //No graph selected
+ if (!graphObjId || scene->getGraphType() == LineGraphType::NoGraph)
+ return; // No graph selected
- //Graph has changed, ensure selected job is still visible (if possible)
+ // Graph has changed, ensure selected job is still visible (if possible)
JobStopEntry selectedJob = scene->getSelectedJob();
- if(!selectedJob.jobId)
- return; //No job selected, nothing to do
+ if (!selectedJob.jobId)
+ return; // No job selected, nothing to do
LineGraphSelectionHelper helper(Session->m_Db);
LineGraphSelectionHelper::SegmentInfo info;
- if(!helper.tryFindJobStopInGraph(scene, selectedJob.jobId, info))
- return; //Cannot find job in current graph, give up
+ if (!helper.tryFindJobStopInGraph(scene, selectedJob.jobId, info))
+ return; // Cannot find job in current graph, give up
- //Ensure job is visible
- scene->requestShowZone(info.firstStationId, info.segmentId, info.arrivalAndStart, info.departure);
+ // Ensure job is visible
+ scene->requestShowZone(info.firstStationId, info.segmentId, info.arrivalAndStart,
+ info.departure);
}
void LineGraphManager::onJobSelected(db_id jobId, int category, db_id stopId)
{
JobCategory cat = JobCategory(category);
- if(lastSelectedJob.jobId == jobId && lastSelectedJob.category == cat && lastSelectedJob.stopId == stopId)
- return; //Selection did not change
+ if (lastSelectedJob.jobId == jobId && lastSelectedJob.category == cat
+ && lastSelectedJob.stopId == stopId)
+ return; // Selection did not change
- lastSelectedJob.jobId = jobId;
+ lastSelectedJob.jobId = jobId;
lastSelectedJob.category = cat;
- lastSelectedJob.stopId = stopId;
+ lastSelectedJob.stopId = stopId;
- if(jobId)
+ if (jobId)
Session->getViewManager()->requestJobEditor(jobId);
else
Session->getViewManager()->requestClearJob();
- if(AppSettings.getSyncSelectionOnAllGraphs())
+ if (AppSettings.getSyncSelectionOnAllGraphs())
{
- //Sync selection among all registered scenes
- for(LineGraphScene *scene : qAsConst(scenes))
+ // Sync selection among all registered scenes
+ for (LineGraphScene *scene : qAsConst(scenes))
{
scene->setSelectedJob(lastSelectedJob);
}
}
- if(activeScene)
+ if (activeScene)
{
const JobStopEntry selectedJob = activeScene->getSelectedJob();
- if(selectedJob.jobId == lastSelectedJob.jobId)
+ if (selectedJob.jobId == lastSelectedJob.jobId)
{
emit jobSelected(lastSelectedJob.jobId, int(lastSelectedJob.category),
lastSelectedJob.stopId);
@@ -302,23 +310,23 @@ void LineGraphManager::onStationNameChanged(db_id stationId)
{
bool found = false;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
- continue; //Already flagged
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ continue; // Already flagged
- if(scene->stations.contains(stationId))
+ if (scene->stations.contains(stationId))
{
scene->pendingUpdate.setFlag(PendingUpdate::ReloadStationNames);
found = true;
}
}
- if(found)
+ if (found)
scheduleUpdate();
}
-void LineGraphManager::onStationJobPlanChanged(const QSet& stationIds)
+void LineGraphManager::onStationJobPlanChanged(const QSet &stationIds)
{
onStationPlanChanged_internal(stationIds, int(PendingUpdate::ReloadJobs));
}
@@ -330,9 +338,9 @@ void LineGraphManager::onStationTrackPlanChanged(const QSet &stationIds)
void LineGraphManager::onStationRemoved(db_id stationId)
{
- //A station can be removed only when not connected and no jobs pass through it.
- //So there is no need to update other scenes because no line will contain
- //The removed station
+ // A station can be removed only when not connected and no jobs pass through it.
+ // So there is no need to update other scenes because no line will contain
+ // The removed station
clearGraphsOfObject(stationId, LineGraphType::SingleStation);
}
@@ -340,25 +348,25 @@ void LineGraphManager::onSegmentNameChanged(db_id segmentId)
{
QString segName;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
- continue; //Already flagged
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ continue; // Already flagged
- if(scene->graphType == LineGraphType::RailwaySegment && scene->graphObjectId == segmentId)
+ if (scene->graphType == LineGraphType::RailwaySegment && scene->graphObjectId == segmentId)
{
- if(segName.isEmpty())
+ if (segName.isEmpty())
{
- //Fetch new name and cache it
+ // Fetch new name and cache it
sqlite3pp::query q(scene->mDb, "SELECT name FROM railway_segments WHERE id=?");
q.bind(1, segmentId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid segment ID" << segmentId;
return;
}
- //Store segment name
+ // Store segment name
segName = q.getRows().get(0);
}
@@ -372,16 +380,16 @@ void LineGraphManager::onSegmentStationsChanged(db_id segmentId)
{
bool found = false;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
- continue; //Already flagged
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ continue; // Already flagged
- if(scene->graphType == LineGraphType::RailwayLine)
+ if (scene->graphType == LineGraphType::RailwayLine)
{
- for(const auto& stPos : qAsConst(scene->stationPositions))
+ for (const auto &stPos : qAsConst(scene->stationPositions))
{
- if(stPos.segmentId == segmentId)
+ if (stPos.segmentId == segmentId)
{
scene->pendingUpdate.setFlag(PendingUpdate::FullReload);
found = true;
@@ -389,23 +397,24 @@ void LineGraphManager::onSegmentStationsChanged(db_id segmentId)
}
}
}
- else if(scene->graphType == LineGraphType::RailwaySegment && scene->graphObjectId == segmentId)
+ else if (scene->graphType == LineGraphType::RailwaySegment
+ && scene->graphObjectId == segmentId)
{
scene->pendingUpdate.setFlag(PendingUpdate::FullReload);
found = true;
}
}
- if(found)
+ if (found)
scheduleUpdate();
}
void LineGraphManager::onSegmentRemoved(db_id segmentId)
{
- //A segment can be removed only when is not on any line
- //And when no jobs pass through it.
- //So there is no need to update other line scenes because no line will contain
- //The removed segment
+ // A segment can be removed only when is not on any line
+ // And when no jobs pass through it.
+ // So there is no need to update other line scenes because no line will contain
+ // The removed segment
clearGraphsOfObject(segmentId, LineGraphType::RailwaySegment);
}
@@ -413,25 +422,25 @@ void LineGraphManager::onLineNameChanged(db_id lineId)
{
QString lineName;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
- continue; //Already flagged
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ continue; // Already flagged
- if(scene->graphType == LineGraphType::RailwayLine && scene->graphObjectId == lineId)
+ if (scene->graphType == LineGraphType::RailwayLine && scene->graphObjectId == lineId)
{
- if(lineName.isEmpty())
+ if (lineName.isEmpty())
{
- //Fetch new name and cache it
+ // Fetch new name and cache it
sqlite3pp::query q(scene->mDb, "SELECT name FROM lines WHERE id=?");
q.bind(1, lineId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid line ID" << lineId;
return;
}
- //Store line name
+ // Store line name
lineName = q.getRows().get(0);
}
@@ -445,60 +454,61 @@ void LineGraphManager::onLineSegmentsChanged(db_id lineId)
{
bool found = false;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
- continue; //Already flagged
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload))
+ continue; // Already flagged
- if(scene->graphType == LineGraphType::RailwayLine && scene->graphObjectId == lineId)
+ if (scene->graphType == LineGraphType::RailwayLine && scene->graphObjectId == lineId)
{
scene->pendingUpdate.setFlag(PendingUpdate::FullReload);
found = true;
}
}
- if(found)
+ if (found)
scheduleUpdate();
}
void LineGraphManager::onLineRemoved(db_id lineId)
{
- //Lines do not affect segments and stations
- //So no other scene needs updating
+ // Lines do not affect segments and stations
+ // So no other scene needs updating
clearGraphsOfObject(lineId, LineGraphType::RailwayLine);
}
void LineGraphManager::onJobChanged(db_id jobId, db_id oldJobId)
{
- //If job changed ID or category, update selection on all scenes which had it selected
- //There is no need to reload jobs because it is already done.
- //In fact when a job changes ID, all station interested by this job get informed, and scenes reloaded
+ // If job changed ID or category, update selection on all scenes which had it selected
+ // There is no need to reload jobs because it is already done.
+ // In fact when a job changes ID, all station interested by this job get informed, and scenes
+ // reloaded
JobStopEntry selectedJob;
selectedJob.jobId = jobId;
LineGraphScene::updateJobSelection(Session->m_Db, selectedJob);
- if(!selectedJob.jobId)
- return; //Invalid job ID
+ if (!selectedJob.jobId)
+ return; // Invalid job ID
- if(activeScene && AppSettings.getSyncSelectionOnAllGraphs())
+ if (activeScene && AppSettings.getSyncSelectionOnAllGraphs())
{
- //Update active scene before others in case selection is synced
- //This way all scenes get updated selection
+ // Update active scene before others in case selection is synced
+ // This way all scenes get updated selection
JobStopEntry oldSelectedJob = activeScene->getSelectedJob();
- if(oldSelectedJob.jobId == oldJobId)
+ if (oldSelectedJob.jobId == oldJobId)
{
activeScene->setSelectedJob(selectedJob);
}
}
else
{
- //Manually update all scenes
- for(LineGraphScene *scene : qAsConst(scenes))
+ // Manually update all scenes
+ for (LineGraphScene *scene : qAsConst(scenes))
{
JobStopEntry oldSelectedJob = scene->getSelectedJob();
- if(oldSelectedJob.jobId == oldJobId)
+ if (oldSelectedJob.jobId == oldJobId)
{
scene->setSelectedJob(selectedJob);
}
@@ -508,64 +518,66 @@ void LineGraphManager::onJobChanged(db_id jobId, db_id oldJobId)
void LineGraphManager::onJobRemoved(db_id jobId)
{
- //We already catch normal job removal with other signals
- if(jobId)
+ // We already catch normal job removal with other signals
+ if (jobId)
return;
- //If jobId is zero, it means all jobs have been deleted
- //Reload all scenes
+ // If jobId is zero, it means all jobs have been deleted
+ // Reload all scenes
bool found = false;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload)
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload)
|| scene->pendingUpdate.testFlag(PendingUpdate(PendingUpdate::ReloadJobs)))
- continue; //Already flagged
+ continue; // Already flagged
scene->pendingUpdate.setFlag(PendingUpdate(PendingUpdate::ReloadJobs));
found = true;
}
- if(found)
+ if (found)
scheduleUpdate();
}
void LineGraphManager::updateGraphOptions()
{
- //TODO: maybe get rid of theese variables in MeetingSession and always use AppSettings?
- int hourOffset = AppSettings.getHourOffset();
- Session->hourOffset = hourOffset;
+ // TODO: maybe get rid of theese variables in MeetingSession and always use AppSettings?
+ int hourOffset = AppSettings.getHourOffset();
+ Session->hourOffset = hourOffset;
- int horizOffset = AppSettings.getHorizontalOffset();
- Session->horizOffset = horizOffset;
+ int horizOffset = AppSettings.getHorizontalOffset();
+ Session->horizOffset = horizOffset;
- int vertOffset = AppSettings.getVerticalOffset();
- Session->vertOffset = vertOffset;
+ int vertOffset = AppSettings.getVerticalOffset();
+ Session->vertOffset = vertOffset;
- Session->stationOffset = AppSettings.getStationOffset();
+ Session->stationOffset = AppSettings.getStationOffset();
Session->platformOffset = AppSettings.getPlatformOffset();
- Session->jobLineWidth = AppSettings.getJobLineWidth();
+ Session->jobLineWidth = AppSettings.getJobLineWidth();
- //Reload all graphs
- for(LineGraphScene *scene : qAsConst(scenes))
+ // Reload all graphs
+ for (LineGraphScene *scene : qAsConst(scenes))
{
scene->reload();
}
- const bool oldVal = m_followJobOnGraphChange;
+ const bool oldVal = m_followJobOnGraphChange;
m_followJobOnGraphChange = AppSettings.getFollowSelectionOnGraphChange();
- if(m_followJobOnGraphChange != oldVal)
+ if (m_followJobOnGraphChange != oldVal)
{
- //Update connections
- for(LineGraphScene *scene : qAsConst(scenes))
+ // Update connections
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(m_followJobOnGraphChange)
- connect(scene, &LineGraphScene::graphChanged, this, &LineGraphManager::onGraphChanged);
+ if (m_followJobOnGraphChange)
+ connect(scene, &LineGraphScene::graphChanged, this,
+ &LineGraphManager::onGraphChanged);
else
- disconnect(scene, &LineGraphScene::graphChanged, this, &LineGraphManager::onGraphChanged);
+ disconnect(scene, &LineGraphScene::graphChanged, this,
+ &LineGraphManager::onGraphChanged);
}
}
}
@@ -574,15 +586,15 @@ void LineGraphManager::onStationPlanChanged_internal(const QSet &stationI
{
bool found = false;
- for(LineGraphScene *scene : qAsConst(scenes))
+ for (LineGraphScene *scene : qAsConst(scenes))
{
- if(scene->pendingUpdate.testFlag(PendingUpdate::FullReload)
+ if (scene->pendingUpdate.testFlag(PendingUpdate::FullReload)
|| scene->pendingUpdate.testFlag(PendingUpdate(flag)))
- continue; //Already flagged
+ continue; // Already flagged
- for(db_id stationId : stationIds)
+ for (db_id stationId : stationIds)
{
- if(scene->stations.contains(stationId))
+ if (scene->stations.contains(stationId))
{
scene->pendingUpdate.setFlag(PendingUpdate(flag));
found = true;
@@ -591,6 +603,6 @@ void LineGraphManager::onStationPlanChanged_internal(const QSet &stationI
}
}
- if(found)
+ if (found)
scheduleUpdate();
}
diff --git a/src/graph/model/linegraphmanager.h b/src/graph/model/linegraphmanager.h
index 0037093..bbdbbb8 100644
--- a/src/graph/model/linegraphmanager.h
+++ b/src/graph/model/linegraphmanager.h
@@ -82,7 +82,10 @@ public:
* \brief get active scene
* \return Scene instance or nullptr if no scene is active
*/
- inline LineGraphScene *getActiveScene() const { return activeScene; }
+ inline LineGraphScene *getActiveScene() const
+ {
+ return activeScene;
+ }
/*!
* \brief get current selected job
@@ -151,32 +154,32 @@ public slots:
void setActiveScene(IGraphScene *scene);
private slots:
- //Scenes
+ // Scenes
void onSceneDestroyed(QObject *obj);
void onGraphChanged(int graphType_, db_id graphObjId, LineGraphScene *scene);
void onJobSelected(db_id jobId, int category, db_id stopId);
- //Stations
+ // Stations
void onStationNameChanged(db_id stationId);
void onStationJobPlanChanged(const QSet &stationIds);
void onStationTrackPlanChanged(const QSet &stationIds);
void onStationRemoved(db_id stationId);
- //Segments
+ // Segments
void onSegmentNameChanged(db_id segmentId);
void onSegmentStationsChanged(db_id segmentId);
void onSegmentRemoved(db_id segmentId);
- //Lines
+ // Lines
void onLineNameChanged(db_id lineId);
void onLineSegmentsChanged(db_id lineId);
void onLineRemoved(db_id lineId);
- //Jobs
+ // Jobs
void onJobChanged(db_id jobId, db_id oldJobId);
void onJobRemoved(db_id jobId);
- //Settings
+ // Settings
void updateGraphOptions();
private:
diff --git a/src/graph/model/linegraphscene.cpp b/src/graph/model/linegraphscene.cpp
index aa4dc17..5fc49fe 100644
--- a/src/graph/model/linegraphscene.cpp
+++ b/src/graph/model/linegraphscene.cpp
@@ -27,7 +27,7 @@
#include
-//TODO: maybe move to utils?
+// TODO: maybe move to utils?
constexpr qreal MSEC_PER_HOUR = 1000 * 60 * 60;
static inline qreal timeToHourFraction(const QTime &t)
@@ -36,17 +36,18 @@ static inline qreal timeToHourFraction(const QTime &t)
return ret;
}
-static inline double stationPlatformPosition(const StationGraphObject& st, const db_id platfId, const double platfOffset)
+static inline double stationPlatformPosition(const StationGraphObject &st, const db_id platfId,
+ const double platfOffset)
{
double x = st.xPos;
- for(const StationGraphObject::PlatformGraph& platf : st.platforms)
+ for (const StationGraphObject::PlatformGraph &platf : st.platforms)
{
- if(platf.platformId == platfId)
+ if (platf.platformId == platfId)
return x;
x += platfOffset;
}
- //Error: requested platform belongs to different station
+ // Error: requested platform belongs to different station
qWarning() << "Station:" << st.stationName << st.stationId << "No platf:" << platfId;
return -1;
}
@@ -58,15 +59,14 @@ LineGraphScene::LineGraphScene(sqlite3pp::database &db, QObject *parent) :
graphType(LineGraphType::NoGraph),
m_drawSelection(true)
{
-
}
void LineGraphScene::renderContents(QPainter *painter, const QRectF &sceneRect)
{
BackgroundHelper::drawBackgroundHourLines(painter, sceneRect);
- if(getGraphType() == LineGraphType::NoGraph)
- return; //Nothing to draw
+ if (getGraphType() == LineGraphType::NoGraph)
+ return; // Nothing to draw
BackgroundHelper::drawStations(painter, this, sceneRect);
BackgroundHelper::drawJobStops(painter, this, sceneRect, m_drawSelection);
@@ -76,7 +76,7 @@ void LineGraphScene::renderContents(QPainter *painter, const QRectF &sceneRect)
void LineGraphScene::renderHeader(QPainter *painter, const QRectF &sceneRect,
Qt::Orientation orient, double /*scroll*/)
{
- if(orient == Qt::Horizontal)
+ if (orient == Qt::Horizontal)
BackgroundHelper::drawStationHeader(painter, this, sceneRect);
else
BackgroundHelper::drawHourPanel(painter, sceneRect);
@@ -86,19 +86,20 @@ void LineGraphScene::recalcContentSize()
{
m_cachedContentsSize = QSize();
- if(graphType == LineGraphType::NoGraph)
- return; //Nothing to draw
+ if (graphType == LineGraphType::NoGraph)
+ return; // Nothing to draw
- if(stationPositions.isEmpty())
+ if (stationPositions.isEmpty())
return;
- const auto entry = stationPositions.last();
+ const auto entry = stationPositions.last();
const int platfCount = stations.value(entry.stationId).platforms.count();
- //Add an additional half station offset after last station
- //This gives extra space to center station label
- const double maxWidth = entry.xPos + platfCount * Session->platformOffset + Session->stationOffset / 2;
- const double lastY = Session->vertOffset + Session->hourOffset * 24 + 10;
+ // Add an additional half station offset after last station
+ // This gives extra space to center station label
+ const double maxWidth =
+ entry.xPos + platfCount * Session->platformOffset + Session->stationOffset / 2;
+ const double lastY = Session->vertOffset + Session->hourOffset * 24 + 10;
m_cachedContentsSize = QSize(maxWidth, lastY);
}
@@ -110,68 +111,67 @@ void LineGraphScene::reload()
bool LineGraphScene::loadGraph(db_id objectId, LineGraphType type, bool force)
{
- if(!force && objectId == graphObjectId && type == graphType)
- return true; //Already loaded
+ if (!force && objectId == graphObjectId && type == graphType)
+ return true; // Already loaded
- //Initial state is invalid
- graphType = LineGraphType::NoGraph;
+ // Initial state is invalid
+ graphType = LineGraphType::NoGraph;
graphObjectId = 0;
graphObjectName.clear();
stations.clear();
stationPositions.clear();
m_cachedContentsSize = QSize();
- if(type == LineGraphType::NoGraph)
+ if (type == LineGraphType::NoGraph)
{
- //Nothing to load
+ // Nothing to load
emit graphChanged(int(graphType), graphObjectId, this);
emit redrawGraph();
return true;
}
- if(!mDb.db())
+ if (!mDb.db())
{
qWarning() << "Database not open on graph loading!";
return false;
}
- if(objectId <= 0)
+ if (objectId <= 0)
{
qWarning() << "Invalid object ID on graph loading!";
return false;
}
- //Leave on left horizOffset plus half station offset to separate first station from HourPanel
- //and to give more space to station label.
+ // Leave on left horizOffset plus half station offset to separate first station from HourPanel
+ // and to give more space to station label.
const double curPos = Session->horizOffset + Session->stationOffset / 2;
- if(type == LineGraphType::SingleStation)
+ if (type == LineGraphType::SingleStation)
{
StationGraphObject st;
st.stationId = objectId;
- if(!loadStation(st, graphObjectName))
+ if (!loadStation(st, graphObjectName))
return false;
- //Register a single station at start position
+ // Register a single station at start position
st.xPos = curPos;
stations.insert(st.stationId, st);
stationPositions = {{st.stationId, 0, st.xPos, {}}};
}
- else if(type == LineGraphType::RailwaySegment)
+ else if (type == LineGraphType::RailwaySegment)
{
- //TODO: maybe show also station gates
+ // TODO: maybe show also station gates
StationGraphObject stA, stB;
- sqlite3pp::query q(mDb,
- "SELECT s.in_gate_id,s.out_gate_id,s.name,s.max_speed_kmh,"
- "s.type,s.distance_meters,"
- "g1.station_id,g2.station_id"
- " FROM railway_segments s"
- " JOIN station_gates g1 ON g1.id=s.in_gate_id"
- " JOIN station_gates g2 ON g2.id=s.out_gate_id"
- " WHERE s.id=?");
+ sqlite3pp::query q(mDb, "SELECT s.in_gate_id,s.out_gate_id,s.name,s.max_speed_kmh,"
+ "s.type,s.distance_meters,"
+ "g1.station_id,g2.station_id"
+ " FROM railway_segments s"
+ " JOIN station_gates g1 ON g1.id=s.in_gate_id"
+ " JOIN station_gates g2 ON g2.id=s.out_gate_id"
+ " WHERE s.id=?");
q.bind(1, objectId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid segment ID" << objectId;
return false;
@@ -190,11 +190,12 @@ bool LineGraphScene::loadGraph(db_id objectId, LineGraphType type, bool force)
stB.stationId = r.get(7);
QString unusedStFullName;
- if(!loadStation(stA, unusedStFullName) || !loadStation(stB, unusedStFullName))
+ if (!loadStation(stA, unusedStFullName) || !loadStation(stB, unusedStFullName))
return false;
stA.xPos = curPos;
- stB.xPos = stA.xPos + stA.platforms.count() * Session->platformOffset + Session->stationOffset;
+ stB.xPos =
+ stA.xPos + stA.platforms.count() * Session->platformOffset + Session->stationOffset;
stations.insert(stA.stationId, stA);
stations.insert(stB.stationId, stB);
@@ -202,9 +203,9 @@ bool LineGraphScene::loadGraph(db_id objectId, LineGraphType type, bool force)
stationPositions = {{stA.stationId, objectId, stA.xPos, {}},
{stB.stationId, 0, stB.xPos, {}}};
}
- else if(type == LineGraphType::RailwayLine)
+ else if (type == LineGraphType::RailwayLine)
{
- if(!loadFullLine(objectId))
+ if (!loadFullLine(objectId))
{
stations.clear();
stationPositions.clear();
@@ -213,14 +214,14 @@ bool LineGraphScene::loadGraph(db_id objectId, LineGraphType type, bool force)
}
graphObjectId = objectId;
- graphType = type;
+ graphType = type;
recalcContentSize();
updateHeaderSize();
reloadJobs();
- //Reset pending update
+ // Reset pending update
pendingUpdate = PendingUpdate::NothingToDo;
emit graphChanged(int(graphType), graphObjectId, this);
@@ -231,52 +232,52 @@ bool LineGraphScene::loadGraph(db_id objectId, LineGraphType type, bool force)
bool LineGraphScene::reloadJobs()
{
- if(graphType == LineGraphType::NoGraph)
+ if (graphType == LineGraphType::NoGraph)
return false;
- //TODO: maybe only load visible
+ // TODO: maybe only load visible
- for(StationGraphObject& st : stations)
+ for (StationGraphObject &st : stations)
{
- if(!loadStationJobStops(st))
+ if (!loadStationJobStops(st))
return false;
}
- //Save last station from previous iteration
+ // Save last station from previous iteration
auto lastSt = stations.constEnd();
- for(int i = 0; i < stationPositions.size(); i++)
+ for (int i = 0; i < stationPositions.size(); i++)
{
- StationPosEntry& stPos = stationPositions[i];
- if(!stPos.segmentId)
- continue; //No segment, skip
+ StationPosEntry &stPos = stationPositions[i];
+ if (!stPos.segmentId)
+ continue; // No segment, skip
db_id fromStId = stPos.stationId;
- db_id toStId = 0;
- if(i <= stationPositions.size() - 1)
+ db_id toStId = 0;
+ if (i <= stationPositions.size() - 1)
toStId = stationPositions.at(i + 1).stationId;
- if(!toStId)
- break; //No next station
+ if (!toStId)
+ break; // No next station
auto fromSt = lastSt;
- if(fromSt == stations.constEnd() || fromSt->stationId != fromStId)
+ if (fromSt == stations.constEnd() || fromSt->stationId != fromStId)
{
fromSt = stations.constFind(fromStId);
- if(fromSt == stations.constEnd())
+ if (fromSt == stations.constEnd())
{
continue;
}
}
auto toSt = stations.constFind(toStId);
- if(toSt == stations.constEnd())
+ if (toSt == stations.constEnd())
continue;
- if(!loadSegmentJobs(stPos, fromSt.value(), toSt.value()))
+ if (!loadSegmentJobs(stPos, fromSt.value(), toSt.value()))
return false;
- //Store last station
+ // Store last station
lastSt = toSt;
}
@@ -290,110 +291,109 @@ bool LineGraphScene::reloadJobs()
void LineGraphScene::updateHeaderSize()
{
QSizeF headerSize(Session->horizOffset, Session->vertOffset);
- if(headerSize != m_cachedHeaderSize)
+ if (headerSize != m_cachedHeaderSize)
{
m_cachedHeaderSize = headerSize;
emit headersSizeChanged();
}
}
-JobStopEntry LineGraphScene::getJobStopAt(const StationGraphObject *prevSt, const StationGraphObject *nextSt,
- const QPointF &pos, const double tolerance)
+JobStopEntry LineGraphScene::getJobStopAt(const StationGraphObject *prevSt,
+ const StationGraphObject *nextSt, const QPointF &pos,
+ const double tolerance)
{
const double platformOffset = Session->platformOffset;
JobStopEntry job;
- //Find nearest station
+ // Find nearest station
const StationGraphObject *nearestSt = nullptr;
- double nextStDistance = 0;
- if(nextSt)
+ double nextStDistance = 0;
+ if (nextSt)
{
nextStDistance = qAbs(nextSt->xPos - pos.x());
- if(nextStDistance <= tolerance)
+ if (nextStDistance <= tolerance)
{
- //Next station is a good candidate
+ // Next station is a good candidate
nearestSt = nextSt;
}
}
- if(prevSt)
+ if (prevSt)
{
const double prevStRight = prevSt->xPos + prevSt->platforms.count() * platformOffset;
- if(pos.x() >= prevSt->xPos && pos.x() <= prevStRight)
+ if (pos.x() >= prevSt->xPos && pos.x() <= prevStRight)
{
- //Requested pos is inside this station
+ // Requested pos is inside this station
nearestSt = prevSt;
}
- else if(pos.x() >= prevStRight)
+ else if (pos.x() >= prevStRight)
{
- //Requested position is between prevSt and nextSt, find nearest
+ // Requested position is between prevSt and nextSt, find nearest
const double prevStDistance = pos.x() - prevStRight;
- if(prevStDistance <= tolerance
- && (!nearestSt || prevStDistance < nextStDistance))
+ if (prevStDistance <= tolerance && (!nearestSt || prevStDistance < nextStDistance))
{
nearestSt = prevSt;
}
}
}
- if(!nearestSt)
- return job; //Both stations exceed tolerance, null selection
-
+ if (!nearestSt)
+ return job; // Both stations exceed tolerance, null selection
const StationGraphObject::PlatformGraph *prevPlatf = nullptr;
const StationGraphObject::PlatformGraph *nextPlatf = nullptr;
- double prevPos = 0;
- double nextPos = 0;
+ double prevPos = 0;
+ double nextPos = 0;
- double xPos = nearestSt->xPos;
- for(const StationGraphObject::PlatformGraph& platf : nearestSt->platforms)
+ double xPos = nearestSt->xPos;
+ for (const StationGraphObject::PlatformGraph &platf : nearestSt->platforms)
{
- if(xPos >= pos.x())
+ if (xPos >= pos.x())
{
- //We went past the requested position
+ // We went past the requested position
nextPlatf = &platf;
- nextPos = xPos;
+ nextPos = xPos;
break;
}
prevPlatf = &platf;
- prevPos = xPos;
+ prevPos = xPos;
xPos += platformOffset;
}
- //Find nearest platform
+ // Find nearest platform
const StationGraphObject::PlatformGraph *resultPlatf = nullptr;
- const double prevDistance = qAbs(prevPos - pos.x());
- if(prevPlatf && prevDistance <= tolerance)
+ const double prevDistance = qAbs(prevPos - pos.x());
+ if (prevPlatf && prevDistance <= tolerance)
{
- //Previous platform is a good candidate
+ // Previous platform is a good candidate
resultPlatf = prevPlatf;
}
const double nextDistance = qAbs(nextPos - pos.x());
- if(nextPlatf && nextDistance <= tolerance)
+ if (nextPlatf && nextDistance <= tolerance)
{
- //Next platform is a good candidate
- if(!resultPlatf || nextDistance < prevDistance)
+ // Next platform is a good candidate
+ if (!resultPlatf || nextDistance < prevDistance)
{
- //We are the nearest
+ // We are the nearest
resultPlatf = nextPlatf;
}
}
- if(!resultPlatf)
- return job; //No match
+ if (!resultPlatf)
+ return job; // No match
- for(const StationGraphObject::JobStopGraph& jobStop : resultPlatf->jobStops)
+ for (const StationGraphObject::JobStopGraph &jobStop : resultPlatf->jobStops)
{
- //NOTE: in stops arrival comes BEFORE departure
- if(jobStop.arrivalY <= pos.y() + tolerance && jobStop.departureY >= pos.y() - tolerance)
+ // NOTE: in stops arrival comes BEFORE departure
+ if (jobStop.arrivalY <= pos.y() + tolerance && jobStop.departureY >= pos.y() - tolerance)
{
- //Found match
+ // Found match
job = jobStop.stop;
break;
}
@@ -406,67 +406,67 @@ JobStopEntry LineGraphScene::getJobAt(const QPointF &pos, const double tolerance
{
JobStopEntry job;
- if(stationPositions.isEmpty())
+ if (stationPositions.isEmpty())
return job;
- db_id prevStId = 0;
- db_id nextStId = 0;
+ db_id prevStId = 0;
+ db_id nextStId = 0;
const StationPosEntry *entry = nullptr;
- for(const StationPosEntry& stPos : qAsConst(stationPositions))
+ for (const StationPosEntry &stPos : qAsConst(stationPositions))
{
- if(stPos.xPos <= pos.x())
+ if (stPos.xPos <= pos.x())
{
prevStId = stPos.stationId;
- entry = &stPos;
+ entry = &stPos;
}
- if(stPos.xPos >= pos.x())
+ if (stPos.xPos >= pos.x())
{
- //We went past the requested position
+ // We went past the requested position
nextStId = stPos.stationId;
break;
}
}
- auto prevSt = stations.constFind(prevStId);
- auto nextSt = stations.constFind(nextStId);
+ auto prevSt = stations.constFind(prevStId);
+ auto nextSt = stations.constFind(nextStId);
const StationGraphObject *prevStPtr = prevSt == stations.constEnd() ? nullptr : &prevSt.value();
const StationGraphObject *nextStPtr = nextSt == stations.constEnd() ? nullptr : &nextSt.value();
- if(!prevStPtr && !nextStPtr)
- return job; //Error
+ if (!prevStPtr && !nextStPtr)
+ return job; // Error
job = getJobStopAt(prevStPtr, nextStPtr, pos, tolerance);
- if(job.jobId)
- return job; //Found match
+ if (job.jobId)
+ return job; // Found match
- //Check job segments
- if(!entry)
- return job; //Error, no match
+ // Check job segments
+ if (!entry)
+ return job; // Error, no match
double prevSegDistance = -1;
- for(const JobSegmentGraph& segment : qAsConst(entry->nextSegmentJobGraphs))
+ for (const JobSegmentGraph &segment : qAsConst(entry->nextSegmentJobGraphs))
{
- //NOTE: in segments arrival comes AFTER departure
+ // NOTE: in segments arrival comes AFTER departure
const QRectF r = QRectF(segment.fromDeparture, segment.toArrival).normalized();
- if(r.contains(pos))
+ if (r.contains(pos))
{
- //Requested position is inside bounds, might be a match
- const double resultingY = r.top() + (pos.x() - r.left()) * r.height() / r.width();
+ // Requested position is inside bounds, might be a match
+ const double resultingY = r.top() + (pos.x() - r.left()) * r.height() / r.width();
const double segDistance = qAbs(resultingY - pos.y());
- if(prevSegDistance < 0 || segDistance < prevSegDistance)
+ if (prevSegDistance < 0 || segDistance < prevSegDistance)
{
- //We are a better match than previous, replace it
- //Use departure station ('from') because arrival station might be last one
- //So there might be no segments after arrival
- job.stopId = segment.fromStopId;
- job.jobId = segment.jobId;
+ // We are a better match than previous, replace it
+ // Use departure station ('from') because arrival station might be last one
+ // So there might be no segments after arrival
+ job.stopId = segment.fromStopId;
+ job.jobId = segment.jobId;
job.category = segment.category;
- //Store new minimum distance
+ // Store new minimum distance
prevSegDistance = segDistance;
}
}
@@ -475,40 +475,41 @@ JobStopEntry LineGraphScene::getJobAt(const QPointF &pos, const double tolerance
return job;
}
-bool LineGraphScene::loadStation(StationGraphObject& st, QString& outFullName)
+bool LineGraphScene::loadStation(StationGraphObject &st, QString &outFullName)
{
sqlite3pp::query q(mDb);
q.prepare("SELECT name,short_name,type FROM stations WHERE id=?");
q.bind(1, st.stationId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid station ID" << st.stationId;
return false;
}
- //Load station
- auto row = q.getRows();
+ // Load station
+ auto row = q.getRows();
- outFullName = row.get(0);
+ outFullName = row.get(0);
st.stationName = row.get(1);
- if(st.stationName.isEmpty())
+ if (st.stationName.isEmpty())
{
- //Empty short name, fallback to full name
+ // Empty short name, fallback to full name
st.stationName = outFullName;
}
st.stationType = utils::StationType(row.get(2));
- //Load platforms
+ // Load platforms
const QRgb white = qRgb(255, 255, 255);
- q.prepare("SELECT id, type, color_rgb, name FROM station_tracks WHERE station_id=? ORDER BY pos");
+ q.prepare(
+ "SELECT id, type, color_rgb, name FROM station_tracks WHERE station_id=? ORDER BY pos");
q.bind(1, st.stationId);
- for(auto r : q)
+ for (auto r : q)
{
StationGraphObject::PlatformGraph platf;
- platf.platformId = r.get(0);
+ platf.platformId = r.get(0);
platf.platformType = utils::StationTrackType(r.get(1));
- if(r.column_type(2) == SQLITE_NULL) //NULL is white (#FFFFFF) -> default value
+ if (r.column_type(2) == SQLITE_NULL) // NULL is white (#FFFFFF) -> default value
platf.color = white;
else
platf.color = QRgb(r.get(2));
@@ -525,29 +526,29 @@ bool LineGraphScene::updateStationNames()
q.prepare("SELECT name,short_name FROM stations WHERE id=?");
- for(StationGraphObject& st : stations)
+ for (StationGraphObject &st : stations)
{
q.bind(1, st.stationId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid station ID" << st.stationId;
continue;
}
- st.stationName = q.getRows().get(1);
+ st.stationName = q.getRows().get(1);
QString fullName = q.getRows().get(0);
- if(st.stationName.isEmpty())
+ if (st.stationName.isEmpty())
{
- //Empty short name, fallback to full name
+ // Empty short name, fallback to full name
st.stationName = fullName;
}
- if(graphObjectId == st.stationId && graphType == LineGraphType::SingleStation)
+ if (graphObjectId == st.stationId && graphType == LineGraphType::SingleStation)
{
- //If we are a station graph also update grah name
+ // If we are a station graph also update grah name
graphObjectName = fullName;
- //Notify views TODO: specify graph didn't really change, just name
+ // Notify views TODO: specify graph didn't really change, just name
emit graphChanged(int(graphType), graphObjectId, this);
}
@@ -559,20 +560,20 @@ bool LineGraphScene::updateStationNames()
bool LineGraphScene::loadFullLine(db_id lineId)
{
- //TODO: maybe show also station gates
- //TODO: load only visible stations, other will be loaded when scrolling graph
+ // TODO: maybe show also station gates
+ // TODO: load only visible stations, other will be loaded when scrolling graph
sqlite3pp::query q(mDb, "SELECT name FROM lines WHERE id=?");
q.bind(1, lineId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
qWarning() << "Graph: invalid line ID" << lineId;
return false;
}
- //Store line name
+ // Store line name
graphObjectName = q.getRows().get(0);
- //Get segments
+ // Get segments
q.prepare("SELECT ls.id, ls.seg_id, ls.direction,"
"seg.name, seg.max_speed_kmh, seg.type, seg.distance_meters,"
"g1.station_id, g2.station_id"
@@ -585,39 +586,39 @@ bool LineGraphScene::loadFullLine(db_id lineId)
q.bind(1, lineId);
db_id lastStationId = 0;
- double curPos = Session->horizOffset + Session->stationOffset / 2;
+ double curPos = Session->horizOffset + Session->stationOffset / 2;
QString unusedStFullName;
- for(auto seg : q)
+ for (auto seg : q)
{
- db_id lineSegmentId = seg.get(0);
+ db_id lineSegmentId = seg.get(0);
db_id railwaySegmentId = seg.get(1);
- bool reversed = seg.get(2) != 0;
+ bool reversed = seg.get(2) != 0;
- //item.segmentName = seg.get(3);
- //item.maxSpeedKmH = seg.get(4);
- //item.segmentType = utils::RailwaySegmentType(seg.get(5));
- //item.distanceMeters = seg.get(6);
+ // item.segmentName = seg.get(3);
+ // item.maxSpeedKmH = seg.get(4);
+ // item.segmentType = utils::RailwaySegmentType(seg.get(5));
+ // item.distanceMeters = seg.get(6);
- //Store first segment end
+ // Store first segment end
db_id fromStationId = seg.get(7);
- //Store also the other end of segment for last item
+ // Store also the other end of segment for last item
db_id otherStationId = seg.get(8);
- if(reversed)
+ if (reversed)
{
- //Swap segments ends
+ // Swap segments ends
qSwap(fromStationId, otherStationId);
}
- if(!lastStationId)
+ if (!lastStationId)
{
- //First line station
+ // First line station
StationGraphObject st;
st.stationId = fromStationId;
- if(!loadStation(st, unusedStFullName))
+ if (!loadStation(st, unusedStFullName))
return false;
st.xPos = curPos;
@@ -625,7 +626,7 @@ bool LineGraphScene::loadFullLine(db_id lineId)
stationPositions.append({st.stationId, railwaySegmentId, st.xPos, {}});
curPos += st.platforms.count() * Session->platformOffset + Session->stationOffset;
}
- else if(fromStationId != lastStationId)
+ else if (fromStationId != lastStationId)
{
qWarning() << "Line segments are not adjacent, ID:" << lineSegmentId
<< "LINE:" << lineId;
@@ -634,7 +635,7 @@ bool LineGraphScene::loadFullLine(db_id lineId)
StationGraphObject stB;
stB.stationId = otherStationId;
- if(!loadStation(stB, unusedStFullName))
+ if (!loadStation(stB, unusedStFullName))
return false;
stB.xPos = curPos;
@@ -652,90 +653,92 @@ bool LineGraphScene::loadFullLine(db_id lineId)
bool LineGraphScene::loadStationJobStops(StationGraphObject &st)
{
- //Reset previous job graphs
- for(StationGraphObject::PlatformGraph& platf : st.platforms)
+ // Reset previous job graphs
+ for (StationGraphObject::PlatformGraph &platf : st.platforms)
{
platf.jobStops.clear();
}
- sqlite3pp::query q_prevSegment(mDb, "SELECT c.seg_id, MAX(stops.departure)"
- " FROM stops"
- " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id"
- " WHERE stops.job_id=? AND stops.departure");
+ sqlite3pp::query q_prevSegment(
+ mDb, "SELECT c.seg_id, MAX(stops.departure)"
+ " FROM stops"
+ " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id"
+ " WHERE stops.job_id=? AND stops.departure");
- sqlite3pp::query q(mDb, "SELECT stops.id, stops.job_id, jobs.category,"
- "stops.arrival, stops.departure,"
- "g_in.track_id, g_out.track_id,"
- "c.seg_id"
- " FROM stops"
- " JOIN jobs ON stops.job_id=jobs.id"
- " LEFT JOIN station_gate_connections g_in ON g_in.id=stops.in_gate_conn"
- " LEFT JOIN station_gate_connections g_out ON g_out.id=stops.out_gate_conn"
- " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id"
- " WHERE stops.station_id=?"
- " ORDER BY stops.arrival");
+ sqlite3pp::query q(mDb,
+ "SELECT stops.id, stops.job_id, jobs.category,"
+ "stops.arrival, stops.departure,"
+ "g_in.track_id, g_out.track_id,"
+ "c.seg_id"
+ " FROM stops"
+ " JOIN jobs ON stops.job_id=jobs.id"
+ " LEFT JOIN station_gate_connections g_in ON g_in.id=stops.in_gate_conn"
+ " LEFT JOIN station_gate_connections g_out ON g_out.id=stops.out_gate_conn"
+ " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id"
+ " WHERE stops.station_id=?"
+ " ORDER BY stops.arrival");
q.bind(1, st.stationId);
const double vertOffset = Session->vertOffset;
const double hourOffset = Session->hourOffset;
- for(auto stop : q)
+ for (auto stop : q)
{
StationGraphObject::JobStopGraph jobStop;
- jobStop.stop.stopId = stop.get(0);
- jobStop.stop.jobId = stop.get(1);
+ jobStop.stop.stopId = stop.get(0);
+ jobStop.stop.jobId = stop.get(1);
jobStop.stop.category = JobCategory(stop.get(2));
- QTime arrival = stop.get(3);
- QTime departure = stop.get(4);
- db_id trackId = stop.get(5);
- db_id outTrackId = stop.get(6);
- db_id nextSegId = stop.get(7);
+ QTime arrival = stop.get(3);
+ QTime departure = stop.get(4);
+ db_id trackId = stop.get(5);
+ db_id outTrackId = stop.get(6);
+ db_id nextSegId = stop.get(7);
- if(trackId && outTrackId && trackId != outTrackId)
+ if (trackId && outTrackId && trackId != outTrackId)
{
- //Not last stop, neither first stop. Tracks must correspond
+ // Not last stop, neither first stop. Tracks must correspond
qWarning() << "Stop:" << jobStop.stop.stopId << "Track not corresponding, using in";
}
- else if(!trackId)
+ else if (!trackId)
{
- if(outTrackId)
- trackId = outTrackId; //First stop, use out gate connection
+ if (outTrackId)
+ trackId = outTrackId; // First stop, use out gate connection
else
{
qWarning() << "Stop:" << jobStop.stop.stopId << "Both in/out track NULL, skipping";
- continue; //Skip this stop
+ continue; // Skip this stop
}
}
StationGraphObject::PlatformGraph *platf = nullptr;
- //Find platform
- for(StationGraphObject::PlatformGraph& p : st.platforms)
+ // Find platform
+ for (StationGraphObject::PlatformGraph &p : st.platforms)
{
- if(p.platformId == trackId)
+ if (p.platformId == trackId)
{
platf = &p;
break;
}
}
- if(!platf)
+ if (!platf)
{
- //Requested platform is not in this station
+ // Requested platform is not in this station
qWarning() << "Stop:" << jobStop.stop.stopId << "Track is not in this station";
- continue; //Skip this stop
+ continue; // Skip this stop
}
- //Check if we need job label
+ // Check if we need job label
bool isSegmentVisible = false;
- if(graphType == LineGraphType::SingleStation)
- isSegmentVisible = true; //Skip checking, always draw label
+ if (graphType == LineGraphType::SingleStation)
+ isSegmentVisible = true; // Skip checking, always draw label
- if(!isSegmentVisible && nextSegId)
+ if (!isSegmentVisible && nextSegId)
{
- for(const StationPosEntry& stPos : qAsConst(stationPositions))
+ for (const StationPosEntry &stPos : qAsConst(stationPositions))
{
- if(stPos.segmentId == nextSegId)
+ if (stPos.segmentId == nextSegId)
{
isSegmentVisible = true;
break;
@@ -743,19 +746,19 @@ bool LineGraphScene::loadStationJobStops(StationGraphObject &st)
}
}
- if(!isSegmentVisible)
+ if (!isSegmentVisible)
{
- //Check if previous segment is visible
+ // Check if previous segment is visible
q_prevSegment.bind(1, jobStop.stop.jobId);
q_prevSegment.bind(2, arrival);
q_prevSegment.step();
auto seg = q_prevSegment.getRows();
- if(seg.column_type(0) != SQLITE_NULL)
+ if (seg.column_type(0) != SQLITE_NULL)
{
db_id prevSegId = seg.get(0);
- for(const StationPosEntry& stPos : qAsConst(stationPositions))
+ for (const StationPosEntry &stPos : qAsConst(stationPositions))
{
- if(stPos.segmentId == prevSegId)
+ if (stPos.segmentId == prevSegId)
{
isSegmentVisible = true;
break;
@@ -765,11 +768,11 @@ bool LineGraphScene::loadStationJobStops(StationGraphObject &st)
q_prevSegment.reset();
}
- //Draw only if neither segment is visible or when graph is SignleStation
+ // Draw only if neither segment is visible or when graph is SignleStation
jobStop.drawLabel = !isSegmentVisible || graphType == LineGraphType::SingleStation;
- //Calculate coordinates
- jobStop.arrivalY = vertOffset + timeToHourFraction(arrival) * hourOffset;
+ // Calculate coordinates
+ jobStop.arrivalY = vertOffset + timeToHourFraction(arrival) * hourOffset;
jobStop.departureY = vertOffset + timeToHourFraction(departure) * hourOffset;
platf->jobStops.append(jobStop);
@@ -778,62 +781,67 @@ bool LineGraphScene::loadStationJobStops(StationGraphObject &st)
return true;
}
-bool LineGraphScene::loadSegmentJobs(LineGraphScene::StationPosEntry& stPos, const StationGraphObject& fromSt, const StationGraphObject& toSt)
+bool LineGraphScene::loadSegmentJobs(LineGraphScene::StationPosEntry &stPos,
+ const StationGraphObject &fromSt,
+ const StationGraphObject &toSt)
{
- //Reset previous job segment graph
+ // Reset previous job segment graph
stPos.nextSegmentJobGraphs.clear();
- const double vertOffset = Session->vertOffset;
- const double hourOffset = Session->hourOffset;
+ const double vertOffset = Session->vertOffset;
+ const double hourOffset = Session->hourOffset;
const double platfOffset = Session->platformOffset;
- sqlite3pp::query q(mDb, "SELECT sub.*, jobs.category, g_out.track_id, g_in.track_id FROM ("
- " SELECT stops.id AS cur_stop_id, lead(stops.id, 1) OVER win AS next_stop_id,"
- " stops.station_id,"
- " stops.job_id,"
- " stops.departure, lead(stops.arrival, 1) OVER win AS next_stop_arrival,"
- " stops.out_gate_conn,"
- " lead(stops.in_gate_conn, 1) OVER win AS next_stop_g_in,"
- " seg_conn.seg_id"
- " FROM stops"
- " LEFT JOIN railway_connections seg_conn ON seg_conn.id=stops.next_segment_conn_id"
- " WINDOW win AS (PARTITION BY stops.job_id ORDER BY stops.arrival)"
- ") AS sub"
- " JOIN station_gate_connections g_out ON g_out.id=sub.out_gate_conn"
- " JOIN station_gate_connections g_in ON g_in.id=sub.next_stop_g_in"
- " JOIN jobs ON jobs.id=sub.job_id"
- " WHERE sub.seg_id=?");
+ sqlite3pp::query q(
+ mDb, "SELECT sub.*, jobs.category, g_out.track_id, g_in.track_id FROM ("
+ " SELECT stops.id AS cur_stop_id, lead(stops.id, 1) OVER win AS next_stop_id,"
+ " stops.station_id,"
+ " stops.job_id,"
+ " stops.departure, lead(stops.arrival, 1) OVER win AS next_stop_arrival,"
+ " stops.out_gate_conn,"
+ " lead(stops.in_gate_conn, 1) OVER win AS next_stop_g_in,"
+ " seg_conn.seg_id"
+ " FROM stops"
+ " LEFT JOIN railway_connections seg_conn ON seg_conn.id=stops.next_segment_conn_id"
+ " WINDOW win AS (PARTITION BY stops.job_id ORDER BY stops.arrival)"
+ ") AS sub"
+ " JOIN station_gate_connections g_out ON g_out.id=sub.out_gate_conn"
+ " JOIN station_gate_connections g_in ON g_in.id=sub.next_stop_g_in"
+ " JOIN jobs ON jobs.id=sub.job_id"
+ " WHERE sub.seg_id=?");
q.bind(1, stPos.segmentId);
- for(auto stop : q)
+ for (auto stop : q)
{
JobSegmentGraph job;
- job.fromStopId = stop.get(0);
- job.toStopId = stop.get(1);
- db_id stId = stop.get(2);
- job.jobId = stop.get(3);
+ job.fromStopId = stop.get(0);
+ job.toStopId = stop.get(1);
+ db_id stId = stop.get(2);
+ job.jobId = stop.get(3);
QTime departure = stop.get(4);
- QTime arrival = stop.get(5);
- //6 - out gate connection
- //7 - in gate connection
- //8 - segment_id
- job.category = JobCategory(stop.get(9));
+ QTime arrival = stop.get(5);
+ // 6 - out gate connection
+ // 7 - in gate connection
+ // 8 - segment_id
+ job.category = JobCategory(stop.get(9));
job.fromPlatfId = stop.get(10);
- job.toPlatfId = stop.get(11);
+ job.toPlatfId = stop.get(11);
- //NOTE: fromPlatfId and toPlatfId do not need to be reversed because represent correct platforms
- //Only stations might be reversed
- bool reverse = toSt.stationId == stId; //If job goes in opposite direction
+ // NOTE: fromPlatfId and toPlatfId do not need to be reversed because represent correct
+ // platforms Only stations might be reversed
+ bool reverse = toSt.stationId == stId; // If job goes in opposite direction
- //Calculate coordinates
- job.fromDeparture.rx() = stationPlatformPosition(reverse ? toSt : fromSt, job.fromPlatfId, platfOffset);
+ // Calculate coordinates
+ job.fromDeparture.rx() =
+ stationPlatformPosition(reverse ? toSt : fromSt, job.fromPlatfId, platfOffset);
job.fromDeparture.ry() = vertOffset + timeToHourFraction(departure) * hourOffset;
- job.toArrival.rx() = stationPlatformPosition(reverse ? fromSt : toSt, job.toPlatfId, platfOffset);
+ job.toArrival.rx() =
+ stationPlatformPosition(reverse ? fromSt : toSt, job.toPlatfId, platfOffset);
job.toArrival.ry() = vertOffset + timeToHourFraction(arrival) * hourOffset;
- if(job.fromDeparture.x() < 0 || job.toArrival.x() < 0)
- continue; //Skip, couldn't find platform
+ if (job.fromDeparture.x() < 0 || job.toArrival.x() < 0)
+ continue; // Skip, couldn't find platform
stPos.nextSegmentJobGraphs.append(job);
}
@@ -843,41 +851,41 @@ bool LineGraphScene::loadSegmentJobs(LineGraphScene::StationPosEntry& stPos, con
void LineGraphScene::updateJobSelection(sqlite3pp::database &db, JobStopEntry &job)
{
- if(!job.jobId)
+ if (!job.jobId)
return;
query q(db);
- if(job.stopId)
+ if (job.stopId)
{
- //Check if stop is valid
+ // Check if stop is valid
q.prepare("SELECT job_id FROM stops WHERE id=?");
q.bind(1, job.stopId);
- if(q.step() == SQLITE_ROW)
+ if (q.step() == SQLITE_ROW)
{
db_id jobId = q.getRows().get(0);
- if(jobId != job.jobId)
- job.stopId = 0; //Stop doesn't belong to this job
+ if (jobId != job.jobId)
+ job.stopId = 0; // Stop doesn't belong to this job
}
else
{
- //This stop doesn't exist anymore
+ // This stop doesn't exist anymore
job.stopId = 0;
}
}
q.prepare("SELECT category FROM jobs WHERE id=?");
q.bind(1, job.jobId);
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
- //Job doesn't exist anymore, clear selection
+ // Job doesn't exist anymore, clear selection
job = JobStopEntry{};
return;
}
JobCategory newCategory = JobCategory(q.getRows().get(0));
- if(newCategory != job.category)
+ if (newCategory != job.category)
{
job.category = newCategory;
}
@@ -892,15 +900,16 @@ void LineGraphScene::setSelectedJob(JobStopEntry stop, bool sendChange)
{
const JobStopEntry oldJob = selectedJob;
- selectedJob = stop;
- if(!selectedJob.jobId)
+ selectedJob = stop;
+ if (!selectedJob.jobId)
{
- //Clear other members too
- selectedJob.stopId = 0;
+ // Clear other members too
+ selectedJob.stopId = 0;
selectedJob.category = JobCategory::NCategories;
}
- if(sendChange && (selectedJob.jobId != oldJob.jobId || selectedJob.category != oldJob.category))
+ if (sendChange
+ && (selectedJob.jobId != oldJob.jobId || selectedJob.category != oldJob.category))
{
emit redrawGraph();
emit jobSelected(selectedJob.jobId, int(selectedJob.category), selectedJob.stopId);
@@ -909,44 +918,44 @@ void LineGraphScene::setSelectedJob(JobStopEntry stop, bool sendChange)
bool LineGraphScene::requestShowZone(db_id stationId, db_id segmentId, QTime from, QTime to)
{
- //TODO: when we will load incrementally, ensure relevant items are loaded
+ // TODO: when we will load incrementally, ensure relevant items are loaded
- const double vertOffset = Session->vertOffset;
- const double hourOffset = Session->hourOffset;
+ const double vertOffset = Session->vertOffset;
+ const double hourOffset = Session->hourOffset;
const double platfOffset = Session->platformOffset;
QRectF result;
result.setTop(vertOffset + timeToHourFraction(from) * hourOffset);
result.setBottom(vertOffset + timeToHourFraction(to) * hourOffset);
- //NOTE: Initially left() is 0 which will always be less than any station position
- //So the first station must set it's position regardless of left() value
+ // NOTE: Initially left() is 0 which will always be less than any station position
+ // So the first station must set it's position regardless of left() value
bool leftEdgeSet = false;
- for(const StationPosEntry& entry : qAsConst(stationPositions))
+ for (const StationPosEntry &entry : qAsConst(stationPositions))
{
- //Match the requested station or both station in the segment
- if(entry.stationId == stationId || entry.segmentId == segmentId)
+ // Match the requested station or both station in the segment
+ if (entry.stationId == stationId || entry.segmentId == segmentId)
{
auto st = stations.constFind(entry.stationId);
- if(st == stations.constEnd())
+ if (st == stations.constEnd())
continue;
- if(result.left() > entry.xPos || !leftEdgeSet)
+ if (result.left() > entry.xPos || !leftEdgeSet)
{
result.setLeft(entry.xPos);
leftEdgeSet = true;
}
- const int platfCount = st->platforms.count();
+ const int platfCount = st->platforms.count();
const double rightPos = entry.xPos + platfCount * platfOffset;
- if(result.right() < rightPos)
+ if (result.right() < rightPos)
result.setRight(rightPos);
}
}
- //Set a margin around the selection so it douesn't end up at view edges
+ // Set a margin around the selection so it douesn't end up at view edges
const double margin = hourOffset / 4;
result.adjust(-margin, -margin, margin, margin);
diff --git a/src/graph/model/linegraphscene.h b/src/graph/model/linegraphscene.h
index 33f9aa2..98d56e7 100644
--- a/src/graph/model/linegraphscene.h
+++ b/src/graph/model/linegraphscene.h
@@ -57,18 +57,18 @@ public:
*/
enum class PendingUpdate
{
- NothingToDo = 0x0, //!< No content needs updating
- ReloadJobs = 0x1, //!< Only Jobs need to be reloaded
+ NothingToDo = 0x0, //!< No content needs updating
+ ReloadJobs = 0x1, //!< Only Jobs need to be reloaded
ReloadStationNames = 0x2, //!< Only Station Names but not Station Plan has changed
- FullReload = 0x4 //!< Do a full reload
+ FullReload = 0x4 //!< Do a full reload
};
Q_DECLARE_FLAGS(PendingUpdateFlags, PendingUpdate)
LineGraphScene(sqlite3pp::database &db, QObject *parent = nullptr);
- void renderContents(QPainter *painter, const QRectF& sceneRect) override;
- void renderHeader(QPainter *painter, const QRectF& sceneRect,
- Qt::Orientation orient, double scroll) override;
+ void renderContents(QPainter *painter, const QRectF &sceneRect) override;
+ void renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient,
+ double scroll) override;
/*!
* \brief Load graph contents
@@ -109,7 +109,7 @@ public:
* \param pos Point in scene coordinates
* \param tolerance A tolerance if mouse doesn't exactly click on job item
*/
- JobStopEntry getJobAt(const QPointF& pos, const double tolerance);
+ JobStopEntry getJobAt(const QPointF &pos, const double tolerance);
inline LineGraphType getGraphType() const
{
@@ -154,7 +154,10 @@ public:
*
* \sa setDrawSelection()
*/
- inline bool getDrawSelection() { return m_drawSelection; }
+ inline bool getDrawSelection()
+ {
+ return m_drawSelection;
+ }
/*!
* \brief setDrawSelection
@@ -165,7 +168,10 @@ public:
*
* \sa getDrawSelection()
*/
- inline void setDrawSelection(bool val) { m_drawSelection = val; }
+ inline void setDrawSelection(bool val)
+ {
+ m_drawSelection = val;
+ }
/*!
* \brief requestShowZone
@@ -208,7 +214,6 @@ public slots:
void reload();
private:
-
/*!
* \brief Graph of the job while is moving
*
@@ -308,7 +313,8 @@ private:
* Load job segments and stores them in 'from' station
* \sa loadStationJobStops()
*/
- bool loadSegmentJobs(StationPosEntry &stPos, const StationGraphObject &fromSt, const StationGraphObject &toSt);
+ bool loadSegmentJobs(StationPosEntry &stPos, const StationGraphObject &fromSt,
+ const StationGraphObject &toSt);
/*!
* \brief Update job selection category
@@ -324,7 +330,7 @@ private:
friend class BackgroundHelper;
friend class LineGraphManager;
- sqlite3pp::database& mDb;
+ sqlite3pp::database &mDb;
/*!
* \brief Graph Object ID
diff --git a/src/graph/model/linegraphselectionhelper.cpp b/src/graph/model/linegraphselectionhelper.cpp
index d64711a..d493950 100644
--- a/src/graph/model/linegraphselectionhelper.cpp
+++ b/src/graph/model/linegraphselectionhelper.cpp
@@ -27,10 +27,10 @@ using namespace sqlite3pp;
LineGraphSelectionHelper::LineGraphSelectionHelper(sqlite3pp::database &db) :
mDb(db)
{
-
}
-bool LineGraphSelectionHelper::tryFindJobStopInGraph(LineGraphScene *scene, db_id jobId, SegmentInfo &info)
+bool LineGraphSelectionHelper::tryFindJobStopInGraph(LineGraphScene *scene, db_id jobId,
+ SegmentInfo &info)
{
query q(mDb);
@@ -72,7 +72,7 @@ bool LineGraphSelectionHelper::tryFindJobStopInGraph(LineGraphScene *scene, db_i
case LineGraphType::NoGraph:
case LineGraphType::NTypes:
{
- //We need to load a new graph, give up
+ // We need to load a new graph, give up
return false;
}
}
@@ -80,18 +80,18 @@ bool LineGraphSelectionHelper::tryFindJobStopInGraph(LineGraphScene *scene, db_i
q.bind(1, jobId);
q.bind(2, scene->getGraphObjectId());
- if(q.step() != SQLITE_ROW || q.getRows().column_type(0) == SQLITE_NULL)
- return false; //We didn't find a stop in current graph, give up
+ if (q.step() != SQLITE_ROW || q.getRows().column_type(0) == SQLITE_NULL)
+ return false; // We didn't find a stop in current graph, give up
- //Get stop info
- auto stop = q.getRows();
- info.firstStopId = stop.get(0);
- info.segmentId = stop.get(1);
+ // Get stop info
+ auto stop = q.getRows();
+ info.firstStopId = stop.get(0);
+ info.segmentId = stop.get(1);
info.arrivalAndStart = stop.get(2);
- info.departure = stop.get(3);
+ info.departure = stop.get(3);
- //If graph is SingleStation we already know the station ID
- if(scene->getGraphType() == LineGraphType::SingleStation)
+ // If graph is SingleStation we already know the station ID
+ if (scene->getGraphType() == LineGraphType::SingleStation)
info.firstStationId = scene->getGraphObjectId();
else
info.firstStationId = stop.get(4);
@@ -99,96 +99,98 @@ bool LineGraphSelectionHelper::tryFindJobStopInGraph(LineGraphScene *scene, db_i
return true;
}
-bool LineGraphSelectionHelper::tryFindJobStopsAfter(db_id jobId, SegmentInfo& info)
+bool LineGraphSelectionHelper::tryFindJobStopsAfter(db_id jobId, SegmentInfo &info)
{
query q(mDb, "SELECT stops.id, MIN(stops.arrival), stops.departure, stops.station_id, c.seg_id"
" FROM stops"
" LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id"
" WHERE stops.job_id=? AND stops.arrival>=?");
- //Find first job stop after or equal to startTime
+ // Find first job stop after or equal to startTime
q.bind(1, jobId);
q.bind(2, info.arrivalAndStart);
- if(q.step() != SQLITE_ROW || q.getRows().column_type(0) == SQLITE_NULL)
+ if (q.step() != SQLITE_ROW || q.getRows().column_type(0) == SQLITE_NULL)
return false;
- //Get first stop info
- auto stop = q.getRows();
- info.firstStopId = stop.get(0);
+ // Get first stop info
+ auto stop = q.getRows();
+ info.firstStopId = stop.get(0);
info.arrivalAndStart = stop.get(1);
- info.departure = stop.get(2);
- info.firstStationId = stop.get(3);
- info.segmentId = stop.get(4);
+ info.departure = stop.get(2);
+ info.firstStationId = stop.get(3);
+ info.segmentId = stop.get(4);
q.reset();
- //Try get a second stop after the first departure
- //NOTE: minimum 60 seconds of travel between 2 consecutive stops
+ // Try get a second stop after the first departure
+ // NOTE: minimum 60 seconds of travel between 2 consecutive stops
q.bind(1, jobId);
q.bind(2, info.departure.addSecs(60));
- if(q.step() != SQLITE_ROW)
+ if (q.step() != SQLITE_ROW)
{
- //We found only 1 stop, return that
+ // We found only 1 stop, return that
info.secondStationId = 0;
return true;
}
- //Get first stop info
+ // Get first stop info
stop = q.getRows();
- //db_id secondStopId = stop.get(0);
- //QTime secondArrival = stop.get(1);
- info.departure = stop.get(2); //Overwrite departure
+ // db_id secondStopId = stop.get(0);
+ // QTime secondArrival = stop.get(1);
+ info.departure = stop.get(2); // Overwrite departure
info.secondStationId = stop.get(3);
return true;
}
-bool LineGraphSelectionHelper::tryFindNewGraphForJob(db_id jobId, SegmentInfo& info,
- db_id &outGraphObjId, LineGraphType &outGraphType)
+bool LineGraphSelectionHelper::tryFindNewGraphForJob(db_id jobId, SegmentInfo &info,
+ db_id &outGraphObjId,
+ LineGraphType &outGraphType)
{
- if(!tryFindJobStopsAfter(jobId, info))
- return false; //No stops found
+ if (!tryFindJobStopsAfter(jobId, info))
+ return false; // No stops found
- if(!info.secondStationId || !info.segmentId)
+ if (!info.secondStationId || !info.segmentId)
{
- //We found only 1 stop, select first station
+ // We found only 1 stop, select first station
outGraphObjId = info.firstStationId;
- outGraphType = LineGraphType::SingleStation;
+ outGraphType = LineGraphType::SingleStation;
return true;
}
- //Try to find a railway line which contains this segment
- //FIXME: better criteria to choose a line (name?, number of segments?, prompt user?)
+ // Try to find a railway line which contains this segment
+ // FIXME: better criteria to choose a line (name?, number of segments?, prompt user?)
query q(mDb, "SELECT ls.line_id"
" FROM line_segments ls"
" WHERE ls.seg_id=?");
q.bind(1, info.segmentId);
- if(q.step() == SQLITE_ROW)
+ if (q.step() == SQLITE_ROW)
{
- //Found a line
+ // Found a line
outGraphObjId = q.getRows().get(0);
- outGraphType = LineGraphType::RailwayLine;
+ outGraphType = LineGraphType::RailwayLine;
return true;
}
- //No lines found, use the railway segment
+ // No lines found, use the railway segment
outGraphObjId = info.segmentId;
- outGraphType = LineGraphType::RailwaySegment;
+ outGraphType = LineGraphType::RailwaySegment;
return true;
}
-bool LineGraphSelectionHelper::requestJobSelection(LineGraphScene *scene, db_id jobId, bool select, bool ensureVisible)
+bool LineGraphSelectionHelper::requestJobSelection(LineGraphScene *scene, db_id jobId, bool select,
+ bool ensureVisible)
{
- //Check jobId is valid and get category
+ // Check jobId is valid and get category
query q(mDb, "SELECT category FROM jobs WHERE id=?");
q.bind(1, jobId);
- if(q.step() != SQLITE_ROW)
- return false; //Job doen't exist
+ if (q.step() != SQLITE_ROW)
+ return false; // Job doen't exist
JobStopEntry selectedJob;
- selectedJob.jobId = jobId;
+ selectedJob.jobId = jobId;
selectedJob.category = JobCategory(q.getRows().get(0));
SegmentInfo info;
@@ -196,65 +198,66 @@ bool LineGraphSelectionHelper::requestJobSelection(LineGraphScene *scene, db_id
// Try to select earliest stop of this job in current graph, if any
const bool found = tryFindJobStopInGraph(scene, selectedJob.jobId, info);
- if(!found)
+ if (!found)
{
- //Find a NEW line graph or segment or station with this job
+ // Find a NEW line graph or segment or station with this job
- //Find first 2 stops of the job
+ // Find first 2 stops of the job
- db_id graphObjId = 0;
+ db_id graphObjId = 0;
LineGraphType graphType = LineGraphType::NoGraph;
- if(!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
+ if (!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
{
- //Could not find a suitable graph, abort
+ // Could not find a suitable graph, abort
return false;
}
- //NOTE: clear selection to avoid LineGraphManager trying to follow selection
- //do not emit change because selection might be synced between all scenes
- //and because it's restored soon after
+ // NOTE: clear selection to avoid LineGraphManager trying to follow selection
+ // do not emit change because selection might be synced between all scenes
+ // and because it's restored soon after
const JobStopEntry oldSelection = scene->getSelectedJob();
- scene->setSelectedJob(JobStopEntry{}, false); //Clear selection
+ scene->setSelectedJob(JobStopEntry{}, false); // Clear selection
- //Select the graph
+ // Select the graph
scene->loadGraph(graphObjId, graphType);
- //Restore previous selection
+ // Restore previous selection
scene->setSelectedJob(oldSelection, false);
}
- //Extract the info
+ // Extract the info
selectedJob.stopId = info.firstStopId;
- if(!selectedJob.stopId)
- return false; //No stop found, abort
+ if (!selectedJob.stopId)
+ return false; // No stop found, abort
- //Select job
- if(select)
+ // Select job
+ if (select)
scene->setSelectedJob(selectedJob);
- if(ensureVisible)
+ if (ensureVisible)
{
- return scene->requestShowZone(info.firstStationId, info.segmentId,
- info.arrivalAndStart, info.departure);
+ return scene->requestShowZone(info.firstStationId, info.segmentId, info.arrivalAndStart,
+ info.departure);
}
return true;
}
-bool LineGraphSelectionHelper::requestCurrentJobPrevSegmentVisible(LineGraphScene *scene, bool goToStart)
+bool LineGraphSelectionHelper::requestCurrentJobPrevSegmentVisible(LineGraphScene *scene,
+ bool goToStart)
{
JobStopEntry selectedJob = scene->getSelectedJob();
- if(!selectedJob.jobId)
- return false; //No job selected, nothing to do
+ if (!selectedJob.jobId)
+ return false; // No job selected, nothing to do
query q(mDb);
SegmentInfo info;
- if(selectedJob.stopId && !goToStart)
+ if (selectedJob.stopId && !goToStart)
{
- //Start from current stop and get previous stop
+ // Start from current stop and get previous stop
q.prepare("SELECT s2.job_id, s1.id, MAX(s1.arrival), s1.station_id, c.seg_id,"
"s2.departure, s2.station_id"
" FROM stops s2"
@@ -263,71 +266,72 @@ bool LineGraphSelectionHelper::requestCurrentJobPrevSegmentVisible(LineGraphScen
" WHERE s2.id=? AND s1.arrival < s2.arrival");
q.bind(1, selectedJob.stopId);
- if(q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
+ if (q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
{
- auto stop = q.getRows();
+ auto stop = q.getRows();
db_id jobId = stop.get(0);
- if(jobId == selectedJob.jobId)
+ if (jobId == selectedJob.jobId)
{
- //Found stop and belongs to requested job
- info.firstStopId = stop.get(1);
+ // Found stop and belongs to requested job
+ info.firstStopId = stop.get(1);
info.arrivalAndStart = stop.get(2);
- info.firstStationId = stop.get(3);
- info.segmentId = stop.get(4);
- info.departure = stop.get(5);
+ info.firstStationId = stop.get(3);
+ info.segmentId = stop.get(4);
+ info.departure = stop.get(5);
info.secondStationId = stop.get(6);
}
}
}
- if(!info.firstStopId)
+ if (!info.firstStopId)
{
- //goToStart or failed to get previous stop so go to start anyway
+ // goToStart or failed to get previous stop so go to start anyway
- if(!tryFindJobStopsAfter(selectedJob.jobId, info))
- return false; //No stops found, give up
+ if (!tryFindJobStopsAfter(selectedJob.jobId, info))
+ return false; // No stops found, give up
}
- db_id graphObjId = 0;
+ db_id graphObjId = 0;
LineGraphType graphType = LineGraphType::NoGraph;
- if(!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
+ if (!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
{
- //Could not find a suitable graph, abort
+ // Could not find a suitable graph, abort
return false;
}
- //NOTE: clear selection to avoid LineGraphManager trying to follow selection
- //do not emit change because selection might be synced between all scenes
- //and because it's restored soon after
- scene->setSelectedJob(JobStopEntry{}, false); //Clear selection
+ // NOTE: clear selection to avoid LineGraphManager trying to follow selection
+ // do not emit change because selection might be synced between all scenes
+ // and because it's restored soon after
+ scene->setSelectedJob(JobStopEntry{}, false); // Clear selection
- //Select the graph
+ // Select the graph
scene->loadGraph(graphObjId, graphType);
- //Restore selection
+ // Restore selection
selectedJob.stopId = info.firstStopId;
- scene->setSelectedJob(selectedJob); //This time emit
+ scene->setSelectedJob(selectedJob); // This time emit
- return scene->requestShowZone(info.firstStationId, info.segmentId,
- info.arrivalAndStart, info.departure);
+ return scene->requestShowZone(info.firstStationId, info.segmentId, info.arrivalAndStart,
+ info.departure);
}
-bool LineGraphSelectionHelper::requestCurrentJobNextSegmentVisible(LineGraphScene *scene, bool goToEnd)
+bool LineGraphSelectionHelper::requestCurrentJobNextSegmentVisible(LineGraphScene *scene,
+ bool goToEnd)
{
- //TODO: maybe go to first segment AFTER last segment in current view.
- //So it may not be 'next' but maybe 2 or 3 segments after current.
+ // TODO: maybe go to first segment AFTER last segment in current view.
+ // So it may not be 'next' but maybe 2 or 3 segments after current.
JobStopEntry selectedJob = scene->getSelectedJob();
- if(!selectedJob.jobId)
- return false; //No job selected, nothing to do
+ if (!selectedJob.jobId)
+ return false; // No job selected, nothing to do
query q(mDb);
SegmentInfo info;
- if(selectedJob.stopId && !goToEnd)
+ if (selectedJob.stopId && !goToEnd)
{
- //Start from current stop and get next stop
+ // Start from current stop and get next stop
q.prepare("SELECT s2.job_id, s1.id, MIN(s1.arrival), s1.departure, s1.station_id, c.seg_id"
" FROM stops s2"
" JOIN stops s1 ON s1.job_id=s2.job_id"
@@ -335,64 +339,64 @@ bool LineGraphSelectionHelper::requestCurrentJobNextSegmentVisible(LineGraphScen
" WHERE s2.id=? AND s1.arrival > s2.arrival");
q.bind(1, selectedJob.stopId);
- if(q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
+ if (q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
{
- auto stop = q.getRows();
+ auto stop = q.getRows();
db_id jobId = stop.get(0);
- if(jobId == selectedJob.jobId)
+ if (jobId == selectedJob.jobId)
{
- //Found stop and belongs to requested job
- info.firstStopId = stop.get(1);
+ // Found stop and belongs to requested job
+ info.firstStopId = stop.get(1);
info.arrivalAndStart = stop.get(2);
- info.departure = stop.get(3);
- info.firstStationId = stop.get(4);
- info.segmentId = stop.get(5);
+ info.departure = stop.get(3);
+ info.firstStationId = stop.get(4);
+ info.segmentId = stop.get(5);
}
}
}
- if(!info.firstStopId)
+ if (!info.firstStopId)
{
- //goToEnd or failed to get next stop so go to end anyway
+ // goToEnd or failed to get next stop so go to end anyway
- //Select last station, no segment
+ // Select last station, no segment
q.prepare("SELECT s1.id, MAX(s1.arrival), s1.departure, s1.station_id"
" FROM stops s1"
" WHERE s1.job_id=?");
q.bind(1, selectedJob.jobId);
- if(q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
+ if (q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL)
{
- //Found stop and belongs to requested job
- auto stop = q.getRows();
- info.firstStopId = stop.get(0);
+ // Found stop and belongs to requested job
+ auto stop = q.getRows();
+ info.firstStopId = stop.get(0);
info.arrivalAndStart = stop.get(1);
- info.departure = stop.get(2);
- info.firstStationId = stop.get(3);
+ info.departure = stop.get(2);
+ info.firstStationId = stop.get(3);
}
}
- db_id graphObjId = 0;
+ db_id graphObjId = 0;
LineGraphType graphType = LineGraphType::NoGraph;
- if(!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
+ if (!tryFindNewGraphForJob(selectedJob.jobId, info, graphObjId, graphType))
{
- //Could not find a suitable graph, abort
+ // Could not find a suitable graph, abort
return false;
}
- //NOTE: clear selection to avoid LineGraphManager trying to follow selection
- //do not emit change because selection might be synced between all scenes
- //and because it's restored soon after
- scene->setSelectedJob(JobStopEntry{}, false); //Clear selection
+ // NOTE: clear selection to avoid LineGraphManager trying to follow selection
+ // do not emit change because selection might be synced between all scenes
+ // and because it's restored soon after
+ scene->setSelectedJob(JobStopEntry{}, false); // Clear selection
- //Select the graph
+ // Select the graph
scene->loadGraph(graphObjId, graphType);
- //Restore selection
+ // Restore selection
selectedJob.stopId = info.firstStopId;
- scene->setSelectedJob(selectedJob); //This time emit
+ scene->setSelectedJob(selectedJob); // This time emit
- return scene->requestShowZone(info.firstStationId, info.segmentId,
- info.arrivalAndStart, info.departure);
+ return scene->requestShowZone(info.firstStationId, info.segmentId, info.arrivalAndStart,
+ info.departure);
}
diff --git a/src/graph/model/linegraphselectionhelper.h b/src/graph/model/linegraphselectionhelper.h
index bdcd231..4c05f58 100644
--- a/src/graph/model/linegraphselectionhelper.h
+++ b/src/graph/model/linegraphselectionhelper.h
@@ -33,16 +33,15 @@ class database;
class LineGraphSelectionHelper
{
public:
-
/*!
* \brief The SegmentInfo struct
*/
struct SegmentInfo
{
- db_id segmentId = 0;
- db_id firstStationId = 0;
+ db_id segmentId = 0;
+ db_id firstStationId = 0;
db_id secondStationId = 0;
- db_id firstStopId = 0;
+ db_id firstStopId = 0;
/*!
* \brief arrival and start
@@ -56,7 +55,7 @@ public:
LineGraphSelectionHelper(sqlite3pp::database &db);
- //Low level API
+ // Low level API
/*!
* \brief find job in current graph
@@ -69,7 +68,7 @@ public:
* If scene has NoGraph or does not contain requested job then returns false
* SegmentInfo::secondStId is always left empty
*/
- bool tryFindJobStopInGraph(LineGraphScene *scene, db_id jobId, SegmentInfo& info);
+ bool tryFindJobStopInGraph(LineGraphScene *scene, db_id jobId, SegmentInfo &info);
/*!
* \brief find 2 job stops after requested hour
@@ -93,10 +92,11 @@ public:
* Try to find a railway line containing the job. If not found try with a railway segment.
* If neither line nor segment are found try with first stop station.
*/
- bool tryFindNewGraphForJob(db_id jobId, SegmentInfo &info, db_id &outGraphObjId, LineGraphType &outGraphType);
+ bool tryFindNewGraphForJob(db_id jobId, SegmentInfo &info, db_id &outGraphObjId,
+ LineGraphType &outGraphType);
public:
- //High level API
+ // High level API
/*!
* \brief request job selection
diff --git a/src/graph/model/stationgraphobject.cpp b/src/graph/model/stationgraphobject.cpp
index f81ab29..0109635 100644
--- a/src/graph/model/stationgraphobject.cpp
+++ b/src/graph/model/stationgraphobject.cpp
@@ -21,5 +21,4 @@
StationGraphObject::StationGraphObject()
{
-
}
diff --git a/src/graph/view/backgroundhelper.cpp b/src/graph/view/backgroundhelper.cpp
index 93493ef..e095451 100644
--- a/src/graph/view/backgroundhelper.cpp
+++ b/src/graph/view/backgroundhelper.cpp
@@ -21,7 +21,7 @@
#include "app/session.h"
-#include "graph/model/linegraphscene.h"
+#include "graph/model/linegraphscene.h"
#include "utils/jobcategorystrings.h"
#include
@@ -31,9 +31,9 @@
#include
-void BackgroundHelper::drawHourPanel(QPainter *painter, const QRectF& rect)
+void BackgroundHelper::drawHourPanel(QPainter *painter, const QRectF &rect)
{
- //TODO: settings
+ // TODO: settings
QFont hourTextFont;
setFontPointSizeDPI(hourTextFont, 15, painter);
@@ -45,14 +45,14 @@ void BackgroundHelper::drawHourPanel(QPainter *painter, const QRectF& rect)
painter->setFont(hourTextFont);
painter->setPen(hourTextPen);
- //qDebug() << "Drawing hours..." << rect << scroll;
+ // qDebug() << "Drawing hours..." << rect << scroll;
const QString fmt(QStringLiteral("%1:00"));
- const qreal top = rect.top() - vertOffset;
+ const qreal top = rect.top() - vertOffset;
const qreal bottom = rect.bottom();
- int h = qFloor(top / hourOffset);
- if(h < 0)
+ int h = qFloor(top / hourOffset);
+ if (h < 0)
h = 0;
QRectF labelRect = rect;
@@ -60,9 +60,9 @@ void BackgroundHelper::drawHourPanel(QPainter *painter, const QRectF& rect)
labelRect.setHeight(hourOffset);
labelRect.moveTop(h * hourOffset + vertOffset - hourOffset / 2);
- for(; h <= 24 && labelRect.top() <= bottom; h++)
+ for (; h <= 24 && labelRect.top() <= bottom; h++)
{
- //qDebug() << "Y:" << y << fmt.arg(h);
+ // qDebug() << "Y:" << y << fmt.arg(h);
painter->drawText(labelRect, fmt.arg(h), QTextOption(Qt::AlignVCenter | Qt::AlignRight));
labelRect.moveTop(labelRect.top() + hourOffset);
}
@@ -71,39 +71,38 @@ void BackgroundHelper::drawHourPanel(QPainter *painter, const QRectF& rect)
void BackgroundHelper::drawBackgroundHourLines(QPainter *painter, const QRectF &rect)
{
const double horizOffset = Session->horizOffset;
- const double vertOffset = Session->vertOffset;
- const double hourOffset = Session->hourOffset;
+ const double vertOffset = Session->vertOffset;
+ const double hourOffset = Session->hourOffset;
QPen hourLinePen(AppSettings.getHourLineColor(), AppSettings.getHourLineWidth());
const qreal x1 = qMax(qreal(horizOffset), rect.left());
const qreal x2 = rect.right();
- const qreal t = qMax(rect.top(), vertOffset);
- const qreal b = rect.bottom();
+ const qreal t = qMax(rect.top(), vertOffset);
+ const qreal b = rect.bottom();
-
- if(x1 > x2 || b < vertOffset || t > b)
+ if (x1 > x2 || b < vertOffset || t > b)
return;
int firstH = qCeil((t - vertOffset) / hourOffset);
- int lastH = qFloor((b - vertOffset) / hourOffset);
+ int lastH = qFloor((b - vertOffset) / hourOffset);
- if(firstH > 24 || lastH < 0)
+ if (firstH > 24 || lastH < 0)
return;
- if(firstH < 0)
+ if (firstH < 0)
firstH = 0;
- if(lastH > 24)
+ if (lastH > 24)
lastH = 24;
const int n = lastH - firstH + 1;
- if(n <= 0)
+ if (n <= 0)
return;
- qreal y = vertOffset + firstH * hourOffset;
+ qreal y = vertOffset + firstH * hourOffset;
QLineF *arr = new QLineF[n];
- for(int i = 0; i < n; i++)
+ for (int i = 0; i < n; i++)
{
arr[i] = QLineF(x1, y, x2, y);
y += hourOffset;
@@ -111,10 +110,11 @@ void BackgroundHelper::drawBackgroundHourLines(QPainter *painter, const QRectF &
painter->setPen(hourLinePen);
painter->drawLines(arr, n);
- delete [] arr;
+ delete[] arr;
}
-void BackgroundHelper::drawStationHeader(QPainter *painter, LineGraphScene *scene, const QRectF &rect)
+void BackgroundHelper::drawStationHeader(QPainter *painter, LineGraphScene *scene,
+ const QRectF &rect)
{
QFont stationFont;
stationFont.setBold(true);
@@ -132,23 +132,23 @@ void BackgroundHelper::drawStationHeader(QPainter *painter, LineGraphScene *scen
QPen nonElectricPlatfPen(Qt::black);
const qreal platformOffset = Session->platformOffset;
- const int stationOffset = Session->stationOffset;
+ const int stationOffset = Session->stationOffset;
- //On left go back by half station offset to center station label
- //and center platform label by going a back of half platformOffset
- const int leftOffset = -stationOffset/2 - platformOffset /2;
+ // On left go back by half station offset to center station label
+ // and center platform label by going a back of half platformOffset
+ const int leftOffset = -stationOffset / 2 - platformOffset / 2;
- const double margin = stationOffset * 0.1;
+ const double margin = stationOffset * 0.1;
- QRectF r = rect;
+ QRectF r = rect;
- for(auto st : qAsConst(scene->stations))
+ for (auto st : qAsConst(scene->stations))
{
- const double left = st.xPos + leftOffset;
+ const double left = st.xPos + leftOffset;
const double right = left + st.platforms.count() * platformOffset + stationOffset;
- if(right < r.left() || left >= r.right())
- continue; //Skip station, it's not visible
+ if (right < r.left() || left >= r.right())
+ continue; // Skip station, it's not visible
QRectF labelRect = r;
labelRect.setLeft(left + margin);
@@ -160,20 +160,20 @@ void BackgroundHelper::drawStationHeader(QPainter *painter, LineGraphScene *scen
painter->drawText(labelRect, Qt::AlignVCenter | Qt::AlignCenter, st.stationName);
labelRect = r;
- labelRect.setTop(r.top() + r.height() * 2/3);
+ labelRect.setTop(r.top() + r.height() * 2 / 3);
- //Go to start of station (first platform)
- //We need to compensate the half stationOffset used to center station label
- double xPos = left + stationOffset/2;
+ // Go to start of station (first platform)
+ // We need to compensate the half stationOffset used to center station label
+ double xPos = left + stationOffset / 2;
labelRect.setWidth(platformOffset);
- for(const StationGraphObject::PlatformGraph& platf : qAsConst(st.platforms))
+ for (const StationGraphObject::PlatformGraph &platf : qAsConst(st.platforms))
{
- if(platf.platformType.testFlag(utils::StationTrackType::Electrified))
+ if (platf.platformType.testFlag(utils::StationTrackType::Electrified))
painter->setPen(electricPlatfPen);
else
painter->setPen(nonElectricPlatfPen);
- if(platf.platformType.testFlag(utils::StationTrackType::Through))
+ if (platf.platformType.testFlag(utils::StationTrackType::Through))
painter->setFont(platfBoldFont);
else
painter->setFont(platfNormalFont);
@@ -191,33 +191,33 @@ void BackgroundHelper::drawStations(QPainter *painter, LineGraphScene *scene, co
{
const QRgb white = qRgb(255, 255, 255);
- //const int horizOffset = Session->horizOffset;
+ // const int horizOffset = Session->horizOffset;
const int vertOffset = Session->vertOffset;
- //const int stationOffset = Session->stationOffset;
- const double platfOffset = Session->platformOffset;
- const int lastY = vertOffset + Session->hourOffset * 24 + 10;
+ // const int stationOffset = Session->stationOffset;
+ const double platfOffset = Session->platformOffset;
+ const int lastY = vertOffset + Session->hourOffset * 24 + 10;
- const int width = AppSettings.getPlatformLineWidth();
+ const int width = AppSettings.getPlatformLineWidth();
const QColor mainPlatfColor = AppSettings.getMainPlatfColor();
- QPen platfPen (mainPlatfColor, width);
+ QPen platfPen(mainPlatfColor, width);
QPointF top(0, vertOffset);
QPointF bottom(0, lastY);
- for(const StationGraphObject &st : qAsConst(scene->stations))
+ for (const StationGraphObject &st : qAsConst(scene->stations))
{
- const double left = st.xPos;
+ const double left = st.xPos;
const double right = left + st.platforms.count() * platfOffset;
- if(left > rect.right() || right < rect.left())
- continue; //Skip station, it's not visible
+ if (left > rect.right() || right < rect.left())
+ continue; // Skip station, it's not visible
top.rx() = bottom.rx() = st.xPos;
- for(const StationGraphObject::PlatformGraph& platf : st.platforms)
+ for (const StationGraphObject::PlatformGraph &platf : st.platforms)
{
- if(platf.color == white)
+ if (platf.color == white)
platfPen.setColor(mainPlatfColor);
else
platfPen.setColor(platf.color);
@@ -232,9 +232,10 @@ void BackgroundHelper::drawStations(QPainter *painter, LineGraphScene *scene, co
}
}
-void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, const QRectF &rect, bool drawSelection)
+void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, const QRectF &rect,
+ bool drawSelection)
{
- const double platfOffset = Session->platformOffset;
+ const double platfOffset = Session->platformOffset;
const double stationOffset = Session->stationOffset;
QFont jobNameFont;
@@ -249,7 +250,7 @@ void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, co
QPen selectedJobPen;
const JobStopEntry selectedJob = scene->getSelectedJob();
- if(drawSelection && selectedJob.jobId)
+ if (drawSelection && selectedJob.jobId)
{
selectedJobPen.setWidthF(jobPen.widthF() * SelectedJobWidthFactor);
selectedJobPen.setCapStyle(Qt::RoundCap);
@@ -266,48 +267,48 @@ void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, co
JobCategory lastJobCategory = JobCategory::NCategories;
QTextOption textOption(Qt::AlignTop | Qt::AlignLeft);
- for(const StationGraphObject &st : qAsConst(scene->stations))
+ for (const StationGraphObject &st : qAsConst(scene->stations))
{
- const double left = st.xPos;
+ const double left = st.xPos;
const double right = left + st.platforms.count() * platfOffset;
- //Set a maximum right edge to Job labels
- //This allows to determine if they have to be drawn
+ // Set a maximum right edge to Job labels
+ // This allows to determine if they have to be drawn
const double maxJobLabelX = right + stationOffset;
- if(left > rect.right() || maxJobLabelX < rect.left())
- continue; //Skip station, it's not visible
+ if (left > rect.right() || maxJobLabelX < rect.left())
+ continue; // Skip station, it's not visible
top.rx() = bottom.rx() = st.xPos;
- for(const StationGraphObject::PlatformGraph& platf : st.platforms)
+ for (const StationGraphObject::PlatformGraph &platf : st.platforms)
{
- for(const StationGraphObject::JobStopGraph& jobStop : platf.jobStops)
+ for (const StationGraphObject::JobStopGraph &jobStop : platf.jobStops)
{
- //NOTE: departure comes AFTER arrival in time, opposite than job segment
- if(jobStop.arrivalY > rect.bottom() || jobStop.departureY < rect.top())
- continue; //Skip, job not visible
+ // NOTE: departure comes AFTER arrival in time, opposite than job segment
+ if (jobStop.arrivalY > rect.bottom() || jobStop.departureY < rect.top())
+ continue; // Skip, job not visible
top.setY(jobStop.arrivalY);
bottom.setY(jobStop.departureY);
const bool nullStopDuration = qFuzzyCompare(top.y(), bottom.y());
- if(drawSelection && selectedJob.jobId == jobStop.stop.jobId)
+ if (drawSelection && selectedJob.jobId == jobStop.stop.jobId)
{
- //Draw selection around segment
+ // Draw selection around segment
painter->setPen(selectedJobPen);
- if(nullStopDuration)
+ if (nullStopDuration)
painter->drawPoint(top);
else
painter->drawLine(top, bottom);
- //Reset pen
+ // Reset pen
painter->setPen(jobPen);
}
- if(lastJobCategory != jobStop.stop.category)
+ if (lastJobCategory != jobStop.stop.category)
{
QColor color = Session->colorForCat(jobStop.stop.category);
jobPen.setColor(color);
@@ -315,17 +316,18 @@ void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, co
lastJobCategory = jobStop.stop.category;
}
- if(nullStopDuration)
+ if (nullStopDuration)
painter->drawPoint(top);
else
painter->drawLine(top, bottom);
- if(jobStop.drawLabel)
+ if (jobStop.drawLabel)
{
- const QString jobName = JobCategoryName::jobName(jobStop.stop.jobId, jobStop.stop.category);
+ const QString jobName =
+ JobCategoryName::jobName(jobStop.stop.jobId, jobStop.stop.category);
- //Put label a bit to the left in respect to the stop arrival point
- //Calculate width so it doesn't go after maxJobLabelX
+ // Put label a bit to the left in respect to the stop arrival point
+ // Calculate width so it doesn't go after maxJobLabelX
const qreal topWithMargin = top.x() + platfOffset / 2;
QRectF r(topWithMargin, top.y(), maxJobLabelX - topWithMargin, 25);
painter->drawText(r, jobName, textOption);
@@ -338,7 +340,8 @@ void BackgroundHelper::drawJobStops(QPainter *painter, LineGraphScene *scene, co
}
}
-void BackgroundHelper::drawJobSegments(QPainter *painter, LineGraphScene *scene, const QRectF &rect, bool drawSelection)
+void BackgroundHelper::drawJobSegments(QPainter *painter, LineGraphScene *scene, const QRectF &rect,
+ bool drawSelection)
{
const double stationOffset = Session->stationOffset;
@@ -357,7 +360,7 @@ void BackgroundHelper::drawJobSegments(QPainter *painter, LineGraphScene *scene,
QPen selectedJobPen;
const JobStopEntry selectedJob = scene->getSelectedJob();
- if(drawSelection && selectedJob.jobId)
+ if (drawSelection && selectedJob.jobId)
{
selectedJobPen.setWidthF(jobPen.widthF() * SelectedJobWidthFactor);
selectedJobPen.setCapStyle(Qt::RoundCap);
@@ -371,47 +374,47 @@ void BackgroundHelper::drawJobSegments(QPainter *painter, LineGraphScene *scene,
JobCategory lastJobCategory = JobCategory::NCategories;
QTextOption textOption(Qt::AlignCenter);
- //Iterate until one but last
- //This way we can always acces next station
- for(int i = 0; i < scene->stationPositions.size() - 1; i++)
+ // Iterate until one but last
+ // This way we can always acces next station
+ for (int i = 0; i < scene->stationPositions.size() - 1; i++)
{
- const LineGraphScene::StationPosEntry& stPos = scene->stationPositions.at(i);
+ const LineGraphScene::StationPosEntry &stPos = scene->stationPositions.at(i);
- const double left = stPos.xPos;
- double right = 0;
+ const double left = stPos.xPos;
+ double right = 0;
- if(i < scene->stationPositions.size() - 2)
+ if (i < scene->stationPositions.size() - 2)
{
- const LineGraphScene::StationPosEntry& afterNextPos = scene->stationPositions.at(i + 2);
- right = afterNextPos.xPos - stationOffset;
+ const LineGraphScene::StationPosEntry &afterNextPos = scene->stationPositions.at(i + 2);
+ right = afterNextPos.xPos - stationOffset;
}
else
{
- right = rect.right(); //Last station, use all space on right side
+ right = rect.right(); // Last station, use all space on right side
}
- if(left > rect.right() || right < rect.left())
- continue; //Skip station, it's not visible
+ if (left > rect.right() || right < rect.left())
+ continue; // Skip station, it's not visible
- for(const LineGraphScene::JobSegmentGraph& job : stPos.nextSegmentJobGraphs)
+ for (const LineGraphScene::JobSegmentGraph &job : stPos.nextSegmentJobGraphs)
{
- //NOTE: departure comes BEFORE arrival in time, opposite than job stop
- if(job.fromDeparture.y() > rect.bottom() || job.toArrival.y() < rect.top())
- continue; //Skip, job not visible
+ // NOTE: departure comes BEFORE arrival in time, opposite than job stop
+ if (job.fromDeparture.y() > rect.bottom() || job.toArrival.y() < rect.top())
+ continue; // Skip, job not visible
const QLineF line(job.fromDeparture, job.toArrival);
- if(drawSelection && selectedJob.jobId == job.jobId)
+ if (drawSelection && selectedJob.jobId == job.jobId)
{
- //Draw selection around segment
+ // Draw selection around segment
painter->setPen(selectedJobPen);
painter->drawLine(line);
- //Reset pen
+ // Reset pen
painter->setPen(jobPen);
}
- if(lastJobCategory != job.category)
+ if (lastJobCategory != job.category)
{
QColor color = Session->colorForCat(job.category);
jobPen.setColor(color);
@@ -423,35 +426,35 @@ void BackgroundHelper::drawJobSegments(QPainter *painter, LineGraphScene *scene,
const QString jobName = JobCategoryName::jobName(job.jobId, job.category);
- //Save old transformation to reset it after drawing text
+ // Save old transformation to reset it after drawing text
const QTransform oldTransf = painter->transform();
- //Move to line center, it will be rotation pivot
+ // Move to line center, it will be rotation pivot
painter->translate(line.center());
- //Rotate by line angle
+ // Rotate by line angle
qreal angle = line.angle();
- if(job.fromDeparture.x() > job.toArrival.x())
- angle += 180.0; //Prevent flipping text
+ if (job.fromDeparture.x() > job.toArrival.x())
+ angle += 180.0; // Prevent flipping text
- painter->rotate(-angle); //minus because QPainter wants clockwise angle
+ painter->rotate(-angle); // minus because QPainter wants clockwise angle
const double lineLength = line.length();
QRectF textRect(-lineLength / 2, -30, lineLength, 25);
- //Try to avoid overlapping text of crossing jobs, move text towards arrival
- if(job.toArrival.x() > job.fromDeparture.x())
+ // Try to avoid overlapping text of crossing jobs, move text towards arrival
+ if (job.toArrival.x() > job.fromDeparture.x())
textRect.moveLeft(textRect.left() + lineLength / 5);
else
textRect.moveLeft(textRect.left() - lineLength / 5);
textRect = painter->boundingRect(textRect, jobName, textOption);
- //Draw a semi transparent background to ease text reading
+ // Draw a semi transparent background to ease text reading
painter->fillRect(textRect, textBackground);
painter->drawText(textRect, jobName, textOption);
- //Reset to old transformation
+ // Reset to old transformation
painter->setTransform(oldTransf);
}
}
diff --git a/src/graph/view/backgroundhelper.h b/src/graph/view/backgroundhelper.h
index c910c43..0bfc6cf 100644
--- a/src/graph/view/backgroundhelper.h
+++ b/src/graph/view/backgroundhelper.h
@@ -36,21 +36,23 @@ class LineGraphScene;
class BackgroundHelper
{
public:
- static void drawHourPanel(QPainter *painter, const QRectF& rect);
+ static void drawHourPanel(QPainter *painter, const QRectF &rect);
- static void drawBackgroundHourLines(QPainter *painter, const QRectF& rect);
+ static void drawBackgroundHourLines(QPainter *painter, const QRectF &rect);
- static void drawStationHeader(QPainter *painter, LineGraphScene *scene, const QRectF& rect);
+ static void drawStationHeader(QPainter *painter, LineGraphScene *scene, const QRectF &rect);
- static void drawStations(QPainter *painter, LineGraphScene *scene, const QRectF& rect);
+ static void drawStations(QPainter *painter, LineGraphScene *scene, const QRectF &rect);
- static void drawJobStops(QPainter *painter, LineGraphScene *scene, const QRectF& rect, bool drawSelection);
+ static void drawJobStops(QPainter *painter, LineGraphScene *scene, const QRectF &rect,
+ bool drawSelection);
- static void drawJobSegments(QPainter *painter, LineGraphScene *scene, const QRectF &rect, bool drawSelection);
+ static void drawJobSegments(QPainter *painter, LineGraphScene *scene, const QRectF &rect,
+ bool drawSelection);
public:
static constexpr double SelectedJobWidthFactor = 3.0;
- static constexpr int SelectedJobAlphaFactor = 127;
+ static constexpr int SelectedJobAlphaFactor = 127;
};
#endif // BACKGROUNDHELPER_H
diff --git a/src/graph/view/linegraphselectionwidget.cpp b/src/graph/view/linegraphselectionwidget.cpp
index c9dc21f..ef6f57d 100644
--- a/src/graph/view/linegraphselectionwidget.cpp
+++ b/src/graph/view/linegraphselectionwidget.cpp
@@ -49,20 +49,22 @@ LineGraphSelectionWidget::LineGraphSelectionWidget(QWidget *parent) :
QStringList items;
items.reserve(int(LineGraphType::NTypes));
- for(int i = 0; i < int(LineGraphType::NTypes); i++)
+ for (int i = 0; i < int(LineGraphType::NTypes); i++)
items.append(utils::getLineGraphTypeName(LineGraphType(i)));
graphTypeCombo->addItems(items);
graphTypeCombo->setCurrentIndex(0);
- connect(graphTypeCombo, qOverload(&QComboBox::activated), this, &LineGraphSelectionWidget::onTypeComboActivated);
- connect(objectCombo, &CustomCompletionLineEdit::completionDone, this, &LineGraphSelectionWidget::onCompletionDone);
+ connect(graphTypeCombo, qOverload(&QComboBox::activated), this,
+ &LineGraphSelectionWidget::onTypeComboActivated);
+ connect(objectCombo, &CustomCompletionLineEdit::completionDone, this,
+ &LineGraphSelectionWidget::onCompletionDone);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
}
LineGraphSelectionWidget::~LineGraphSelectionWidget()
{
- if(matchModel)
+ if (matchModel)
{
objectCombo->setModel(nullptr);
delete matchModel;
@@ -77,7 +79,7 @@ LineGraphType LineGraphSelectionWidget::getGraphType() const
void LineGraphSelectionWidget::setGraphType(LineGraphType type)
{
- if(getGraphType() == type)
+ if (getGraphType() == type)
return;
graphTypeCombo->setCurrentIndex(int(type));
@@ -98,16 +100,16 @@ const QString &LineGraphSelectionWidget::getObjectName() const
void LineGraphSelectionWidget::setObjectId(db_id objectId, const QString &name)
{
- if(m_graphType == LineGraphType::NoGraph)
- return; //Object ID must be null
+ if (m_graphType == LineGraphType::NoGraph)
+ return; // Object ID must be null
m_name = name;
- if(!objectId)
+ if (!objectId)
m_name.clear();
objectCombo->setData(objectId, name);
- if(m_objectId != objectId)
+ if (m_objectId != objectId)
emit graphChanged(int(m_graphType), m_objectId);
}
@@ -119,7 +121,7 @@ void LineGraphSelectionWidget::onTypeComboActivated(int index)
void LineGraphSelectionWidget::onCompletionDone()
{
- if(!objectCombo->getData(m_objectId, m_name))
+ if (!objectCombo->getData(m_objectId, m_name))
return;
emit graphChanged(int(m_graphType), m_objectId);
@@ -127,17 +129,17 @@ void LineGraphSelectionWidget::onCompletionDone()
void LineGraphSelectionWidget::setupModel(LineGraphType type)
{
- if(type != m_graphType)
+ if (type != m_graphType)
{
- //Clear old model
- if(matchModel)
+ // Clear old model
+ if (matchModel)
{
objectCombo->setModel(nullptr);
delete matchModel;
matchModel = nullptr;
}
- //Manually clear line edit
+ // Manually clear line edit
m_objectId = 0;
m_name.clear();
objectCombo->setData(m_objectId, m_name);
@@ -147,7 +149,7 @@ void LineGraphSelectionWidget::setupModel(LineGraphType type)
case LineGraphType::NoGraph:
default:
{
- //Prevent recursion on loadGraph() calling back to us
+ // Prevent recursion on loadGraph() calling back to us
type = LineGraphType::NoGraph;
break;
}
@@ -168,14 +170,13 @@ void LineGraphSelectionWidget::setupModel(LineGraphType type)
case LineGraphType::RailwayLine:
{
LinesMatchModel *m = new LinesMatchModel(Session->m_Db, true, this);
- matchModel = m;
+ matchModel = m;
break;
}
}
- if(matchModel)
+ if (matchModel)
objectCombo->setModel(matchModel);
}
m_graphType = type;
}
-
diff --git a/src/graph/view/linegraphselectionwidget.h b/src/graph/view/linegraphselectionwidget.h
index 72a7321..f00cc6e 100644
--- a/src/graph/view/linegraphselectionwidget.h
+++ b/src/graph/view/linegraphselectionwidget.h
@@ -51,7 +51,7 @@ public:
db_id getObjectId() const;
const QString &getObjectName() const;
- void setObjectId(db_id objectId, const QString& name);
+ void setObjectId(db_id objectId, const QString &name);
void setName(const QString &newName);
diff --git a/src/graph/view/linegraphtoolbar.cpp b/src/graph/view/linegraphtoolbar.cpp
index 909a14f..c5f16b7 100644
--- a/src/graph/view/linegraphtoolbar.cpp
+++ b/src/graph/view/linegraphtoolbar.cpp
@@ -49,7 +49,8 @@ LineGraphToolbar::LineGraphToolbar(QWidget *parent) :
lay->setContentsMargins(0, 0, 0, 0);
selectionWidget = new LineGraphSelectionWidget;
- connect(selectionWidget, &LineGraphSelectionWidget::graphChanged, this, &LineGraphToolbar::onWidgetGraphChanged);
+ connect(selectionWidget, &LineGraphSelectionWidget::graphChanged, this,
+ &LineGraphToolbar::onWidgetGraphChanged);
lay->addWidget(selectionWidget);
redrawBut = new QPushButton(tr("Redraw"));
@@ -70,57 +71,59 @@ LineGraphToolbar::LineGraphToolbar(QWidget *parent) :
zoomSpinBox->setRange(25, 400);
zoomSpinBox->setValue(mZoom);
zoomSpinBox->setSuffix(QChar('%'));
- connect(zoomSpinBox, qOverload(&QSpinBox::valueChanged), this, &LineGraphToolbar::updateZoomLevel);
+ connect(zoomSpinBox, qOverload(&QSpinBox::valueChanged), this,
+ &LineGraphToolbar::updateZoomLevel);
lay->addWidget(zoomSpinBox);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
- //Accept focus events by click
+ // Accept focus events by click
setFocusPolicy(Qt::ClickFocus);
- //Install event filter to catch focus events on children widgets
- for(QObject *child : selectionWidget->children())
+ // Install event filter to catch focus events on children widgets
+ for (QObject *child : selectionWidget->children())
{
- if(child->isWidgetType())
+ if (child->isWidgetType())
child->installEventFilter(this);
}
- //Install event filter on Zoom Slider to catch double click
+ // Install event filter on Zoom Slider to catch double click
zoomSlider->installEventFilter(this);
}
LineGraphToolbar::~LineGraphToolbar()
{
-
}
void LineGraphToolbar::setScene(LineGraphScene *scene)
{
- if(m_scene)
+ if (m_scene)
{
- disconnect(m_scene, &LineGraphScene::graphChanged, this, &LineGraphToolbar::onSceneGraphChanged);
+ disconnect(m_scene, &LineGraphScene::graphChanged, this,
+ &LineGraphToolbar::onSceneGraphChanged);
disconnect(m_scene, &QObject::destroyed, this, &LineGraphToolbar::onSceneDestroyed);
}
m_scene = scene;
- if(m_scene)
+ if (m_scene)
{
- connect(m_scene, &LineGraphScene::graphChanged, this, &LineGraphToolbar::onSceneGraphChanged);
+ connect(m_scene, &LineGraphScene::graphChanged, this,
+ &LineGraphToolbar::onSceneGraphChanged);
connect(m_scene, &QObject::destroyed, this, &LineGraphToolbar::onSceneDestroyed);
}
}
bool LineGraphToolbar::eventFilter(QObject *watched, QEvent *ev)
{
- if(ev->type() == QEvent::FocusIn)
+ if (ev->type() == QEvent::FocusIn)
{
- //If any of our child widgets receives focus, activate our scene
- if(m_scene)
+ // If any of our child widgets receives focus, activate our scene
+ if (m_scene)
m_scene->activateScene();
}
- if(watched == zoomSlider && ev->type() == QEvent::MouseButtonDblClick)
+ if (watched == zoomSlider && ev->type() == QEvent::MouseButtonDblClick)
{
- //Zoom Slider was double clicked, reset zoom level to 100
+ // Zoom Slider was double clicked, reset zoom level to 100
updateZoomLevel(100);
}
@@ -130,14 +133,14 @@ bool LineGraphToolbar::eventFilter(QObject *watched, QEvent *ev)
void LineGraphToolbar::resetToolbarToScene()
{
LineGraphType type = LineGraphType::NoGraph;
- db_id objectId = 0;
+ db_id objectId = 0;
QString name;
- if(m_scene)
+ if (m_scene)
{
- type = m_scene->getGraphType();
+ type = m_scene->getGraphType();
objectId = m_scene->getGraphObjectId();
- name = m_scene->getGraphObjectName();
+ name = m_scene->getGraphObjectName();
}
selectionWidget->setGraphType(type);
@@ -146,7 +149,7 @@ void LineGraphToolbar::resetToolbarToScene()
void LineGraphToolbar::updateZoomLevel(int zoom)
{
- if(mZoom == zoom)
+ if (mZoom == zoom)
return;
mZoom = zoom;
@@ -160,13 +163,13 @@ void LineGraphToolbar::updateZoomLevel(int zoom)
void LineGraphToolbar::onWidgetGraphChanged(int type, db_id objectId)
{
LineGraphType graphType = LineGraphType(type);
- if(graphType == LineGraphType::NoGraph)
+ if (graphType == LineGraphType::NoGraph)
objectId = 0;
- if(graphType != LineGraphType::NoGraph && !objectId)
- return; //User is still selecting an object
+ if (graphType != LineGraphType::NoGraph && !objectId)
+ return; // User is still selecting an object
- if(m_scene)
+ if (m_scene)
m_scene->loadGraph(objectId, graphType);
}
@@ -175,7 +178,7 @@ void LineGraphToolbar::onSceneGraphChanged(int type, db_id objectId)
selectionWidget->setGraphType(LineGraphType(type));
QString name;
- if(m_scene && m_scene->getGraphObjectId() == objectId)
+ if (m_scene && m_scene->getGraphObjectId() == objectId)
name = m_scene->getGraphObjectName();
selectionWidget->setObjectId(objectId, name);
}
@@ -183,12 +186,12 @@ void LineGraphToolbar::onSceneGraphChanged(int type, db_id objectId)
void LineGraphToolbar::onSceneDestroyed()
{
m_scene = nullptr;
- resetToolbarToScene(); //Clear UI
+ resetToolbarToScene(); // Clear UI
}
void LineGraphToolbar::focusInEvent(QFocusEvent *e)
{
- if(m_scene)
+ if (m_scene)
m_scene->activateScene();
QWidget::focusInEvent(e);
diff --git a/src/graph/view/linegraphview.cpp b/src/graph/view/linegraphview.cpp
index a76bf0e..75f557f 100644
--- a/src/graph/view/linegraphview.cpp
+++ b/src/graph/view/linegraphview.cpp
@@ -31,27 +31,28 @@
LineGraphView::LineGraphView(QWidget *parent) :
BasicGraphView(parent)
{
-
}
bool LineGraphView::viewportEvent(QEvent *e)
{
LineGraphScene *lineScene = qobject_cast(scene());
- if(e->type() == QEvent::ToolTip && lineScene && lineScene->getGraphType() != LineGraphType::NoGraph)
+ if (e->type() == QEvent::ToolTip && lineScene
+ && lineScene->getGraphType() != LineGraphType::NoGraph)
{
- QHelpEvent *ev = static_cast(e);
+ QHelpEvent *ev = static_cast(e);
const QPointF scenePos = mapToScene(ev->pos());
- JobStopEntry job = lineScene->getJobAt(scenePos, Session->platformOffset / 2);
+ JobStopEntry job = lineScene->getJobAt(scenePos, Session->platformOffset / 2);
- if(job.jobId)
+ if (job.jobId)
{
- QToolTip::showText(ev->globalPos(),
- JobCategoryName::jobName(job.jobId, job.category),
+ QToolTip::showText(ev->globalPos(), JobCategoryName::jobName(job.jobId, job.category),
viewport());
- }else{
+ }
+ else
+ {
QToolTip::hideText();
}
@@ -71,11 +72,11 @@ void LineGraphView::mouseDoubleClickEvent(QMouseEvent *e)
{
LineGraphScene *lineScene = qobject_cast(scene());
- if(!lineScene || lineScene->getGraphType() == LineGraphType::NoGraph)
- return; //Nothing to select
+ if (!lineScene || lineScene->getGraphType() == LineGraphType::NoGraph)
+ return; // Nothing to select
const QPointF scenePos = mapToScene(e->pos());
- JobStopEntry job = lineScene->getJobAt(scenePos, Session->platformOffset / 2);
+ JobStopEntry job = lineScene->getJobAt(scenePos, Session->platformOffset / 2);
lineScene->setSelectedJob(job);
}
diff --git a/src/graph/view/linegraphwidget.cpp b/src/graph/view/linegraphwidget.cpp
index 5b282c4..3e32a68 100644
--- a/src/graph/view/linegraphwidget.cpp
+++ b/src/graph/view/linegraphwidget.cpp
@@ -36,7 +36,7 @@ LineGraphWidget::LineGraphWidget(QWidget *parent) :
{
QVBoxLayout *lay = new QVBoxLayout(this);
- toolBar = new LineGraphToolbar(this);
+ toolBar = new LineGraphToolbar(this);
lay->addWidget(toolBar);
@@ -45,12 +45,13 @@ LineGraphWidget::LineGraphWidget(QWidget *parent) :
m_scene = new LineGraphScene(Session->m_Db, this);
- //Subscribe to notifications and to session managment
+ // Subscribe to notifications and to session managment
Session->getViewManager()->getLineGraphMgr()->registerScene(m_scene);
view->setScene(m_scene);
toolBar->setScene(m_scene);
- connect(view, &LineGraphView::syncToolbarToScene, toolBar, &LineGraphToolbar::resetToolbarToScene);
+ connect(view, &LineGraphView::syncToolbarToScene, toolBar,
+ &LineGraphToolbar::resetToolbarToScene);
connect(toolBar, &LineGraphToolbar::requestRedraw, m_scene, &LineGraphScene::reload);
connect(toolBar, &LineGraphToolbar::requestZoom, view, &LineGraphView::setZoomLevel);
@@ -59,7 +60,7 @@ LineGraphWidget::LineGraphWidget(QWidget *parent) :
bool LineGraphWidget::tryLoadGraph(db_id graphObjId, LineGraphType type)
{
- if(!m_scene)
+ if (!m_scene)
return false;
return m_scene->loadGraph(graphObjId, type);
diff --git a/src/graph/view/linegraphwidget.h b/src/graph/view/linegraphwidget.h
index 567d539..487ba82 100644
--- a/src/graph/view/linegraphwidget.h
+++ b/src/graph/view/linegraphwidget.h
@@ -46,9 +46,20 @@ class LineGraphWidget : public QWidget
public:
explicit LineGraphWidget(QWidget *parent = nullptr);
- inline LineGraphScene *getScene() const { return m_scene; }
- inline LineGraphView *getView() const { return view; }
- inline LineGraphToolbar *getToolbar() const { return toolBar; }
+ inline LineGraphScene *getScene() const
+ {
+ return m_scene;
+ }
+
+ inline LineGraphView *getView() const
+ {
+ return view;
+ }
+
+ inline LineGraphToolbar *getToolbar() const
+ {
+ return toolBar;
+ }
bool tryLoadGraph(db_id graphObjId, LineGraphType type);
diff --git a/src/jobs/jobeditor/editstopdialog.cpp b/src/jobs/jobeditor/editstopdialog.cpp
index b40a66d..79cc268 100644
--- a/src/jobs/jobeditor/editstopdialog.cpp
+++ b/src/jobs/jobeditor/editstopdialog.cpp
@@ -48,7 +48,6 @@
#include "app/scopedebug.h"
-
EditStopDialog::EditStopDialog(StopModel *m, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditStopDialog),
@@ -57,12 +56,13 @@ EditStopDialog::EditStopDialog(StopModel *m, QWidget *parent) :
{
ui->setupUi(this);
- //Stop
- helper = new StopEditingHelper(Session->m_Db, stopModel,
- ui->outGateTrackSpin, ui->arrivalTimeEdit, ui->departureTimeEdit,
- this);
- connect(helper, &StopEditingHelper::nextSegmentChosen, this, &EditStopDialog::updateAdditionalNotes);
- connect(helper, &StopEditingHelper::stationTrackChosen, this, &EditStopDialog::updateAdditionalNotes);
+ // Stop
+ helper = new StopEditingHelper(Session->m_Db, stopModel, ui->outGateTrackSpin,
+ ui->arrivalTimeEdit, ui->departureTimeEdit, this);
+ connect(helper, &StopEditingHelper::nextSegmentChosen, this,
+ &EditStopDialog::updateAdditionalNotes);
+ connect(helper, &StopEditingHelper::stationTrackChosen, this,
+ &EditStopDialog::updateAdditionalNotes);
CustomCompletionLineEdit *mStationEdit = helper->getStationEdit();
CustomCompletionLineEdit *mStTrackEdit = helper->getStTrackEdit();
@@ -72,17 +72,17 @@ EditStopDialog::EditStopDialog(StopModel *m, QWidget *parent) :
ui->curStopLay->setWidget(2, QFormLayout::FieldRole, mStTrackEdit);
ui->curStopLay->setWidget(3, QFormLayout::FieldRole, mOutGateEdit);
- //Coupling
- couplingMgr = new RSCouplingInterface(Session->m_Db, this);
+ // Coupling
+ couplingMgr = new RSCouplingInterface(Session->m_Db, this);
coupledModel = new StopCouplingModel(Session->m_Db, this);
- auto ps = new ModelPageSwitcher(true, this);
+ auto ps = new ModelPageSwitcher(true, this);
ps->setModel(coupledModel);
ui->coupledView->setModel(coupledModel);
ui->coupledLayout->insertWidget(1, ps);
uncoupledModel = new StopCouplingModel(Session->m_Db, this);
- ps = new ModelPageSwitcher(true, this);
+ ps = new ModelPageSwitcher(true, this);
ps->setModel(uncoupledModel);
ui->uncoupledView->setModel(uncoupledModel);
ui->uncoupledLayout->insertWidget(1, ps);
@@ -93,28 +93,32 @@ EditStopDialog::EditStopDialog(StopModel *m, QWidget *parent) :
ui->coupledView->setContextMenuPolicy(Qt::CustomContextMenu);
ui->uncoupledView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui->coupledView, &QAbstractItemView::customContextMenuRequested, this, &EditStopDialog::couplingCustomContextMenuRequested);
- connect(ui->uncoupledView, &QAbstractItemView::customContextMenuRequested, this, &EditStopDialog::couplingCustomContextMenuRequested);
+ connect(ui->coupledView, &QAbstractItemView::customContextMenuRequested, this,
+ &EditStopDialog::couplingCustomContextMenuRequested);
+ connect(ui->uncoupledView, &QAbstractItemView::customContextMenuRequested, this,
+ &EditStopDialog::couplingCustomContextMenuRequested);
- //Setup train asset models
+ // Setup train asset models
trainAssetModelBefore = new TrainAssetModel(Session->m_Db, this);
- ps = new ModelPageSwitcher(true, this);
+ ps = new ModelPageSwitcher(true, this);
ps->setModel(trainAssetModelBefore);
ui->assetBeforeView->setModel(trainAssetModelBefore);
ui->trainAssetGridLayout->addWidget(ps, 2, 0);
trainAssetModelAfter = new TrainAssetModel(Session->m_Db, this);
- ps = new ModelPageSwitcher(true, this);
+ ps = new ModelPageSwitcher(true, this);
ps->setModel(trainAssetModelAfter);
ui->assetAfterView->setModel(trainAssetModelAfter);
ui->trainAssetGridLayout->addWidget(ps, 2, 1);
ui->assetBeforeView->setContextMenuPolicy(Qt::CustomContextMenu);
ui->assetAfterView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui->assetBeforeView, &QAbstractItemView::customContextMenuRequested, this, &EditStopDialog::couplingCustomContextMenuRequested);
- connect(ui->assetAfterView, &QAbstractItemView::customContextMenuRequested, this, &EditStopDialog::couplingCustomContextMenuRequested);
+ connect(ui->assetBeforeView, &QAbstractItemView::customContextMenuRequested, this,
+ &EditStopDialog::couplingCustomContextMenuRequested);
+ connect(ui->assetAfterView, &QAbstractItemView::customContextMenuRequested, this,
+ &EditStopDialog::couplingCustomContextMenuRequested);
- //Setup Crossings/Passings
+ // Setup Crossings/Passings
passingsModel = new JobPassingsModel(this);
ui->passingsView->setModel(passingsModel);
@@ -123,13 +127,15 @@ EditStopDialog::EditStopDialog(StopModel *m, QWidget *parent) :
connect(ui->calcPassingsBut, &QPushButton::clicked, this, &EditStopDialog::calcPassings);
- //BIG TODO: temporarily disable option to Cancel dialog
- //This is because at the moment it doesn't seem Coupling are canceled
- //So you get a mixed state: Arrival/Departure/Descriptio ecc changes are canceled but Coupling changes are still applied
+ // BIG TODO: temporarily disable option to Cancel dialog
+ // This is because at the moment it doesn't seem Coupling are canceled
+ // So you get a mixed state: Arrival/Departure/Descriptio ecc changes are canceled but Coupling
+ // changes are still applied
ui->buttonBox->setStandardButtons(QDialogButtonBox::Ok);
- ui->buttonBox->button(QDialogButtonBox::Ok)->setToolTip(tr("Press SHIFT modifier and click to save changes"
- " without recalculating travel times."));
+ ui->buttonBox->button(QDialogButtonBox::Ok)
+ ->setToolTip(tr("Press SHIFT modifier and click to save changes"
+ " without recalculating travel times."));
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
@@ -149,15 +155,15 @@ void EditStopDialog::clearUi()
{
helper->stopOutTrackTimer();
- stopIdx = QModelIndex();
+ stopIdx = QModelIndex();
- m_jobId = 0;
+ m_jobId = 0;
m_jobCat = JobCategory::FREIGHT;
trainAssetModelBefore->setStop(0, QTime(), TrainAssetModel::BeforeStop);
trainAssetModelAfter->setStop(0, QTime(), TrainAssetModel::AfterStop);
- //TODO: clear UI properly
+ // TODO: clear UI properly
}
void EditStopDialog::showBeforeAsset(bool val)
@@ -172,78 +178,79 @@ void EditStopDialog::showAfterAsset(bool val)
ui->assetAfterLabel->setVisible(val);
}
-void EditStopDialog::setStop(const QModelIndex& idx)
+void EditStopDialog::setStop(const QModelIndex &idx)
{
DEBUG_ENTRY;
- if(!idx.isValid())
+ if (!idx.isValid())
{
clearUi();
return;
}
- m_jobId = stopModel->getJobId();
- m_jobCat = stopModel->getCategory();
+ m_jobId = stopModel->getJobId();
+ m_jobCat = stopModel->getCategory();
- stopIdx = idx;
+ stopIdx = idx;
- const StopItem& curStop = stopModel->getItemAt(idx.row());
+ const StopItem &curStop = stopModel->getItemAt(idx.row());
StopItem prevStop;
- if(idx.row() == 0)
- prevStop = StopItem(); //First stop has no previous stop
+ if (idx.row() == 0)
+ prevStop = StopItem(); // First stop has no previous stop
else
prevStop = stopModel->getItemAt(idx.row() - 1);
helper->setStop(curStop, prevStop);
- //Setup Train Asset
+ // Setup Train Asset
trainAssetModelBefore->setStop(m_jobId, curStop.arrival, TrainAssetModel::BeforeStop);
trainAssetModelAfter->setStop(m_jobId, curStop.arrival, TrainAssetModel::AfterStop);
- //Hide train asset before stop on First stop
+ // Hide train asset before stop on First stop
showBeforeAsset(curStop.type != StopType::First);
- //Hide train asset after stop on Last stop
+ // Hide train asset after stop on Last stop
showAfterAsset(curStop.type != StopType::Last);
- //Coupling operations
+ // Coupling operations
coupledModel->setStop(curStop.stopId, RsOp::Coupled);
uncoupledModel->setStop(curStop.stopId, RsOp::Uncoupled);
- //Update UI
+ // Update UI
updateInfo();
- //Calc passings
+ // Calc passings
calcPassings();
- //Update Title
+ // Update Title
const QString jobName = JobCategoryName::jobName(m_jobId, m_jobCat);
setWindowTitle(jobName);
}
void EditStopDialog::updateInfo()
{
- const StopItem& curStop = helper->getCurItem();
- const StopItem& prevStop = helper->getPrevItem();
+ const StopItem &curStop = helper->getCurItem();
+ const StopItem &prevStop = helper->getPrevItem();
- const QString inGateStr = helper->getGateString(curStop.fromGate.gateId,
- prevStop.nextSegment.reversed);
+ const QString inGateStr =
+ helper->getGateString(curStop.fromGate.gateId, prevStop.nextSegment.reversed);
ui->inGateEdit->setText(inGateStr);
- if(curStop.type == StopType::First)
+ if (curStop.type == StopType::First)
{
- //Hide box of previous stop
+ // Hide box of previous stop
ui->prevStopBox->setVisible(false);
ui->curStopBox->setTitle(tr("First Stop"));
}
else
{
- //Show box of previous stop
+ // Show box of previous stop
ui->prevStopBox->setVisible(true);
- ui->curStopBox->setTitle(curStop.type == StopType::Last ? tr("Last Stop") : tr("Current Stop"));
+ ui->curStopBox->setTitle(curStop.type == StopType::Last ? tr("Last Stop")
+ : tr("Current Stop"));
QString prevStName;
- if(prevStop.stationId)
+ if (prevStop.stationId)
{
query q(Session->m_Db, "SELECT name FROM stations WHERE id=?");
q.bind(1, prevStop.stationId);
@@ -252,17 +259,17 @@ void EditStopDialog::updateInfo()
}
ui->prevStEdit->setText(prevStName);
- const QString outGateStr = helper->getGateString(prevStop.toGate.gateId,
- prevStop.nextSegment.reversed);
+ const QString outGateStr =
+ helper->getGateString(prevStop.toGate.gateId, prevStop.nextSegment.reversed);
ui->prevOutGateEdit->setText(outGateStr);
}
const QString descr = stopModel->getDescription(curStop);
ui->descriptionEdit->setPlainText(descr);
- if(curStop.type == StopType::Transit)
+ if (curStop.type == StopType::Transit)
{
- //On transit you cannot couple/uncouple rollingstock
+ // On transit you cannot couple/uncouple rollingstock
ui->editCoupledBut->setEnabled(false);
ui->editUncoupledBut->setEnabled(false);
}
@@ -276,13 +283,12 @@ void EditStopDialog::saveDataToModel()
{
DEBUG_ENTRY;
- const StopItem& curStop = helper->getCurItem();
- const StopItem& prevStop = helper->getPrevItem();
+ const StopItem &curStop = helper->getCurItem();
+ const StopItem &prevStop = helper->getPrevItem();
- if(ui->descriptionEdit->document()->isModified())
+ if (ui->descriptionEdit->document()->isModified())
{
- stopModel->setDescription(stopIdx,
- ui->descriptionEdit->toPlainText());
+ stopModel->setDescription(stopIdx, ui->descriptionEdit->toPlainText());
}
bool avoidTimeRecalc = QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier);
@@ -291,8 +297,8 @@ void EditStopDialog::saveDataToModel()
void EditStopDialog::importJobRS()
{
- const StopItem& curStop = helper->getCurItem();
- if(!curStop.stationId)
+ const StopItem &curStop = helper->getCurItem();
+ if (!curStop.stationId)
{
QMessageBox::warning(this, tr("Import Error"),
tr("In order to import rollingstock from other
"
@@ -305,48 +311,49 @@ void EditStopDialog::importJobRS()
jobsMatch.setDefaultId(JobMatchModel::StopId);
jobsMatch.setFilter(m_jobId, curStop.stationId, curStop.departure);
- QString stName = helper->getStationEdit()->text();
+ QString stName = helper->getStationEdit()->text();
OwningQPointer dlg = new ChooseItemDlg(&jobsMatch, this);
- dlg->setDescription(tr("Please choose a Job among the ones stopping at %1 before %2.
"
- "All rollingstock uncoupled by selected Job at current station
"
- "will be coupled to current Job.")
- .arg(stName,
- curStop.departure.toString("HH:mm")));
+ dlg->setDescription(
+ tr("Please choose a Job among the ones stopping at %1 before %2.
"
+ "All rollingstock uncoupled by selected Job at current station
"
+ "will be coupled to current Job.")
+ .arg(stName, curStop.departure.toString("HH:mm")));
dlg->setPlaceholder(tr("Job number without category"));
- //Select model
+ // Select model
int ret = dlg->exec();
- if(ret != QDialog::Accepted || !dlg)
+ if (ret != QDialog::Accepted || !dlg)
return;
db_id otherJobStopId = dlg->getItemId();
- if(!otherJobStopId)
+ if (!otherJobStopId)
return;
- //Import rollingstock
+ // Import rollingstock
int count = couplingMgr->importRSFromJob(otherJobStopId);
- //Refresh views
+ // Refresh views
coupledModel->refreshData(true);
trainAssetModelAfter->refreshData(true);
- //Tell user it's completed
- QMessageBox::information(this, tr("Importation Finished"),
- tr("%1 rollingstock items were successfully imported")
- .arg(count));
+ // Tell user it's completed
+ QMessageBox::information(
+ this, tr("Importation Finished"),
+ tr("%1 rollingstock items were successfully imported").arg(count));
}
void EditStopDialog::editCoupled()
{
- const StopItem& curStop = helper->getCurItem();
+ const StopItem &curStop = helper->getCurItem();
coupledModel->clearCache();
trainAssetModelAfter->clearCache();
OwningQPointer dlg = new RSCoupleDialog(couplingMgr, RsOp::Coupled, this);
dlg->setWindowTitle(tr("Couple"));
- dlg->loadProxyModels(Session->m_Db, m_jobId, curStop.stopId, curStop.stationId, curStop.arrival);
+ dlg->loadProxyModels(Session->m_Db, m_jobId, curStop.stopId, curStop.stationId,
+ curStop.arrival);
dlg->exec();
@@ -356,14 +363,15 @@ void EditStopDialog::editCoupled()
void EditStopDialog::editUncoupled()
{
- const StopItem& curStop = helper->getCurItem();
+ const StopItem &curStop = helper->getCurItem();
uncoupledModel->clearCache();
trainAssetModelAfter->clearCache();
OwningQPointer dlg = new RSCoupleDialog(couplingMgr, RsOp::Uncoupled, this);
dlg->setWindowTitle(tr("Uncouple"));
- dlg->loadProxyModels(Session->m_Db, m_jobId, curStop.stopId, curStop.stationId, curStop.arrival);
+ dlg->loadProxyModels(Session->m_Db, m_jobId, curStop.stopId, curStop.stationId,
+ curStop.arrival);
dlg->exec();
@@ -381,20 +389,21 @@ void EditStopDialog::calcPassings()
{
DEBUG_ENTRY;
- const StopItem& curStop = helper->getCurItem();
+ const StopItem &curStop = helper->getCurItem();
JobStopDirectionHelper dirHelper(Session->m_Db);
utils::Side myDirection = dirHelper.getStopOutSide(curStop.stopId);
- query q(Session->m_Db, "SELECT s.id, s.job_id, jobs.category, s.arrival, s.departure,"
- "t1.name,t2.name"
- " FROM stops s"
- " JOIN jobs ON jobs.id=s.job_id"
- " LEFT JOIN station_gate_connections g1 ON g1.id=s.in_gate_conn"
- " LEFT JOIN station_gate_connections g2 ON g2.id=s.out_gate_conn"
- " LEFT JOIN station_tracks t1 ON t1.id=g1.track_id"
- " LEFT JOIN station_tracks t2 ON t2.id=g2.track_id"
- " WHERE s.station_id=? AND s.departure >=? AND s.arrival<=? AND s.job_id <> ?");
+ query q(Session->m_Db,
+ "SELECT s.id, s.job_id, jobs.category, s.arrival, s.departure,"
+ "t1.name,t2.name"
+ " FROM stops s"
+ " JOIN jobs ON jobs.id=s.job_id"
+ " LEFT JOIN station_gate_connections g1 ON g1.id=s.in_gate_conn"
+ " LEFT JOIN station_gate_connections g2 ON g2.id=s.out_gate_conn"
+ " LEFT JOIN station_tracks t1 ON t1.id=g1.track_id"
+ " LEFT JOIN station_tracks t2 ON t2.id=g2.track_id"
+ " WHERE s.station_id=? AND s.departure >=? AND s.arrival<=? AND s.job_id <> ?");
q.bind(1, curStop.stationId);
q.bind(2, curStop.arrival);
@@ -403,27 +412,27 @@ void EditStopDialog::calcPassings()
QVector passings, crossings;
- for(auto r : q)
+ for (auto r : q)
{
JobPassingsModel::Entry e;
db_id otherStopId = r.get(0);
- e.jobId = r.get(1);
- e.category = JobCategory(r.get(2));
- e.arrival = r.get(3);
- e.departure = r.get(4);
- e.platform = r.get(5);
+ e.jobId = r.get(1);
+ e.category = JobCategory(r.get(2));
+ e.arrival = r.get(3);
+ e.departure = r.get(4);
+ e.platform = r.get(5);
- e.platform = r.get(6);
- if(e.platform.isEmpty())
- e.platform = r.get(7); //Use out gate to get track name
+ e.platform = r.get(6);
+ if (e.platform.isEmpty())
+ e.platform = r.get(7); // Use out gate to get track name
utils::Side otherDir = dirHelper.getStopOutSide(otherStopId);
- if(myDirection == otherDir)
- passings.append(e); //Same direction -> Passing
+ if (myDirection == otherDir)
+ passings.append(e); // Same direction -> Passing
else
- crossings.append(e); //Opposite direction -> Crossing
+ crossings.append(e); // Opposite direction -> Crossing
}
q.reset();
@@ -435,20 +444,21 @@ void EditStopDialog::calcPassings()
ui->crossingsView->resizeColumnsToContents();
}
-void EditStopDialog::couplingCustomContextMenuRequested(const QPoint& pos)
+void EditStopDialog::couplingCustomContextMenuRequested(const QPoint &pos)
{
OwningQPointer menu = new QMenu(this);
- QAction *act = menu->addAction(tr("Refresh"));
+ QAction *act = menu->addAction(tr("Refresh"));
- //HACK: could be ui->coupledView or ui->uncoupledView or ui->assetBeforeView or ui->assetAfterView
+ // HACK: could be ui->coupledView or ui->uncoupledView or ui->assetBeforeView or
+ // ui->assetAfterView
QAbstractItemView *view = qobject_cast(sender());
- if(!view)
- return; //Error: not called by the view?
+ if (!view)
+ return; // Error: not called by the view?
- if(menu->exec(view->viewport()->mapToGlobal(pos)) != act)
- return; //User didn't select 'Refresh' action
+ if (menu->exec(view->viewport()->mapToGlobal(pos)) != act)
+ return; // User didn't select 'Refresh' action
- //Refresh data
+ // Refresh data
coupledModel->refreshData(true);
uncoupledModel->refreshData(true);
trainAssetModelBefore->refreshData(true);
@@ -457,7 +467,7 @@ void EditStopDialog::couplingCustomContextMenuRequested(const QPoint& pos)
int EditStopDialog::getTrainSpeedKmH(bool afterStop)
{
- const StopItem& curStop = helper->getCurItem();
+ const StopItem &curStop = helper->getCurItem();
query q(Session->m_Db, "SELECT MIN(rs_models.max_speed), rs_id FROM("
"SELECT coupling.rs_id AS rs_id, MAX(stops.arrival)"
@@ -468,11 +478,11 @@ int EditStopDialog::getTrainSpeedKmH(bool afterStop)
" HAVING coupling.operation=1)"
" JOIN rs_list ON rs_list.id=rs_id"
" JOIN rs_models ON rs_models.id=rs_list.model_id");
- q.bind(1, m_jobId); //TODO: maybe move to model
+ q.bind(1, m_jobId); // TODO: maybe move to model
- //HACK: 1 minute is the min interval between stops,
- //by adding 1 minute we include the current stop but leave out the next one
- if(afterStop)
+ // HACK: 1 minute is the min interval between stops,
+ // by adding 1 minute we include the current stop but leave out the next one
+ if (afterStop)
q.bind(2, curStop.arrival.addSecs(60));
else
q.bind(2, curStop.arrival);
@@ -483,48 +493,48 @@ int EditStopDialog::getTrainSpeedKmH(bool afterStop)
void EditStopDialog::updateAdditionalNotes()
{
- const StopItem& curStop = helper->getCurItem();
+ const StopItem &curStop = helper->getCurItem();
QString msg;
- //Check direction
- if(curStop.fromGate.gateConnId && curStop.toGate.gateConnId
- && curStop.type != StopType::First && curStop.type != StopType::Last)
+ // Check direction
+ if (curStop.fromGate.gateConnId && curStop.toGate.gateConnId && curStop.type != StopType::First
+ && curStop.type != StopType::Last)
{
- //Ignore First and Last stop (sometimes they have fake in/out gates set which might trigger this message)
- //Both entry and exit path are set, check direction
- if(curStop.fromGate.stationTrackSide == curStop.toGate.stationTrackSide)
+ // Ignore First and Last stop (sometimes they have fake in/out gates set which might trigger
+ // this message) Both entry and exit path are set, check direction
+ if (curStop.fromGate.stationTrackSide == curStop.toGate.stationTrackSide)
{
- //Train leaves station track from same side of entrance
+ // Train leaves station track from same side of entrance
msg = tr("Train reverses direction.");
}
}
- //Check line traction
- if(curStop.type != StopType::Last && curStop.nextSegment.segmentId)
+ // Check line traction
+ if (curStop.type != StopType::Last && curStop.nextSegment.segmentId)
{
- //Last has no next segment so do not show traction type
+ // Last has no next segment so do not show traction type
bool nextSegmentElectrified = stopModel->isRailwayElectrifiedAfterRow(stopIdx.row());
- bool prevSegmentElectrified = !nextSegmentElectrified; //Trigger change on First stop
+ bool prevSegmentElectrified = !nextSegmentElectrified; // Trigger change on First stop
- if(curStop.type != StopType::First && stopIdx.row() >= 0)
+ if (curStop.type != StopType::First && stopIdx.row() >= 0)
{
- //Get real previous railway type
+ // Get real previous railway type
prevSegmentElectrified = stopModel->isRailwayElectrifiedAfterRow(stopIdx.row() - 1);
}
- if(!msg.isEmpty())
- msg.append("\n\n"); //Separate from previous message
+ if (!msg.isEmpty())
+ msg.append("\n\n"); // Separate from previous message
- if(nextSegmentElectrified)
+ if (nextSegmentElectrified)
msg.append(tr("Electric traction is ALLOWED."));
else
msg.append(tr("Electric traction is NOT ALLOWED."));
- if(nextSegmentElectrified != prevSegmentElectrified && curStop.type != StopType::First)
+ if (nextSegmentElectrified != prevSegmentElectrified && curStop.type != StopType::First)
{
- //Railway type changed
+ // Railway type changed
msg.append('\n');
msg.append(tr("(Different traction then previous line!)"));
}
@@ -536,7 +546,7 @@ void EditStopDialog::updateAdditionalNotes()
void EditStopDialog::setReadOnly(bool value)
{
- readOnly = value;
+ readOnly = value;
CustomCompletionLineEdit *mStationEdit = helper->getStationEdit();
CustomCompletionLineEdit *mStTrackEdit = helper->getStTrackEdit();
@@ -557,73 +567,78 @@ void EditStopDialog::setReadOnly(bool value)
void EditStopDialog::done(int val)
{
- if(val == QDialog::Accepted)
+ if (val == QDialog::Accepted)
{
- if(stopIdx.row() < stopModel->rowCount() - 2)
+ if (stopIdx.row() < stopModel->rowCount() - 2)
{
- //We are not last stop
+ // We are not last stop
- //Check if train has at least one engine after this stop
- //But not if we are Last stop (size - 1 - AddHere)
- //because the train doesn't have to leave the station
+ // Check if train has at least one engine after this stop
+ // But not if we are Last stop (size - 1 - AddHere)
+ // because the train doesn't have to leave the station
bool electricOnNonElectrifiedLine = false;
- if(!couplingMgr->hasEngineAfterStop(&electricOnNonElectrifiedLine) || electricOnNonElectrifiedLine)
+ if (!couplingMgr->hasEngineAfterStop(&electricOnNonElectrifiedLine)
+ || electricOnNonElectrifiedLine)
{
- int ret = QMessageBox::warning(this,
- tr("No Engine Left"),
- electricOnNonElectrifiedLine ?
- tr("It seems you have uncoupled all job engines except for electric ones "
- "but the line is not electrified\n"
- "(The train isn't able to move)\n"
- "Do you want to couple a non electric engine?") :
- tr("It seems you have uncoupled all job engines\n"
- "(The train isn't able to move)\n"
- "Do you want to couple an engine?"),
- QMessageBox::Yes | QMessageBox::No);
+ int ret = QMessageBox::warning(
+ this, tr("No Engine Left"),
+ electricOnNonElectrifiedLine
+ ? tr("It seems you have uncoupled all job engines except for electric ones "
+ "but the line is not electrified\n"
+ "(The train isn't able to move)\n"
+ "Do you want to couple a non electric engine?")
+ : tr("It seems you have uncoupled all job engines\n"
+ "(The train isn't able to move)\n"
+ "Do you want to couple an engine?"),
+ QMessageBox::Yes | QMessageBox::No);
- if(ret == QMessageBox::Yes)
+ if (ret == QMessageBox::Yes)
{
- return; //Second chance to edit couplings
+ return; // Second chance to edit couplings
}
}
#ifdef ENABLE_AUTO_TIME_RECALC
- if(originalSpeedAfterStop != newSpeedAfterStop)
+ if (originalSpeedAfterStop != newSpeedAfterStop)
{
- int speedBefore = originalSpeedAfterStop;
- int speedAfter = newSpeedAfterStop;
+ int speedBefore = originalSpeedAfterStop;
+ int speedAfter = newSpeedAfterStop;
LinesModel *linesModel = stopModel->getLinesModel();
- db_id lineId = curLine ? curLine : stopIdx.data(NEXT_LINE_ROLE).toLongLong();
+ db_id lineId = curLine ? curLine : stopIdx.data(NEXT_LINE_ROLE).toLongLong();
int lineSpeed = linesModel->getLineSpeed(lineId);
- if(speedBefore == 0)
+ if (speedBefore == 0)
{
- //If speed is null (likely because there weren't RS coupled before)
- //Fall back to line max speed
+ // If speed is null (likely because there weren't RS coupled before)
+ // Fall back to line max speed
speedBefore = lineSpeed;
}
- if(speedAfter == 0)
+ if (speedAfter == 0)
{
- //If speed is null (likely because there isn't RS coupled after this stop)
- //Fall back to line max speed
+ // If speed is null (likely because there isn't RS coupled after this stop)
+ // Fall back to line max speed
speedAfter = lineSpeed;
}
- int ret = QMessageBox::question(this,
- tr("Train Speed Changed"),
- tr("Train speed after this stop has changed from a value of %1 km/h to %2 km/h
"
- "Do you want to rebase travel times to this new speed?
"
- "NOTE: this doesn't affect stop times but you will lose manual adjustments to travel times")
- .arg(speedBefore).arg(speedAfter),
- QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes);
+ int ret = QMessageBox::question(
+ this, tr("Train Speed Changed"),
+ tr("Train speed after this stop has changed from a value of %1 km/h to %2 "
+ "km/h
"
+ "Do you want to rebase travel times to this new speed?
"
+ "NOTE: this doesn't affect stop times but you will lose manual adjustments to "
+ "travel times")
+ .arg(speedBefore)
+ .arg(speedAfter),
+ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes);
- if(ret == QMessageBox::Cancel)
+ if (ret == QMessageBox::Cancel)
{
- return; //Second chance to edit couplings
+ return; // Second chance to edit couplings
}
- if(ret == QMessageBox::Yes)
+ if (ret == QMessageBox::Yes)
{
- stopModel->rebaseTimesToSpeed(stopIdx.row(), ui->arrivalTimeEdit->time(), ui->departureTimeEdit->time());
+ stopModel->rebaseTimesToSpeed(stopIdx.row(), ui->arrivalTimeEdit->time(),
+ ui->departureTimeEdit->time());
}
}
#endif
diff --git a/src/jobs/jobeditor/editstopdialog.h b/src/jobs/jobeditor/editstopdialog.h
index fefe56e..b55135e 100644
--- a/src/jobs/jobeditor/editstopdialog.h
+++ b/src/jobs/jobeditor/editstopdialog.h
@@ -95,11 +95,11 @@ private:
StopCouplingModel *coupledModel;
StopCouplingModel *uncoupledModel;
- TrainAssetModel *trainAssetModelBefore;
- TrainAssetModel *trainAssetModelAfter;
+ TrainAssetModel *trainAssetModelBefore;
+ TrainAssetModel *trainAssetModelAfter;
- JobPassingsModel *passingsModel;
- JobPassingsModel *crossingsModel;
+ JobPassingsModel *passingsModel;
+ JobPassingsModel *crossingsModel;
bool readOnly;
};
diff --git a/src/jobs/jobeditor/jobpatheditor.cpp b/src/jobs/jobeditor/jobpatheditor.cpp
index 2a14dab..8a9f2da 100644
--- a/src/jobs/jobeditor/jobpatheditor.cpp
+++ b/src/jobs/jobeditor/jobpatheditor.cpp
@@ -46,7 +46,6 @@
#include "utils/delegates/sql/customcompletionlineedit.h"
#include "shifts/shiftcombomodel.h"
-
#include "utils/owningqpointer.h"
#include
#include
@@ -55,7 +54,6 @@
#include
-
JobPathEditor::JobPathEditor(QWidget *parent) :
QDialog(parent),
ui(new Ui::JobPathEditor),
@@ -69,7 +67,7 @@ JobPathEditor::JobPathEditor(QWidget *parent) :
QStringList catNames;
catNames.reserve(int(JobCategory::NCategories));
- for(int cat = 0; cat < int(JobCategory::NCategories); cat++)
+ for (int cat = 0; cat < int(JobCategory::NCategories); cat++)
{
catNames.append(JobCategoryName::fullName(JobCategory(cat)));
}
@@ -79,17 +77,18 @@ JobPathEditor::JobPathEditor(QWidget *parent) :
ui->categoryCombo->setCurrentIndex(-1);
ShiftComboModel *shiftComboModel = new ShiftComboModel(Session->m_Db, this);
- shiftCombo = new CustomCompletionLineEdit(shiftComboModel);
+ shiftCombo = new CustomCompletionLineEdit(shiftComboModel);
- //Get Catecory combo position and insert shift below
+ // Get Catecory combo position and insert shift below
int categoryRow = 0;
QFormLayout::ItemRole unusedRole;
ui->formLayout->getWidgetPosition(ui->categoryCombo, &categoryRow, &unusedRole);
ui->formLayout->insertRow(categoryRow + 1, tr("Shift:"), shiftCombo);
- //Stops
+ // Stops
stopModel = new StopModel(Session->m_Db, this);
- connect(shiftCombo, &CustomCompletionLineEdit::dataIdChanged, stopModel, &StopModel::setNewShiftId);
+ connect(shiftCombo, &CustomCompletionLineEdit::dataIdChanged, stopModel,
+ &StopModel::setNewShiftId);
ui->stopsView->setModel(stopModel);
delegate = new StopDelegate(Session->m_Db, this);
@@ -99,7 +98,7 @@ JobPathEditor::JobPathEditor(QWidget *parent) :
ui->stopsView->setMovement(QListView::Static);
ui->stopsView->setSelectionMode(QListView::ContiguousSelection);
- //Next/Prev Jobs
+ // Next/Prev Jobs
prevJobsModel = new NextPrevRSJobsModel(Session->m_Db, this);
prevJobsModel->setMode(NextPrevRSJobsModel::PrevJobs);
ui->prevJobsView->setModel(prevJobsModel);
@@ -108,11 +107,12 @@ JobPathEditor::JobPathEditor(QWidget *parent) :
nextJobsModel->setMode(NextPrevRSJobsModel::NextJobs);
ui->nextJobsView->setModel(nextJobsModel);
-
- connect(ui->categoryCombo, static_cast(&QComboBox::activated), stopModel, &StopModel::setCategory);
+ connect(ui->categoryCombo, static_cast(&QComboBox::activated),
+ stopModel, &StopModel::setCategory);
connect(stopModel, &StopModel::categoryChanged, this, &JobPathEditor::onCategoryChanged);
- connect(ui->jobIdSpin, static_cast(&QSpinBox::valueChanged), this, &JobPathEditor::startJobNumberTimer);
+ connect(ui->jobIdSpin, static_cast(&QSpinBox::valueChanged), this,
+ &JobPathEditor::startJobNumberTimer);
connect(stopModel, &StopModel::jobIdChanged, this, &JobPathEditor::onJobIdChanged);
connect(stopModel, &StopModel::edited, this, &JobPathEditor::setEdited);
@@ -123,14 +123,17 @@ JobPathEditor::JobPathEditor(QWidget *parent) :
connect(ui->sheetBut, &QPushButton::clicked, this, &JobPathEditor::onSaveSheet);
ui->stopsView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui->stopsView, &QListView::customContextMenuRequested, this, &JobPathEditor::showStopsContextMenu);
+ connect(ui->stopsView, &QListView::customContextMenuRequested, this,
+ &JobPathEditor::showStopsContextMenu);
connect(ui->stopsView, &QListView::clicked, this, &JobPathEditor::onStopIndexClicked);
ui->prevJobsView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui->prevJobsView, &QListView::customContextMenuRequested, this, &JobPathEditor::showJobContextMenu);
+ connect(ui->prevJobsView, &QListView::customContextMenuRequested, this,
+ &JobPathEditor::showJobContextMenu);
ui->nextJobsView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui->nextJobsView, &QListView::customContextMenuRequested, this, &JobPathEditor::showJobContextMenu);
+ connect(ui->nextJobsView, &QListView::customContextMenuRequested, this,
+ &JobPathEditor::showJobContextMenu);
connect(Session, &MeetingSession::jobRemoved, this, &JobPathEditor::onJobRemoved);
connect(&AppSettings, &MRTPSettings::jobColorsChanged, this, &JobPathEditor::updateSpinColor);
@@ -149,16 +152,16 @@ JobPathEditor::~JobPathEditor()
bool JobPathEditor::setJob(db_id jobId)
{
- if(!canSetJob)
- return false; //We are busy - (Avoid nested loop calls from inside 'saveChanges()')
+ if (!canSetJob)
+ return false; // We are busy - (Avoid nested loop calls from inside 'saveChanges()')
- if(!isClear && stopModel->getJobId() == jobId)
- return true; //Fake return, we already set this job
+ if (!isClear && stopModel->getJobId() == jobId)
+ return true; // Fake return, we already set this job
- if(isEdited())
+ if (isEdited())
{
- if(!maybeSave())
- return false; //User still wants to edit the current job
+ if (!maybeSave())
+ return false; // User still wants to edit the current job
}
return setJob_internal(jobId);
@@ -168,32 +171,32 @@ bool JobPathEditor::setJob_internal(db_id jobId)
{
DEBUG_IMPORTANT_ENTRY;
- if(!canSetJob)
- return false; //We are busy - (Avoid nested loop calls from inside 'saveChanges()')
+ if (!canSetJob)
+ return false; // We are busy - (Avoid nested loop calls from inside 'saveChanges()')
- if(!isClear && stopModel->getJobId() == jobId)
- return true; //Fake return, we already set this job
+ if (!isClear && stopModel->getJobId() == jobId)
+ return true; // Fake return, we already set this job
isClear = false;
stopJobNumberTimer();
- //Load from database
- if(!stopModel->loadJobStops(jobId))
+ // Load from database
+ if (!stopModel->loadJobStops(jobId))
{
- //Error: job could not be loaded, maybe invalid jobId
+ // Error: job could not be loaded, maybe invalid jobId
clearJob();
setEnabled(false);
QMessageBox::warning(this, tr("Error Loading Job"),
- tr("Job %1 could not be loaded.
"
- "Maybe it's number was changed or maybe it doesn't exist at all.")
- .arg(jobId));
+ tr("Job %1 could not be loaded.
"
+ "Maybe it's number was changed or maybe it doesn't exist at all.")
+ .arg(jobId));
return false;
}
- //If read-only hide 'AddHere' row (last one)
+ // If read-only hide 'AddHere' row (last one)
ui->stopsView->setRowHidden(stopModel->rowCount() - 1, m_readOnly);
prevJobsModel->setJobId(jobId);
@@ -204,16 +207,16 @@ bool JobPathEditor::setJob_internal(db_id jobId)
void JobPathEditor::startJobNumberTimer()
{
- //Give user a small time to scroll values in ID QSpinBox
- //This will skip eventual non available IDs (already existent)
- //On timeout check ID and reset to old value if not available
+ // Give user a small time to scroll values in ID QSpinBox
+ // This will skip eventual non available IDs (already existent)
+ // On timeout check ID and reset to old value if not available
stopJobNumberTimer();
jobNumberTimerId = startTimer(700);
}
void JobPathEditor::stopJobNumberTimer()
{
- if(jobNumberTimerId)
+ if (jobNumberTimerId)
{
killTimer(jobNumberTimerId);
jobNumberTimerId = 0;
@@ -222,15 +225,16 @@ void JobPathEditor::stopJobNumberTimer()
void JobPathEditor::checkJobNumberValid()
{
- //Kill timer
+ // Kill timer
stopJobNumberTimer();
db_id jobId = ui->jobIdSpin->value();
- if(!stopModel->setNewJobId(jobId))
+ if (!stopModel->setNewJobId(jobId))
{
QMessageBox::warning(this, tr("Invalid"),
tr("Job number %1 is already exists.
"
- "Please choose a different number.").arg(jobId));
+ "Please choose a different number.")
+ .arg(jobId));
}
}
@@ -249,43 +253,43 @@ bool JobPathEditor::createNewJob(db_id *out)
* or if user doesn't add at least 2 stops to the job
*/
- if(out)
+ if (out)
*out = 0;
- if(!clearJob())
- return false; //Busy JobPathEditor
+ if (!clearJob())
+ return false; // Busy JobPathEditor
db_id jobId = 0;
- if(!JobsHelper::createNewJob(Session->m_Db, jobId) || jobId == 0)
+ if (!JobsHelper::createNewJob(Session->m_Db, jobId) || jobId == 0)
{
- return false; //An error occurred in database, abort
+ return false; // An error occurred in database, abort
}
- if(!setJob_internal(jobId))
+ if (!setJob_internal(jobId))
{
- //If we fail opening JobPathEditor remove the job
+ // If we fail opening JobPathEditor remove the job
JobsHelper::removeJob(Session->m_Db, jobId);
return false;
}
- if(out)
+ if (out)
*out = jobId;
return true;
}
-void JobPathEditor::showStopsContextMenu(const QPoint& pos)
+void JobPathEditor::showStopsContextMenu(const QPoint &pos)
{
QModelIndex index = ui->stopsView->indexAt(pos);
- if(!index.isValid() || index.row()>= stopModel->rowCount() || stopModel->isAddHere(index))
+ if (!index.isValid() || index.row() >= stopModel->rowCount() || stopModel->isAddHere(index))
return;
OwningQPointer menu = new QMenu(this);
- QAction *toggleTransitAct = menu->addAction(tr("Toggle transit"));
- QAction *setToTransitAct = menu->addAction(tr("Set transit"));
- QAction *unsetTransit = menu->addAction(tr("Unset transit"));
+ QAction *toggleTransitAct = menu->addAction(tr("Toggle transit"));
+ QAction *setToTransitAct = menu->addAction(tr("Set transit"));
+ QAction *unsetTransit = menu->addAction(tr("Unset transit"));
menu->insertSeparator(unsetTransit);
- QAction *editStopAct = menu->addAction(tr("Edit stop"));
+ QAction *editStopAct = menu->addAction(tr("Edit stop"));
QAction *showStationSVG = menu->addAction(tr("Station SVG Plan"));
menu->insertSeparator(editStopAct);
QAction *removeStopAct = menu->addAction(tr("Remove"));
@@ -296,24 +300,24 @@ void JobPathEditor::showStopsContextMenu(const QPoint& pos)
removeStopAct->setEnabled(!m_readOnly);
const StopItem stop = stopModel->getItemAt(index.row());
- showStationSVG->setEnabled(stop.stationId != 0); //Enable only if station is set
+ showStationSVG->setEnabled(stop.stationId != 0); // Enable only if station is set
- QAction *act = menu->exec(ui->stopsView->viewport()->mapToGlobal(pos));
+ QAction *act = menu->exec(ui->stopsView->viewport()->mapToGlobal(pos));
QItemSelectionModel *sm = ui->stopsView->selectionModel();
QItemSelectionRange range;
QItemSelection s = ui->stopsView->selectionModel()->selection();
- if(s.count() > 0)
+ if (s.count() > 0)
{
- //Take the first range only
- range = s.at(0); //Save range for later
+ // Take the first range only
+ range = s.at(0); // Save range for later
}
- //Select only 1 index
+ // Select only 1 index
sm->select(index, QItemSelectionModel::ClearAndSelect);
- if(act == editStopAct)
+ if (act == editStopAct)
{
OwningQPointer dlg = new EditStopDialog(stopModel, this);
dlg->setReadOnly(m_readOnly);
@@ -322,86 +326,87 @@ void JobPathEditor::showStopsContextMenu(const QPoint& pos)
return;
}
- if(act == showStationSVG)
+ if (act == showStationSVG)
{
Session->getViewManager()->requestStSVGPlan(stop.stationId, true, stop.arrival);
}
- if(m_readOnly)
+ if (m_readOnly)
return;
- if(range.isValid())
+ if (range.isValid())
{
StopType type = StopType::ToggleType;
bool useRange = true;
- if(act == toggleTransitAct)
+ if (act == toggleTransitAct)
type = StopType::ToggleType;
- else if(act == setToTransitAct)
+ else if (act == setToTransitAct)
type = StopType::Transit;
- else if(act == unsetTransit)
+ else if (act == unsetTransit)
type = StopType::Normal;
else
useRange = false;
- if(useRange)
+ if (useRange)
{
stopModel->setStopTypeRange(range.top(), range.bottom(), type);
- //Select only the range we changed (unselect possible other indexes)
- sm->select(QItemSelection(range.topLeft(), range.bottomRight()), QItemSelectionModel::ClearAndSelect);
+ // Select only the range we changed (unselect possible other indexes)
+ sm->select(QItemSelection(range.topLeft(), range.bottomRight()),
+ QItemSelectionModel::ClearAndSelect);
return;
}
}
- if(act == removeStopAct)
+ if (act == removeStopAct)
{
stopModel->removeStop(index);
}
}
-void JobPathEditor::showJobContextMenu(const QPoint& pos)
+void JobPathEditor::showJobContextMenu(const QPoint &pos)
{
- QTableView *jobView = qobject_cast(sender());
+ QTableView *jobView = qobject_cast(sender());
NextPrevRSJobsModel *jobModel = nextJobsModel;
- if(jobView == ui->prevJobsView)
+ if (jobView == ui->prevJobsView)
jobModel = prevJobsModel;
- QModelIndex index = jobView->indexAt(pos);
+ QModelIndex index = jobView->indexAt(pos);
NextPrevRSJobsModel::Item item = jobModel->getItemAtRow(index.row());
- OwningQPointer menu = new QMenu(this);
- QAction *goToStop = menu->addAction(tr("Go to Stop"));
- QAction *goToJob = menu->addAction(tr("Show Job"));
- QAction *showRSPlan = menu->addAction(tr("Show RS Plan"));
+ OwningQPointer menu = new QMenu(this);
+ QAction *goToStop = menu->addAction(tr("Go to Stop"));
+ QAction *goToJob = menu->addAction(tr("Show Job"));
+ QAction *showRSPlan = menu->addAction(tr("Show RS Plan"));
menu->addSeparator();
QAction *refreshViews = menu->addAction(tr("Refresh"));
- //Enable only if RS is not going to depot
+ // Enable only if RS is not going to depot
goToStop->setEnabled(index.isValid());
goToJob->setEnabled(index.isValid() && item.otherJobId != 0);
showRSPlan->setEnabled(index.isValid());
QAction *act = menu->exec(jobView->viewport()->mapToGlobal(pos));
- if(act == goToStop)
+ if (act == goToStop)
{
selectStop(item.stopId);
}
- else if(act == goToJob)
+ else if (act == goToJob)
{
- if(isEdited()) //Prevent selecting other job before saving
+ if (isEdited()) // Prevent selecting other job before saving
{
- if(!maybeSave())
+ if (!maybeSave())
return;
}
Session->getViewManager()->requestJobSelection(item.otherJobId, true, true);
}
- else if(act == showRSPlan)
+ else if (act == showRSPlan)
{
Session->getViewManager()->requestRSInfo(item.rsId);
}
- else if(act == refreshViews)
+ else if (act == refreshViews)
{
prevJobsModel->refreshData();
nextJobsModel->refreshData();
@@ -412,18 +417,18 @@ bool JobPathEditor::clearJob()
{
DEBUG_ENTRY;
- if(!canSetJob)
+ if (!canSetJob)
return false;
- if(isEdited())
+ if (isEdited())
{
- if(!maybeSave())
+ if (!maybeSave())
return false;
}
isClear = true;
- //Reset color
+ // Reset color
ui->jobIdSpin->setPalette(QPalette());
stopModel->clearJob();
@@ -438,23 +443,23 @@ bool JobPathEditor::clearJob()
void JobPathEditor::done(int res)
{
- if(res == Accepted)
+ if (res == Accepted)
{
- //Accepted: save changes
- if(!saveChanges())
- return; //Give user a second chance to edit job
+ // Accepted: save changes
+ if (!saveChanges())
+ return; // Give user a second chance to edit job
}
else
{
- //Rejected: discard changes
+ // Rejected: discard changes
discardChanges();
}
- //NOTE: if we call QDialog::done() the dialog is closed and QDockWidget remains open but empty
+ // NOTE: if we call QDialog::done() the dialog is closed and QDockWidget remains open but empty
setResult(res);
- if(res == QDialog::Accepted)
+ if (res == QDialog::Accepted)
emit accepted();
- else if(res == QDialog::Rejected)
+ else if (res == QDialog::Rejected)
emit rejected();
emit finished(res);
}
@@ -463,7 +468,7 @@ bool JobPathEditor::saveChanges()
{
DEBUG_IMPORTANT_ENTRY;
- if(!canSetJob)
+ if (!canSetJob)
return false;
canSetJob = false;
@@ -474,15 +479,14 @@ bool JobPathEditor::saveChanges()
stopModel->removeLastIfEmpty();
stopModel->uncoupleStillCoupledAtLastStop();
- if(stopModel->rowCount() < 3) //At least 2 stops + AddHere
+ if (stopModel->rowCount() < 3) // At least 2 stops + AddHere
{
- int res = QMessageBox::warning(this,
- tr("Error"),
+ int res = QMessageBox::warning(this, tr("Error"),
tr("You must register at least 2 stops.\n"
"Do you want to delete this job?"),
QMessageBox::Yes | QMessageBox::No);
- if(res == QMessageBox::Yes)
+ if (res == QMessageBox::Yes)
{
qDebug() << "User wants to delete job:" << stopModel->getJobId();
stopModel->commitChanges();
@@ -494,19 +498,18 @@ bool JobPathEditor::saveChanges()
}
canSetJob = true;
- return false; //Give user a second chance
+ return false; // Give user a second chance
}
- //Re-check shift because user may have added stops so this job could last longer!
- if(stopModel->getNewShiftId())
+ // Re-check shift because user may have added stops so this job could last longer!
+ if (stopModel->getNewShiftId())
{
auto times = stopModel->getFirstLastTimes();
ShiftBusyModel model(Session->m_Db);
- model.loadData(stopModel->getNewShiftId(),
- stopModel->getJobId(),
- times.first, times.second);
- if(model.hasConcurrentJobs())
+ model.loadData(stopModel->getNewShiftId(), stopModel->getJobId(), times.first,
+ times.second);
+ if (model.hasConcurrentJobs())
{
OwningQPointer dlg = new ShiftBusyDlg(this);
dlg->setModel(&model);
@@ -525,7 +528,7 @@ bool JobPathEditor::saveChanges()
prevJobsModel->setJobId(newJobId);
nextJobsModel->setJobId(newJobId);
- //When updating the path selection gets cleared so we restore it
+ // When updating the path selection gets cleared so we restore it
Session->getViewManager()->requestJobSelection(newJobId, true, true);
canSetJob = true;
@@ -536,28 +539,29 @@ void JobPathEditor::discardChanges()
{
DEBUG_ENTRY;
- if(!canSetJob)
+ if (!canSetJob)
return;
canSetJob = false;
- closeStopEditor(); //Close before rolling savepoint
+ closeStopEditor(); // Close before rolling savepoint
stopJobNumberTimer();
- stopModel->revertChanges(); //Re-load old job from db
+ stopModel->revertChanges(); // Re-load old job from db
- //After re-load but before possible 'clearJob()' (Below)
- //Because this hides 'AddHere' so after 'loadJobStops()'
- //Before 'clearJob()' because sets isEdited = false and
+ // After re-load but before possible 'clearJob()' (Below)
+ // Because this hides 'AddHere' so after 'loadJobStops()'
+ // Before 'clearJob()' because sets isEdited = false and
//'maybeSave()' doesn't be called in an infinite loop
canSetJob = true;
- if(stopModel->rowCount() < 3) //At least 2 stops + AddHere
+ if (stopModel->rowCount() < 3) // At least 2 stops + AddHere
{
- //User discarded an invalid job so we delete it
- //This usually happens when you create a new job but then you change your mind and press 'Discard'
+ // User discarded an invalid job so we delete it
+ // This usually happens when you create a new job but then you change your mind and press
+ // 'Discard'
qDebug() << "User wants to delete job:" << stopModel->getJobId();
stopModel->commitChanges();
JobsHelper::removeJob(Session->m_Db, stopModel->getJobId());
@@ -574,11 +578,9 @@ db_id JobPathEditor::currentJobId() const
bool JobPathEditor::maybeSave()
{
DEBUG_ENTRY;
- QMessageBox::StandardButton ret = QMessageBox::question(this,
- tr("Save?"),
- tr("Do you want to save changes to job %1")
- .arg(stopModel->getJobId()),
- QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
+ QMessageBox::StandardButton ret = QMessageBox::question(
+ this, tr("Save?"), tr("Do you want to save changes to job %1").arg(stopModel->getJobId()),
+ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
switch (ret)
{
case QMessageBox::Yes:
@@ -594,7 +596,7 @@ bool JobPathEditor::maybeSave()
void JobPathEditor::updateSpinColor()
{
- if(!isClear)
+ if (!isClear)
{
QColor col = Session->colorForCat(stopModel->getCategory());
setSpinColor(col);
@@ -603,7 +605,7 @@ void JobPathEditor::updateSpinColor()
void JobPathEditor::timerEvent(QTimerEvent *e)
{
- if(e->timerId() == jobNumberTimerId)
+ if (e->timerId() == jobNumberTimerId)
{
checkJobNumberValid();
return;
@@ -614,10 +616,10 @@ void JobPathEditor::timerEvent(QTimerEvent *e)
void JobPathEditor::onJobRemoved(db_id jobId)
{
- //If the job shown is about to be removed clear JobPathEditor
- if(stopModel->getJobId() == jobId)
+ // If the job shown is about to be removed clear JobPathEditor
+ if (stopModel->getJobId() == jobId)
{
- if(clearJob())
+ if (clearJob())
setEnabled(false);
}
}
@@ -627,7 +629,7 @@ void JobPathEditor::onJobIdChanged(db_id jobId)
ui->jobIdSpin->setValue(int(jobId));
}
-void JobPathEditor::setSpinColor(const QColor& col)
+void JobPathEditor::setSpinColor(const QColor &col)
{
QPalette pal = ui->jobIdSpin->palette();
pal.setColor(QPalette::Text, col);
@@ -644,15 +646,13 @@ void JobPathEditor::onJobShiftChanged(db_id shiftId)
{
shiftCombo->setData(shiftId);
- if(shiftId)
+ if (shiftId)
{
auto times = stopModel->getFirstLastTimes();
ShiftBusyModel model(Session->m_Db);
- model.loadData(shiftId,
- stopModel->getJobId(),
- times.first, times.second);
- if(model.hasConcurrentJobs())
+ model.loadData(shiftId, stopModel->getJobId(), times.first, times.second);
+ if (model.hasConcurrentJobs())
{
OwningQPointer dlg = new ShiftBusyDlg(this);
dlg->setModel(&model);
@@ -667,8 +667,7 @@ void JobPathEditor::onJobShiftChanged(db_id shiftId)
void JobPathEditor::onShiftError()
{
- QMessageBox::warning(this,
- tr("Empty Job"),
+ QMessageBox::warning(this, tr("Empty Job"),
tr("Before setting a shift you should add stops to this job"),
QMessageBox::Ok);
}
@@ -686,7 +685,7 @@ void JobPathEditor::setEdited(bool val)
void JobPathEditor::setReadOnly(bool readOnly)
{
- if(m_readOnly == readOnly)
+ if (m_readOnly == readOnly)
return;
m_readOnly = readOnly;
@@ -697,12 +696,12 @@ void JobPathEditor::setReadOnly(bool readOnly)
ui->buttonBox->setVisible(!m_readOnly);
- //If read-only hide 'AddHere' row (last one)
+ // If read-only hide 'AddHere' row (last one)
int size = stopModel->rowCount();
- if(size > 0)
+ if (size > 0)
ui->stopsView->setRowHidden(size - 1, m_readOnly);
- if(m_readOnly)
+ if (m_readOnly)
{
ui->stopsView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
@@ -716,7 +715,7 @@ void JobPathEditor::onSaveSheet()
{
const QLatin1String job_sheet_key = QLatin1String("job_sheet_dir");
- OwningQPointer dlg = new QFileDialog(this, tr("Save Job Sheet"));
+ OwningQPointer dlg = new QFileDialog(this, tr("Save Job Sheet"));
dlg->setFileMode(QFileDialog::AnyFile);
dlg->setAcceptMode(QFileDialog::AcceptSave);
dlg->setDirectory(RecentDirStore::getDir(job_sheet_key, RecentDirStore::Documents));
@@ -726,12 +725,12 @@ void JobPathEditor::onSaveSheet()
filters << FileFormats::tr(FileFormats::odtFormat);
dlg->setNameFilters(filters);
- if(dlg->exec() != QDialog::Accepted || !dlg)
+ if (dlg->exec() != QDialog::Accepted || !dlg)
return;
QString fileName = dlg->selectedUrls().value(0).toLocalFile();
- if(fileName.isEmpty())
+ if (fileName.isEmpty())
return;
RecentDirStore::setPath(job_sheet_key, fileName);
@@ -743,14 +742,14 @@ void JobPathEditor::onSaveSheet()
utils::OpenFileInFolderDlg::askUser(tr("Job Sheet Saved"), fileName, this);
}
-void JobPathEditor::onStopIndexClicked(const QModelIndex& index)
+void JobPathEditor::onStopIndexClicked(const QModelIndex &index)
{
DEBUG_ENTRY;
- if(m_readOnly)
+ if (m_readOnly)
return;
- if(stopModel->isAddHere(index))
+ if (stopModel->isAddHere(index))
{
qDebug() << index << "AddHere";
@@ -758,22 +757,22 @@ void JobPathEditor::onStopIndexClicked(const QModelIndex& index)
int row = index.row();
- if(row > 0)
+ if (row > 0)
{
- //idx - 1 is former Last Stop (now it became a normal Stop)
- //idx is new Last Stop (former AddHere)
- //idx + 1 is the new AddHere
+ // idx - 1 is former Last Stop (now it became a normal Stop)
+ // idx is new Last Stop (former AddHere)
+ // idx + 1 is the new AddHere
- //Edit former Last Stop
+ // Edit former Last Stop
QModelIndex prev = stopModel->index(row - 1, 0);
ui->stopsView->setCurrentIndex(prev);
ui->stopsView->scrollTo(prev);
ui->stopsView->edit(prev);
- //Tell editor to popup lines combo
- //QAbstractItemView::edit doesn't let you pass additional arguments
- //So we work around by emitting a signal
- //See 'StopDelegate::createEditor()'
+ // Tell editor to popup lines combo
+ // QAbstractItemView::edit doesn't let you pass additional arguments
+ // So we work around by emitting a signal
+ // See 'StopDelegate::createEditor()'
emit delegate->popupEditorSegmentCombo();
}
else
@@ -794,8 +793,8 @@ bool JobPathEditor::getCanSetJob() const
void JobPathEditor::closeStopEditor()
{
QModelIndex idx = ui->stopsView->currentIndex();
- QWidget *ed = ui->stopsView->indexWidget(idx);
- if(ed == nullptr)
+ QWidget *ed = ui->stopsView->indexWidget(idx);
+ if (ed == nullptr)
return;
emit delegate->commitData(ed);
emit delegate->closeEditor(ed);
@@ -803,10 +802,10 @@ void JobPathEditor::closeStopEditor()
void JobPathEditor::closeEvent(QCloseEvent *e)
{
- //TODO: prevent QDockWidget closing even if we ignore this event
- if(isEdited())
+ // TODO: prevent QDockWidget closing even if we ignore this event
+ if (isEdited())
{
- if(maybeSave())
+ if (maybeSave())
e->accept();
else
e->ignore();
@@ -820,7 +819,7 @@ void JobPathEditor::closeEvent(QCloseEvent *e)
void JobPathEditor::selectStop(db_id stopId)
{
int row = stopModel->getStopRow(stopId);
- if(row >= 0)
+ if (row >= 0)
{
QModelIndex idx = stopModel->index(row, 0);
ui->stopsView->setCurrentIndex(idx);
diff --git a/src/jobs/jobeditor/jobpatheditor.h b/src/jobs/jobeditor/jobpatheditor.h
index 397a8e2..5211dda 100644
--- a/src/jobs/jobeditor/jobpatheditor.h
+++ b/src/jobs/jobeditor/jobpatheditor.h
@@ -48,7 +48,7 @@ class JobPathEditor : public QDialog
public:
explicit JobPathEditor(QWidget *parent = nullptr);
- ~JobPathEditor()override;
+ ~JobPathEditor() override;
bool setJob(db_id jobId);
bool createNewJob(db_id *out = nullptr);
@@ -122,10 +122,10 @@ private:
int jobNumberTimerId;
- //TODO: there are too many bools
+ // TODO: there are too many bools
bool isClear;
- bool canSetJob; //TODO: better name
+ bool canSetJob; // TODO: better name
bool m_readOnly;
};
diff --git a/src/jobs/jobeditor/model/jobpassingsmodel.cpp b/src/jobs/jobeditor/model/jobpassingsmodel.cpp
index c29e67a..3e06908 100644
--- a/src/jobs/jobeditor/model/jobpassingsmodel.cpp
+++ b/src/jobs/jobeditor/model/jobpassingsmodel.cpp
@@ -30,7 +30,7 @@ JobPassingsModel::JobPassingsModel(QObject *parent) :
QVariant JobPassingsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
+ if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
@@ -71,7 +71,7 @@ QVariant JobPassingsModel::data(const QModelIndex &idx, int role) const
if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols)
return QVariant();
- const Entry& e = m_data.at(idx.row());
+ const Entry &e = m_data.at(idx.row());
switch (role)
{
case Qt::DisplayRole:
@@ -97,7 +97,7 @@ QVariant JobPassingsModel::data(const QModelIndex &idx, int role) const
{
QFont f;
f.setPointSize(10);
- if(idx.column() == JobNameCol)
+ if (idx.column() == JobNameCol)
f.setBold(true);
return f;
}
diff --git a/src/jobs/jobeditor/model/jobpassingsmodel.h b/src/jobs/jobeditor/model/jobpassingsmodel.h
index f46ab05..02b91ac 100644
--- a/src/jobs/jobeditor/model/jobpassingsmodel.h
+++ b/src/jobs/jobeditor/model/jobpassingsmodel.h
@@ -33,7 +33,8 @@ class JobPassingsModel : public QAbstractTableModel
Q_OBJECT
public:
- enum Columns {
+ enum Columns
+ {
JobNameCol = 0,
ArrivalCol,
DepartureCol,
@@ -60,7 +61,7 @@ public:
QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override;
- void setJobs(const QVector& vec);
+ void setJobs(const QVector &vec);
private:
QVector m_data;
diff --git a/src/jobs/jobeditor/model/nextprevrsjobsmodel.cpp b/src/jobs/jobeditor/model/nextprevrsjobsmodel.cpp
index d394f35..20fbdf5 100644
--- a/src/jobs/jobeditor/model/nextprevrsjobsmodel.cpp
+++ b/src/jobs/jobeditor/model/nextprevrsjobsmodel.cpp
@@ -34,7 +34,7 @@ NextPrevRSJobsModel::NextPrevRSJobsModel(sqlite3pp::database &db, QObject *paren
QVariant NextPrevRSJobsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
+ if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
@@ -67,7 +67,7 @@ QVariant NextPrevRSJobsModel::data(const QModelIndex &idx, int role) const
if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols)
return QVariant();
- const Item& item = m_data.at(idx.row());
+ const Item &item = m_data.at(idx.row());
switch (role)
{
@@ -77,8 +77,8 @@ QVariant NextPrevRSJobsModel::data(const QModelIndex &idx, int role) const
{
case JobIdCol:
{
- if(item.otherJobCat == JobCategory::NCategories)
- return tr("Depot"); //Rollingstock item taken from/released to depot
+ if (item.otherJobCat == JobCategory::NCategories)
+ return tr("Depot"); // Rollingstock item taken from/released to depot
return JobCategoryName::jobName(item.otherJobId, item.otherJobCat);
}
case RsNameCol:
@@ -90,9 +90,9 @@ QVariant NextPrevRSJobsModel::data(const QModelIndex &idx, int role) const
}
case Qt::FontRole:
{
- if(idx.column() == JobIdCol && item.otherJobCat == JobCategory::NCategories)
+ if (idx.column() == JobIdCol && item.otherJobCat == JobCategory::NCategories)
{
- //Rollingstock item taken from/released to depot, distinguish font from job names
+ // Rollingstock item taken from/released to depot, distinguish font from job names
QFont f;
f.setItalic(true);
return f;
@@ -108,34 +108,38 @@ QVariant NextPrevRSJobsModel::data(const QModelIndex &idx, int role) const
void NextPrevRSJobsModel::refreshData()
{
- //GROUP by rollingstock
- QByteArray sql = "SELECT c.id, c.rs_id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type, stops.%time0,"
- " %min(s1.%time0), stops.id, s1.job_id AS job_id, j1.category"
- " FROM stops"
- " JOIN coupling c ON c.stop_id=stops.id"
- " JOIN rs_list ON rs_list.id=c.rs_id"
- " JOIN rs_models ON rs_models.id=rs_list.model_id"
- " LEFT JOIN coupling c1 ON c1.rs_id=c.rs_id"
- " LEFT JOIN stops s1 ON s1.id=c1.stop_id"
- " LEFT JOIN jobs j1 ON j1.id=s1.job_id"
- " WHERE stops.job_id=?1 AND c.operation=%rem AND c1.operation=%add AND s1.%time0 %gt stops.%time1"
- " GROUP BY c.rs_id"
- " UNION ALL "
- "SELECT c.id, c.rs_id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type, stops.%time0,"
- " %max(s1.%time0), stops.id, NULL AS job_id, NULL"
- " FROM stops"
- " JOIN coupling c ON c.stop_id=stops.id"
- " JOIN rs_list ON rs_list.id=c.rs_id"
- " JOIN rs_models ON rs_models.id=rs_list.model_id"
- " LEFT JOIN coupling c1 ON c1.rs_id=c.rs_id"
- " LEFT JOIN stops s1 ON s1.id=c1.stop_id"
- " WHERE stops.job_id=?1 AND c.operation=%rem AND c1.operation=%add"
- " GROUP BY c.rs_id"
- " HAVING s1.%time1 %lt stops.%time0"
- " ORDER BY stops.%time0, job_id, rs_models.type, rs_models.name, rs_list.number"
- " LIMIT 100";
+ // GROUP by rollingstock
+ QByteArray sql =
+ "SELECT c.id, c.rs_id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type, "
+ "stops.%time0,"
+ " %min(s1.%time0), stops.id, s1.job_id AS job_id, j1.category"
+ " FROM stops"
+ " JOIN coupling c ON c.stop_id=stops.id"
+ " JOIN rs_list ON rs_list.id=c.rs_id"
+ " JOIN rs_models ON rs_models.id=rs_list.model_id"
+ " LEFT JOIN coupling c1 ON c1.rs_id=c.rs_id"
+ " LEFT JOIN stops s1 ON s1.id=c1.stop_id"
+ " LEFT JOIN jobs j1 ON j1.id=s1.job_id"
+ " WHERE stops.job_id=?1 AND c.operation=%rem AND c1.operation=%add AND s1.%time0 %gt "
+ "stops.%time1"
+ " GROUP BY c.rs_id"
+ " UNION ALL "
+ "SELECT c.id, c.rs_id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type, "
+ "stops.%time0,"
+ " %max(s1.%time0), stops.id, NULL AS job_id, NULL"
+ " FROM stops"
+ " JOIN coupling c ON c.stop_id=stops.id"
+ " JOIN rs_list ON rs_list.id=c.rs_id"
+ " JOIN rs_models ON rs_models.id=rs_list.model_id"
+ " LEFT JOIN coupling c1 ON c1.rs_id=c.rs_id"
+ " LEFT JOIN stops s1 ON s1.id=c1.stop_id"
+ " WHERE stops.job_id=?1 AND c.operation=%rem AND c1.operation=%add"
+ " GROUP BY c.rs_id"
+ " HAVING s1.%time1 %lt stops.%time0"
+ " ORDER BY stops.%time0, job_id, rs_models.type, rs_models.name, rs_list.number"
+ " LIMIT 100";
- if(m_mode == NextJobs)
+ if (m_mode == NextJobs)
{
sql.replace("%time0", "arrival");
sql.replace("%time1", "departure");
@@ -148,7 +152,7 @@ void NextPrevRSJobsModel::refreshData()
}
else
{
- //Invert all
+ // Invert all
sql.replace("%time0", "departure");
sql.replace("%time1", "arrival");
sql.replace("%min", "MAX");
@@ -194,33 +198,29 @@ void NextPrevRSJobsModel::refreshData()
beginResetModel();
m_data.clear();
- for(auto row : q)
+ for (auto row : q)
{
Item item;
- item.couplingId = row.get(0);
- item.rsId = row.get(1);
+ item.couplingId = row.get(0);
+ item.rsId = row.get(1);
- int number = row.get(2);
- int modelNameLen = sqlite3_column_bytes(q.stmt(), 3);
- const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 3));
+ int number = row.get(2);
+ int modelNameLen = sqlite3_column_bytes(q.stmt(), 3);
+ const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 3));
- int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 4);
- const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 4));
- RsType rsType = RsType(row.get(5));
+ int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 4);
+ const char *modelSuffix = reinterpret_cast