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.departurevertOffset; 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(sqlite3_column_text(q.stmt(), 4)); + RsType rsType = RsType(row.get(5)); - item.rsName = rs_utils::formatNameRef(modelName, - modelNameLen, - number, - modelSuffix, - modelSuffixLen, - rsType); + item.rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, rsType); item.opTime = row.get(6); - //Ignore column 7, which is used just for MIN/MAX - item.stopId = row.get(8); - item.otherJobId = row.get(9); + // Ignore column 7, which is used just for MIN/MAX + item.stopId = row.get(8); + item.otherJobId = row.get(9); item.otherJobCat = JobCategory(row.get(10)); - if(row.column_type(10) == SQLITE_NULL) + if (row.column_type(10) == SQLITE_NULL) item.otherJobCat = JobCategory::NCategories; m_data.append(item); @@ -245,7 +245,7 @@ db_id NextPrevRSJobsModel::jobId() const void NextPrevRSJobsModel::setJobId(db_id newJobId) { m_jobId = newJobId; - if(m_jobId) + if (m_jobId) refreshData(); else clearData(); @@ -259,7 +259,7 @@ NextPrevRSJobsModel::Mode NextPrevRSJobsModel::mode() const void NextPrevRSJobsModel::setMode(Mode newMode) { m_mode = newMode; - if(m_jobId) + if (m_jobId) refreshData(); } diff --git a/src/jobs/jobeditor/model/nextprevrsjobsmodel.h b/src/jobs/jobeditor/model/nextprevrsjobsmodel.h index 51e5c90..e1c280d 100644 --- a/src/jobs/jobeditor/model/nextprevrsjobsmodel.h +++ b/src/jobs/jobeditor/model/nextprevrsjobsmodel.h @@ -61,8 +61,8 @@ public: { db_id otherJobId = 0; db_id couplingId = 0; - db_id rsId = 0; - db_id stopId = 0; + db_id rsId = 0; + db_id stopId = 0; QString rsName; QTime opTime; @@ -73,7 +73,8 @@ public: NextPrevRSJobsModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &p = QModelIndex()) const override; @@ -93,7 +94,6 @@ public: Item getItemAtRow(int row) const; private: - sqlite3pp::database &mDb; db_id m_jobId = 0; diff --git a/src/jobs/jobeditor/model/rscouplinginterface.cpp b/src/jobs/jobeditor/model/rscouplinginterface.cpp index 0520d22..1ac2f2d 100644 --- a/src/jobs/jobeditor/model/rscouplinginterface.cpp +++ b/src/jobs/jobeditor/model/rscouplinginterface.cpp @@ -39,16 +39,15 @@ RSCouplingInterface::RSCouplingInterface(database &db, QObject *parent) : " coupling(stop_id,rs_id,operation)" " VALUES(?, ?, ?)") { - } void RSCouplingInterface::loadCouplings(StopModel *model, db_id stopId, db_id jobId, QTime arr) { stopsModel = model; - m_stopId = stopId; - m_jobId = jobId; - arrival = arr; + m_stopId = stopId; + m_jobId = jobId; + arrival = arr; coupled.clear(); uncoupled.clear(); @@ -56,12 +55,12 @@ void RSCouplingInterface::loadCouplings(StopModel *model, db_id stopId, db_id jo query q(mDb, "SELECT rs_id, operation FROM coupling WHERE stop_id=?"); q.bind(1, m_stopId); - for(auto rs : q) + for (auto rs : q) { db_id rsId = rs.get(0); - RsOp op = RsOp(rs.get(1)); + RsOp op = RsOp(rs.get(1)); - if(op == RsOp::Coupled) + if (op == RsOp::Coupled) coupled.append(rsId); else uncoupled.append(rsId); @@ -70,20 +69,21 @@ void RSCouplingInterface::loadCouplings(StopModel *model, db_id stopId, db_id jo bool RSCouplingInterface::contains(db_id rsId, RsOp op) const { - if(op == RsOp::Coupled) + if (op == RsOp::Coupled) return coupled.contains(rsId); else return uncoupled.contains(rsId); } -bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, bool checkTractionType) +bool RSCouplingInterface::coupleRS(db_id rsId, const QString &rsName, bool on, + bool checkTractionType) { stopsModel->startStopsEditing(); stopsModel->markRsToUpdate(rsId); - if(on) + if (on) { - if(coupled.contains(rsId)) + if (coupled.contains(rsId)) { qWarning() << "Error already checked:" << rsId; return true; @@ -99,78 +99,79 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b " AND stops.arrival(1)); //Get last operation - jobId = row.get(2); - isOccupied = (operation == RsOp::Coupled); + auto row = q_RS_lastOp.getRows(); + RsOp operation = RsOp(row.get(1)); // Get last operation + jobId = row.get(2); + isOccupied = (operation == RsOp::Coupled); } - if(isOccupied) + if (isOccupied) { - if(jobId == m_jobId) + if (jobId == m_jobId) { - qWarning() << "Error while adding coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Already coupled by this job:" << m_jobId; + qWarning() << "Error while adding coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Already coupled by this job:" << m_jobId; - QMessageBox::warning(qApp->activeWindow(), - tr("Error"), + QMessageBox::warning(qApp->activeWindow(), tr("Error"), tr("Error while adding coupling operation.\n" "Rollingstock %1 is already coupled by this job (%2)") - .arg(rsName).arg(m_jobId), + .arg(rsName) + .arg(m_jobId), QMessageBox::Ok); return false; } else { - qWarning() << "Error while adding coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Occupied by this job:" << jobId; + qWarning() << "Error while adding coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Occupied by this job:" << jobId; - int but = QMessageBox::warning(qApp->activeWindow(), - tr("Error"), - tr("Error while adding coupling operation.\n" - "Rollingstock %1 is already coupled to another job (%2)\n" - "Do you still want to couple it?") - .arg(rsName).arg(jobId), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + int but = + QMessageBox::warning(qApp->activeWindow(), tr("Error"), + tr("Error while adding coupling operation.\n" + "Rollingstock %1 is already coupled to another job (%2)\n" + "Do you still want to couple it?") + .arg(rsName) + .arg(jobId), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if(but == QMessageBox::No) - return false; //Abort + if (but == QMessageBox::No) + return false; // Abort } } - if(checkTractionType && !stopsModel->isRailwayElectrifiedAfterStop(m_stopId)) + if (checkTractionType && !stopsModel->isRailwayElectrifiedAfterStop(m_stopId)) { - //Query RS type + // Query RS type query q_getRSType(mDb, "SELECT rs_models.type,rs_models.sub_type" " FROM rs_list" " JOIN rs_models ON rs_models.id=rs_list.model_id" " WHERE rs_list.id=?"); q_getRSType.bind(1, rsId); - if(q_getRSType.step() != SQLITE_ROW) + if (q_getRSType.step() != SQLITE_ROW) { qWarning() << "RS seems to not exist, ID:" << rsId; } - auto rs = q_getRSType.getRows(); - RsType type = RsType(rs.get(0)); + auto rs = q_getRSType.getRows(); + RsType type = RsType(rs.get(0)); RsEngineSubType subType = RsEngineSubType(rs.get(1)); - if(type == RsType::Engine && subType == RsEngineSubType::Electric) + if (type == RsType::Engine && subType == RsEngineSubType::Electric) { - int but = QMessageBox::warning(qApp->activeWindow(), - tr("Warning"), - tr("Rollingstock %1 is an Electric engine but the line is not electrified\n" - "This engine will not be albe to move a train.\n" - "Do you still want to couple it?") - .arg(rsName), - QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if(but == QMessageBox::No) - return false; //Cancel coupling operation + int but = QMessageBox::warning( + qApp->activeWindow(), tr("Warning"), + tr("Rollingstock %1 is an Electric engine but the line is not electrified\n" + "This engine will not be albe to move a train.\n" + "Do you still want to couple it?") + .arg(rsName), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + if (but == QMessageBox::No) + return false; // Cancel coupling operation } } @@ -180,44 +181,45 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b ret = q_addCoupling.execute(); q_addCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error while adding coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Op: Coupled " << "Ret:" << ret - << mDb.error_msg(); + qWarning() << "Error while adding coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Op: Coupled " + << "Ret:" << ret << mDb.error_msg(); return false; } coupled.append(rsId); - //Check if there is a next coupling operation in the same job + // Check if there is a next coupling operation in the same job query q(mDb, "SELECT s2.id, s2.arrival, s2.station_id, stations.name" " FROM coupling" " JOIN stops s2 ON s2.id=coupling.stop_id" " JOIN stops s1 ON s1.id=?" " JOIN stations ON stations.id=s2.station_id" - " WHERE coupling.rs_id=? AND coupling.operation=? AND s1.job_id=s2.job_id AND s1.arrival < s2.arrival"); + " WHERE coupling.rs_id=? AND coupling.operation=? AND s1.job_id=s2.job_id AND " + "s1.arrival < s2.arrival"); q.bind(1, m_stopId); q.bind(2, rsId); q.bind(3, int(RsOp::Coupled)); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { - auto r = q.getRows(); - db_id stopId = r.get(0); - QTime arr = r.get(1); - db_id stId = r.get(2); + auto r = q.getRows(); + db_id stopId = r.get(0); + QTime arr = r.get(1); + db_id stId = r.get(2); QString stName = r.get(3); qDebug() << "Found coupling, RS:" << rsId << "Stop:" << stopId << "St:" << stId << arr; - int but = QMessageBox::question(qApp->activeWindow(), - tr("Delete coupling?"), - tr("You couple %1 also in a next stop in %2 at %3.\n" - "Do you want to remove the other coupling operation?") - .arg(rsName, stName, arr.toString("HH:mm")), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - if(but == QMessageBox::Yes) + int but = + QMessageBox::question(qApp->activeWindow(), tr("Delete coupling?"), + tr("You couple %1 also in a next stop in %2 at %3.\n" + "Do you want to remove the other coupling operation?") + .arg(rsName, stName, arr.toString("HH:mm")), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + if (but == QMessageBox::Yes) { qDebug() << "Deleting coupling"; @@ -226,11 +228,11 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b ret = q_deleteCoupling.execute(); q_deleteCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qWarning() << "Error while deleting next coupling op. Stop:" << stopId - << "Rs:" << rsId << "Op: Uncoupled " << "Ret:" << ret - << mDb.error_msg(); + << "Rs:" << rsId << "Op: Uncoupled " + << "Ret:" << ret << mDb.error_msg(); } } else @@ -242,7 +244,7 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b else { int row = coupled.indexOf(rsId); - if(row == -1) + if (row == -1) return false; q_deleteCoupling.bind(1, m_stopId); @@ -250,44 +252,46 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b int ret = q_deleteCoupling.execute(); q_deleteCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error while deleting coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Op: Coupled " << "Ret:" << ret - << mDb.error_msg(); + qWarning() << "Error while deleting coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Op: Coupled " + << "Ret:" << ret << mDb.error_msg(); return false; } coupled.removeAt(row); - //Check if there is a next uncoupling operation + // Check if there is a next uncoupling operation query q(mDb, "SELECT s2.id, MIN(s2.arrival), s2.station_id, stations.name" " FROM coupling" " JOIN stops s2 ON s2.id=coupling.stop_id" " JOIN stops s1 ON s1.id=?" " JOIN stations ON stations.id=s2.station_id" - " WHERE coupling.rs_id=? AND coupling.operation=? AND s2.arrival > s1.arrival AND s2.job_id=s1.job_id"); + " WHERE coupling.rs_id=? AND coupling.operation=? AND s2.arrival > s1.arrival " + "AND s2.job_id=s1.job_id"); q.bind(1, m_stopId); q.bind(2, rsId); q.bind(3, int(RsOp::Uncoupled)); - 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 r = q.getRows(); - db_id stopId = r.get(0); - QTime arr = r.get(1); - db_id stId = r.get(2); + auto r = q.getRows(); + db_id stopId = r.get(0); + QTime arr = r.get(1); + db_id stId = r.get(2); QString stName = r.get(3); - qDebug() << "Found uncoupling, RS:" << rsId << "Stop:" << stopId << "St:" << stId << arr; + qDebug() << "Found uncoupling, RS:" << rsId << "Stop:" << stopId << "St:" << stId + << arr; - int but = QMessageBox::question(qApp->activeWindow(), - tr("Delete uncoupling?"), - tr("You don't couple %1 anymore.\n" - "Do you want to remove also the uncoupling operation in %2 at %3?") - .arg(rsName, stName, arr.toString("HH:mm")), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - if(but == QMessageBox::Yes) + int but = QMessageBox::question( + qApp->activeWindow(), tr("Delete uncoupling?"), + tr("You don't couple %1 anymore.\n" + "Do you want to remove also the uncoupling operation in %2 at %3?") + .arg(rsName, stName, arr.toString("HH:mm")), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + if (but == QMessageBox::Yes) { qDebug() << "Deleting coupling"; @@ -296,11 +300,11 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b ret = q_deleteCoupling.execute(); q_deleteCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qWarning() << "Error while deleting next uncoupling op. Stop:" << stopId - << "Rs:" << rsId << "Op: Uncoupled " << "Ret:" << ret - << mDb.error_msg(); + << "Rs:" << rsId << "Op: Uncoupled " + << "Ret:" << ret << mDb.error_msg(); } } else @@ -313,14 +317,14 @@ bool RSCouplingInterface::coupleRS(db_id rsId, const QString& rsName, bool on, b return true; } -bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString& rsName, bool on) +bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString &rsName, bool on) { stopsModel->startStopsEditing(); stopsModel->markRsToUpdate(rsId); - if(on) + if (on) { - if(uncoupled.contains(rsId)) + if (uncoupled.contains(rsId)) { qWarning() << "Error already checked:" << rsId; return true; @@ -332,44 +336,46 @@ bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString& rsName, bool on) int ret = q_addCoupling.execute(); q_addCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error while adding coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Op: Uncoupled " << "Ret:" << ret - << mDb.error_msg(); + qWarning() << "Error while adding coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Op: Uncoupled " + << "Ret:" << ret << mDb.error_msg(); return false; } uncoupled.append(rsId); - //Check if there is a next uncoupling operation + // Check if there is a next uncoupling operation query q(mDb, "SELECT s2.id, MIN(s2.arrival), s2.station_id, stations.name" " FROM coupling" " JOIN stops s2 ON s2.id=coupling.stop_id" " JOIN stops s1 ON s1.id=?" " JOIN stations ON stations.id=s2.station_id" - " WHERE coupling.rs_id=? AND coupling.operation=? AND s2.arrival > s1.arrival AND s2.job_id=s1.job_id"); + " WHERE coupling.rs_id=? AND coupling.operation=? AND s2.arrival > s1.arrival " + "AND s2.job_id=s1.job_id"); q.bind(1, m_stopId); q.bind(2, rsId); q.bind(3, int(RsOp::Uncoupled)); - 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 r = q.getRows(); - db_id stopId = r.get(0); - QTime arr = r.get(1); - db_id stId = r.get(2); + auto r = q.getRows(); + db_id stopId = r.get(0); + QTime arr = r.get(1); + db_id stId = r.get(2); QString stName = r.get(3); - qDebug() << "Found uncoupling, RS:" << rsId << "Stop:" << stopId << "St:" << stId << arr; + qDebug() << "Found uncoupling, RS:" << rsId << "Stop:" << stopId << "St:" << stId + << arr; - int but = QMessageBox::question(qApp->activeWindow(), - tr("Delete uncoupling?"), - tr("You uncouple %1 also in %2 at %3.\n" - "Do you want to remove the other uncoupling operation?") - .arg(rsName, stName, arr.toString("HH:mm")), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - if(but == QMessageBox::Yes) + int but = + QMessageBox::question(qApp->activeWindow(), tr("Delete uncoupling?"), + tr("You uncouple %1 also in %2 at %3.\n" + "Do you want to remove the other uncoupling operation?") + .arg(rsName, stName, arr.toString("HH:mm")), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + if (but == QMessageBox::Yes) { qDebug() << "Deleting coupling"; @@ -378,11 +384,11 @@ bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString& rsName, bool on) ret = q_deleteCoupling.execute(); q_deleteCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qWarning() << "Error while deleting next uncoupling op. Stop:" << stopId - << "Rs:" << rsId << "Op: Uncoupled " << "Ret:" << ret - << mDb.error_msg(); + << "Rs:" << rsId << "Op: Uncoupled " + << "Ret:" << ret << mDb.error_msg(); } } else @@ -394,7 +400,7 @@ bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString& rsName, bool on) else { int row = uncoupled.indexOf(rsId); - if(row == -1) + if (row == -1) return false; q_deleteCoupling.bind(1, m_stopId); @@ -402,11 +408,11 @@ bool RSCouplingInterface::uncoupleRS(db_id rsId, const QString& rsName, bool on) int ret = q_deleteCoupling.execute(); q_deleteCoupling.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error while deleting coupling op. Stop:" << m_stopId - << "Rs:" << rsId << "Op: Uncoupled " << "Ret:" << ret - << mDb.error_msg(); + qWarning() << "Error while deleting coupling op. Stop:" << m_stopId << "Rs:" << rsId + << "Op: Uncoupled " + << "Ret:" << ret << mDb.error_msg(); return false; } @@ -426,48 +432,45 @@ int RSCouplingInterface::importRSFromJob(db_id otherStopId) " WHERE coupling.stop_id=? AND coupling.operation=0"); q_getUncoupled.bind(1, otherStopId); - int count = 0; + int count = 0; bool lineElectrified = stopsModel->isRailwayElectrifiedAfterStop(m_stopId); QElapsedTimer timer; timer.start(); - for(auto rs : q_getUncoupled) + for (auto rs : q_getUncoupled) { - db_id rsId = rs.get(0); + db_id rsId = rs.get(0); - int number = rs.get(1); + int number = rs.get(1); int modelNameLen = sqlite3_column_bytes(q_getUncoupled.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q_getUncoupled.stmt(), 2)); + const char *modelName = + reinterpret_cast(sqlite3_column_text(q_getUncoupled.stmt(), 2)); int modelSuffixLen = sqlite3_column_bytes(q_getUncoupled.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q_getUncoupled.stmt(), 3)); - RsType rsType = RsType(rs.get(4)); + const char *modelSuffix = + reinterpret_cast(sqlite3_column_text(q_getUncoupled.stmt(), 3)); + RsType rsType = RsType(rs.get(4)); - QString rsName = rs_utils::formatNameRef(modelName, - modelNameLen, - number, - modelSuffix, - modelSuffixLen, - rsType); + QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, rsType); - //TODO: optimize work - if(coupleRS(rsId, rsName, true, !lineElectrified)) + // TODO: optimize work + if (coupleRS(rsId, rsName, true, !lineElectrified)) count++; - if(timer.elapsed() > 10000) + if (timer.elapsed() > 10000) { - //After 10 seconds, give opportunity to stop + // After 10 seconds, give opportunity to stop int ret = QMessageBox::question( - qApp->activeWindow(), - tr("Continue Importation?"), - tr("Rollingstock importation is taking more time than expected.\n" - "Do you want to continue?")); + qApp->activeWindow(), tr("Continue Importation?"), + tr("Rollingstock importation is taking more time than expected.\n" + "Do you want to continue?")); - if(ret == QMessageBox::No) - return count; //Abort here + if (ret == QMessageBox::No) + return count; // Abort here - timer.restart(); //Count again + timer.restart(); // Count again } } @@ -487,13 +490,14 @@ bool RSCouplingInterface::hasEngineAfterStop(bool *isElectricOnNonElectrifiedLin " LIMIT 1"); q_hasEngine.bind(1, m_jobId); q_hasEngine.bind(2, arrival); - if(q_hasEngine.step() != SQLITE_ROW) - return false; //No engine + if (q_hasEngine.step() != SQLITE_ROW) + return false; // No engine - if(isElectricOnNonElectrifiedLine) + if (isElectricOnNonElectrifiedLine) { RsEngineSubType subType = RsEngineSubType(q_hasEngine.getRows().get(1)); - *isElectricOnNonElectrifiedLine = (subType == RsEngineSubType::Electric) && (!isRailwayElectrified()); + *isElectricOnNonElectrifiedLine = + (subType == RsEngineSubType::Electric) && (!isRailwayElectrified()); } return true; } diff --git a/src/jobs/jobeditor/model/rslistondemandmodel.cpp b/src/jobs/jobeditor/model/rslistondemandmodel.cpp index fe5b81b..2aae24d 100644 --- a/src/jobs/jobeditor/model/rslistondemandmodel.cpp +++ b/src/jobs/jobeditor/model/rslistondemandmodel.cpp @@ -35,18 +35,18 @@ QVariant RSListOnDemandModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const RSItem& item = cache.at(row - cacheFirstRow); + const RSItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -63,9 +63,9 @@ QVariant RSListOnDemandModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(item.type == RsType::Engine) + if (item.type == RsType::Engine) { - //Engines in bold + // Engines in bold QFont f; f.setBold(true); return f; diff --git a/src/jobs/jobeditor/model/rslistondemandmodel.h b/src/jobs/jobeditor/model/rslistondemandmodel.h index 28ed655..8d15662 100644 --- a/src/jobs/jobeditor/model/rslistondemandmodel.h +++ b/src/jobs/jobeditor/model/rslistondemandmodel.h @@ -38,9 +38,13 @@ class RSListOnDemandModel : public IPagedItemModelImpl - -RSProxyModel::RSProxyModel(RSCouplingInterface *mgr, - RsOp o, - RsType type, - QObject *parent) : - QAbstractListModel (parent), +RSProxyModel::RSProxyModel(RSCouplingInterface *mgr, RsOp o, RsType type, QObject *parent) : + QAbstractListModel(parent), couplingMgr(mgr), op(o), targetType(type) { - } int RSProxyModel::rowCount(const QModelIndex &parent) const @@ -45,10 +40,10 @@ int RSProxyModel::rowCount(const QModelIndex &parent) const QVariant RSProxyModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid() || idx.column() > 0 || idx.row() >= m_data.size()) + if (!idx.isValid() || idx.column() > 0 || idx.row() >= m_data.size()) return QVariant(); - const RsItem& item = m_data.at(idx.row()); + const RsItem &item = m_data.at(idx.row()); switch (role) { @@ -58,92 +53,104 @@ QVariant RSProxyModel::data(const QModelIndex &idx, int role) const { return couplingMgr->contains(item.rsId, op) ? Qt::Checked : Qt::Unchecked; } - case Qt::BackgroundRole: //NOTE SYNC: RSCoupleDialog + case Qt::BackgroundRole: // NOTE SYNC: RSCoupleDialog { - if(item.flag == ErrNotCoupledBefore || item.flag == ErrAlreadyCoupled) + if (item.flag == ErrNotCoupledBefore || item.flag == ErrAlreadyCoupled) { - //Error: already coupled or already uncoupled or not coupled at all before this stop - return QBrush(qRgb(255, 86, 255)); //Solid light magenta #FF56FF + // Error: already coupled or already uncoupled or not coupled at all before this stop + return QBrush(qRgb(255, 86, 255)); // Solid light magenta #FF56FF } - if(item.flag == WrongStation) + if (item.flag == WrongStation) { - //Error: RS is not in this station - return QBrush(qRgb(255, 61, 67)); //Solid light red #FF3d43 + // Error: RS is not in this station + return QBrush(qRgb(255, 61, 67)); // Solid light red #FF3d43 } - if(targetType == RsType::Engine && item.engineType == RsEngineSubType::Electric && !couplingMgr->isRailwayElectrified()) + if (targetType == RsType::Engine && item.engineType == RsEngineSubType::Electric + && !couplingMgr->isRailwayElectrified()) { - //Warn Electric traction not possible - return QBrush(qRgb(0, 0, 255), Qt::FDiagPattern); //Blue + // Warn Electric traction not possible + return QBrush(qRgb(0, 0, 255), Qt::FDiagPattern); // Blue } - if(item.flag == FirstUseOfRS) + if (item.flag == FirstUseOfRS) { - return QBrush(qRgb(0, 255, 255)); //Cyan + return QBrush(qRgb(0, 255, 255)); // Cyan } - if(item.flag == UnusedRS) + if (item.flag == UnusedRS) { - return QBrush(qRgb(0, 255, 0)); //Green + return QBrush(qRgb(0, 255, 0)); // Green } break; } case Qt::ToolTipRole: { - if(item.flag == ErrNotCoupledBefore) + if (item.flag == ErrNotCoupledBefore) { - //Error - return tr("Rollingstock %1 cannot be uncoupled here because it wasn't coupled to this job before this stop " + // Error + return tr("Rollingstock %1 cannot be uncoupled here because it wasn't coupled " + "to this job before this stop " "or because it was already uncoupled before this stop.
" - "Please remove the tick").arg(item.rsName); + "Please remove the tick") + .arg(item.rsName); } - if(item.flag == ErrAlreadyCoupled) + if (item.flag == ErrAlreadyCoupled) { - //Error - if(item.jobId == couplingMgr->getJobId()) + // Error + if (item.jobId == couplingMgr->getJobId()) { - return tr("Rollingstock %1 cannot be coupled here because it was already coupled to this job before this stop
" - "Please remove the tick").arg(item.rsName); - }else{ - return tr("Rollingstock %1 cannot be coupled here because it was already coupled before this stop
" + return tr("Rollingstock %1 cannot be coupled here because it was already " + "coupled to this job before this stop
" + "Please remove the tick") + .arg(item.rsName); + } + else + { + return tr("Rollingstock %1 cannot be coupled here because it was already " + "coupled before this stop
" "to job %2
" "Please remove the tick") - .arg(item.rsName, - JobCategoryName::jobName(item.jobId, item.jobCat)); + .arg(item.rsName, JobCategoryName::jobName(item.jobId, item.jobCat)); } } - if(item.flag == WrongStation) + if (item.flag == WrongStation) { - //Error - return tr("Rollingstock %1 cannot be coupled here because it is not in this station.
" - "Please remove the tick").arg(item.rsName); + // Error + return tr("Rollingstock %1 cannot be coupled here because it is not in this " + "station.
" + "Please remove the tick") + .arg(item.rsName); } - if(targetType == RsType::Engine && item.engineType == RsEngineSubType::Electric && !couplingMgr->isRailwayElectrified()) + if (targetType == RsType::Engine && item.engineType == RsEngineSubType::Electric + && !couplingMgr->isRailwayElectrified()) { - //Warn Electric traction not possible - return tr("Engine %1 is electric but the line is not electrified!").arg(item.rsName); + // Warn Electric traction not possible + return tr("Engine %1 is electric but the line is not electrified!") + .arg(item.rsName); } - if(item.flag == HasNextOperation) + if (item.flag == HasNextOperation) { - return tr("Rollingstock %1 is coupled in this station also by %2 at %3.") - .arg(item.rsName, - JobCategoryName::jobName(item.jobId, item.jobCat), - item.time.toString("HH:mm")); + return tr("Rollingstock %1 is coupled in this station also by %2 at " + "%3.") + .arg(item.rsName, JobCategoryName::jobName(item.jobId, item.jobCat), + item.time.toString("HH:mm")); } - if(item.flag == LastOperation) + if (item.flag == LastOperation) { return tr("Rollingstock %1 was left in this station by %2 at %3.") - .arg(item.rsName, - JobCategoryName::jobName(item.jobId, item.jobCat), - item.time.toString("HH:mm")); + .arg(item.rsName, JobCategoryName::jobName(item.jobId, item.jobCat), + item.time.toString("HH:mm")); } - if(item.flag == FirstUseOfRS) + if (item.flag == FirstUseOfRS) { - if(op == RsOp::Coupled && couplingMgr->contains(item.rsId, RsOp::Coupled)) + if (op == RsOp::Coupled && couplingMgr->contains(item.rsId, RsOp::Coupled)) return tr("This is the first use of this rollingstock %1").arg(item.rsName); - return tr("This would be the first use of this rollingstock %1").arg(item.rsName); + return tr("This would be the first use of this rollingstock %1") + .arg(item.rsName); } - if(item.flag == UnusedRS) + if (item.flag == UnusedRS) { - return tr("Rollingstock %1 is never used in this session. You can couple it for the first time from any one station") - .arg(item.rsName); + return tr("Rollingstock %1 is never used in this session. You can couple it for " + "the first time from any one station") + .arg(item.rsName); } break; } @@ -154,21 +161,23 @@ QVariant RSProxyModel::data(const QModelIndex &idx, int role) const bool RSProxyModel::setData(const QModelIndex &idx, const QVariant &value, int role) { - if(role != Qt::CheckStateRole || !idx.isValid() || idx.column() > 0 || idx.row() >= m_data.size()) + if (role != Qt::CheckStateRole || !idx.isValid() || idx.column() > 0 + || idx.row() >= m_data.size()) return false; Qt::CheckState state = value.value(); - const RsItem& item = m_data.at(idx.row()); + const RsItem &item = m_data.at(idx.row()); - bool ret = false; + bool ret = false; - if(op == RsOp::Coupled) //Check traction type only if we are dealing with RsType::Engine - ret = couplingMgr->coupleRS(item.rsId, item.rsName, state == Qt::Checked, targetType == RsType::Engine); + if (op == RsOp::Coupled) // Check traction type only if we are dealing with RsType::Engine + ret = couplingMgr->coupleRS(item.rsId, item.rsName, state == Qt::Checked, + targetType == RsType::Engine); else ret = couplingMgr->uncoupleRS(item.rsId, item.rsName, state == Qt::Checked); - if(ret) + if (ret) emit dataChanged(idx, idx); return ret; @@ -176,11 +185,9 @@ bool RSProxyModel::setData(const QModelIndex &idx, const QVariant &value, int ro Qt::ItemFlags RSProxyModel::flags(const QModelIndex &index) const { - if(index.isValid()) - return Qt::ItemIsEnabled - | Qt::ItemNeverHasChildren - | Qt::ItemIsSelectable - | Qt::ItemIsUserCheckable; + if (index.isValid()) + return Qt::ItemIsEnabled | Qt::ItemNeverHasChildren | Qt::ItemIsSelectable + | Qt::ItemIsUserCheckable; return Qt::NoItemFlags; } diff --git a/src/jobs/jobeditor/model/rsproxymodel.h b/src/jobs/jobeditor/model/rsproxymodel.h index a8b70f7..f488d3b 100644 --- a/src/jobs/jobeditor/model/rsproxymodel.h +++ b/src/jobs/jobeditor/model/rsproxymodel.h @@ -33,11 +33,7 @@ class RSProxyModel : public QAbstractListModel Q_OBJECT public: - - RSProxyModel(RSCouplingInterface *mgr, - RsOp o, - RsType type, - QObject *parent = nullptr); + RSProxyModel(RSCouplingInterface *mgr, RsOp o, RsType type, QObject *parent = nullptr); int rowCount(const QModelIndex &parent) const override; @@ -48,28 +44,28 @@ public: enum RSItemFlg { - NoFlag = 0, - WrongStation = 1, - LastOperation = 2, - HasNextOperation = 3, - FirstUseOfRS = 4, - UnusedRS = 5, + NoFlag = 0, + WrongStation = 1, + LastOperation = 2, + HasNextOperation = 3, + FirstUseOfRS = 4, + UnusedRS = 5, ErrNotCoupledBefore = 6, - ErrAlreadyCoupled = 7 + ErrAlreadyCoupled = 7 }; struct RsItem { db_id rsId; - db_id jobId; //Can be next job or previous job + db_id jobId; // Can be next job or previous job QString rsName; int flag; - QTime time; //Can be next or previous operation time + QTime time; // Can be next or previous operation time JobCategory jobCat; RsEngineSubType engineType; }; - void loadData(const QVector& items); + void loadData(const QVector &items); private: QVector m_data; diff --git a/src/jobs/jobeditor/model/stopcouplingmodel.cpp b/src/jobs/jobeditor/model/stopcouplingmodel.cpp index c9d6960..5f40aab 100644 --- a/src/jobs/jobeditor/model/stopcouplingmodel.cpp +++ b/src/jobs/jobeditor/model/stopcouplingmodel.cpp @@ -26,7 +26,6 @@ using namespace sqlite3pp; #include "utils/rs_utils.h" - StopCouplingModel::StopCouplingModel(sqlite3pp::database &db, QObject *parent) : RSListOnDemandModel(db, parent), m_stopId(0), @@ -46,65 +45,65 @@ qint64 StopCouplingModel::recalcTotalItemCount() void StopCouplingModel::setStop(db_id stopId, RsOp op) { - m_stopId = stopId; + m_stopId = stopId; m_operation = op; refreshData(true); } -void StopCouplingModel::internalFetch(int first, int /*sortCol*/, int /*valRow*/, const QVariant& /*val*/) +void StopCouplingModel::internalFetch(int first, int /*sortCol*/, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); int offset = first + curPage * ItemsPerPage; - QByteArray sql = "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" - " FROM coupling" - " JOIN rs_list ON rs_list.id=coupling.rs_id" - " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" - " WHERE coupling.stop_id=?2 AND coupling.operation=?3" - " ORDER BY rs_models.type,rs_models.name,rs_list.number,rs_models.suffix"; + QByteArray sql = + "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" + " FROM coupling" + " JOIN rs_list ON rs_list.id=coupling.rs_id" + " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" + " WHERE coupling.stop_id=?2 AND coupling.operation=?3" + " ORDER BY rs_models.type,rs_models.name,rs_list.number,rs_models.suffix"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); q.bind(2, m_stopId); q.bind(3, int(m_operation)); - if(offset) + if (offset) q.bind(2, offset); QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; + int i = 0; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - RSItem &item = vec[i]; - item.rsId = r.get(0); + auto r = *it; + RSItem &item = vec[i]; + item.rsId = r.get(0); - int number = r.get(1); - int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); + int number = r.get(1); + int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); - int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); - item.type = RsType(sqlite3_column_int(q.stmt(), 4)); + int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); + item.type = RsType(sqlite3_column_int(q.stmt(), 4)); - item.name = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - item.type); + item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, item.type); i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/jobs/jobeditor/model/stopcouplingmodel.h b/src/jobs/jobeditor/model/stopcouplingmodel.h index 9cc3f4b..be279b3 100644 --- a/src/jobs/jobeditor/model/stopcouplingmodel.h +++ b/src/jobs/jobeditor/model/stopcouplingmodel.h @@ -22,7 +22,6 @@ #include "rslistondemandmodel.h" - class StopCouplingModel : public RSListOnDemandModel { Q_OBJECT diff --git a/src/jobs/jobeditor/model/stopmodel.cpp b/src/jobs/jobeditor/model/stopmodel.cpp index dfad23d..774cc7c 100644 --- a/src/jobs/jobeditor/model/stopmodel.cpp +++ b/src/jobs/jobeditor/model/stopmodel.cpp @@ -53,13 +53,15 @@ StopModel::StopModel(database &db, QObject *parent) : connect(Session, &MeetingSession::shiftJobsChanged, this, &StopModel::onExternalShiftChange); connect(Session, &MeetingSession::shiftNameChanged, this, &StopModel::onShiftNameChanged); - connect(Session, &MeetingSession::segmentNameChanged, this, &StopModel::onStationSegmentNameChanged); - connect(Session, &MeetingSession::stationNameChanged, this, &StopModel::onStationSegmentNameChanged); + connect(Session, &MeetingSession::segmentNameChanged, this, + &StopModel::onStationSegmentNameChanged); + connect(Session, &MeetingSession::stationNameChanged, this, + &StopModel::onStationSegmentNameChanged); } -QVariant StopModel::data(const QModelIndex &/*index*/, int /*role*/) const +QVariant StopModel::data(const QModelIndex & /*index*/, int /*role*/) const { - return QVariant(); //Use setters and getters instead of data() and setData() + return QVariant(); // Use setters and getters instead of data() and setData() } int StopModel::rowCount(const QModelIndex &parent) const @@ -107,14 +109,14 @@ bool StopModel::loadJobStops(db_id jobId) { query q_getCatAndShift(mDb, "SELECT category,shift_id FROM jobs WHERE id=?"); q_getCatAndShift.bind(1, mJobId); - if(q_getCatAndShift.step() != SQLITE_ROW) + if (q_getCatAndShift.step() != SQLITE_ROW) { - //Error: job does not exist + // Error: job does not exist endResetModel(); return false; } - auto r = q_getCatAndShift.getRows(); + auto r = q_getCatAndShift.getRows(); oldCategory = category = JobCategory(r.get(0)); emit categoryChanged(int(category)); @@ -122,19 +124,18 @@ bool StopModel::loadJobStops(db_id jobId) emit jobShiftChanged(jobShiftId); } - query q_selectStops(mDb, "SELECT COUNT(id) FROM stops WHERE job_id=?"); q_selectStops.bind(1, mJobId); - if(q_selectStops.step() != SQLITE_ROW) + if (q_selectStops.step() != SQLITE_ROW) { qWarning() << database_error(mDb).what(); } int count = q_selectStops.getRows().get(0); q_selectStops.finish(); - if(count == 0) + if (count == 0) { - //Job has no stops, start editing so it cannot be saved without adding stops to it + // Job has no stops, start editing so it cannot be saved without adding stops to it endResetModel(); insertAddHere(0, 1); @@ -152,124 +153,136 @@ bool StopModel::loadJobStops(db_id jobId) StopItem::Segment prevSegment; db_id prevOutGateId = 0; - q_selectStops.prepare("SELECT stops.id, stops.station_id, stops.arrival, stops.departure, stops.type," - "stops.in_gate_conn, g1.gate_id, g1.gate_track, g1.track_id, g1.track_side," - "stops.out_gate_conn, g2.gate_id, g2.gate_track, g2.track_id, g2.track_side," - "stops.next_segment_conn_id, c.seg_id, c.in_track, c.out_track," - "seg.in_gate_id, seg.out_gate_id" - " FROM stops" - " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id" - " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" - " LEFT JOIN station_gate_connections g2 ON g2.id=stops.out_gate_conn" - " LEFT JOIN railway_segments seg ON seg.id=c.seg_id" - " WHERE stops.job_id=?1" - " ORDER BY stops.arrival ASC"); + q_selectStops.prepare( + "SELECT stops.id, stops.station_id, stops.arrival, stops.departure, stops.type," + "stops.in_gate_conn, g1.gate_id, g1.gate_track, g1.track_id, g1.track_side," + "stops.out_gate_conn, g2.gate_id, g2.gate_track, g2.track_id, g2.track_side," + "stops.next_segment_conn_id, c.seg_id, c.in_track, c.out_track," + "seg.in_gate_id, seg.out_gate_id" + " FROM stops" + " LEFT JOIN railway_connections c ON c.id=stops.next_segment_conn_id" + " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" + " LEFT JOIN station_gate_connections g2 ON g2.id=stops.out_gate_conn" + " LEFT JOIN railway_segments seg ON seg.id=c.seg_id" + " WHERE stops.job_id=?1" + " ORDER BY stops.arrival ASC"); q_selectStops.bind(1, mJobId); - for(auto stop : q_selectStops) + for (auto stop : q_selectStops) { StopItem s; - s.stopId = stop.get(0); - s.stationId = stop.get(1); + s.stopId = stop.get(0); + s.stationId = stop.get(1); - s.arrival = stop.get(2); - s.departure = stop.get(3); + s.arrival = stop.get(2); + s.departure = stop.get(3); - int stopType = stop.get(4); + int stopType = stop.get(4); - s.fromGate.gateConnId = stop.get(5); - s.fromGate.gateId = stop.get(6); - s.fromGate.gateTrackNum = stop.get(7); - s.trackId = stop.get(8); + s.fromGate.gateConnId = stop.get(5); + s.fromGate.gateId = stop.get(6); + s.fromGate.gateTrackNum = stop.get(7); + s.trackId = stop.get(8); s.fromGate.stationTrackSide = utils::Side(stop.get(9)); - s.toGate.gateConnId = stop.get(10); - s.toGate.gateId = stop.get(11); - s.toGate.gateTrackNum = stop.get(12); - db_id otherTrackId = stop.get(13); - s.toGate.stationTrackSide = utils::Side(stop.get(14)); + s.toGate.gateConnId = stop.get(10); + s.toGate.gateId = stop.get(11); + s.toGate.gateTrackNum = stop.get(12); + db_id otherTrackId = stop.get(13); + s.toGate.stationTrackSide = utils::Side(stop.get(14)); - s.nextSegment.segConnId = stop.get(15); - s.nextSegment.segmentId = stop.get(16); - s.nextSegment.inTrackNum = stop.get(17); - s.nextSegment.outTrackNum = stop.get(18); + s.nextSegment.segConnId = stop.get(15); + s.nextSegment.segmentId = stop.get(16); + s.nextSegment.inTrackNum = stop.get(17); + s.nextSegment.outTrackNum = stop.get(18); - db_id segInGateId = stop.get(19); - db_id segOutGateId = stop.get(20); + db_id segInGateId = stop.get(19); + db_id segOutGateId = stop.get(20); - if(s.toGate.gateId && s.toGate.gateId == segOutGateId) + if (s.toGate.gateId && s.toGate.gateId == segOutGateId) { - //Segment is reversed + // Segment is reversed qSwap(segInGateId, segOutGateId); qSwap(s.nextSegment.inTrackNum, s.nextSegment.outTrackNum); s.nextSegment.reversed = true; } - //Fix station track on First stop - if(!s.fromGate.gateConnId) + // Fix station track on First stop + if (!s.fromGate.gateConnId) { - //If station has no 'in' connection use 'out' connection - //This might happen on first stop + // If station has no 'in' connection use 'out' connection + // This might happen on first stop s.trackId = otherTrackId; } - //Check consistency - if(s.trackId != otherTrackId && s.toGate.gateConnId) + // Check consistency + if (s.trackId != otherTrackId && s.toGate.gateConnId) { - //Last stop has no 'out' connection so do not check track if on 'Last' stop - //In gate leads to a different station track than out gate - qWarning() << "Stop:" << s.stopId << "Different track:" << s.fromGate.gateConnId << s.toGate.gateConnId; + // Last stop has no 'out' connection so do not check track if on 'Last' stop + // In gate leads to a different station track than out gate + qWarning() << "Stop:" << s.stopId << "Different track:" << s.fromGate.gateConnId + << s.toGate.gateConnId; } - if(prevSegment.segmentId != 0) + if (prevSegment.segmentId != 0) { - if(prevOutGateId != s.fromGate.gateId) + if (prevOutGateId != s.fromGate.gateId) { - //Previous segment leads to a different in gate - qWarning() << "Stop:" << s.stopId << "Different prev segment:" << prevSegment.segConnId << s.fromGate.gateConnId; + // Previous segment leads to a different in gate + qWarning() << "Stop:" << s.stopId + << "Different prev segment:" << prevSegment.segConnId + << s.fromGate.gateConnId; } - if(s.fromGate.gateTrackNum != prevSegment.outTrackNum) + if (s.fromGate.gateTrackNum != prevSegment.outTrackNum) { - //Previous segment leads to a different track than in gate track - qWarning() << "Stop:" << s.stopId << "Different in gate track:" << s.fromGate.gateConnId << s.toGate.gateConnId; + // Previous segment leads to a different track than in gate track + qWarning() << "Stop:" << s.stopId + << "Different in gate track:" << s.fromGate.gateConnId + << s.toGate.gateConnId; } } - if(s.nextSegment.segmentId != 0) + if (s.nextSegment.segmentId != 0) { - if(segInGateId != s.toGate.gateId) + if (segInGateId != s.toGate.gateId) { - //Out gate leads to a different next semgent - qWarning() << "Stop:" << s.stopId << "Different next segment:" << s.nextSegment.segConnId << s.toGate.gateConnId; + // Out gate leads to a different next semgent + qWarning() << "Stop:" << s.stopId + << "Different next segment:" << s.nextSegment.segConnId + << s.toGate.gateConnId; } - if(s.toGate.gateTrackNum != s.nextSegment.inTrackNum) + if (s.toGate.gateTrackNum != s.nextSegment.inTrackNum) { - //Out gate leads to a different than next segment in track - qWarning() << "Stop:" << s.stopId << "Different out gate track:" << s.toGate.gateConnId << s.nextSegment.segConnId; + // Out gate leads to a different than next segment in track + qWarning() << "Stop:" << s.stopId + << "Different out gate track:" << s.toGate.gateConnId + << s.nextSegment.segConnId; } } - prevSegment = s.nextSegment; + prevSegment = s.nextSegment; prevOutGateId = segOutGateId; - s.type = StopType::Normal; + s.type = StopType::Normal; - if(i == 0) + if (i == 0) { s.type = StopType::First; - if(stopType != 0) + if (stopType != 0) { - //Error First cannot be a transit - qWarning() << "Error: First stop cannot be transit! Job:" << mJobId << "StopId:" << s.stopId; + // Error First cannot be a transit + qWarning() << "Error: First stop cannot be transit! Job:" << mJobId + << "StopId:" << s.stopId; } } else if (stopType) { s.type = StopType::Transit; - if(i == count - 1) + if (i == count - 1) { - //Error Last cannot be a transit - qWarning() << "Error: Last stop cannot be transit! Job:" << mJobId << "StopId:" << s.stopId; + // Error Last cannot be a transit + qWarning() << "Error: Last stop cannot be transit! Job:" << mJobId + << "StopId:" << s.stopId; } } @@ -278,15 +291,15 @@ bool StopModel::loadJobStops(db_id jobId) } q_selectStops.finish(); - if(!stops.isEmpty() && stops.last().type != StopType::First) - stops.last().type = StopType::Last; //Update Last stop type unless it's First + if (!stops.isEmpty() && stops.last().type != StopType::First) + stops.last().type = StopType::Last; // Update Last stop type unless it's First endResetModel(); insertAddHere(stops.count(), 1); - if(stops.count() < 3) //First + Last + AddHere - startStopsEditing(); //Set editied to enable deletion if user clicks Cancel + if (stops.count() < 3) // First + Last + AddHere + startStopsEditing(); // Set editied to enable deletion if user clicks Cancel stops.squeeze(); rsToUpdate.squeeze(); @@ -307,7 +320,7 @@ void StopModel::clearJob() emit categoryChanged(int(category)); int count = stops.count(); - if(count == 0) + if (count == 0) return; beginRemoveRows(QModelIndex(), 0, count - 1); @@ -324,17 +337,17 @@ bool StopModel::isEdited() const bool StopModel::commitChanges() { - if(editState == NotEditing) + if (editState == NotEditing) return true; command q(mDb, "UPDATE jobs SET category=?, shift_id=? WHERE id=?"); q.bind(1, int(category)); - if(newShiftId) + if (newShiftId) q.bind(2, newShiftId); else - q.bind(2); //NULL shift + q.bind(2); // NULL shift q.bind(3, mJobId); - if(q.execute() != SQLITE_OK) + if (q.execute() != SQLITE_OK) { category = oldCategory; emit categoryChanged(int(category)); @@ -344,30 +357,30 @@ bool StopModel::commitChanges() db_id oldJobId = mJobId; - if(mNewJobId != mJobId) + if (mNewJobId != mJobId) { q.prepare("UPDATE jobs SET id=? WHERE id=?"); q.bind(1, mNewJobId); q.bind(2, mJobId); int ret = q.execute(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) { mJobId = mNewJobId; } else { - //Reset to old value + // Reset to old value mNewJobId = oldJobId; emit jobIdChanged(mJobId); } } - if(category != oldCategory || mJobId != oldJobId) + if (category != oldCategory || mJobId != oldJobId) { - //When category or job number changes, inform all stations - for(const StopItem& item : qAsConst(stops)) + // When category or job number changes, inform all stations + for (const StopItem &item : qAsConst(stops)) { - if(item.stationId) + if (item.stationId) stationsToUpdate.insert(item.stationId); } @@ -377,7 +390,7 @@ bool StopModel::commitChanges() " WHERE stops.job_id=?" " GROUP BY coupling.rs_id"); q.bind(1, mJobId); - for(auto rs : q_rs) + for (auto rs : q_rs) { rsToUpdate.insert(rs.get(0)); } @@ -385,12 +398,12 @@ bool StopModel::commitChanges() oldCategory = category; - if(jobShiftId != newShiftId) + if (jobShiftId != newShiftId) emit Session->shiftJobsChanged(jobShiftId, oldJobId); emit Session->shiftJobsChanged(newShiftId, mNewJobId); jobShiftId = newShiftId; - //Update station and rollingstock views + // Update station and rollingstock views emit Session->stationJobsPlanChanged(stationsToUpdate); emit Session->rollingStockPlanChanged(rsToUpdate); @@ -401,63 +414,67 @@ bool StopModel::commitChanges() bool StopModel::revertChanges() { - if(editState == NotEditing) + if (editState == NotEditing) return true; bool needsStopReload = false; - if(editState == StopsEditing) + if (editState == StopsEditing) { - //Delete current data + // Delete current data - //Clear stops (will automatically clear couplings with FK: ON DELETE CASCADE) + // Clear stops (will automatically clear couplings with FK: ON DELETE CASCADE) command cmd(mDb, "DELETE FROM stops WHERE job_id=?"); cmd.bind(1, mJobId); int ret = cmd.execute(); cmd.finish(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error while clearing current stops:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qDebug() << "Error while clearing current stops:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } - //Now restore old data + // Now restore old data - //Restore stops + // Restore stops cmd.prepare("INSERT INTO stops SELECT * FROM old_stops WHERE job_id=?"); cmd.bind(1, mJobId); ret = cmd.execute(); cmd.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error while restoring old stops:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qDebug() << "Error while restoring old stops:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } - //Restore couplings + // Restore couplings cmd.prepare("INSERT INTO coupling(id, stop_id, rs_id, operation)" - " SELECT old_coupling.id, old_coupling.stop_id, old_coupling.rs_id, old_coupling.operation" + " SELECT old_coupling.id, old_coupling.stop_id, old_coupling.rs_id, " + "old_coupling.operation" " FROM old_coupling" " JOIN stops ON stops.id=old_coupling.stop_id WHERE stops.job_id=?"); cmd.bind(1, mJobId); ret = cmd.execute(); cmd.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error while restoring old couplings:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qDebug() << "Error while restoring old couplings:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } - //Reload info and stops + // Reload info and stops needsStopReload = true; } else { - //Just reset info in case of InfoEditing - //StopsEditing triggers stop loading so already resets info + // Just reset info in case of InfoEditing + // StopsEditing triggers stop loading so already resets info mNewJobId = mJobId; emit jobIdChanged(mJobId); @@ -469,15 +486,15 @@ bool StopModel::revertChanges() emit jobShiftChanged(jobShiftId); } - //Update station and rollingstock views + // Update station and rollingstock views emit Session->stationJobsPlanChanged(stationsToUpdate); emit Session->rollingStockPlanChanged(rsToUpdate); bool ret = endStopsEditing(); - if(!ret) + if (!ret) return ret; - if(needsStopReload) + if (needsStopReload) loadJobStops(mJobId); return true; @@ -486,34 +503,34 @@ bool StopModel::revertChanges() void StopModel::addStop() { DEBUG_IMPORTANT_ENTRY; - if(stops.count() == 0) + if (stops.count() == 0) return; startStopsEditing(); - int idx = stops.count() - 1; - StopItem& last = stops[idx]; + int idx = stops.count() - 1; + StopItem &last = stops[idx]; - if(last.addHere != 1) + if (last.addHere != 1) { qWarning() << "Error: addStop not an AddHere Item"; } - last.addHere = 0; //Reset AddHere + last.addHere = 0; // Reset AddHere - int prevIdx = idx - 1; - if(prevIdx >= 0) //Has stops before + int prevIdx = idx - 1; + if (prevIdx >= 0) // Has stops before { - last.type = StopType::Last; + last.type = StopType::Last; - StopItem& s = stops[prevIdx]; - if(prevIdx > 0) + StopItem &s = stops[prevIdx]; + if (prevIdx > 0) { - //Update stop time and type - s.type = StopType::Normal; + // Update stop time and type + s.type = StopType::Normal; int secs = defaultStopTimeSec(); - if(secs == 0) + if (secs == 0) s.type = StopType::Transit; s.departure = s.arrival.addSecs(secs); @@ -529,91 +546,92 @@ void StopModel::addStop() * This is to prevent contemporary stops that will break ORDER BY arrival queries */ int travelSecs = 60; - if(s.nextSegment.segmentId) + if (s.nextSegment.segmentId) travelSecs = calcTravelTime(s.nextSegment.segmentId); const QTime time = s.departure.addSecs(travelSecs); - last.arrival = time; - last.departure = last.arrival; - last.stopId = createStop(mJobId, last.arrival, last.departure, last.type); + last.arrival = time; + last.departure = last.arrival; + last.stopId = createStop(mJobId, last.arrival, last.departure, last.type); - //Set station if previous stop has a next segment selected - if(s.nextSegment.segConnId) + // Set station if previous stop has a next segment selected + if (s.nextSegment.segConnId) updateCurrentInGate(last, s.nextSegment); - if(autoMoveUncoupleToNewLast) + if (autoMoveUncoupleToNewLast) { - if(prevIdx >= 1) + if (prevIdx >= 1) { - //We are new last stop and previous is not First (>= 1) - //Move uncoupled rs from former last stop (now last but one) to new last stop - command q_moveUncoupled(mDb, "UPDATE OR IGNORE coupling SET stop_id=? WHERE stop_id=? AND operation=?"); + // We are new last stop and previous is not First (>= 1) + // Move uncoupled rs from former last stop (now last but one) to new last stop + command q_moveUncoupled( + mDb, "UPDATE OR IGNORE coupling SET stop_id=? WHERE stop_id=? AND operation=?"); q_moveUncoupled.bind(1, last.stopId); q_moveUncoupled.bind(2, s.stopId); q_moveUncoupled.bind(3, int(RsOp::Uncoupled)); int ret = q_moveUncoupled.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error shifting uncoupling from stop:" << s.stopId << "to:" << last.stopId << "Job:" << mJobId - << "err:" << ret << mDb.error_msg(); - + qDebug() << "Error shifting uncoupling from stop:" << s.stopId + << "to:" << last.stopId << "Job:" << mJobId << "err:" << ret + << mDb.error_msg(); } } uncoupleStillCoupledAtStop(last); - //Select them to update them + // Select them to update them query q_selectMoved(mDb, "SELECT rs_id FROM coupling WHERE stop_id=?"); q_selectMoved.bind(1, last.stopId); - for(auto rs : q_selectMoved) + for (auto rs : q_selectMoved) { db_id rsId = rs.get(0); rsToUpdate.insert(rsId); } } - emit dataChanged(index(prevIdx, 0), - index(prevIdx, 0)); + emit dataChanged(index(prevIdx, 0), index(prevIdx, 0)); } else { - last.type = StopType::First; + last.type = StopType::First; - last.arrival = QTime(0, 0); + last.arrival = QTime(0, 0); last.departure = last.arrival; - last.stopId = createStop(mJobId, last.arrival, last.departure, last.type); + last.stopId = createStop(mJobId, last.arrival, last.departure, last.type); } - emit dataChanged(index(idx, 0), - index(idx, 0)); + emit dataChanged(index(idx, 0), index(idx, 0)); - insertAddHere(idx + 1, 1); //Insert only at end because may invalidate StopItem& references due to mem realloc + insertAddHere( + idx + 1, + 1); // Insert only at end because may invalidate StopItem& references due to mem realloc } void StopModel::removeStop(const QModelIndex &idx) { const int row = idx.row(); - if(!idx.isValid() && row >= stops.count()) + if (!idx.isValid() && row >= stops.count()) return; - StopItem& s = stops[row]; - if(s.addHere != 0) + StopItem &s = stops[row]; + if (s.addHere != 0) return; startStopsEditing(); - //Mark the station for update - if(s.stationId) + // Mark the station for update + if (s.stationId) stationsToUpdate.insert(s.stationId); - //BIG TODO: refactor code (Too many if/else) and emit dataChanged signal + // BIG TODO: refactor code (Too many if/else) and emit dataChanged signal - if(stops.count() == 2) //First + AddHere + if (stops.count() == 2) // First + AddHere { - //Special case: - //Remove First but we don't need to update next stops because there aren't - //After this operation there is only the AddHere + // Special case: + // Remove First but we don't need to update next stops because there aren't + // After this operation there is only the AddHere beginRemoveRows(QModelIndex(), row, row); @@ -624,18 +642,18 @@ void StopModel::removeStop(const QModelIndex &idx) return; } - if(s.type == StopType::First) + if (s.type == StopType::First) { beginRemoveRows(QModelIndex(), row, row); QModelIndex nextIdx = index(row + 1, 0); - StopItem& next = stops[nextIdx.row()]; - next.type = StopType::First; - const QTime oldArr = next.arrival; - const QTime oldDep = next.arrival; + StopItem &next = stops[nextIdx.row()]; + next.type = StopType::First; + const QTime oldArr = next.arrival; + const QTime oldDep = next.arrival; updateStopTime(next, row + 1, true, oldArr, oldDep); - //Set type to Normal + // Set type to Normal command cmd(mDb, "UPDATE stops SET type=? WHERE id=?"); cmd.bind(1, int(StopType::Normal)); cmd.bind(2, next.stopId); @@ -647,51 +665,55 @@ void StopModel::removeStop(const QModelIndex &idx) endRemoveRows(); QModelIndex newFirstIdx = index(0, 0); - emit dataChanged(newFirstIdx, newFirstIdx); //Update new First Stop + emit dataChanged(newFirstIdx, newFirstIdx); // Update new First Stop } else if (s.type == StopType::Last) { QModelIndex prevIdx = index(row - 1, idx.column()); - StopItem& prev = stops[prevIdx.row()]; + StopItem &prev = stops[prevIdx.row()]; - if(autoMoveUncoupleToNewLast) + if (autoMoveUncoupleToNewLast) { - //We are new last stop and previous is not First (>= 1) - //Move couplings from former last stop (now removed) to new last stop (former last but one) + // We are new last stop and previous is not First (>= 1) + // Move couplings from former last stop (now removed) to new last stop (former last but + // one) command q_moveUncoupled(mDb, "UPDATE OR IGNORE coupling SET stop_id=? WHERE stop_id=?"); q_moveUncoupled.bind(1, prev.stopId); q_moveUncoupled.bind(2, s.stopId); int ret = q_moveUncoupled.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error shifting uncoupling from stop:" << s.stopId << "to:" << prev.stopId << "Job:" << mJobId - << "err:" << ret << mDb.error_msg(); - + qDebug() << "Error shifting uncoupling from stop:" << s.stopId + << "to:" << prev.stopId << "Job:" << mJobId << "err:" << ret + << mDb.error_msg(); } - //Select them to update them + // Select them to update them query q_selectMoved(mDb, "SELECT rs_id FROM coupling WHERE stop_id=?"); q_selectMoved.bind(1, prev.stopId); - for(auto rs : q_selectMoved) + for (auto rs : q_selectMoved) { db_id rsId = rs.get(0); rsToUpdate.insert(rsId); } } - //Clear previous 'out' gate and next segment, set type to Normal, reset Departure so it's equal to Arrival - command cmd(mDb, "UPDATE stops SET out_gate_conn=NULL,next_segment_conn_id=NULL,type=?,departure=arrival WHERE id=?"); + // Clear previous 'out' gate and next segment, set type to Normal, reset Departure so it's + // equal to Arrival + command cmd( + mDb, "UPDATE stops SET " + "out_gate_conn=NULL,next_segment_conn_id=NULL,type=?,departure=arrival WHERE id=?"); cmd.bind(1, int(StopType::Normal)); cmd.bind(2, prev.stopId); cmd.execute(); - prev.toGate = StopItem::Gate{}; + prev.toGate = StopItem::Gate{}; prev.nextSegment = StopItem::Segment{}; - prev.departure = prev.arrival; + prev.departure = prev.arrival; - //Set previous stop to be Last - //unless it's First: First remains of type Fisrt obviuosly - if(prev.type != StopType::First) + // Set previous stop to be Last + // unless it's First: First remains of type Fisrt obviuosly + if (prev.type != StopType::First) prev.type = StopType::Last; beginRemoveRows(QModelIndex(), row, row); @@ -699,70 +721,71 @@ void StopModel::removeStop(const QModelIndex &idx) stops.removeAt(row); endRemoveRows(); - emit dataChanged(prevIdx, prevIdx); //Update previous stop + emit dataChanged(prevIdx, prevIdx); // Update previous stop } else { - //BIG TODO: what if 'prev' is a transit??? - //Maybe we should go up to a non-transit stop? - //Or set transit-linechange? + // BIG TODO: what if 'prev' is a transit??? + // Maybe we should go up to a non-transit stop? + // Or set transit-linechange? - //QModelIndex prevIdx = index(row - 1, 0); - //StopItem& prev = stops[prevIdx.row()]; + // QModelIndex prevIdx = index(row - 1, 0); + // StopItem& prev = stops[prevIdx.row()]; } } void StopModel::removeLastIfEmpty() { - if(stops.count() < 2) //Empty stop + AddHere + if (stops.count() < 2) // Empty stop + AddHere return; - int row = stops.count() - 2; //Last index (size - 1) is AddHere so we need 'size() - 2' + int row = stops.count() - 2; // Last index (size - 1) is AddHere so we need 'size() - 2' - //Recursively remove empty stops - //GreaterEqual because we include First + // Recursively remove empty stops + // GreaterEqual because we include First while (row >= 0) { - const StopItem& stop = stops[row]; + const StopItem &stop = stops[row]; - if(stop.stationId == 0) + if (stop.stationId == 0) { removeStop(index(row)); } else { - //This stop is valid so it will be the actual Last stop + // This stop is valid so it will be the actual Last stop //(Or First if we removed all rows but first one) - //So stop the loop + // So stop the loop break; } - //Try with previous stop + // Try with previous stop row--; } } void StopModel::uncoupleStillCoupledAtLastStop() { - if(!autoUncoupleAtLast) + if (!autoUncoupleAtLast) return; - for(int i = stops.size() - 1; i >= 0; i--) + for (int i = stops.size() - 1; i >= 0; i--) { - const StopItem& s = stops.at(i); - if(s.addHere != 0 || !s.stationId) + const StopItem &s = stops.at(i); + if (s.addHere != 0 || !s.stationId) continue; - //Found last stop with a station set + // Found last stop with a station set uncoupleStillCoupledAtStop(s); break; } } -void StopModel::uncoupleStillCoupledAtStop(const StopItem& s) +void StopModel::uncoupleStillCoupledAtStop(const StopItem &s) { - //Uncouple all still-coupled RS - command q_uncoupleRS(mDb, "INSERT OR REPLACE INTO coupling(id,stop_id,rs_id,operation) VALUES(NULL,?,?,0)"); + // Uncouple all still-coupled RS + command q_uncoupleRS( + mDb, "INSERT OR REPLACE INTO coupling(id,stop_id,rs_id,operation) VALUES(NULL,?,?,0)"); query q_selectStillOn(mDb, "SELECT coupling.rs_id,MAX(stops.arrival)" " FROM stops" " JOIN coupling ON coupling.stop_id=stops.id" @@ -771,7 +794,7 @@ void StopModel::uncoupleStillCoupledAtStop(const StopItem& s) " HAVING coupling.operation=1"); q_selectStillOn.bind(1, mJobId); q_selectStillOn.bind(2, s.arrival); - for(auto rs : q_selectStillOn) + for (auto rs : q_selectStillOn) { db_id rsId = rs.get(0); rsToUpdate.insert(rsId); @@ -804,7 +827,7 @@ db_id StopModel::getJobShiftId() const void StopModel::setCategory(int value) { - if(int(category) == value) + if (int(category) == value) return; startInfoEditing(); @@ -815,37 +838,36 @@ void StopModel::setCategory(int value) bool StopModel::setNewJobId(db_id jobId) { - if(mNewJobId == jobId) + if (mNewJobId == jobId) return true; - if(jobId != mJobId) + if (jobId != mJobId) { - //If setting a different id than original, check if it's already existent + // If setting a different id than original, check if it's already existent query q_getJob(mDb, "SELECT 1 FROM jobs WHERE id=?"); q_getJob.bind(1, jobId); int ret = q_getJob.step(); - if(ret == SQLITE_ROW) + if (ret == SQLITE_ROW) { - //Already exists, revert back to previous job id + // Already exists, revert back to previous job id emit jobIdChanged(mNewJobId); return false; } } - //The new job id is valid + // The new job id is valid startInfoEditing(); mNewJobId = jobId; emit jobIdChanged(mNewJobId); return true; } - void StopModel::setNewShiftId(db_id shiftId) { - if(newShiftId == shiftId) + if (newShiftId == shiftId) return; - if(stops.count() < 3) //First + Last + AddHere + if (stops.count() < 3) // First + Last + AddHere { emit errorSetShiftWithoutStops(); return; @@ -858,115 +880,119 @@ void StopModel::setNewShiftId(db_id shiftId) emit jobShiftChanged(newShiftId); } -void StopModel::setStopInfo(const QModelIndex &idx, StopItem newStop, StopItem::Segment prevSeg, bool avoidTimeRecalc) +void StopModel::setStopInfo(const QModelIndex &idx, StopItem newStop, StopItem::Segment prevSeg, + bool avoidTimeRecalc) { - const int row = idx.row(); + const int row = idx.row(); int lastUpdatedRow = row; - if(!idx.isValid() && row >= stops.count()) + if (!idx.isValid() && row >= stops.count()) return; command cmd(mDb); - StopItem& s = stops[row]; + StopItem &s = stops[row]; stationsToUpdate.insert(s.stationId); stationsToUpdate.insert(newStop.stationId); - if(s.type != StopType::First && row > 0) + if (s.type != StopType::First && row > 0) { - //Update previous segment - StopItem& prevStop = stops[row - 1]; - if(prevStop.nextSegment.segmentId != prevSeg.segmentId) + // Update previous segment + StopItem &prevStop = stops[row - 1]; + if (prevStop.nextSegment.segmentId != prevSeg.segmentId) { db_id suggestedTrackId = 0; - if(!trySelectNextSegment(prevStop, prevSeg.segmentId, prevStop.toGate.gateTrackNum, + if (!trySelectNextSegment(prevStop, prevSeg.segmentId, prevStop.toGate.gateTrackNum, newStop.stationId, newStop.fromGate.gateId, suggestedTrackId)) return; startStopsEditing(); - //Update prev stop + // Update prev stop cmd.prepare("UPDATE stops SET out_gate_conn=?, next_segment_conn_id=? WHERE id=?"); cmd.bind(1, prevStop.toGate.gateConnId); cmd.bind(2, prevStop.nextSegment.segConnId); cmd.bind(3, prevStop.stopId); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) { - qWarning() << "StopModel: cannot update previous stop segment:" << mDb.error_msg() << prevStop.stopId; + qWarning() << "StopModel: cannot update previous stop segment:" << mDb.error_msg() + << prevStop.stopId; return; } - prevSeg = prevStop.nextSegment; - newStop.fromGate.gateConnId = 0; + prevSeg = prevStop.nextSegment; + newStop.fromGate.gateConnId = 0; newStop.fromGate.gateTrackNum = prevStop.nextSegment.outTrackNum; } } - if(s.stationId != newStop.stationId) + if (s.stationId != newStop.stationId) { startStopsEditing(); - //Update station, reset out gate + // Update station, reset out gate cmd.prepare("UPDATE stops SET station_id=?,out_gate_conn=NULL WHERE id=?"); cmd.bind(1, newStop.stationId); cmd.bind(2, s.stopId); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) return; - s.stationId = newStop.stationId; + s.stationId = newStop.stationId; s.toGate.gateConnId = 0; } - if(s.fromGate.gateConnId != newStop.fromGate.gateConnId) + if (s.fromGate.gateConnId != newStop.fromGate.gateConnId) { startStopsEditing(); updateCurrentInGate(newStop, prevSeg); s.fromGate = newStop.fromGate; - s.trackId = newStop.trackId; + s.trackId = newStop.trackId; } - if(s.arrival != newStop.arrival || s.departure != newStop.departure) + if (s.arrival != newStop.arrival || s.departure != newStop.departure) { startStopsEditing(); - if(updateStopTime(newStop, row, true, s.arrival, s.departure)) + if (updateStopTime(newStop, row, true, s.arrival, s.departure)) { - //Succeded, store new sanitized values - s.arrival = newStop.arrival; - s.departure = newStop.departure; + // Succeded, store new sanitized values + s.arrival = newStop.arrival; + s.departure = newStop.departure; lastUpdatedRow = stops.count() - 2; } } const db_id oldSegConnId = s.nextSegment.segConnId; - if(s.toGate.gateConnId != newStop.toGate.gateConnId || oldSegConnId != newStop.nextSegment.segConnId) + if (s.toGate.gateConnId != newStop.toGate.gateConnId + || oldSegConnId != newStop.nextSegment.segConnId) { - //We check also for segConnId changes even if gate did not change - //This is needed to fix some database corruption situations - //when rail segment was editd (adding tracks, changing connections) - //but jobs were not correctly updated. + // We check also for segConnId changes even if gate did not change + // This is needed to fix some database corruption situations + // when rail segment was editd (adding tracks, changing connections) + // but jobs were not correctly updated. startStopsEditing(); - //Update next stop + // Update next stop cmd.prepare("UPDATE stops SET out_gate_conn=?, next_segment_conn_id=? WHERE id=?"); cmd.bind(1, newStop.toGate.gateConnId); cmd.bind(2, newStop.nextSegment.segConnId); cmd.bind(3, newStop.stopId); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) { - qWarning() << "StopModel: cannot update previous stop segment:" << mDb.error_msg() << s.stopId; + qWarning() << "StopModel: cannot update previous stop segment:" << mDb.error_msg() + << s.stopId; return; } - s.toGate = newStop.toGate; + s.toGate = newStop.toGate; s.nextSegment = newStop.nextSegment; - if(s.type == StopType::First && s.toGate.gateConnId) + if (s.type == StopType::First && s.toGate.gateConnId) { - //No need to fake an in gate to set station track, we already have out gate + // No need to fake an in gate to set station track, we already have out gate cmd.prepare("UPDATE stops SET in_gate_conn=NULL WHERE id=?"); cmd.bind(1, s.stopId); cmd.execute(); @@ -974,39 +1000,39 @@ void StopModel::setStopInfo(const QModelIndex &idx, StopItem newStop, StopItem:: } } - if(row < stops.count() - 2 && s.nextSegment.segConnId) + if (row < stops.count() - 2 && s.nextSegment.segConnId) { - //Before Last and AddHere, so there is a stop after this - StopItem& nextStop = stops[row + 1]; + // Before Last and AddHere, so there is a stop after this + StopItem &nextStop = stops[row + 1]; - if(s.nextSegment.segConnId != oldSegConnId + if (s.nextSegment.segConnId != oldSegConnId || s.nextSegment.outTrackNum != nextStop.fromGate.gateTrackNum) { - //Update next station because "next" segment of previous (current) stop changed - //or because segment and gate track did not match (happenss on database corruption) + // Update next station because "next" segment of previous (current) stop changed + // or because segment and gate track did not match (happenss on database corruption) startStopsEditing(); - nextStop.fromGate.gateConnId = 0; //Reset to trigger update - if(!updateCurrentInGate(nextStop, s.nextSegment)) + nextStop.fromGate.gateConnId = 0; // Reset to trigger update + if (!updateCurrentInGate(nextStop, s.nextSegment)) return; - if(lastUpdatedRow == row) - lastUpdatedRow++; //We updated also next row + if (lastUpdatedRow == row) + lastUpdatedRow++; // We updated also next row - if(timeCalcEnabled && !avoidTimeRecalc) + if (timeCalcEnabled && !avoidTimeRecalc) { - const int secs = calcTravelTime(s.nextSegment.segmentId); + const int secs = calcTravelTime(s.nextSegment.segmentId); const QTime oldNextArr = nextStop.arrival; const QTime oldNextDep = nextStop.departure; - nextStop.arrival = s.departure.addSecs(secs); + nextStop.arrival = s.departure.addSecs(secs); - if(oldNextArr != nextStop.arrival) + if (oldNextArr != nextStop.arrival) { - if(!updateStopTime(nextStop, row + 1, true, oldNextArr, oldNextDep)) + if (!updateStopTime(nextStop, row + 1, true, oldNextArr, oldNextDep)) { - //Failed, Reset to old values - nextStop.arrival = oldNextArr; + // Failed, Reset to old values + nextStop.arrival = oldNextArr; nextStop.departure = oldNextDep; } @@ -1016,23 +1042,23 @@ void StopModel::setStopInfo(const QModelIndex &idx, StopItem newStop, StopItem:: } } - //Tell view to update + // Tell view to update const QModelIndex firstIdx = index(row, 0); - const QModelIndex lastIdx = index(lastUpdatedRow, 0); + const QModelIndex lastIdx = index(lastUpdatedRow, 0); emit dataChanged(firstIdx, lastIdx); } bool StopModel::setStopTypeRange(int firstRow, int lastRow, StopType type) { - if(firstRow < 0 || firstRow > lastRow || lastRow >= stops.count()) + if (firstRow < 0 || firstRow > lastRow || lastRow >= stops.count()) return false; - if(type == StopType::First || type == StopType::Last) + if (type == StopType::First || type == StopType::Last) return false; - int defaultStopMsec = qMax(60, defaultStopTimeSec()) * 1000; //At least 1 minute + int defaultStopMsec = qMax(60, defaultStopTimeSec()) * 1000; // At least 1 minute - StopType destType = type; + StopType destType = type; startStopsEditing(); shiftStopsBy24hoursFrom(stops.at(firstRow).arrival); @@ -1042,16 +1068,17 @@ bool StopModel::setStopTypeRange(int firstRow, int lastRow, StopType type) int msecOffset = 0; - for(int r = firstRow; r <= lastRow; r++) + for (int r = firstRow; r <= lastRow; r++) { - StopItem& s = stops[r]; + StopItem &s = stops[r]; - if(s.type == StopType::First || s.type == StopType::Last) + if (s.type == StopType::First || s.type == StopType::Last) { - qWarning() << "Error: tried change type of First/Last stop:" << r << s.stopId << "Job:" << mJobId; + qWarning() << "Error: tried change type of First/Last stop:" << r << s.stopId + << "Job:" << mJobId; - //Always update time even if msecOffset == 0, because they have been shifted - s.arrival = s.arrival.addMSecs(msecOffset); + // Always update time even if msecOffset == 0, because they have been shifted + s.arrival = s.arrival.addMSecs(msecOffset); s.departure = s.departure.addMSecs(msecOffset); cmd.bind(1, s.arrival); cmd.bind(2, s.departure); @@ -1062,56 +1089,57 @@ bool StopModel::setStopTypeRange(int firstRow, int lastRow, StopType type) continue; } - if(type == StopType::ToggleType) + if (type == StopType::ToggleType) { - if(s.type == StopType::Normal) + if (s.type == StopType::Normal) destType = StopType::Transit; else destType = StopType::Normal; } - //Cannot couple or uncouple in transits + // Cannot couple or uncouple in transits bool canBeTransit = true; - if(destType == StopType::Transit) + if (destType == StopType::Transit) { q_getCoupled.bind(1, s.stopId); int res = q_getCoupled.step(); q_getCoupled.reset(); - if(res == SQLITE_ROW) + if (res == SQLITE_ROW) { - qWarning() << "Error: trying to set Transit on stop:" << s.stopId << "Job:" << mJobId - << "while having coupling operation for this stop"; + qWarning() << "Error: trying to set Transit on stop:" << s.stopId + << "Job:" << mJobId << "while having coupling operation for this stop"; canBeTransit = false; } - if(res != SQLITE_OK && res != SQLITE_DONE) + if (res != SQLITE_OK && res != SQLITE_DONE) { - qWarning() << "Error while setting stopType for stop:" << s.stopId << "Job:" << mJobId - << "DB Err:" << res << mDb.error_msg() << mDb.extended_error_code(); + qWarning() << "Error while setting stopType for stop:" << s.stopId + << "Job:" << mJobId << "DB Err:" << res << mDb.error_msg() + << mDb.extended_error_code(); return false; } } - //Mark the station for update + // Mark the station for update stationsToUpdate.insert(s.stationId); - s.arrival = s.arrival.addMSecs(msecOffset); + s.arrival = s.arrival.addMSecs(msecOffset); s.departure = s.departure.addMSecs(msecOffset); - if(destType == StopType::Normal) + if (destType == StopType::Normal) { s.type = StopType::Normal; - if(s.arrival == s.departure) + if (s.arrival == s.departure) { msecOffset += defaultStopMsec; s.departure = s.arrival.addMSecs(defaultStopMsec); } } - else if(canBeTransit) + else if (canBeTransit) { s.type = StopType::Transit; - //Transit don't stop so departure is the same of arrival -> stop time = 0 minutes + // Transit don't stop so departure is the same of arrival -> stop time = 0 minutes msecOffset -= s.arrival.msecsTo(s.departure); s.departure = s.arrival; } @@ -1124,17 +1152,17 @@ bool StopModel::setStopTypeRange(int firstRow, int lastRow, StopType type) } QModelIndex firstIdx = index(firstRow, 0); - QModelIndex lastIdx = index(stops.count() - 1, 0); + QModelIndex lastIdx = index(stops.count() - 1, 0); - //Always update time even if msecOffset == 0, because they have been shifted - for(int r = lastRow + 1; r < stops.count(); r++) + // Always update time even if msecOffset == 0, because they have been shifted + for (int r = lastRow + 1; r < stops.count(); r++) { - StopItem& s = stops[r]; - destType = s.type; - if(s.type == StopType::First || s.type == StopType::Last) + StopItem &s = stops[r]; + destType = s.type; + if (s.type == StopType::First || s.type == StopType::Last) destType = StopType::Normal; - s.arrival = s.arrival.addMSecs(msecOffset); + s.arrival = s.arrival.addMSecs(msecOffset); s.departure = s.departure.addMSecs(msecOffset); cmd.bind(1, s.arrival); cmd.bind(2, s.departure); @@ -1149,9 +1177,9 @@ bool StopModel::setStopTypeRange(int firstRow, int lastRow, StopType type) return true; } -QString StopModel::getDescription(const StopItem& s) const +QString StopModel::getDescription(const StopItem &s) const { - if(s.addHere != 0) + if (s.addHere != 0) return QString(); query q_getDescr(mDb, "SELECT description FROM stops WHERE id=?"); @@ -1163,18 +1191,18 @@ QString StopModel::getDescription(const StopItem& s) const return descr; } -void StopModel::setDescription(const QModelIndex& idx, const QString& descr) +void StopModel::setDescription(const QModelIndex &idx, const QString &descr) { - if(!idx.isValid() && idx.row() >= stops.count()) + if (!idx.isValid() && idx.row() >= stops.count()) return; - StopItem& s = stops[idx.row()]; - if(s.addHere != 0) + StopItem &s = stops[idx.row()]; + if (s.addHere != 0) return; startStopsEditing(); - //Mark the station for update + // Mark the station for update stationsToUpdate.insert(s.stationId); command q_setDescr(mDb, "UPDATE stops SET description=? WHERE id=?"); @@ -1188,9 +1216,9 @@ void StopModel::setDescription(const QModelIndex& idx, const QString& descr) int StopModel::getStopRow(db_id stopId) const { - for(int row = 0; row < stops.size(); row++) + for (int row = 0; row < stops.size(); row++) { - if(stops.at(row).stopId == stopId) + if (stops.at(row).stopId == stopId) return row; } @@ -1199,7 +1227,7 @@ int StopModel::getStopRow(db_id stopId) const bool StopModel::isAddHere(const QModelIndex &idx) { - if(idx.isValid() && idx.row() < stops.count()) + if (idx.isValid() && idx.row() < stops.count()) return (stops[idx.row()].addHere != 0); return false; } @@ -1208,26 +1236,26 @@ std::pair StopModel::getFirstLastTimes() const { QTime first, last; - if(stops.count() > 1) //First + AddHere + if (stops.count() > 1) // First + AddHere { first = stops[0].departure; } - int row = stops.count() - 2; //Last indx (size - 1) is AddHere so we need 'size() - 2' + int row = stops.count() - 2; // Last indx (size - 1) is AddHere so we need 'size() - 2' - //GreaterEqual because we include First - //Recursively skip last stop if empty + // GreaterEqual because we include First + // Recursively skip last stop if empty while (row >= 0) { - const StopItem& stop = stops[row]; + const StopItem &stop = stops[row]; - if(stop.stationId != 0) + if (stop.stationId != 0) { last = stop.arrival; break; } - //Try with previous stop + // Try with previous stop row--; } @@ -1247,25 +1275,25 @@ const QSet &StopModel::getStationsToUpdate() const bool StopModel::isRailwayElectrifiedAfterStop(db_id stopId) const { int row = getStopRow(stopId); - if(row == -1) - return true; //Error + if (row == -1) + return true; // Error return isRailwayElectrifiedAfterRow(row); } bool StopModel::isRailwayElectrifiedAfterRow(int row) const { - if(row < 0 || row >= stops.count()) - return true; //Error + if (row < 0 || row >= stops.count()) + return true; // Error - const StopItem& item = stops.at(row); - if(!item.nextSegment.segmentId) - return true; //Error + const StopItem &item = stops.at(row); + if (!item.nextSegment.segmentId) + return true; // Error query q(mDb, "SELECT type FROM railway_segments WHERE id=?"); q.bind(1, item.nextSegment.segmentId); - if(q.step() != SQLITE_ROW) - return true; //Error + if (q.step() != SQLITE_ROW) + return true; // Error QFlags type = utils::RailwaySegmentType(q.getRows().get(0)); return type.testFlag(utils::RailwaySegmentType::Electrified); @@ -1274,10 +1302,11 @@ bool StopModel::isRailwayElectrifiedAfterRow(int row) const bool StopModel::trySelectTrackForStop(StopItem &item) { query q(mDb); - if(item.fromGate.gateId) + if (item.fromGate.gateId) { - //TODO: choose 'default' track, corretto tracciato - //Try to keep previous selected station track otherwise choose lowest position track possible + // TODO: choose 'default' track, corretto tracciato + // Try to keep previous selected station track otherwise choose lowest position track + // possible q.prepare("SELECT c.id, c.track_side, t.id" " FROM station_gate_connections c" " JOIN station_tracks t ON c.track_id=t.id" @@ -1287,34 +1316,34 @@ bool StopModel::trySelectTrackForStop(StopItem &item) q.bind(1, item.fromGate.gateId); q.bind(2, item.fromGate.gateTrackNum); q.bind(3, item.trackId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - auto gate = q.getRows(); - item.fromGate.gateConnId = gate.get(0); + auto gate = q.getRows(); + item.fromGate.gateConnId = gate.get(0); item.fromGate.stationTrackSide = utils::Side(gate.get(1)); - item.trackId = gate.get(2); + item.trackId = gate.get(2); return true; } - //Select a random gate for first use + // Select a random gate for first use q.prepare("SELECT c.id, c.gate_id, c.gate_track, c.track_side, t.id, MIN(t.pos)" " FROM station_tracks t" " JOIN station_gate_connections c ON c.track_id=t.id" " WHERE t.station_id=?" " LIMIT 1"); q.bind(1, item.stationId); - 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; - auto gate = q.getRows(); - item.fromGate.gateConnId = gate.get(0); - item.fromGate.gateId = gate.get(1); - item.fromGate.gateTrackNum = gate.get(2); + auto gate = q.getRows(); + item.fromGate.gateConnId = gate.get(0); + item.fromGate.gateId = gate.get(1); + item.fromGate.gateTrackNum = gate.get(2); item.fromGate.stationTrackSide = utils::Side(gate.get(3)); - item.trackId = gate.get(4); + item.trackId = gate.get(4); - //TODO: should we reset out gate here? + // TODO: should we reset out gate here? return true; } @@ -1323,57 +1352,62 @@ bool StopModel::trySetTrackConnections(StopItem &item, db_id trackId, QString *o { query q(mDb, "SELECT station_id FROM station_tracks WHERE id=?"); q.bind(1, trackId); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { db_id stId = q.getRows().get(0); - if(item.stationId != stId) + if (item.stationId != stId) { - if(outErr) + if (outErr) *outErr = tr("Track belongs to a different station."); return false; } - }else{ - if(outErr) + } + else + { + if (outErr) *outErr = tr("Track doesn't exist."); return false; } - if(item.type == StopType::First) + if (item.type == StopType::First) { - //Fake in gate, select one just to set the track - q.prepare("SELECT id,gate_id,gate_track,track_side FROM station_gate_connections WHERE track_id=? LIMIT 1"); + // Fake in gate, select one just to set the track + q.prepare("SELECT id,gate_id,gate_track,track_side FROM station_gate_connections WHERE " + "track_id=? LIMIT 1"); q.bind(1, trackId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) { - if(outErr) + if (outErr) *outErr = tr("Track is not connected to any of station gates."); return false; } - auto gate = q.getRows(); - item.fromGate.gateConnId = gate.get(0); - item.fromGate.gateId = gate.get(1); - item.fromGate.gateTrackNum = gate.get(2); + auto gate = q.getRows(); + item.fromGate.gateConnId = gate.get(0); + item.fromGate.gateId = gate.get(1); + item.fromGate.gateTrackNum = gate.get(2); item.fromGate.stationTrackSide = utils::Side(gate.get(3)); } q.prepare("SELECT id, track_side FROM station_gate_connections" " WHERE gate_id=? AND gate_track=? AND track_id=?"); - if(item.type != StopType::First) + if (item.type != StopType::First) { - //Item is not First stop, check in gate + // Item is not First stop, check in gate q.bind(1, item.fromGate.gateId); q.bind(2, item.fromGate.gateTrackNum); q.bind(3, trackId); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { - //Found a connection - item.fromGate.gateConnId = q.getRows().get(0); + // Found a connection + item.fromGate.gateConnId = q.getRows().get(0); item.fromGate.stationTrackSide = utils::Side(q.getRows().get(1)); - }else{ - if(outErr) + } + else + { + if (outErr) *outErr = tr("Track is not connected to in gate track.\n" "Please choose a new track or change previous segment."); return false; @@ -1381,85 +1415,90 @@ bool StopModel::trySetTrackConnections(StopItem &item, db_id trackId, QString *o q.reset(); } - if(item.toGate.gateConnId) + if (item.toGate.gateConnId) { - //For every type of stop, check out gate - //User already chose an out gate but now changed station track - //Check if they are connected together + // For every type of stop, check out gate + // User already chose an out gate but now changed station track + // Check if they are connected together q.bind(1, item.toGate.gateId); q.bind(2, item.toGate.gateTrackNum); q.bind(3, trackId); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { - //Found a connection - item.toGate.gateConnId = q.getRows().get(0); + // Found a connection + item.toGate.gateConnId = q.getRows().get(0); item.toGate.stationTrackSide = utils::Side(q.getRows().get(1)); - }else{ - //Connection not found, inform user and reset out gate - item.toGate = StopItem::Gate{}; - item.nextSegment = StopItem::Segment{}; //Reset next segment + } + else + { + // Connection not found, inform user and reset out gate + item.toGate = StopItem::Gate{}; + item.nextSegment = StopItem::Segment{}; // Reset next segment - if(outErr) - *outErr = tr("Track is not connected to selected out gate track.\n" - "Please choose a new out gate or out track, this might change next segment."); - //Still return true to let user change out gate + if (outErr) + *outErr = + tr("Track is not connected to selected out gate track.\n" + "Please choose a new out gate or out track, this might change next segment."); + // Still return true to let user change out gate } } - //Store new track ID + // Store new track ID item.trackId = trackId; return true; } -bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int suggestedOutGateTrk, db_id nextStationId, - db_id &seg_out_gateId, db_id &out_suggestedTrackId) +bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int suggestedOutGateTrk, + db_id nextStationId, db_id &seg_out_gateId, + db_id &out_suggestedTrackId) { out_suggestedTrackId = -1; - bool reversed = false; + bool reversed = false; query q(mDb, "SELECT s.in_gate_id,g1.station_id,s.out_gate_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, segmentId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - auto seg = q.getRows(); + auto seg = q.getRows(); db_id seg_in_gateId = seg.get(0); - db_id in_stationId = seg.get(1); - seg_out_gateId = seg.get(2); + db_id in_stationId = seg.get(1); + seg_out_gateId = seg.get(2); db_id out_stationId = seg.get(3); - if(out_stationId == item.stationId) + if (out_stationId == item.stationId) { - //Segment is reversed + // Segment is reversed qSwap(seg_in_gateId, seg_out_gateId); qSwap(in_stationId, out_stationId); reversed = true; } - else if(in_stationId != item.stationId) + else if (in_stationId != item.stationId) { - //Error: segment is not connected to previous station + // Error: segment is not connected to previous station return false; } - if(nextStationId && out_stationId != nextStationId) + if (nextStationId && out_stationId != nextStationId) { - //Error: segment is not connected to next (current) station + // Error: segment is not connected to next (current) station return false; } - //Station out gate = segment in gate - if(seg_in_gateId != item.toGate.gateId || item.toGate.gateTrackNum != item.nextSegment.inTrackNum) + // Station out gate = segment in gate + if (seg_in_gateId != item.toGate.gateId + || item.toGate.gateTrackNum != item.nextSegment.inTrackNum) { out_suggestedTrackId = 0; - //Try to find a gate connected to previous track_id - //Prefer suggested gate out track num if possible or lowest one possible + // Try to find a gate connected to previous track_id + // Prefer suggested gate out track num if possible or lowest one possible QByteArray sql = "SELECT c.id,c.gate_track,c.track_side,sc.id,sc.%2_track" " FROM station_gate_connections c" " JOIN railway_connections sc ON sc.seg_id=?3 AND sc.%1_track=c.gate_track" @@ -1475,10 +1514,11 @@ bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int sugges q.bind(2, seg_in_gateId); q.bind(3, segmentId); q.bind(4, suggestedOutGateTrk); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) { - //Error: gate is not connected to previous track - //User must change previous track, make a suggestion (lowest track connected to in and out gates) + // Error: gate is not connected to previous track + // User must change previous track, make a suggestion (lowest track connected to in and + // out gates) sql = "SELECT c2.track_id" " FROM station_gate_connections c2" @@ -1489,15 +1529,16 @@ bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int sugges " ORDER BY c2.gate_track=?3 DESC,c2.gate_track ASC,t.pos ASC" " LIMIT 1"; - if(item.type != StopType::First) + if (item.type != StopType::First) { - //Check also in gate - sql.replace("%3", "JOIN station_gate_connections c1 ON" - " c1.gate_id=?4 AND c1.gate_track=?5 AND c1.track_id=c2.track_id"); + // Check also in gate + sql.replace("%3", + "JOIN station_gate_connections c1 ON" + " c1.gate_id=?4 AND c1.gate_track=?5 AND c1.track_id=c2.track_id"); } else { - //Do not check in gate for first stop + // Do not check in gate for first stop sql.replace("%3", ""); } @@ -1509,13 +1550,13 @@ bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int sugges q.bind(2, segmentId); q.bind(3, suggestedOutGateTrk); - if(item.type != StopType::First) + if (item.type != StopType::First) { q.bind(4, item.fromGate.gateId); q.bind(5, item.fromGate.gateTrackNum); } - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { out_suggestedTrackId = q.getRows().get(0); } @@ -1523,31 +1564,31 @@ bool StopModel::trySelectNextSegment(StopItem &item, db_id segmentId, int sugges return false; } - auto conn = q.getRows(); - item.toGate.gateConnId = conn.get(0); - item.toGate.gateId = seg_in_gateId; - item.toGate.gateTrackNum = conn.get(1); + auto conn = q.getRows(); + item.toGate.gateConnId = conn.get(0); + item.toGate.gateId = seg_in_gateId; + item.toGate.gateTrackNum = conn.get(1); item.toGate.stationTrackSide = utils::Side(conn.get(2)); - item.nextSegment.segConnId = conn.get(3); - item.nextSegment.segmentId = segmentId; - item.nextSegment.inTrackNum = item.toGate.gateTrackNum; + item.nextSegment.segConnId = conn.get(3); + item.nextSegment.segmentId = segmentId; + item.nextSegment.inTrackNum = item.toGate.gateTrackNum; item.nextSegment.outTrackNum = conn.get(4); - item.nextSegment.reversed = reversed; + item.nextSegment.reversed = reversed; } return true; } -//Called for example when changing a job's shift from the ShiftGraphEditor +// Called for example when changing a job's shift from the ShiftGraphEditor void StopModel::onExternalShiftChange(db_id shiftId, db_id jobId) { - if(jobId == mJobId) + if (jobId == mJobId) { - if(shiftId == jobShiftId && shiftId != newShiftId) - return; //This happens when notifying job was removed from previous shift, do nothing + if (shiftId == jobShiftId && shiftId != newShiftId) + return; // This happens when notifying job was removed from previous shift, do nothing - //Don't start stop/info editing because the change was already made by JobsModel - //Prevent discarding the change by updating also original shift + // Don't start stop/info editing because the change was already made by JobsModel + // Prevent discarding the change by updating also original shift jobShiftId = newShiftId = shiftId; emit jobShiftChanged(jobShiftId); @@ -1556,7 +1597,7 @@ void StopModel::onExternalShiftChange(db_id shiftId, db_id jobId) void StopModel::onShiftNameChanged(db_id shiftId) { - if(newShiftId == shiftId) + if (newShiftId == shiftId) { emit jobShiftChanged(newShiftId); } @@ -1564,10 +1605,10 @@ void StopModel::onShiftNameChanged(db_id shiftId) void StopModel::onStationSegmentNameChanged() { - //Station and segment names are fetched by delegate while painting - //We just need to repaint + // Station and segment names are fetched by delegate while painting + // We just need to repaint QModelIndex start = index(0, 0); - QModelIndex end = index(stops.count(), 0); + QModelIndex end = index(stops.count(), 0); emit dataChanged(start, end); } @@ -1591,10 +1632,10 @@ void StopModel::insertAddHere(int row, int type) endInsertRows(); } -db_id StopModel::createStop(db_id jobId, const QTime& arr, const QTime& dep, StopType type) +db_id StopModel::createStop(db_id jobId, const QTime &arr, const QTime &dep, StopType type) { - if(type != StopType::Transit) - type = StopType::Normal; //Fix possible invalid values + if (type != StopType::Transit) + type = StopType::Normal; // Fix possible invalid values command q_addStop(mDb, "INSERT INTO stops" "(id,job_id,station_id,arrival,departure,type,description," @@ -1620,9 +1661,10 @@ void StopModel::deleteStop(db_id stopId) command q_removeStop(mDb, "DELETE FROM stops WHERE id=?"); q_removeStop.bind(1, stopId); int ret = q_removeStop.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "DB err:" << ret << mDb.error_code() << mDb.error_msg() << mDb.extended_error_code(); + qWarning() << "DB err:" << ret << mDb.error_code() << mDb.error_msg() + << mDb.extended_error_code(); } q_removeStop.reset(); } @@ -1630,30 +1672,31 @@ void StopModel::deleteStop(db_id stopId) #ifdef ENABLE_AUTO_TIME_RECALC void StopModel::rebaseTimesToSpeed(int firstIdx, QTime firstArr, QTime firstDep) { - //Recalc times from this stop until last, also apply offset with new departure - if(firstIdx < 0 || firstIdx >= stops.size() - 2) //At least one before Last stop - return; //Error + // Recalc times from this stop until last, also apply offset with new departure + if (firstIdx < 0 || firstIdx >= stops.size() - 2) // At least one before Last stop + return; // Error startStopsEditing(); - StopItem& firstStop = stops[firstIdx]; + StopItem &firstStop = stops[firstIdx]; QTime minArrival; - if(firstIdx > 0) + if (firstIdx > 0) minArrival = stops.at(firstIdx - 1).departure.addSecs(60); - if(firstArr < minArrival) + if (firstArr < minArrival) { firstDep = firstDep.addSecs(minArrival.secsTo(firstArr)); } - if(firstDep < firstArr) + if (firstDep < firstArr) { - firstDep = firstArr.addSecs(60); //At least 1 minute stop, it cannot be a transit if we couple RS + firstDep = + firstArr.addSecs(60); // At least 1 minute stop, it cannot be a transit if we couple RS } - int offsetSecs = firstStop.departure.secsTo(firstDep); - firstStop.arrival = firstArr; + int offsetSecs = firstStop.departure.secsTo(firstDep); + firstStop.arrival = firstArr; firstStop.departure = firstDep; query q(Session->m_Db, "SELECT MIN(rs_models.max_speed), rs_id FROM(" @@ -1666,86 +1709,87 @@ void StopModel::rebaseTimesToSpeed(int firstIdx, QTime firstArr, QTime firstDep) " JOIN rs_list ON rs_list.id=rs_id" " JOIN rs_models ON rs_models.id=rs_list.model_id"); - QTime prevDep = firstDep; + QTime prevDep = firstDep; db_id prevStId = firstStop.stationId; - db_id lineId = firstStop.nextLine ? firstStop.nextLine : firstStop.curLine; - int lineSpeed = linesModel->getLineSpeed(lineId); + db_id lineId = firstStop.nextLine ? firstStop.nextLine : firstStop.curLine; + int lineSpeed = linesModel->getLineSpeed(lineId); - //size() - 1 to exclude AddHere - for(int idx = firstIdx + 1; idx < stops.size() - 1; idx++) + // size() - 1 to exclude AddHere + for (int idx = firstIdx + 1; idx < stops.size() - 1; idx++) { - StopItem& item = stops[idx]; - if(item.curLine != lineId) + StopItem &item = stops[idx]; + if (item.curLine != lineId) { - lineId = item.curLine; + lineId = item.curLine; lineSpeed = linesModel->getLineSpeed(lineId); } stationsToUpdate.insert(item.stationId); - //TODO: should update also RS + // TODO: should update also RS - //Use original arrival to query train max speed + // Use original arrival to query train max speed - //Temporarily set arrival and departure - //Don't sync with database otherwise we could mess with stop order - //Sync at end when we calculated all new times - //If a previous stop gets postponed it appears after current stop - //until we postpone also current stop. This temp reorder breaks the - //query for retrieving train speed because this query is based on sorting by time + // Temporarily set arrival and departure + // Don't sync with database otherwise we could mess with stop order + // Sync at end when we calculated all new times + // If a previous stop gets postponed it appears after current stop + // until we postpone also current stop. This temp reorder breaks the + // query for retrieving train speed because this query is based on sorting by time - //Get train speed + // Get train speed q.bind(1, mJobId); q.bind(2, item.arrival); q.step(); int speedKmH = q.getRows().get(0); q.reset(); - //If line is slower or we couldn't get trains speed (likely no RS coupled) use line max speed instead - if(speed <= 0 || (lineSpeed >= 0 && lineSpeed < speed)) + // If line is slower or we couldn't get trains speed (likely no RS coupled) use line max + // speed instead + if (speed <= 0 || (lineSpeed >= 0 && lineSpeed < speed)) speed = lineSpeed; double distanceMeters = linesModel->getStationsDistance(lineId, prevStId, item.stationId); - if(qFuzzyIsNull(distance) || speed < 1.0) + if (qFuzzyIsNull(distance) || speed < 1.0) { - //Error + // Error } - const double secs = (distanceMeters + accelerationDistMeters)/double(speed) * 3.6; - int roundedTop = qCeil(secs) + offsetSecs; + const double secs = (distanceMeters + accelerationDistMeters) / double(speed) * 3.6; + int roundedTop = qCeil(secs) + offsetSecs; - if(roundedTop < 60) + if (roundedTop < 60) { - //At least 1 minute between stops + // At least 1 minute between stops roundedTop = 60; } else { - //Align to minutes, we don't support seconds in train scheduled times + // Align to minutes, we don't support seconds in train scheduled times int rem = roundedTop % 60; - if(rem > 10) //TODO: maybe 20 as treshold, sync calcTimeBetweenStations() - roundedTop += 60 - rem; //Round to next minute + if (rem > 10) // TODO: maybe 20 as treshold, sync calcTimeBetweenStations() + roundedTop += 60 - rem; // Round to next minute else roundedTop -= rem; } - int stopTime = item.arrival.secsTo(item.departure); - item.arrival = prevDep.addSecs(roundedTop); + int stopTime = item.arrival.secsTo(item.departure); + item.arrival = prevDep.addSecs(roundedTop); item.departure = prevDep.addSecs(roundedTop + stopTime); - prevStId = item.stationId; - prevDep = item.departure; + prevStId = item.stationId; + prevDep = item.departure; } - //Now prepare query to set Arrival and departure + // Now prepare query to set Arrival and departure q.prepare("UPDATE stops SET arrival=?,departure=? WHERE id=?"); - for(int idx = firstIdx; idx < stops.size() - 1; idx++) + for (int idx = firstIdx; idx < stops.size() - 1; idx++) { - //Now sync with database + // Now sync with database - const StopItem& item = stops.at(idx); + const StopItem &item = stops.at(idx); q.bind(1, item.arrival); q.bind(2, item.departure); q.bind(3, item.stopId); @@ -1753,9 +1797,9 @@ void StopModel::rebaseTimesToSpeed(int firstIdx, QTime firstArr, QTime firstDep) q.reset(); } - //Finally inform the view + // Finally inform the view QModelIndex first = index(firstIdx, 0); - QModelIndex last = index(stops.size() - 1); + QModelIndex last = index(stops.size() - 1); emit dataChanged(first, last); } #endif @@ -1764,55 +1808,55 @@ bool StopModel::updateCurrentInGate(StopItem &curStop, const StopItem::Segment & { command cmd(mDb); - if(!curStop.fromGate.gateConnId) + if (!curStop.fromGate.gateConnId) { - const db_id oldGateId = curStop.fromGate.gateId; + const db_id oldGateId = curStop.fromGate.gateId; const db_id oldTrackNum = curStop.fromGate.gateTrackNum; query q(mDb, "SELECT in_gate_id,out_gate_id FROM railway_segments WHERE id=?"); q.bind(1, prevSeg.segmentId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - auto r = q.getRows(); - db_id segInGate = r.get(0); + auto r = q.getRows(); + db_id segInGate = r.get(0); db_id segOutGate = r.get(1); q.prepare("SELECT in_track,out_track FROM railway_connections WHERE id=?"); q.bind(1, prevSeg.segConnId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - r = q.getRows(); - int segInTrack = r.get(0); + r = q.getRows(); + int segInTrack = r.get(0); int segOutTrack = r.get(1); - //Segment out gate = next station in gate (unless segment is reversed) - curStop.fromGate.gateId = prevSeg.reversed ? segInGate : segOutGate; + // Segment out gate = next station in gate (unless segment is reversed) + curStop.fromGate.gateId = prevSeg.reversed ? segInGate : segOutGate; curStop.fromGate.gateTrackNum = prevSeg.reversed ? segInTrack : segOutTrack; - //Check station + // Check station q.prepare("SELECT station_id FROM station_gates WHERE id=?"); q.bind(1, curStop.fromGate.gateId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - r = q.getRows(); + r = q.getRows(); db_id stationId = r.get(0); - if(curStop.fromGate.gateId != oldGateId || curStop.fromGate.gateTrackNum != oldTrackNum) + if (curStop.fromGate.gateId != oldGateId || curStop.fromGate.gateTrackNum != oldTrackNum) { - //Different gate, reset track and out gate - if(!trySelectTrackForStop(curStop)) + // Different gate, reset track and out gate + if (!trySelectTrackForStop(curStop)) return false; - if(curStop.stationId != stationId) + if (curStop.stationId != stationId) { - //Update station + // Update station cmd.prepare("UPDATE stops SET station_id=? WHERE id=?"); cmd.bind(1, stationId); cmd.bind(2, curStop.stopId); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) return false; curStop.stationId = stationId; @@ -1820,7 +1864,7 @@ bool StopModel::updateCurrentInGate(StopItem &curStop, const StopItem::Segment & } } - //Set gate + // Set gate cmd.prepare("UPDATE stops SET in_gate_conn=? WHERE id=?"); cmd.bind(1, curStop.fromGate.gateConnId); cmd.bind(2, curStop.stopId); @@ -1828,81 +1872,82 @@ bool StopModel::updateCurrentInGate(StopItem &curStop, const StopItem::Segment & return ret == SQLITE_OK; } -bool StopModel::updateStopTime(StopItem &item, int row, bool propagate, const QTime& oldArr, const QTime& oldDep) +bool StopModel::updateStopTime(StopItem &item, int row, bool propagate, const QTime &oldArr, + const QTime &oldDep) { - //Update Arrival and Departure - //NOTE: they must be set togheter so CHECK constraint fires at the end - //Otherwise it would be impossible to set arrival > departure and then update departure + // Update Arrival and Departure + // NOTE: they must be set togheter so CHECK constraint fires at the end + // Otherwise it would be impossible to set arrival > departure and then update departure - //Check time values and fix them if necessary - if(item.type == StopType::First) - item.arrival = item.departure; //We set departure, arrival follows same value - else if(item.type == StopType::Last || item.type == StopType::Transit) - item.departure = item.arrival; //We set arrival, departure follows same value + // Check time values and fix them if necessary + if (item.type == StopType::First) + item.arrival = item.departure; // We set departure, arrival follows same value + else if (item.type == StopType::Last || item.type == StopType::Transit) + item.departure = item.arrival; // We set arrival, departure follows same value - if(item.type != StopType::First && row > 0) + if (item.type != StopType::First && row > 0) { - //Check minimum arrival + // Check minimum arrival /* Next stop must be at least one minute after * This is to prevent contemporary stops that will break ORDER BY arrival queries */ - const StopItem& prevStop = stops.at(row - 1); - const QTime minArr = prevStop.departure.addSecs(60); - if(item.arrival < minArr) + const StopItem &prevStop = stops.at(row - 1); + const QTime minArr = prevStop.departure.addSecs(60); + if (item.arrival < minArr) item.arrival = minArr; } QTime minDep = item.arrival; - if(item.type == StopType::Normal) - minDep = minDep.addSecs(60); //At least stop for 1 minute + if (item.type == StopType::Normal) + minDep = minDep.addSecs(60); // At least stop for 1 minute - if(item.departure < minDep) + if (item.departure < minDep) item.departure = minDep; - //Update stops - if(row < stops.count() - 2) //Not last stop or AddHere + // Update stops + if (row < stops.count() - 2) // Not last stop or AddHere { - const QTime minNextArr = item.departure.addSecs(60); - const StopItem& nextStop = stops.at(row + 1); - if(nextStop.arrival < minNextArr) - propagate = true; //We need to shift stops after current + const QTime minNextArr = item.departure.addSecs(60); + const StopItem &nextStop = stops.at(row + 1); + if (nextStop.arrival < minNextArr) + propagate = true; // We need to shift stops after current } else { - propagate = false; //We are last stop, nothing to propagate + propagate = false; // We are last stop, nothing to propagate } - if(propagate) + if (propagate) shiftStopsBy24hoursFrom(oldArr); - //Update Arrival and Departure in database + // Update Arrival and Departure in database command cmd(mDb); cmd.prepare("UPDATE stops SET arrival=?,departure=? WHERE id=?"); cmd.bind(1, item.arrival); cmd.bind(2, item.departure); cmd.bind(3, item.stopId); - //Mark RS to update + // Mark RS to update query q_selectRS(mDb, "SELECT rs_id FROM coupling WHERE stop_id=?"); q_selectRS.bind(1, item.stopId); - for(auto rs : q_selectRS) + for (auto rs : q_selectRS) { db_id rsId = rs.get(0); rsToUpdate.insert(rsId); } q_selectRS.reset(); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) return false; - if(propagate) + if (propagate) { - int msecOffset = oldDep.msecsTo(item.departure); //Calculate shift amount + int msecOffset = oldDep.msecsTo(item.departure); // Calculate shift amount - //Loop until Last stop (before AddHere) - for(int i = row + 1; i < stops.count() - 1; i++) + // Loop until Last stop (before AddHere) + for (int i = row + 1; i < stops.count() - 1; i++) { - StopItem& s = stops[i]; - s.arrival = s.arrival.addMSecs(msecOffset); + StopItem &s = stops[i]; + s.arrival = s.arrival.addMSecs(msecOffset); s.departure = s.departure.addMSecs(msecOffset); cmd.reset(); @@ -1912,7 +1957,7 @@ bool StopModel::updateStopTime(StopItem &item, int row, bool propagate, const QT cmd.execute(); q_selectRS.bind(1, s.stopId); - for(auto rs : q_selectRS) + for (auto rs : q_selectRS) { db_id rsId = rs.get(0); rsToUpdate.insert(rsId); @@ -1932,35 +1977,39 @@ int StopModel::calcTravelTime(db_id segmentId) query q(mDb, "SELECT max_speed_kmh,distance_meters FROM railway_segments WHERE id=?"); q.bind(1, segmentId); - if(q.step() != SQLITE_ROW) - return 60; //Error + if (q.step() != SQLITE_ROW) + return 60; // Error - auto r = q.getRows(); + auto r = q.getRows(); const int speedKmH = r.get(0); - const int meters = r.get(1); + const int meters = r.get(1); - if(meters == 0 || speedKmH < 1.0) - return 60; //Error + if (meters == 0 || speedKmH < 1.0) + return 60; // Error - const double secs = (meters + accelerationDistMeters)/speedKmH * 3.6; + const double secs = (meters + accelerationDistMeters) / speedKmH * 3.6; return qMax(60, qCeil(secs)); } int StopModel::defaultStopTimeSec() { - //TODO: the prefernces should be stored also in database + // TODO: the prefernces should be stored also in database return AppSettings.getDefaultStopMins(int(category)) * 60; } void StopModel::shiftStopsBy24hoursFrom(const QTime &startTime) { - //HACK: when applying msecOffset to stops query might not work because there might be a (next) stop with the same arrival - // that is being set and thus SQL hits UNIQUE constraint and rejects the modification - //SOLUTION: shift all subsequent stops by 24 hours so there will be no conflicts and then reset the time once at a time - // so in the end they all will have correct time (no need to shift backwards) + // HACK: when applying msecOffset to stops query might not work because there might be a (next) + // stop with the same arrival + // that is being set and thus SQL hits UNIQUE constraint and rejects the modification + // SOLUTION: shift all subsequent stops by 24 hours so there will be no conflicts and then reset + // the time once at a time + // so in the end they all will have correct time (no need to shift backwards) - command q_shiftArrDep(mDb, "UPDATE stops SET arrival=arrival+?1,departure=departure+?1 WHERE job_id=?2 AND arrival>?3"); - const int shiftMin = 24 * 60; //Shift by 24h + command q_shiftArrDep( + mDb, + "UPDATE stops SET arrival=arrival+?1,departure=departure+?1 WHERE job_id=?2 AND arrival>?3"); + const int shiftMin = 24 * 60; // Shift by 24h q_shiftArrDep.bind(1, shiftMin); q_shiftArrDep.bind(2, mJobId); q_shiftArrDep.bind(3, startTime); @@ -1968,12 +2017,13 @@ void StopModel::shiftStopsBy24hoursFrom(const QTime &startTime) q_shiftArrDep.finish(); } -bool StopModel::startInfoEditing() //Faster than 'startStopEditing()' use this if change doesen.t affect stops +bool StopModel::startInfoEditing() // Faster than 'startStopEditing()' use this if change doesen.t + // affect stops { - if(editState != NotEditing) + if (editState != NotEditing) return true; - if(!mJobId) + if (!mJobId) return false; editState = InfoEditing; @@ -1982,32 +2032,32 @@ bool StopModel::startInfoEditing() //Faster than 'startStopEditing()' use this i return true; } - -//NOTE: this must be called before any edit to database in order to save previous state +// NOTE: this must be called before any edit to database in order to save previous state bool StopModel::startStopsEditing() { - if(editState == StopsEditing) + if (editState == StopsEditing) return true; - if(!mJobId) + if (!mJobId) return false; bool alreadyEditing = editState == InfoEditing; - editState = StopsEditing; + editState = StopsEditing; - //Backup stops + // Backup stops command q_backup(mDb, "INSERT INTO old_stops SELECT * FROM stops WHERE job_id=?"); q_backup.bind(1, mJobId); int ret = q_backup.execute(); q_backup.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error while saving old stops:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qWarning() << "Error while saving old stops:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } - //Backup couplings + // Backup couplings q_backup.prepare("INSERT INTO old_coupling(id, stop_id, rs_id, operation)" " SELECT coupling.id, coupling.stop_id, coupling.rs_id, coupling.operation" " FROM coupling" @@ -2016,13 +2066,14 @@ bool StopModel::startStopsEditing() ret = q_backup.execute(); q_backup.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error while saving old couplings:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qDebug() << "Error while saving old couplings:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } - if(!alreadyEditing) + if (!alreadyEditing) emit edited(true); return true; @@ -2030,20 +2081,21 @@ bool StopModel::startStopsEditing() bool StopModel::endStopsEditing() { - if(editState == NotEditing) + if (editState == NotEditing) return false; - if(editState == StopsEditing) + if (editState == StopsEditing) { - //Clear old_stops (will automatically clear old_couplings with FK: ON DELETE CASCADE) + // Clear old_stops (will automatically clear old_couplings with FK: ON DELETE CASCADE) command q_clearOldStops(mDb, "DELETE FROM old_stops WHERE job_id=?"); q_clearOldStops.bind(1, mJobId); int ret = q_clearOldStops.execute(); q_clearOldStops.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "Error while clearing old stops:" << ret << mDb.error_msg() << mDb.extended_error_code(); + qDebug() << "Error while clearing old stops:" << ret << mDb.error_msg() + << mDb.extended_error_code(); return false; } } diff --git a/src/jobs/jobeditor/model/stopmodel.h b/src/jobs/jobeditor/model/stopmodel.h index 0f9c69c..33d17a3 100644 --- a/src/jobs/jobeditor/model/stopmodel.h +++ b/src/jobs/jobeditor/model/stopmodel.h @@ -36,9 +36,9 @@ struct StopItem { struct Gate { - db_id gateConnId = 0; - db_id gateId = 0; - int gateTrackNum = -1; + db_id gateConnId = 0; + db_id gateId = 0; + int gateTrackNum = -1; utils::Side stationTrackSide = utils::Side::NSides; }; @@ -48,7 +48,7 @@ struct StopItem db_id segmentId = 0; int inTrackNum = -1; int outTrackNum = -1; - bool reversed = false; + bool reversed = false; }; db_id stopId = 0; @@ -62,12 +62,11 @@ struct StopItem QTime arrival; QTime departure; - int addHere = 0; + int addHere = 0; StopType type = StopType::Normal; }; - /*! * \brief The StopModel class * @@ -80,7 +79,7 @@ class StopModel : public QAbstractListModel { Q_OBJECT public: - StopModel(sqlite3pp::database& db, QObject *parent = nullptr); + StopModel(sqlite3pp::database &db, QObject *parent = nullptr); // QAbstractListModel QVariant data(const QModelIndex &index, int role) const override; @@ -105,7 +104,7 @@ public: // Editing void addStop(); - void removeStop(const QModelIndex& idx); + void removeStop(const QModelIndex &idx); void removeLastIfEmpty(); void uncoupleStillCoupledAtLastStop(); @@ -118,7 +117,8 @@ public: db_id getNewShiftId() const; // Setters - void setStopInfo(const QModelIndex& idx, StopItem newStop, StopItem::Segment prevSeg, bool avoidTimeRecalc = false); + void setStopInfo(const QModelIndex &idx, StopItem newStop, StopItem::Segment prevSeg, + bool avoidTimeRecalc = false); bool setStopTypeRange(int firstRow, int lastRow, StopType type); @@ -129,7 +129,7 @@ public: // Convinience int getStopRow(db_id stopId) const; - bool isAddHere(const QModelIndex& idx); + bool isAddHere(const QModelIndex &idx); std::pair getFirstLastTimes() const; @@ -139,10 +139,18 @@ public: bool isRailwayElectrifiedAfterStop(db_id stopId) const; bool isRailwayElectrifiedAfterRow(int row) const; - inline StopItem getItemAt(int row) const { return stops.at(row); } - inline StopType getItemTypeAt(int row) const { return stops.at(row).type; } - inline db_id getItemStationAt(int row) const { return stops.at(row).stationId; } - + inline StopItem getItemAt(int row) const + { + return stops.at(row); + } + inline StopType getItemTypeAt(int row) const + { + return stops.at(row).type; + } + inline db_id getItemStationAt(int row) const + { + return stops.at(row).stationId; + } #ifdef ENABLE_AUTO_TIME_RECALC void rebaseTimesToSpeed(int firstIdx, QTime firstArr, QTime firstDep); @@ -150,8 +158,7 @@ public: bool trySelectTrackForStop(StopItem &item); - bool trySetTrackConnections(StopItem &item, db_id trackId, - QString *outErr); + bool trySetTrackConnections(StopItem &item, db_id trackId, QString *outErr); bool trySelectNextSegment(StopItem &item, db_id segmentId, int suggestedOutGateTrk, db_id nextStationId, db_id &out_gateId, db_id &out_suggestedTrackId); @@ -162,7 +169,7 @@ signals: void categoryChanged(int newCat); void jobIdChanged(db_id jobId); void jobShiftChanged(db_id shiftId); - void errorSetShiftWithoutStops(); //TODO: find better way to show errors + void errorSetShiftWithoutStops(); // TODO: find better way to show errors public slots: void setCategory(int value); @@ -182,25 +189,29 @@ private: db_id createStop(db_id jobId, const QTime &arr, const QTime &dep, StopType type); void deleteStop(db_id stopId); - bool updateCurrentInGate(StopItem& curStop, const StopItem::Segment& prevSeg); - bool updateStopTime(StopItem& item, int row, bool propagate, const QTime &oldArr, const QTime &oldDep); + bool updateCurrentInGate(StopItem &curStop, const StopItem::Segment &prevSeg); + bool updateStopTime(StopItem &item, int row, bool propagate, const QTime &oldArr, + const QTime &oldDep); int calcTravelTime(db_id segmentId); int defaultStopTimeSec(); - void shiftStopsBy24hoursFrom(const QTime& startTime); + void shiftStopsBy24hoursFrom(const QTime &startTime); friend class RSCouplingInterface; bool startInfoEditing(); bool startStopsEditing(); bool endStopsEditing(); - inline void markRsToUpdate(db_id rsId) { rsToUpdate.insert(rsId); } + inline void markRsToUpdate(db_id rsId) + { + rsToUpdate.insert(rsId); + } private: - //To simulate acceleration/braking we add 4 km to distance + // To simulate acceleration/braking we add 4 km to distance static constexpr double accelerationDistMeters = 4000.0; - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; QVector stops; @@ -218,8 +229,8 @@ private: enum EditState { - NotEditing = 0, - InfoEditing = 1, + NotEditing = 0, + InfoEditing = 1, StopsEditing = 2 }; diff --git a/src/jobs/jobeditor/model/trainassetmodel.cpp b/src/jobs/jobeditor/model/trainassetmodel.cpp index 4d61f54..a5c9a59 100644 --- a/src/jobs/jobeditor/model/trainassetmodel.cpp +++ b/src/jobs/jobeditor/model/trainassetmodel.cpp @@ -28,7 +28,7 @@ using namespace sqlite3pp; #include -TrainAssetModel::TrainAssetModel(database& db, QObject *parent) : +TrainAssetModel::TrainAssetModel(database &db, QObject *parent) : RSListOnDemandModel(db, parent), m_jobId(0), m_mode(BeforeStop) @@ -45,30 +45,33 @@ qint64 TrainAssetModel::recalcTotalItemCount() " GROUP BY coupling.rs_id" " HAVING coupling.operation=1)"); q.bind(1, m_jobId); - //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(m_mode == 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 (m_mode == AfterStop) q.bind(2, m_arrival.addSecs(60)); else q.bind(2, m_arrival); int ret = q.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) qWarning() << "TrainAssetModel: " << mDb.error_msg() << mDb.error_code(); const qint64 count = q.getRows().get(0); return count; } -void TrainAssetModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant &/*val*/) +void TrainAssetModel::internalFetch(int first, int sortCol, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); int offset = first + curPage * ItemsPerPage; - //const char *whereCol; + // const char *whereCol; QByteArray sql = "SELECT sub.rs_id,sub.number,sub.name,sub.suffix,sub.type FROM(" - "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type,MAX(stops.arrival)" + "SELECT " + "coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type," + "MAX(stops.arrival)" " FROM stops" " JOIN coupling ON coupling.stop_id=stops.id" " JOIN rs_list ON rs_list.id=rs_id" @@ -103,49 +106,47 @@ void TrainAssetModel::internalFetch(int first, int sortCol, int /*valRow*/, cons // sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); q.bind(3, m_jobId); - //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(m_mode == 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 (m_mode == AfterStop) q.bind(4, m_arrival.addSecs(60)); else q.bind(4, m_arrival); - if(offset) + if (offset) q.bind(2, offset); QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; - RSItem &item = vec[i]; - item.rsId = r.get(0); + auto r = *it; + RSItem &item = vec[i]; + item.rsId = r.get(0); - int number = r.get(1); - int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); + int number = r.get(1); + int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); - int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); - item.type = RsType(sqlite3_column_int(q.stmt(), 4)); + int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); + item.type = RsType(sqlite3_column_int(q.stmt(), 4)); - item.name = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - item.type); + item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, item.type); i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); @@ -153,9 +154,9 @@ void TrainAssetModel::internalFetch(int first, int sortCol, int /*valRow*/, cons void TrainAssetModel::setStop(db_id jobId, QTime arrival, Mode mode) { - m_jobId = jobId; + m_jobId = jobId; m_arrival = arrival; - m_mode = mode; + m_mode = mode; refreshData(true); } diff --git a/src/jobs/jobeditor/model/trainassetmodel.h b/src/jobs/jobeditor/model/trainassetmodel.h index fbd2d61..587e56a 100644 --- a/src/jobs/jobeditor/model/trainassetmodel.h +++ b/src/jobs/jobeditor/model/trainassetmodel.h @@ -27,12 +27,13 @@ class TrainAssetModel : public RSListOnDemandModel { Q_OBJECT public: - enum Mode { + enum Mode + { BeforeStop, AfterStop }; - TrainAssetModel(sqlite3pp::database& db, QObject *parent = nullptr); + TrainAssetModel(sqlite3pp::database &db, QObject *parent = nullptr); // TrainAssetModel void setStop(db_id jobId, QTime arrival, Mode mode); diff --git a/src/jobs/jobeditor/rscoupledialog.cpp b/src/jobs/jobeditor/rscoupledialog.cpp index e68c143..f34e581 100644 --- a/src/jobs/jobeditor/rscoupledialog.cpp +++ b/src/jobs/jobeditor/rscoupledialog.cpp @@ -36,15 +36,15 @@ #include "app/session.h" RSCoupleDialog::RSCoupleDialog(RSCouplingInterface *mgr, RsOp o, QWidget *parent) : - QDialog (parent), + QDialog(parent), couplingMgr(mgr), legend(nullptr), m_showLegend(false), op(o) { - engModel = new RSProxyModel(couplingMgr, op, RsType::Engine, this); - coachModel = new RSProxyModel(couplingMgr, op, RsType::Coach, this); - freightModel = new RSProxyModel(couplingMgr, op, RsType::FreightWagon, this); + engModel = new RSProxyModel(couplingMgr, op, RsType::Engine, this); + coachModel = new RSProxyModel(couplingMgr, op, RsType::Coach, this); + freightModel = new RSProxyModel(couplingMgr, op, RsType::FreightWagon, this); QGridLayout *lay = new QGridLayout(this); @@ -86,7 +86,8 @@ RSCoupleDialog::RSCoupleDialog(RSCouplingInterface *mgr, RsOp o, QWidget *parent showHideLegendBut = new QPushButton; buttonLay->addWidget(showHideLegendBut); - QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok); //TODO: implement also cancel + QDialogButtonBox *box = + new QDialogButtonBox(QDialogButtonBox::Ok); // TODO: implement also cancel connect(box, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(box, &QDialogButtonBox::rejected, this, &QDialog::reject); buttonLay->addWidget(box); @@ -100,13 +101,14 @@ RSCoupleDialog::RSCoupleDialog(RSCouplingInterface *mgr, RsOp o, QWidget *parent setLegendVisible(AppSettings.getShowCouplingLegend()); } -void RSCoupleDialog::loadProxyModels(sqlite3pp::database& db, db_id jobId, db_id stopId, db_id stationId, const QTime& arrival) +void RSCoupleDialog::loadProxyModels(sqlite3pp::database &db, db_id jobId, db_id stopId, + db_id stationId, const QTime &arrival) { QVector engines, freight, coaches; sqlite3pp::query q(db); - if(op == RsOp::Coupled) + if (op == RsOp::Coupled) { /* Show Couple-able RS: * - RS free in this station @@ -117,59 +119,68 @@ void RSCoupleDialog::loadProxyModels(sqlite3pp::database& db, db_id jobId, db_id * - Possible wrong operations to let the user remove them */ - q.prepare("SELECT MAX(sub.p), sub.rs_id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type, rs_models.sub_type, sub.arr, sub.job_id, jobs.category FROM (" + q.prepare( + "SELECT MAX(sub.p), sub.rs_id, rs_list.number, rs_models.name, rs_models.suffix, " + "rs_models.type, rs_models.sub_type, sub.arr, sub.job_id, jobs.category FROM (" - //Select possible wrong operations to let user remove (un-check) them - " SELECT 1 AS p, coupling.rs_id AS rs_id, NULL AS arr, NULL AS job_id FROM coupling WHERE coupling.stop_id=?3 AND coupling.operation=1" - " UNION ALL" + // Select possible wrong operations to let user remove (un-check) them + " SELECT 1 AS p, coupling.rs_id AS rs_id, NULL AS arr, NULL AS job_id FROM coupling " + "WHERE coupling.stop_id=?3 AND coupling.operation=1" + " UNION ALL" - //Select RS uncoupled before our arrival (included RS uncoupled at exact same time) (except uncoupled by us) - " SELECT 2 AS p, coupling.rs_id AS rs_id, MAX(stops.arrival) AS arr, stops.job_id AS job_id" - " FROM stops" - " JOIN coupling ON coupling.stop_id=stops.id" - " WHERE stops.station_id=?1 AND stops.arrival <= ?2 AND stops.id<>?3" - " GROUP BY coupling.rs_id" - " HAVING coupling.operation=0" - " UNION ALL" + // Select RS uncoupled before our arrival (included RS uncoupled at exact same time) + // (except uncoupled by us) + " SELECT 2 AS p, coupling.rs_id AS rs_id, MAX(stops.arrival) AS arr, stops.job_id AS " + "job_id" + " FROM stops" + " JOIN coupling ON coupling.stop_id=stops.id" + " WHERE stops.station_id=?1 AND stops.arrival <= ?2 AND stops.id<>?3" + " GROUP BY coupling.rs_id" + " HAVING coupling.operation=0" + " UNION ALL" - //Select RS coupled after our arrival (excluded RS coupled at exact same time) - " SELECT 3 AS p, coupling.rs_id, MIN(stops.arrival) AS arr, stops.job_id AS job_id" - " FROM coupling" - " JOIN stops ON stops.id=coupling.stop_id" - " WHERE stops.station_id=?1 AND stops.arrival > ?2" - " GROUP BY coupling.rs_id" - " HAVING coupling.operation=1" - " UNION ALL" + // Select RS coupled after our arrival (excluded RS coupled at exact same time) + " SELECT 3 AS p, coupling.rs_id, MIN(stops.arrival) AS arr, stops.job_id AS job_id" + " FROM coupling" + " JOIN stops ON stops.id=coupling.stop_id" + " WHERE stops.station_id=?1 AND stops.arrival > ?2" + " GROUP BY coupling.rs_id" + " HAVING coupling.operation=1" + " UNION ALL" - //Select coupled RS for first time - " SELECT 4 AS p, rs_list.id AS rs_id, NULL AS arr, NULL AS job_id" - " FROM rs_list" - " WHERE NOT EXISTS (" - " SELECT coupling.rs_id FROM coupling" - " JOIN stops ON stops.id=coupling.stop_id WHERE coupling.rs_id=rs_list.id AND stops.arrival(0); - item.rsId = rs.get(1); + item.flag = rs.get(0); + item.rsId = rs.get(1); - int number = rs.get(2); - int modelNameLen = sqlite3_column_bytes(q.stmt(), 3); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); + int number = rs.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 type = RsType(rs.get(5)); + int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 4); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 4)); + RsType type = RsType(rs.get(5)); RsEngineSubType subType = RsEngineSubType(rs.get(6)); - item.rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + item.rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); item.engineType = RsEngineSubType::Invalid; - item.time = rs.get(7); - item.jobId = rs.get(8); - item.jobCat = JobCategory(rs.get(9)); + item.time = rs.get(7); + item.jobId = rs.get(8); + item.jobCat = JobCategory(rs.get(9)); switch (type) { @@ -274,7 +287,7 @@ void RSCoupleDialog::loadProxyModels(sqlite3pp::database& db, db_id jobId, db_id void RSCoupleDialog::done(int ret) { - //Save legend state + // Save legend state AppSettings.setShowCouplingLegend(m_showLegend); QDialog::done(ret); @@ -294,35 +307,43 @@ void RSCoupleDialog::setLegendVisible(bool val) { m_showLegend = val; - if(legend->isVisible() && !m_showLegend) + if (legend->isVisible() && !m_showLegend) { legend->hide(); } - else if(m_showLegend && !legend->isVisible()) + else if (m_showLegend && !legend->isVisible()) { legend->show(); - if(!legend->layout()) + if (!legend->layout()) { - double fontPt = font().pointSizeF() * 1.2; + double fontPt = font().pointSizeF() * 1.2; QVBoxLayout *legendLay = new QVBoxLayout(legend); - QLabel *label = new QLabel(tr("" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
___ This item is free in current station.___ The item isn't in this station.
___ First use of this item.___ The item isn't coupled before or already coupled.
___ This item is never used in this session.\\\\\\\\ Railway line doesn't allow electric traction.
").arg(fontPt)); + QLabel *label = new QLabel( + tr("" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
___ This item is free in " + "current station.___ The item isn't in this " + "station.
___ First use of this " + "item.___ The item isn't coupled " + "before or already coupled.
___ This item is never used " + "in this session.\\\\\\\\ " + "Railway line doesn't allow electric traction.
") + .arg(fontPt)); label->setTextFormat(Qt::RichText); label->setWordWrap(true); legendLay->addWidget(label); diff --git a/src/jobs/jobeditor/rscoupledialog.h b/src/jobs/jobeditor/rscoupledialog.h index 99ca678..13545ed 100644 --- a/src/jobs/jobeditor/rscoupledialog.h +++ b/src/jobs/jobeditor/rscoupledialog.h @@ -32,14 +32,15 @@ namespace sqlite3pp { class database; } -//FIXME: on-demand load and filter +// FIXME: on-demand load and filter class RSCoupleDialog : public QDialog { Q_OBJECT public: RSCoupleDialog(RSCouplingInterface *mgr, RsOp o, QWidget *parent = nullptr); - void loadProxyModels(sqlite3pp::database &db, db_id jobId, db_id stopId, db_id stationId, const QTime &arrival); + void loadProxyModels(sqlite3pp::database &db, db_id jobId, db_id stopId, db_id stationId, + const QTime &arrival); protected: void done(int ret) override; diff --git a/src/jobs/jobeditor/shiftbusy/shiftbusydialog.cpp b/src/jobs/jobeditor/shiftbusy/shiftbusydialog.cpp index b131a2b..7628df3 100644 --- a/src/jobs/jobeditor/shiftbusy/shiftbusydialog.cpp +++ b/src/jobs/jobeditor/shiftbusy/shiftbusydialog.cpp @@ -34,7 +34,7 @@ ShiftBusyDlg::ShiftBusyDlg(QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - m_label = new QLabel; + m_label = new QLabel; lay->addWidget(m_label); view = new QTableView; @@ -57,8 +57,7 @@ void ShiftBusyDlg::setModel(ShiftBusyModel *m) m_label->setText(tr("Cannot set shift %1 to job %2.
" "The selected shift is busy:
" "From: %3 To: %4") - .arg(model->getShiftName(), - model->getJobName(), - model->getStart().toString("HH:mm"), - model->getEnd().toString("HH:mm"))); + .arg(model->getShiftName(), model->getJobName(), + model->getStart().toString("HH:mm"), + model->getEnd().toString("HH:mm"))); } diff --git a/src/jobs/jobeditor/shiftbusy/shiftbusydialog.h b/src/jobs/jobeditor/shiftbusy/shiftbusydialog.h index cac8890..d672da0 100644 --- a/src/jobs/jobeditor/shiftbusy/shiftbusydialog.h +++ b/src/jobs/jobeditor/shiftbusy/shiftbusydialog.h @@ -36,6 +36,7 @@ public: explicit ShiftBusyDlg(QWidget *parent = nullptr); void setModel(ShiftBusyModel *m); + private: QLabel *m_label; QTableView *view; diff --git a/src/jobs/jobeditor/shiftbusy/shiftbusymodel.cpp b/src/jobs/jobeditor/shiftbusy/shiftbusymodel.cpp index f1f1346..acbe48a 100644 --- a/src/jobs/jobeditor/shiftbusy/shiftbusymodel.cpp +++ b/src/jobs/jobeditor/shiftbusy/shiftbusymodel.cpp @@ -35,9 +35,10 @@ ShiftBusyModel::ShiftBusyModel(sqlite3pp::database &db, QObject *parent) : QVariant ShiftBusyModel::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) { + switch (section) + { case JobCol: return tr("Job"); case Start: @@ -66,7 +67,7 @@ QVariant ShiftBusyModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= m_data.size() || idx.column() >= NCols) return QVariant(); - const JobInfo& info = m_data.at(row); + const JobInfo &info = m_data.at(row); switch (role) { @@ -94,13 +95,13 @@ void ShiftBusyModel::loadData(db_id shiftId, db_id jobId, const QTime &start, co m_data.clear(); m_shiftId = shiftId; - m_jobId = jobId; - m_start = start; - m_end = end; + m_jobId = jobId; + m_start = start; + m_end = end; query q(mDb, "SELECT name FROM jobshifts WHERE id=?"); q.bind(1, m_shiftId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) { endResetModel(); return; @@ -118,7 +119,7 @@ void ShiftBusyModel::loadData(db_id shiftId, db_id jobId, const QTime &start, co q.bind(2, m_start); q.bind(3, m_end); q.step(); - int count = q.getRows().get(0) - 1; //Do not count ourself + int count = q.getRows().get(0) - 1; // Do not count ourself m_data.reserve(count); q.prepare("SELECT jobs.id, jobs.category," @@ -133,20 +134,20 @@ void ShiftBusyModel::loadData(db_id shiftId, db_id jobId, const QTime &start, co q.bind(2, m_start); q.bind(3, m_end); - for(auto j : q) + for (auto j : q) { JobInfo info; - info.jobId = j.get(0); + info.jobId = j.get(0); info.jobCat = JobCategory(j.get(1)); - if(info.jobId == m_jobId) + if (info.jobId == m_jobId) { m_jobCat = info.jobCat; continue; } info.start = j.get(3); - info.end = j.get(4); + info.end = j.get(4); m_data.append(info); } diff --git a/src/jobs/jobeditor/shiftbusy/shiftbusymodel.h b/src/jobs/jobeditor/shiftbusy/shiftbusymodel.h index f83bd05..452bcba 100644 --- a/src/jobs/jobeditor/shiftbusy/shiftbusymodel.h +++ b/src/jobs/jobeditor/shiftbusy/shiftbusymodel.h @@ -30,14 +30,14 @@ namespace sqlite3pp { class database; } -//TODO: move to shifts subdir +// TODO: move to shifts subdir class ShiftBusyModel : public QAbstractTableModel { Q_OBJECT public: - - enum Columns { + enum Columns + { JobCol = 0, Start, End, @@ -55,7 +55,8 @@ public: ShiftBusyModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -63,14 +64,26 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; - void loadData(db_id shiftId, db_id jobId, const QTime& start, const QTime& end); + void loadData(db_id shiftId, db_id jobId, const QTime &start, const QTime &end); - inline bool hasConcurrentJobs() const { return m_data.size(); } + inline bool hasConcurrentJobs() const + { + return m_data.size(); + } - inline QTime getStart() const { return m_start; } - inline QTime getEnd() const { return m_end; } + inline QTime getStart() const + { + return m_start; + } + inline QTime getEnd() const + { + return m_end; + } - inline QString getShiftName() const { return m_shiftName; } + inline QString getShiftName() const + { + return m_shiftName; + } QString getJobName() const; private: diff --git a/src/jobs/jobeditor/stopdelegate.cpp b/src/jobs/jobeditor/stopdelegate.cpp index e5e626b..918f250 100644 --- a/src/jobs/jobeditor/stopdelegate.cpp +++ b/src/jobs/jobeditor/stopdelegate.cpp @@ -41,11 +41,11 @@ StopDelegate::StopDelegate(sqlite3pp::database &db, QObject *parent) : void StopDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - QRect rect = option.rect.adjusted(5, 5, -5, -5); + QRect rect = option.rect.adjusted(5, 5, -5, -5); const StopModel *model = static_cast(index.model()); - const StopItem item = model->getItemAt(index.row()); - const bool isTransit = item.type == StopType::Transit; + const StopItem item = model->getItemAt(index.row()); + const bool isTransit = item.type == StopType::Transit; query q(mDb, "SELECT name FROM stations WHERE id=?"); q.bind(1, item.stationId); @@ -56,7 +56,7 @@ void StopDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); - //Draw bottom border + // Draw bottom border painter->setPen(QPen(Qt::black, 1)); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); @@ -73,120 +73,117 @@ void StopDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, painter->setBrush(option.palette.text()); - const double top = rect.top(); - const double bottom = rect.bottom(); - const double left = rect.left(); - const double width = rect.width(); - const double height = rect.height(); + const double top = rect.top(); + const double bottom = rect.bottom(); + const double left = rect.left(); + const double width = rect.width(); + const double height = rect.height(); - const double stHeight = top + (isTransit ? 0.0 : height * 0.1); - const double timeHeight = top + height * 0.4; - const double lineHeight = top + height * 0.65; + const double stHeight = top + (isTransit ? 0.0 : height * 0.1); + const double timeHeight = top + height * 0.4; + const double lineHeight = top + height * 0.65; - const double arrX = left + width * (isTransit ? 0.4 : 0.2); - const double depX = left + width * 0.6; + const double arrX = left + width * (isTransit ? 0.4 : 0.2); + const double depX = left + width * 0.6; const double transitLineX = left + width * 0.2; - - if(item.addHere == 0) + if (item.addHere == 0) { - //Draw item - //Station name - painter->drawText(QRectF(left, stHeight, width, bottom - stHeight), - station, + // Draw item + // Station name + painter->drawText(QRectF(left, stHeight, width, bottom - stHeight), station, QTextOption(Qt::AlignHCenter)); - if(item.type != StopType::First) + if (item.type != StopType::First) { - //Arrival + // Arrival painter->drawText(QRectF(arrX, timeHeight, width, bottom - timeHeight), item.arrival.toString("HH:mm")); } - if(item.type == StopType::First || item.type == StopType::Normal) //Last, Transit don't have a separate departure + if (item.type == StopType::First + || item.type == StopType::Normal) // Last, Transit don't have a separate departure { - //Departure + // Departure painter->drawText(QRectF(depX, timeHeight, width, bottom - timeHeight), item.departure.toString("HH:mm")); } - //Check direction - if(item.fromGate.gateConnId && item.toGate.gateConnId - && item.type != StopType::First && item.type != StopType::Last) + // Check direction + if (item.fromGate.gateConnId && item.toGate.gateConnId && item.type != StopType::First + && item.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(item.fromGate.stationTrackSide == item.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 (item.fromGate.stationTrackSide == item.toGate.stationTrackSide) { - //Train leaves station track from same side of entrance, draw reverse icon + // Train leaves station track from same side of entrance, draw reverse icon QPointF iconTopLeft(left, bottom - PixHeight); painter->drawPixmap(iconTopLeft, m_reverseDirPix); } } - if(item.type != StopType::Last && item.nextSegment.segmentId) + if (item.type != StopType::Last && item.nextSegment.segmentId) { - //Last has no next segment so do not draw lightning + // Last has no next segment so do not draw lightning bool nextSegmentElectrified = model->isRailwayElectrifiedAfterRow(index.row()); - bool prevSegmentElectrified = !nextSegmentElectrified; //Trigger change on First stop + bool prevSegmentElectrified = !nextSegmentElectrified; // Trigger change on First stop - if(item.type != StopType::First && index.row() >= 0) + if (item.type != StopType::First && index.row() >= 0) { - //Get real previous railway type + // Get real previous railway type prevSegmentElectrified = model->isRailwayElectrifiedAfterRow(index.row() - 1); } - if(nextSegmentElectrified != prevSegmentElectrified) + if (nextSegmentElectrified != prevSegmentElectrified) { - //Railway type changed, draw a lightning + // Railway type changed, draw a lightning QPointF lightningTopLeft(left, top + qMin(5.0, height * 0.1)); painter->drawPixmap(lightningTopLeft, m_lightningPix); - if(!nextSegmentElectrified) + if (!nextSegmentElectrified) { - //Next railway is not electrified, cross the lightning - //Then keep red pen to draw next segment name + // Next railway is not electrified, cross the lightning + // Then keep red pen to draw next segment name painter->setPen(QPen(Qt::red, 4)); - painter->drawLine(lightningTopLeft, lightningTopLeft + QPointF(PixWidth, PixHeight)); + painter->drawLine(lightningTopLeft, + lightningTopLeft + QPointF(PixWidth, PixHeight)); } } - //Draw next segment name + // Draw next segment name q.prepare("SELECT name FROM railway_segments WHERE id=?"); q.bind(1, item.nextSegment.segmentId); q.step(); - auto r = q.getRows(); + auto r = q.getRows(); const QString segName = r.get(0); q.reset(); const double lineRightX = left + width * 0.8; - painter->drawText(QRectF(transitLineX, lineHeight, lineRightX - left, bottom - lineHeight), - tr("Seg: %1").arg(segName), - QTextOption(Qt::AlignHCenter)); + painter->drawText( + QRectF(transitLineX, lineHeight, lineRightX - left, bottom - lineHeight), + tr("Seg: %1").arg(segName), QTextOption(Qt::AlignHCenter)); - if(item.toGate.gateTrackNum != 0) + if (item.toGate.gateTrackNum != 0) { painter->setPen(QPen(Qt::red, 4)); - painter->drawText(QRectF(lineRightX, lineHeight, left + width - lineRightX, bottom - lineHeight), - QString::number(item.toGate.gateTrackNum), - QTextOption(Qt::AlignHCenter)); + painter->drawText( + QRectF(lineRightX, lineHeight, left + width - lineRightX, bottom - lineHeight), + QString::number(item.toGate.gateTrackNum), QTextOption(Qt::AlignHCenter)); } } - if(isTransit) + if (isTransit) { - //Draw a vertical -0- to tell this is a transit + // Draw a vertical -0- to tell this is a transit painter->setPen(QPen(Qt::red, 4)); painter->setBrush(Qt::red); - painter->drawLine(QLineF(transitLineX, rect.top(), - transitLineX, rect.bottom())); + painter->drawLine(QLineF(transitLineX, rect.top(), transitLineX, rect.bottom())); - painter->drawEllipse(QRectF(transitLineX - 12 / 2, - rect.top() + rect.height() * 0.4, - 12, 12)); + painter->drawEllipse( + QRectF(transitLineX - 12 / 2, rect.top() + rect.height() * 0.4, 12, 12)); } - } else if (item.addHere == 1) { @@ -200,30 +197,29 @@ void StopDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, painter->restore(); } -QSize StopDelegate::sizeHint(const QStyleOptionViewItem &/*option*/, +QSize StopDelegate::sizeHint(const QStyleOptionViewItem & /*option*/, const QModelIndex &index) const { - int w = 200; - int h = NormalStopHeight; + int w = 200; + int h = NormalStopHeight; const StopModel *model = static_cast(index.model()); - if(index.row() < 0 || index.row() >= model->rowCount()) + if (index.row() < 0 || index.row() >= model->rowCount()) return QSize(w, AddHereHeight); - const StopItem& item = model->getItemAt(index.row()); - if(item.type == StopType::Transit) + const StopItem &item = model->getItemAt(index.row()); + if (item.type == StopType::Transit) h = TransitStopHeight; - if(item.addHere != 0) + if (item.addHere != 0) h = AddHereHeight; return QSize(w, h); } -QWidget *StopDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &/*option*/, +QWidget *StopDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, const QModelIndex &index) const { - StopModel *model = const_cast(static_cast(index.model())); - if(model->isAddHere(index)) + StopModel *model = const_cast(static_cast(index.model())); + if (model->isAddHere(index)) { qDebug() << index << "is AddHere"; return nullptr; @@ -231,35 +227,34 @@ QWidget *StopDelegate::createEditor(QWidget *parent, StopEditor *editor = new StopEditor(mDb, model, parent); editor->setAutoFillBackground(true); - editor->setEnabled(false); //Mark it + editor->setEnabled(false); // Mark it - //Prevent JobPathEditor context menu in table view during stop editing + // Prevent JobPathEditor context menu in table view during stop editing editor->setContextMenuPolicy(Qt::PreventContextMenu); - //See 'StopEditor::popupLinesCombo' + // See 'StopEditor::popupLinesCombo' connect(this, &StopDelegate::popupEditorSegmentCombo, editor, &StopEditor::popupSegmentCombo); connect(editor, &StopEditor::nextSegmentChosen, this, &StopDelegate::onEditorSegmentChosen); return editor; } -void StopDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void StopDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { - StopEditor *ed = static_cast(editor); - if(ed->isEnabled()) //We already set data + StopEditor *ed = static_cast(editor); + if (ed->isEnabled()) // We already set data return; - ed->setEnabled(true); //Mark it + ed->setEnabled(true); // Mark it const StopModel *model = static_cast(index.model()); - const StopItem item = model->getItemAt(index.row()); + const StopItem item = model->getItemAt(index.row()); StopItem prev; int r = index.row(); - if(r > 0) + if (r > 0) { - //Current stop is not First, get also previous one + // Current stop is not First, get also previous one prev = model->getItemAt(r - 1); } @@ -272,7 +267,7 @@ void StopDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, DEBUG_IMPORTANT_ENTRY; qDebug() << "End editing: stop" << index.row(); - StopEditor *ed = static_cast(editor); + StopEditor *ed = static_cast(editor); StopModel *stopModel = static_cast(model); bool avoidTimeRecalc = QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier); @@ -280,14 +275,15 @@ void StopDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, stopModel->setStopInfo(index, ed->getCurItem(), ed->getPrevItem().nextSegment, avoidTimeRecalc); } -void StopDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const +void StopDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex & /*index*/) const { editor->setGeometry(option.rect); } void StopDelegate::onEditorSegmentChosen(StopEditor *editor) { - if(editor->closeOnSegmentChosen()) + if (editor->closeOnSegmentChosen()) { emit commitData(editor); emit closeEditor(editor, StopDelegate::EditNextItem); @@ -296,10 +292,11 @@ void StopDelegate::onEditorSegmentChosen(StopEditor *editor) void StopDelegate::refreshPixmaps() { - const QString iconPath = QCoreApplication::instance()->applicationDirPath() + QStringLiteral("/icons"); + const QString iconPath = + QCoreApplication::instance()->applicationDirPath() + QStringLiteral("/icons"); - //Square pixmaps - m_lightningPix = QPixmap(PixWidth, PixHeight); + // Square pixmaps + m_lightningPix = QPixmap(PixWidth, PixHeight); m_reverseDirPix = QPixmap(PixWidth, PixHeight); m_lightningPix.fill(Qt::transparent); @@ -309,26 +306,26 @@ void StopDelegate::refreshPixmaps() QPainter painter; QRectF iconRect; - //Cache Lightning + // Cache Lightning mSvg.load(iconPath + QStringLiteral("/lightning.svg")); - //Scale SVG to fit requested size + // Scale SVG to fit requested size iconRect.setSize(mSvg.defaultSize().scaled(PixWidth, PixHeight, Qt::KeepAspectRatio)); - //Center on pixmap + // Center on pixmap iconRect.moveTop((PixHeight - iconRect.height()) / 2); iconRect.moveLeft((PixWidth - iconRect.width()) / 2); painter.begin(&m_lightningPix); mSvg.render(&painter, iconRect); painter.end(); - //Cache Reverse Direction + // Cache Reverse Direction mSvg.load(iconPath + QStringLiteral("/reverse_direction.svg")); - //Scale SVG to fit requested size + // Scale SVG to fit requested size iconRect.setSize(mSvg.defaultSize().scaled(PixWidth, PixHeight, Qt::KeepAspectRatio)); - //Center on pixmap + // Center on pixmap iconRect.moveTop((PixHeight - iconRect.height()) / 2); iconRect.moveLeft((PixWidth - iconRect.width()) / 2); painter.begin(&m_reverseDirPix); diff --git a/src/jobs/jobeditor/stopdelegate.h b/src/jobs/jobeditor/stopdelegate.h index 339bff3..2df5d46 100644 --- a/src/jobs/jobeditor/stopdelegate.h +++ b/src/jobs/jobeditor/stopdelegate.h @@ -46,15 +46,15 @@ public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &) const override; signals: /*! @@ -87,12 +87,12 @@ private: QPixmap m_lightningPix; QPixmap m_reverseDirPix; - static constexpr int NormalStopHeight = 100; + static constexpr int NormalStopHeight = 100; static constexpr int TransitStopHeight = 80; - static constexpr int AddHereHeight = 30; + static constexpr int AddHereHeight = 30; - static constexpr int PixWidth = 35; - static constexpr int PixHeight = PixWidth; + static constexpr int PixWidth = 35; + static constexpr int PixHeight = PixWidth; }; #endif // STOPDELEGATE_H diff --git a/src/jobs/jobeditor/stopeditinghelper.cpp b/src/jobs/jobeditor/stopeditinghelper.cpp index 37e3d24..5ac9ec4 100644 --- a/src/jobs/jobeditor/stopeditinghelper.cpp +++ b/src/jobs/jobeditor/stopeditinghelper.cpp @@ -33,43 +33,47 @@ #include -StopEditingHelper::StopEditingHelper(database &db, StopModel *m, - QSpinBox *outTrackSpin, QTimeEdit *arr, QTimeEdit *dep, - QWidget *editor) : +StopEditingHelper::StopEditingHelper(database &db, StopModel *m, QSpinBox *outTrackSpin, + QTimeEdit *arr, QTimeEdit *dep, QWidget *editor) : QObject(editor), mEditor(editor), model(m), mTimerOutTrack(0) { - stationsMatchModel = new StationsMatchModel(db, this); - stationTrackMatchModel = new StationTracksMatchModel(db, this); + stationsMatchModel = new StationsMatchModel(db, this); + stationTrackMatchModel = new StationTracksMatchModel(db, this); stationOutGateMatchModel = new StationGatesMatchModel(db, this); - mStationEdit = new CustomCompletionLineEdit(stationsMatchModel, mEditor); + mStationEdit = new CustomCompletionLineEdit(stationsMatchModel, mEditor); mStationEdit->setPlaceholderText(tr("Station name")); mStationEdit->setToolTip(mStationEdit->placeholderText()); - connect(mStationEdit, &CustomCompletionLineEdit::completionDone, this, &StopEditingHelper::onStationSelected); + connect(mStationEdit, &CustomCompletionLineEdit::completionDone, this, + &StopEditingHelper::onStationSelected); mStTrackEdit = new CustomCompletionLineEdit(stationTrackMatchModel, mEditor); mStTrackEdit->setPlaceholderText(tr("Track")); mStTrackEdit->setToolTip(mStTrackEdit->placeholderText()); - connect(mStTrackEdit, &CustomCompletionLineEdit::completionDone, this, &StopEditingHelper::onTrackSelected); + connect(mStTrackEdit, &CustomCompletionLineEdit::completionDone, this, + &StopEditingHelper::onTrackSelected); mOutGateEdit = new CustomCompletionLineEdit(stationOutGateMatchModel, mEditor); mOutGateEdit->setPlaceholderText(tr("Next segment")); mOutGateEdit->setToolTip(mOutGateEdit->placeholderText()); - connect(mOutGateEdit, &CustomCompletionLineEdit::indexSelected, this, &StopEditingHelper::onOutGateSelected); + connect(mOutGateEdit, &CustomCompletionLineEdit::indexSelected, this, + &StopEditingHelper::onOutGateSelected); mOutGateTrackSpin = outTrackSpin; mOutGateTrackSpin->setMaximum(0); mOutGateTrackSpin->setToolTip(tr("Out Gate track")); - connect(mOutGateTrackSpin, qOverload(&QSpinBox::valueChanged), this, &StopEditingHelper::startOutTrackTimer); - connect(mOutGateTrackSpin, &QSpinBox::editingFinished, this, &StopEditingHelper::checkOutGateTrack); + connect(mOutGateTrackSpin, qOverload(&QSpinBox::valueChanged), this, + &StopEditingHelper::startOutTrackTimer); + connect(mOutGateTrackSpin, &QSpinBox::editingFinished, this, + &StopEditingHelper::checkOutGateTrack); arrEdit = arr; depEdit = dep; - //Do not set tooltip on arrEdit, it is done inside setStop() already + // Do not set tooltip on arrEdit, it is done inside setStop() already depEdit->setToolTip(tr("Departure")); connect(arrEdit, &QTimeEdit::timeChanged, this, &StopEditingHelper::arrivalChanged); @@ -83,69 +87,70 @@ StopEditingHelper::~StopEditingHelper() void StopEditingHelper::setStop(const StopItem &item, const StopItem &prev) { - curStop = item; + curStop = item; prevStop = prev; - //Update match models + // Update match models stationsMatchModel->setFilter(prevStop.stationId); stationTrackMatchModel->setFilter(curStop.stationId); - stationOutGateMatchModel->setFilter(curStop.stationId, true, prevStop.nextSegment.segmentId, true); + stationOutGateMatchModel->setFilter(curStop.stationId, true, prevStop.nextSegment.segmentId, + true); - //Check Arrival and Departure + // Check Arrival and Departure QTime minArr, minDep; - if(curStop.type != StopType::First) + if (curStop.type != StopType::First) { - //First stop: arrival is hidden, you can change only departure so do not set a minimum + // First stop: arrival is hidden, you can change only departure so do not set a minimum - //Next stop must be at least one minute after previous (minimum travel duration) - //This is to prevent contemporary stops that will break ORDER BY arrival queries + // Next stop must be at least one minute after previous (minimum travel duration) + // This is to prevent contemporary stops that will break ORDER BY arrival queries minArr = prevStop.departure.addSecs(60); - //Normal stop: at least 1 minute stop - //Transit, Last: departure = arrival + // Normal stop: at least 1 minute stop + // Transit, Last: departure = arrival minDep = curStop.arrival; - if(curStop.type == StopType::Normal) + if (curStop.type == StopType::Normal) minDep = minDep.addSecs(60); - if(curStop.arrival < minArr) + if (curStop.arrival < minArr) curStop.arrival = minArr; - if(curStop.departure < minDep) + if (curStop.departure < minDep) curStop.arrival = minDep; } - //Show/Hide relevant fields for current stop + // Show/Hide relevant fields for current stop - //First stop has no Arrival, only Departure + // First stop has no Arrival, only Departure arrEdit->setEnabled(curStop.type != StopType::First); arrEdit->setVisible(curStop.type != StopType::First); - QString arrTootlip = tr("Arrival"); //No message by default - if(curStop.type == StopType::Normal) + QString arrTootlip = tr("Arrival"); // No message by default + if (curStop.type == StopType::Normal) { - arrTootlip.append('\n'); //Separate from usage tooltip + arrTootlip.append('\n'); // Separate from usage tooltip arrTootlip.append(tr("Press shift if you don't want to change also departure time.")); } arrEdit->setToolTip(arrTootlip); - //Transit and Last stop only have Arrival + // Transit and Last stop only have Arrival depEdit->setEnabled(curStop.type != StopType::Last && curStop.type != StopType::Transit); depEdit->setVisible(curStop.type != StopType::Last && curStop.type != StopType::Transit); - //Last stop has no Out Gate because there's no stop after last + // Last stop has no Out Gate because there's no stop after last mOutGateEdit->setVisible(curStop.type != StopType::Last); mOutGateTrackSpin->setVisible(curStop.type != StopType::Last); - //Enable track edit only if station is selected + // Enable track edit only if station is selected mStTrackEdit->setEnabled(curStop.stationId != 0); - //Update UI fields + // Update UI fields mStationEdit->setData(curStop.stationId); mStTrackEdit->setData(curStop.trackId); mOutGateEdit->setData(curStop.toGate.gateId); updateGateTrackSpin(curStop.toGate); - //Set Arrival and Departure + // Set Arrival and Departure arrEdit->blockSignals(true); arrEdit->setMinimumTime(minArr); arrEdit->setTime(curStop.arrival); @@ -159,39 +164,41 @@ void StopEditingHelper::setStop(const StopItem &item, const StopItem &prev) void StopEditingHelper::popupSegmentCombo() { - //Look for all possible segments + // Look for all possible segments stationOutGateMatchModel->autoSuggest(QString()); const int count = stationOutGateMatchModel->rowCount(); - if(count > 1 && !stationOutGateMatchModel->isEmptyRow(0) + if (count > 1 && !stationOutGateMatchModel->isEmptyRow(0) && (stationOutGateMatchModel->isEmptyRow(1) || stationOutGateMatchModel->isEllipsesRow(1))) { - //Only 1 segment available, use it - db_id newSegId = stationOutGateMatchModel->getSegmentIdAtRow(0); + // Only 1 segment available, use it + db_id newSegId = stationOutGateMatchModel->getSegmentIdAtRow(0); - db_id segOutGateId = 0; + db_id segOutGateId = 0; db_id suggestedTrackId = 0; - if(model->trySelectNextSegment(curStop, newSegId, 0, 0, segOutGateId, suggestedTrackId)) + if (model->trySelectNextSegment(curStop, newSegId, 0, 0, segOutGateId, suggestedTrackId)) { - //Success, close editor + // Success, close editor emit nextSegmentChosen(); return; } } - //We have multiple segments, let the user choose + // We have multiple segments, let the user choose mOutGateEdit->showPopup(); } QString StopEditingHelper::getGateString(db_id gateId, bool reversed) { QString str = QLatin1String(""); - if(gateId) + if (gateId) { str += stationOutGateMatchModel->getName(gateId); - if(reversed) + if (reversed) str += tr(" (reversed)"); - }else{ + } + else + { str += tr("Not set!"); } str.append(QLatin1String("")); @@ -200,7 +207,7 @@ QString StopEditingHelper::getGateString(db_id gateId, bool reversed) void StopEditingHelper::timerEvent(QTimerEvent *e) { - if(e->timerId() == mTimerOutTrack) + if (e->timerId() == mTimerOutTrack) { checkOutGateTrack(); return; @@ -213,32 +220,33 @@ void StopEditingHelper::onStationSelected() { db_id newStId = 0; QString tmp; - if(!mStationEdit->getData(newStId, tmp)) + if (!mStationEdit->getData(newStId, tmp)) return; - if(newStId == curStop.stationId) + if (newStId == curStop.stationId) return; curStop.stationId = newStId; - //Update track + // Update track stationTrackMatchModel->setFilter(curStop.stationId); - mStTrackEdit->setEnabled(curStop.stationId != 0); //Enable only if station is selected + mStTrackEdit->setEnabled(curStop.stationId != 0); // Enable only if station is selected - if(curStop.stationId) + if (curStop.stationId) { - if(!model->trySelectTrackForStop(curStop)) - curStop.trackId = 0; //Could not find a track + if (!model->trySelectTrackForStop(curStop)) + curStop.trackId = 0; // Could not find a track mStTrackEdit->setData(curStop.trackId); } - //Update prev segment - prevStop.nextSegment = StopItem::Segment{}; //Reset, will be reloaded by model + // Update prev segment + prevStop.nextSegment = StopItem::Segment{}; // Reset, will be reloaded by model - //Update next segment - stationOutGateMatchModel->setFilter(curStop.stationId, true, prevStop.nextSegment.segmentId, true); - mOutGateEdit->setData(0); //Reset, user must choose again + // Update next segment + stationOutGateMatchModel->setFilter(curStop.stationId, true, prevStop.nextSegment.segmentId, + true); + mOutGateEdit->setData(0); // Reset, user must choose again curStop.nextSegment = StopItem::Segment{}; @@ -249,19 +257,19 @@ void StopEditingHelper::onTrackSelected() { db_id newTrackId = 0; QString str; - if(!mStTrackEdit->getData(newTrackId, str)) + if (!mStTrackEdit->getData(newTrackId, str)) return; str.clear(); - //Check if track is connected to gates - if(!model->trySetTrackConnections(curStop, newTrackId, &str)) + // Check if track is connected to gates + if (!model->trySetTrackConnections(curStop, newTrackId, &str)) { - //Show error to the user + // Show error to the user bool stillSucceded = (curStop.trackId == newTrackId); QMessageBox::warning(mEditor, stillSucceded ? tr("Gate Warning") : tr("Track Error"), str); - if(!stillSucceded) - mStTrackEdit->setData(curStop.trackId); //Reset to previous track + if (!stillSucceded) + mStTrackEdit->setData(curStop.trackId); // Reset to previous track } emit stationTrackChosen(); @@ -271,25 +279,26 @@ void StopEditingHelper::onOutGateSelected(const QModelIndex &idx) { db_id newGateId = 0; QString gateSegmentName; - if(!mOutGateEdit->getData(newGateId, gateSegmentName)) + if (!mOutGateEdit->getData(newGateId, gateSegmentName)) return; - const db_id newSegId = stationOutGateMatchModel->getSegmentIdAtRow(idx.row()); - const db_id oldGateId = curStop.toGate.gateId; - db_id segOutGateId = 0; + const db_id newSegId = stationOutGateMatchModel->getSegmentIdAtRow(idx.row()); + const db_id oldGateId = curStop.toGate.gateId; + db_id segOutGateId = 0; db_id suggestedTrackId = 0; - if(model->trySelectNextSegment(curStop, newSegId, 0, 0, segOutGateId, suggestedTrackId)) + if (model->trySelectNextSegment(curStop, newSegId, 0, 0, segOutGateId, suggestedTrackId)) { - //Update gate track + // Update gate track updateGateTrackSpin(curStop.toGate); - //Success, close editor + // Success, close editor emit nextSegmentChosen(); } else { - //Warn user and reset to previous chosen segment if any - QMessageBox::warning(mEditor, tr("Stop Error"), tr("Cannot set segment %1").arg(gateSegmentName)); + // Warn user and reset to previous chosen segment if any + QMessageBox::warning(mEditor, tr("Stop Error"), + tr("Cannot set segment %1").arg(gateSegmentName)); mOutGateEdit->setData(oldGateId); } } @@ -298,38 +307,40 @@ void StopEditingHelper::checkOutGateTrack() { stopOutTrackTimer(); - if(!curStop.nextSegment.segmentId) - return; //First we need to have a segment + if (!curStop.nextSegment.segmentId) + return; // First we need to have a segment - int trackNum = mOutGateTrackSpin->value(); - curStop.toGate.gateTrackNum = trackNum; //Trigger checking of railway segment connections + int trackNum = mOutGateTrackSpin->value(); + curStop.toGate.gateTrackNum = trackNum; // Trigger checking of railway segment connections - db_id segOutGateId = 0; - db_id suggestedTrackId = 0; - if(model->trySelectNextSegment(curStop, curStop.nextSegment.segmentId, trackNum, 0, segOutGateId, suggestedTrackId)) + db_id segOutGateId = 0; + db_id suggestedTrackId = 0; + if (model->trySelectNextSegment(curStop, curStop.nextSegment.segmentId, trackNum, 0, + segOutGateId, suggestedTrackId)) { - //Update gate track + // Update gate track updateGateTrackSpin(curStop.toGate); - if(curStop.toGate.gateTrackNum != trackNum) + if (curStop.toGate.gateTrackNum != trackNum) { - //It wasn't possible to set requested track - QMessageBox::warning(mEditor, tr("Stop Error"), - tr("Requested gate out track %1 is not connected to segment %2.
" - "Out track %3 was chosen instead.
" - "Look segment track connection from Stations Manager for more information" - " on available tracks.") - .arg(trackNum) - .arg(mOutGateEdit->text()) - .arg(curStop.toGate.gateTrackNum)); + // It wasn't possible to set requested track + QMessageBox::warning( + mEditor, tr("Stop Error"), + tr("Requested gate out track %1 is not connected to segment %2.
" + "Out track %3 was chosen instead.
" + "Look segment track connection from Stations Manager for more information" + " on available tracks.") + .arg(trackNum) + .arg(mOutGateEdit->text()) + .arg(curStop.toGate.gateTrackNum)); } - //Success, close editor + // Success, close editor emit nextSegmentChosen(); } else { - //Warn user and reset to previous chosen segment if any + // Warn user and reset to previous chosen segment if any QMessageBox::warning(mEditor, tr("Stop Error"), tr("Cannot set segment track!")); } } @@ -337,26 +348,26 @@ void StopEditingHelper::checkOutGateTrack() void StopEditingHelper::arrivalChanged(const QTime &arrival) { bool shiftPressed = QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier); - QTime dep = depEdit->time(); - if(!shiftPressed) + QTime dep = depEdit->time(); + if (!shiftPressed) { - //Shift departure by the same amount if SHIFT NOT pressed + // Shift departure by the same amount if SHIFT NOT pressed int diff = curStop.arrival.msecsTo(arrival); - dep = dep.addMSecs(diff); + dep = dep.addMSecs(diff); } QTime minDep = arrival; - if(curStop.type == StopType::Normal) + if (curStop.type == StopType::Normal) { - minDep = arrival.addSecs(60); //At least stop for 1 minute in Normal stops + minDep = arrival.addSecs(60); // At least stop for 1 minute in Normal stops } depEdit->blockSignals(true); - depEdit->setMinimumTime(minDep); //Set minimum before setting value + depEdit->setMinimumTime(minDep); // Set minimum before setting value depEdit->setTime(dep); depEdit->blockSignals(false); - //Reset diff to 0 for next call - curStop.arrival = arrival; + // Reset diff to 0 for next call + curStop.arrival = arrival; curStop.departure = dep; } @@ -367,16 +378,16 @@ void StopEditingHelper::departureChanged(const QTime &dep) void StopEditingHelper::startOutTrackTimer() { - //Give user a small time to scroll values in out gate track QSpinBox - //This will skip eventual non available tracks (not connected) - //On timeout check track and reset to old value if not available + // Give user a small time to scroll values in out gate track QSpinBox + // This will skip eventual non available tracks (not connected) + // On timeout check track and reset to old value if not available stopOutTrackTimer(); mTimerOutTrack = startTimer(700); } void StopEditingHelper::stopOutTrackTimer() { - if(mTimerOutTrack) + if (mTimerOutTrack) { killTimer(mTimerOutTrack); mTimerOutTrack = 0; @@ -388,12 +399,12 @@ void StopEditingHelper::updateGateTrackSpin(const StopItem::Gate &toGate) stopOutTrackTimer(); int outTrackCount = 0; - if(toGate.gateId) + if (toGate.gateId) outTrackCount = stationOutGateMatchModel->getGateTrackCount(toGate.gateId); - //Prevent trigger valueChanged() signal + // Prevent trigger valueChanged() signal mOutGateTrackSpin->blockSignals(true); - mOutGateTrackSpin->setMaximum(qMax(0, outTrackCount - 1)); //At least one track numbered 0 + mOutGateTrackSpin->setMaximum(qMax(0, outTrackCount - 1)); // At least one track numbered 0 mOutGateTrackSpin->setValue(toGate.gateTrackNum); mOutGateTrackSpin->blockSignals(false); } diff --git a/src/jobs/jobeditor/stopeditinghelper.h b/src/jobs/jobeditor/stopeditinghelper.h index f04cc7c..499512c 100644 --- a/src/jobs/jobeditor/stopeditinghelper.h +++ b/src/jobs/jobeditor/stopeditinghelper.h @@ -43,23 +43,37 @@ class StopEditingHelper : public QObject { Q_OBJECT public: - StopEditingHelper(sqlite3pp::database &db, StopModel *m, - QSpinBox *outTrackSpin, QTimeEdit *arr, QTimeEdit *dep, - QWidget *editor = nullptr); + StopEditingHelper(sqlite3pp::database &db, StopModel *m, QSpinBox *outTrackSpin, QTimeEdit *arr, + QTimeEdit *dep, QWidget *editor = nullptr); ~StopEditingHelper(); - void setStop(const StopItem& item, const StopItem& prev); + void setStop(const StopItem &item, const StopItem &prev); void popupSegmentCombo(); QString getGateString(db_id gateId, bool reversed); - inline CustomCompletionLineEdit *getStationEdit() const { return mStationEdit; } - inline CustomCompletionLineEdit *getStTrackEdit() const { return mStTrackEdit; } - inline CustomCompletionLineEdit *getOutGateEdit() const { return mOutGateEdit; } + inline CustomCompletionLineEdit *getStationEdit() const + { + return mStationEdit; + } + inline CustomCompletionLineEdit *getStTrackEdit() const + { + return mStTrackEdit; + } + inline CustomCompletionLineEdit *getOutGateEdit() const + { + return mOutGateEdit; + } - inline const StopItem& getCurItem() const { return curStop; } - inline const StopItem& getPrevItem() const { return prevStop; } + inline const StopItem &getCurItem() const + { + return curStop; + } + inline const StopItem &getPrevItem() const + { + return prevStop; + } protected: void timerEvent(QTimerEvent *e) override; @@ -82,7 +96,7 @@ public slots: void stopOutTrackTimer(); private: - void updateGateTrackSpin(const StopItem::Gate& toGate); + void updateGateTrackSpin(const StopItem::Gate &toGate); private: QWidget *mEditor; diff --git a/src/jobs/jobeditor/stopeditor.cpp b/src/jobs/jobeditor/stopeditor.cpp index 0149d5a..7a871ed 100644 --- a/src/jobs/jobeditor/stopeditor.cpp +++ b/src/jobs/jobeditor/stopeditor.cpp @@ -27,19 +27,17 @@ #include #include - StopEditor::StopEditor(sqlite3pp::database &db, StopModel *m, QWidget *parent) : QFrame(parent), m_closeOnSegmentChosen(false) { mOutGateTrackSpin = new QSpinBox; - arrEdit = new QTimeEdit; - depEdit = new QTimeEdit; + arrEdit = new QTimeEdit; + depEdit = new QTimeEdit; - helper = new StopEditingHelper(db, m, - mOutGateTrackSpin, arrEdit, depEdit, - this); - connect(helper, &StopEditingHelper::nextSegmentChosen, this, &StopEditor::onHelperSegmentChoosen); + helper = new StopEditingHelper(db, m, mOutGateTrackSpin, arrEdit, depEdit, this); + connect(helper, &StopEditingHelper::nextSegmentChosen, this, + &StopEditor::onHelperSegmentChoosen); #ifdef PRINT_DBG_MSG setObjectName(QStringLiteral("StopEditor (%1)").arg(qintptr(this))); @@ -51,7 +49,7 @@ StopEditor::StopEditor(sqlite3pp::database &db, StopModel *m, QWidget *parent) : CustomCompletionLineEdit *mStTrackEdit = helper->getStTrackEdit(); CustomCompletionLineEdit *mOutGateEdit = helper->getOutGateEdit(); - lay = new QGridLayout(this); + lay = new QGridLayout(this); lay->addWidget(mStationEdit, 0, 0); lay->addWidget(arrEdit, 0, 1); lay->addWidget(depEdit, 0, 2); @@ -63,7 +61,8 @@ StopEditor::StopEditor(sqlite3pp::database &db, StopModel *m, QWidget *parent) : setTabOrder(arrEdit, depEdit); setTabOrder(depEdit, mOutGateEdit); - setToolTip(tr("To avoid recalculation of travel times when saving changes, hold SHIFT modifier while closing editor")); + setToolTip(tr("To avoid recalculation of travel times when saving changes, hold SHIFT modifier " + "while closing editor")); } StopEditor::~StopEditor() @@ -76,7 +75,7 @@ void StopEditor::setStop(const StopItem &item, const StopItem &prev) { helper->setStop(item, prev); - if(item.stationId == 0) + if (item.stationId == 0) setFocusProxy(helper->getStationEdit()); } @@ -97,21 +96,21 @@ void StopEditor::setCloseOnSegmentChosen(bool value) void StopEditor::popupSegmentCombo() { - //This code is used when adding a new stop. - //When user clicks on 'AddHere' a new stop is added - //but before editing it, user must choose the railway segment - //that the job will take from former Last Stop. + // This code is used when adding a new stop. + // When user clicks on 'AddHere' a new stop is added + // but before editing it, user must choose the railway segment + // that the job will take from former Last Stop. //(It was Last Stop before we added this stop, so it didn't have a 'next segment') - //1 - We popup lines combo from former last stop - //2 - When user chooses a line we close the editor (emit lineChosen()) - //3 - We edit edit new Last Stop (EditNextItem) + // 1 - We popup lines combo from former last stop + // 2 - When user chooses a line we close the editor (emit lineChosen()) + // 3 - We edit edit new Last Stop (EditNextItem) setCloseOnSegmentChosen(true); helper->popupSegmentCombo(); } void StopEditor::onHelperSegmentChoosen() { - //Forward signal and pass self instance + // Forward signal and pass self instance emit nextSegmentChosen(this); } diff --git a/src/jobs/jobeditor/stopeditor.h b/src/jobs/jobeditor/stopeditor.h index 1759066..600dc68 100644 --- a/src/jobs/jobeditor/stopeditor.h +++ b/src/jobs/jobeditor/stopeditor.h @@ -49,16 +49,19 @@ public: StopEditor(sqlite3pp::database &db, StopModel *m, QWidget *parent = nullptr); ~StopEditor(); - void setStop(const StopItem& item, const StopItem& prev); + void setStop(const StopItem &item, const StopItem &prev); - const StopItem& getCurItem() const; - const StopItem& getPrevItem() const; + const StopItem &getCurItem() const; + const StopItem &getPrevItem() const; /*! * \brief closeOnSegmentChosen * \return true if editor should be closed after user has chosen a valid next segment */ - inline bool closeOnSegmentChosen() const { return m_closeOnSegmentChosen; }; + inline bool closeOnSegmentChosen() const + { + return m_closeOnSegmentChosen; + }; void setCloseOnSegmentChosen(bool value); signals: diff --git a/src/jobs/jobs_checker/crossing/job_crossing_data.cpp b/src/jobs/jobs_checker/crossing/job_crossing_data.cpp index 37370cc..76cdbe5 100644 --- a/src/jobs/jobs_checker/crossing/job_crossing_data.cpp +++ b/src/jobs/jobs_checker/crossing/job_crossing_data.cpp @@ -21,78 +21,74 @@ JobCrossingErrorMap::JobCrossingErrorMap() { - } void JobCrossingErrorMap::removeJob(db_id jobId) { auto job = map.find(jobId); - if(job == map.end()) - return; //Not contained in map + if (job == map.end()) + return; // Not contained in map - //Remove all errors referencing to us - for(const JobCrossingErrorData& err : qAsConst(job->errors)) + // Remove all errors referencing to us + for (const JobCrossingErrorData &err : qAsConst(job->errors)) { auto otherJob = map.find(err.otherJob.jobId); - if(otherJob == map.end()) - continue; //Maybe already remove, skip + if (otherJob == map.end()) + continue; // Maybe already remove, skip - //Remove all errors regarding job in otherJob - std::remove_if(otherJob->errors.begin(), - otherJob->errors.end(), - [jobId](const JobCrossingErrorData& otherErr) -> bool - { - return otherErr.otherJob.jobId == jobId; - }); + // Remove all errors regarding job in otherJob + std::remove_if(otherJob->errors.begin(), otherJob->errors.end(), + [jobId](const JobCrossingErrorData &otherErr) -> bool + { return otherErr.otherJob.jobId == jobId; }); - if(otherJob->errors.isEmpty()) + if (otherJob->errors.isEmpty()) { - //otherJob has no errors, remove it + // otherJob has no errors, remove it map.erase(otherJob); } } - //Remove job + // Remove job map.erase(job); } void JobCrossingErrorMap::renameJob(db_id newJobId, db_id oldJobId) { auto job = map.find(oldJobId); - if(job == map.end()) - return; //Not contained in map + if (job == map.end()) + return; // Not contained in map - //Uodate all errors referencing to us - for(const JobCrossingErrorData& err : qAsConst(job->errors)) + // Uodate all errors referencing to us + for (const JobCrossingErrorData &err : qAsConst(job->errors)) { auto otherJob = map.find(err.otherJob.jobId); - if(otherJob == map.end()) - continue; //Maybe already remove, skip + if (otherJob == map.end()) + continue; // Maybe already remove, skip - for(JobCrossingErrorData& otherErr : otherJob->errors) + for (JobCrossingErrorData &otherErr : otherJob->errors) { - if(otherErr.otherJob.jobId == oldJobId) + if (otherErr.otherJob.jobId == oldJobId) { otherErr.otherJob.jobId = newJobId; } } } - //Update job - auto errList = map.take(oldJobId); + // Update job + auto errList = map.take(oldJobId); errList.job.jobId = newJobId; map.insert(newJobId, errList); } void JobCrossingErrorMap::merge(const ErrorMap &results) { - for(const JobCrossingErrorList& list : results) + for (const JobCrossingErrorList &list : results) { - //First clear Job + // First clear Job removeJob(list.job.jobId); - //Then add new errors if not empty (already duplicated) - if(!list.errors.isEmpty()) + // Then add new errors if not empty (already duplicated) + if (!list.errors.isEmpty()) map.insert(list.job.jobId, list); } } diff --git a/src/jobs/jobs_checker/crossing/job_crossing_data.h b/src/jobs/jobs_checker/crossing/job_crossing_data.h index cff5ddc..d98b128 100644 --- a/src/jobs/jobs_checker/crossing/job_crossing_data.h +++ b/src/jobs/jobs_checker/crossing/job_crossing_data.h @@ -22,16 +22,16 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include -#include +# include +# include -#include "utils/types.h" +# include "utils/types.h" struct JobCrossingErrorData { - db_id jobId = 0; + db_id jobId = 0; - db_id stopId = 0; + db_id stopId = 0; db_id stationId = 0; JobStopEntry otherJob; @@ -44,7 +44,8 @@ struct JobCrossingErrorData enum Type { NoError = 0, - JobCrossing, //NOTE: arrival refers to next job stop so it comes after departure (same for otherArr/Dep) + JobCrossing, // NOTE: arrival refers to next job stop so it comes after departure (same for + // otherArr/Dep) JobPassing }; @@ -56,8 +57,14 @@ struct JobCrossingErrorList JobEntry job; QVector errors; - inline int childCount() const { return errors.size(); } - inline const JobCrossingErrorData *ptrForRow(int row) const { return &errors.at(row); } + inline int childCount() const + { + return errors.size(); + } + inline const JobCrossingErrorData *ptrForRow(int row) const + { + return &errors.at(row); + } }; /*! @@ -74,11 +81,14 @@ public: JobCrossingErrorMap(); - inline int topLevelCount() const { return map.size(); } + inline int topLevelCount() const + { + return map.size(); + } inline const JobCrossingErrorList *getTopLevelAtRow(int row) const { - if(row >= topLevelCount()) + if (row >= topLevelCount()) return nullptr; return &(map.constBegin() + row).value(); } @@ -86,7 +96,7 @@ public: inline const JobCrossingErrorList *getParent(JobCrossingErrorData *child) const { auto it = map.constFind(child->jobId); - if(it == map.constEnd()) + if (it == map.constEnd()) return nullptr; return &it.value(); } @@ -94,7 +104,7 @@ public: inline int getParentRow(JobCrossingErrorData *child) const { auto it = map.constFind(child->jobId); - if(it == map.constEnd()) + if (it == map.constEnd()) return -1; return std::distance(map.constBegin(), it); } @@ -103,7 +113,7 @@ public: void renameJob(db_id newJobId, db_id oldJobId); - void merge(const ErrorMap& results); + void merge(const ErrorMap &results); public: ErrorMap map; diff --git a/src/jobs/jobs_checker/crossing/jobcrossingchecker.cpp b/src/jobs/jobs_checker/crossing/jobcrossingchecker.cpp index f3928ba..45d6b17 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingchecker.cpp +++ b/src/jobs/jobs_checker/crossing/jobcrossingchecker.cpp @@ -19,22 +19,22 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "jobcrossingchecker.h" +# include "jobcrossingchecker.h" -#include "jobcrossingtask.h" -#include "jobcrossingmodel.h" +# include "jobcrossingtask.h" +# include "jobcrossingmodel.h" -#include "app/session.h" -#include "viewmanager/viewmanager.h" +# include "app/session.h" +# include "viewmanager/viewmanager.h" -#include "utils/owningqpointer.h" -#include +# include "utils/owningqpointer.h" +# include JobCrossingChecker::JobCrossingChecker(sqlite3pp::database &db, QObject *parent) : IBackgroundChecker(db, parent), mDb(db) { - eventType = int(JobCrossingResultEvent::_Type); + eventType = int(JobCrossingResultEvent::_Type); errorsModel = new JobCrossingModel(this); connect(Session, &MeetingSession::jobChanged, this, &JobCrossingChecker::onJobChanged); @@ -51,36 +51,37 @@ void JobCrossingChecker::clearModel() static_cast(errorsModel)->clear(); } -void JobCrossingChecker::showContextMenu(QWidget *panel, const QPoint &pos, const QModelIndex &idx) const +void JobCrossingChecker::showContextMenu(QWidget *panel, const QPoint &pos, + const QModelIndex &idx) const { const JobCrossingModel *model = static_cast(errorsModel); - auto item = model->getItem(idx); - if(!item) + auto item = model->getItem(idx); + if (!item) return; OwningQPointer menu = new QMenu(panel); - QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); - QAction *showInGraph = new QAction(tr("Show in graph"), menu); + QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); + QAction *showInGraph = new QAction(tr("Show in graph"), menu); menu->addAction(showInJobEditor); menu->addAction(showInGraph); QAction *act = menu->exec(pos); - if(act == showInJobEditor) + if (act == showInJobEditor) { Session->getViewManager()->requestJobEditor(item->jobId, item->stopId); } - else if(act == showInGraph) + else if (act == showInGraph) { - //TODO: pass stopId + // TODO: pass stopId Session->getViewManager()->requestJobSelection(item->jobId, true, true); } } void JobCrossingChecker::sessionLoadedHandler() { - if(AppSettings.getCheckCrossingWhenOpeningDB()) + if (AppSettings.getCheckCrossingWhenOpeningDB()) startWorker(); } @@ -92,8 +93,8 @@ IQuittableTask *JobCrossingChecker::createMainWorker() void JobCrossingChecker::setErrors(QEvent *e, bool merge) { auto model = static_cast(errorsModel); - auto ev = static_cast(e); - if(merge) + auto ev = static_cast(e); + if (merge) model->mergeErrors(ev->results); else model->setErrors(ev->results); @@ -104,8 +105,8 @@ void JobCrossingChecker::onJobChanged(db_id newJobId, db_id oldJobId) auto model = static_cast(errorsModel); model->renameJob(oldJobId, newJobId); - //After renaming check job - if(AppSettings.getCheckCrossingOnJobEdit()) + // After renaming check job + if (AppSettings.getCheckCrossingOnJobEdit()) startWorker(); } diff --git a/src/jobs/jobs_checker/crossing/jobcrossingchecker.h b/src/jobs/jobs_checker/crossing/jobcrossingchecker.h index ef67b52..1e93596 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingchecker.h +++ b/src/jobs/jobs_checker/crossing/jobcrossingchecker.h @@ -22,9 +22,9 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "backgroundmanager/ibackgroundchecker.h" +# include "backgroundmanager/ibackgroundchecker.h" -#include "utils/types.h" +# include "utils/types.h" class JobCrossingChecker : public IBackgroundChecker { @@ -34,7 +34,7 @@ public: QString getName() const override; void clearModel() override; - void showContextMenu(QWidget *panel, const QPoint& pos, const QModelIndex& idx) const override; + void showContextMenu(QWidget *panel, const QPoint &pos, const QModelIndex &idx) const override; void sessionLoadedHandler() override; diff --git a/src/jobs/jobs_checker/crossing/jobcrossingmodel.cpp b/src/jobs/jobs_checker/crossing/jobcrossingmodel.cpp index 7e23b06..670950f 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingmodel.cpp +++ b/src/jobs/jobs_checker/crossing/jobcrossingmodel.cpp @@ -21,25 +21,23 @@ #include "utils/jobcategorystrings.h" -static const char* error_texts[] = { - nullptr, - QT_TRANSLATE_NOOP("JobErrors", "Job crosses another Job on same track."), - QT_TRANSLATE_NOOP("JobErrors", "Job passes another Job on same track.") -}; +static const char *error_texts[] = { + nullptr, QT_TRANSLATE_NOOP("JobErrors", "Job crosses another Job on same track."), + QT_TRANSLATE_NOOP("JobErrors", "Job passes another Job on same track.")}; class JobErrors { Q_DECLARE_TR_FUNCTIONS(JobErrors) }; -JobCrossingModel::JobCrossingModel(QObject *parent) : JobCrossingModelBase(parent) +JobCrossingModel::JobCrossingModel(QObject *parent) : + JobCrossingModelBase(parent) { - } QVariant JobCrossingModel::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) { @@ -63,11 +61,11 @@ QVariant JobCrossingModel::headerData(int section, Qt::Orientation orientation, QVariant JobCrossingModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid() || role != Qt::DisplayRole) + if (!idx.isValid() || role != Qt::DisplayRole) return QVariant(); const JobCrossingErrorData *item = getItem(idx); - if(item) + if (item) { switch (idx.column()) { @@ -87,8 +85,8 @@ QVariant JobCrossingModel::data(const QModelIndex &idx, int role) const } else { - //Caption - if(idx.row() >= m_data.topLevelCount() || idx.column() != 0) + // Caption + if (idx.row() >= m_data.topLevelCount() || idx.column() != 0) return QVariant(); auto topLevel = m_data.getTopLevelAtRow(idx.row()); @@ -135,5 +133,4 @@ void JobCrossingModel::renameJob(db_id newJobId, db_id oldJobId) void JobCrossingModel::renameStation(db_id stationId, const QString &name) { - } diff --git a/src/jobs/jobs_checker/crossing/jobcrossingmodel.h b/src/jobs/jobs_checker/crossing/jobcrossingmodel.h index 6e6a5e4..49d1e82 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingmodel.h +++ b/src/jobs/jobs_checker/crossing/jobcrossingmodel.h @@ -22,14 +22,15 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "utils/singledepthtreemodelhelper.h" +# include "utils/singledepthtreemodelhelper.h" -#include "job_crossing_data.h" +# include "job_crossing_data.h" class JobCrossingModel; -typedef SingleDepthTreeModelHelper JobCrossingModelBase; +typedef SingleDepthTreeModelHelper + JobCrossingModelBase; -//TODO: make on-demand +// TODO: make on-demand class JobCrossingModel : public JobCrossingModelBase { Q_OBJECT @@ -48,7 +49,8 @@ public: JobCrossingModel(QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; @@ -62,7 +64,7 @@ public: void renameJob(db_id newJobId, db_id oldJobId); - void renameStation(db_id stationId, const QString& name); + void renameStation(db_id stationId, const QString &name); }; #endif // ENABLE_BACKGROUND_MANAGER diff --git a/src/jobs/jobs_checker/crossing/jobcrossingtask.cpp b/src/jobs/jobs_checker/crossing/jobcrossingtask.cpp index 38c2b6b..c1456da 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingtask.cpp +++ b/src/jobs/jobs_checker/crossing/jobcrossingtask.cpp @@ -22,41 +22,42 @@ #include using namespace sqlite3pp; -inline bool fillCrossingErrorData(query::rows& job, JobCrossingErrorData& err, bool first, JobCategory &outCat) +inline bool fillCrossingErrorData(query::rows &job, JobCrossingErrorData &err, bool first, + JobCategory &outCat) { - err.stopId = job.get(0); - err.otherJob.stopId = job.get(1); - err.jobId = job.get(2); - outCat = JobCategory(job.get(3)); - err.otherJob.jobId = job.get(4); + err.stopId = job.get(0); + err.otherJob.stopId = job.get(1); + err.jobId = job.get(2); + outCat = JobCategory(job.get(3)); + err.otherJob.jobId = job.get(4); err.otherJob.category = JobCategory(job.get(5)); - err.departure = job.get(6); - err.arrival = job.get(7); - err.otherDep = job.get(8); - err.otherArr = job.get(9); - bool passing = job.get(10) == 1; - err.stationId = job.get(11); - err.stationName = job.get(12); + err.departure = job.get(6); + err.arrival = job.get(7); + err.otherDep = job.get(8); + err.otherArr = job.get(9); + bool passing = job.get(10) == 1; + err.stationId = job.get(11); + err.stationName = job.get(12); - if(passing) + if (passing) { - //In passings: - //job A starts before B but gets passed and ends after B - //job B starts after A but ends before - //B travel period is contained in A travel period + // In passings: + // job A starts before B but gets passed and ends after B + // job B starts after A but ends before + // B travel period is contained in A travel period - //We need stricter checking of time, one travel must be contained in the other - if(err.departure < err.otherDep && err.arrival < err.otherArr) - return false; //A travels before B, no passing - if(err.departure > err.otherDep && err.arrival > err.otherArr) - return false; //A travels after B, no passing + // We need stricter checking of time, one travel must be contained in the other + if (err.departure < err.otherDep && err.arrival < err.otherArr) + return false; // A travels before B, no passing + if (err.departure > err.otherDep && err.arrival > err.otherArr) + return false; // A travels after B, no passing } err.type = passing ? JobCrossingErrorData::JobPassing : JobCrossingErrorData::JobCrossing; - if(!first) + if (!first) { - //Swap points of view + // Swap points of view qSwap(err.jobId, err.otherJob.jobId); qSwap(outCat, err.otherJob.category); qSwap(err.stopId, err.otherJob.stopId); @@ -67,43 +68,45 @@ inline bool fillCrossingErrorData(query::rows& job, JobCrossingErrorData& err, b return true; } -JobCrossingResultEvent::JobCrossingResultEvent(JobCrossingTask *worker, const JobCrossingErrorMap::ErrorMap &data, bool merge) : +JobCrossingResultEvent::JobCrossingResultEvent(JobCrossingTask *worker, + const JobCrossingErrorMap::ErrorMap &data, + bool merge) : GenericTaskEvent(_Type, worker), results(data), mergeErrors(merge) { - } -JobCrossingTask::JobCrossingTask(sqlite3pp::database &db, QObject *receiver, const QVector& jobs) : +JobCrossingTask::JobCrossingTask(sqlite3pp::database &db, QObject *receiver, + const QVector &jobs) : IQuittableTask(receiver), mDb(db), jobsToCheck(jobs) { - } void JobCrossingTask::run() { - //TODO: allow checking a single job + // TODO: allow checking a single job - //Look for passing or crossings on same segment - query q(mDb, "SELECT s1.id, s2.id, s1.job_id, j1.category, s2.job_id, j2.category," - "s1.departure, MIN(s1_next.arrival)," - "s2.departure, MIN(s2_next.arrival)," - "g1.gate_id=g2.gate_id," //1 = passing, 0 = crossing (opposite direction) - "s1.station_id, stations.name" - " FROM stops s1" - " JOIN stops s1_next ON s1_next.job_id=s1.job_id AND s1_next.arrival>s1.arrival" - " JOIN stops s2 ON s2.next_segment_conn_id=s1.next_segment_conn_id AND s2.id<>s1.id" - " JOIN stops s2_next ON s2_next.job_id=s2.job_id AND s2_next.arrival>s2.arrival" - " JOIN jobs j1 ON j1.id=s1.job_id" - " JOIN jobs j2 ON j2.id=s2.job_id" - " JOIN station_gate_connections g1 ON g1.id=s1.out_gate_conn" - " JOIN station_gate_connections g2 ON g2.id=s2.out_gate_conn" - " JOIN stations ON stations.id=s1.station_id" - " GROUP BY s1.id,s2.id" - " HAVING s1.departure<=s2_next.arrival AND s1_next.arrival>=s2.departure"); + // Look for passing or crossings on same segment + query q(mDb, + "SELECT s1.id, s2.id, s1.job_id, j1.category, s2.job_id, j2.category," + "s1.departure, MIN(s1_next.arrival)," + "s2.departure, MIN(s2_next.arrival)," + "g1.gate_id=g2.gate_id," // 1 = passing, 0 = crossing (opposite direction) + "s1.station_id, stations.name" + " FROM stops s1" + " JOIN stops s1_next ON s1_next.job_id=s1.job_id AND s1_next.arrival>s1.arrival" + " JOIN stops s2 ON s2.next_segment_conn_id=s1.next_segment_conn_id AND s2.id<>s1.id" + " JOIN stops s2_next ON s2_next.job_id=s2.job_id AND s2_next.arrival>s2.arrival" + " JOIN jobs j1 ON j1.id=s1.job_id" + " JOIN jobs j2 ON j2.id=s2.job_id" + " JOIN station_gate_connections g1 ON g1.id=s1.out_gate_conn" + " JOIN station_gate_connections g2 ON g2.id=s2.out_gate_conn" + " JOIN stations ON stations.id=s1.station_id" + " GROUP BY s1.id,s2.id" + " HAVING s1.departure<=s2_next.arrival AND s1_next.arrival>=s2.departure"); QMap errorMap; checkCrossAndPassSegments(errorMap, q); @@ -147,25 +150,26 @@ void JobCrossingTask::run() // } } -void JobCrossingTask::checkCrossAndPassSegments(JobCrossingErrorMap::ErrorMap &errMap, sqlite3pp::query &q) +void JobCrossingTask::checkCrossAndPassSegments(JobCrossingErrorMap::ErrorMap &errMap, + sqlite3pp::query &q) { - for(auto job : q) + for (auto job : q) { JobCrossingErrorData err; JobCategory category = JobCategory::NCategories; - if(!fillCrossingErrorData(job, err, true, category)) + if (!fillCrossingErrorData(job, err, true, category)) continue; auto it = errMap.find(err.jobId); - if(it == errMap.end()) + if (it == errMap.end()) { - //Insert Job into map for first time + // Insert Job into map for first time JobCrossingErrorList list; - list.job.jobId = err.jobId; + list.job.jobId = err.jobId; list.job.category = category; - it = errMap.insert(list.job.jobId, list); + it = errMap.insert(list.job.jobId, list); } it.value().errors.append(err); diff --git a/src/jobs/jobs_checker/crossing/jobcrossingtask.h b/src/jobs/jobs_checker/crossing/jobcrossingtask.h index aa14f6f..12fa123 100644 --- a/src/jobs/jobs_checker/crossing/jobcrossingtask.h +++ b/src/jobs/jobs_checker/crossing/jobcrossingtask.h @@ -31,7 +31,7 @@ namespace sqlite3pp { class database; class query; -} +} // namespace sqlite3pp class JobCrossingTask; @@ -40,7 +40,8 @@ class JobCrossingResultEvent : public GenericTaskEvent public: static const Type _Type = Type(CustomEvents::JobsCrossingCheckResult); - JobCrossingResultEvent(JobCrossingTask *worker, const JobCrossingErrorMap::ErrorMap &data, bool merge); + JobCrossingResultEvent(JobCrossingTask *worker, const JobCrossingErrorMap::ErrorMap &data, + bool merge); QMap results; bool mergeErrors; @@ -49,11 +50,11 @@ public: class JobCrossingTask : public IQuittableTask { public: - JobCrossingTask(sqlite3pp::database &db, QObject *receiver, const QVector& jobs); + JobCrossingTask(sqlite3pp::database &db, QObject *receiver, const QVector &jobs); void run() override; - void checkCrossAndPassSegments(JobCrossingErrorMap::ErrorMap& errMap, sqlite3pp::query &q); + void checkCrossAndPassSegments(JobCrossingErrorMap::ErrorMap &errMap, sqlite3pp::query &q); private: sqlite3pp::database &mDb; diff --git a/src/jobs/jobsmanager/jobsmanager.cpp b/src/jobs/jobsmanager/jobsmanager.cpp index 2621fb0..b25810c 100644 --- a/src/jobs/jobsmanager/jobsmanager.cpp +++ b/src/jobs/jobsmanager/jobsmanager.cpp @@ -45,15 +45,17 @@ JobsManager::JobsManager(QWidget *parent) : QVBoxLayout *l = new QVBoxLayout(this); setMinimumSize(750, 300); - QToolBar *toolBar = new QToolBar(this); + QToolBar *toolBar = new QToolBar(this); QAction *actNewJob = toolBar->addAction(tr("New Job"), this, &JobsManager::onNewJob); - actRemoveJob = toolBar->addAction(tr("Remove"), this, &JobsManager::onRemove); - actNewJobSamePath = toolBar->addAction(tr("New Same Path"), this, &JobsManager::onNewJobSamePath); + actRemoveJob = toolBar->addAction(tr("Remove"), this, &JobsManager::onRemove); + actNewJobSamePath = + toolBar->addAction(tr("New Same Path"), this, &JobsManager::onNewJobSamePath); toolBar->addSeparator(); - actEditJob = toolBar->addAction(tr("Edit"), this, &JobsManager::onEditJob); + actEditJob = toolBar->addAction(tr("Edit"), this, &JobsManager::onEditJob); actShowJobInGraph = toolBar->addAction(tr("Show Graph"), this, &JobsManager::onShowJobGraph); toolBar->addSeparator(); - QAction *actRemoveAll = toolBar->addAction(tr("Remove All"), this, &JobsManager::onRemoveAllJobs); + QAction *actRemoveAll = + toolBar->addAction(tr("Remove All"), this, &JobsManager::onRemoveAllJobs); l->addWidget(toolBar); view = new QTableView; @@ -61,7 +63,7 @@ JobsManager::JobsManager(QWidget *parent) : connect(view, &QTableView::doubleClicked, this, &JobsManager::editJobAtRow); l->addWidget(view); - //Custom sorting and filtering + // Custom sorting and filtering FilterHeaderView *header = new FilterHeaderView(view); header->installOnTable(view); @@ -72,12 +74,13 @@ JobsManager::JobsManager(QWidget *parent) : l->addWidget(ps); ps->setModel(jobsModel); - connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, this, &JobsManager::onSelectionChanged); + connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &JobsManager::onSelectionChanged); connect(jobsModel, &QAbstractItemModel::modelReset, this, &JobsManager::onSelectionChanged); jobsModel->refreshData(); - //Action Tooltips + // Action Tooltips actNewJob->setToolTip(tr("Create new Job and open Job Editor")); actRemoveJob->setToolTip(tr("Delete selected Job")); actNewJobSamePath->setToolTip(tr("Create new Job with same path of selected one")); @@ -89,10 +92,10 @@ JobsManager::JobsManager(QWidget *parent) : setWindowTitle("Jobs Manager"); } -void JobsManager::editJobAtRow(const QModelIndex& idx) +void JobsManager::editJobAtRow(const QModelIndex &idx) { db_id jobId = jobsModel->getIdAtRow(idx.row()); - if(!jobId) + if (!jobId) return; Session->getViewManager()->requestJobEditor(jobId); } @@ -105,64 +108,65 @@ void JobsManager::onNewJob() void JobsManager::onRemove() { QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; - db_id jobId = jobsModel->getIdAtRow(idx.row()); + db_id jobId = jobsModel->getIdAtRow(idx.row()); JobCategory jobCat = jobsModel->getShiftAnCatAtRow(idx.row()).second; - QString jobName = JobCategoryName::jobName(jobId, jobCat); + QString jobName = JobCategoryName::jobName(jobId, jobCat); - int ret = QMessageBox::question(this, - tr("Job deletion"), - tr("Are you sure to delete job %1?").arg(jobName), - QMessageBox::Yes | QMessageBox::Cancel); - if(ret == QMessageBox::Yes) + int ret = QMessageBox::question(this, tr("Job deletion"), + tr("Are you sure to delete job %1?").arg(jobName), + QMessageBox::Yes | QMessageBox::Cancel); + if (ret == QMessageBox::Yes) { - if(!JobsHelper::removeJob(Session->m_Db, jobId)) + if (!JobsHelper::removeJob(Session->m_Db, jobId)) { - qWarning() << "Error while deleting job:" << jobId << "from JobManager" << Session->m_Db.error_msg(); - //ERRORMSG: message box or statusbar + qWarning() << "Error while deleting job:" << jobId << "from JobManager" + << Session->m_Db.error_msg(); + // ERRORMSG: message box or statusbar } } } void JobsManager::onRemoveAllJobs() { - int ret = QMessageBox::question(this, tr("Delete all jobs?"), - tr("Are you really sure you want to delete all jobs from this session?")); - if(ret == QMessageBox::Yes) + int ret = QMessageBox::question( + this, tr("Delete all jobs?"), + tr("Are you really sure you want to delete all jobs from this session?")); + if (ret == QMessageBox::Yes) JobsHelper::removeAllJobs(Session->m_Db); } void JobsManager::onNewJobSamePath() { QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; db_id jobId = jobsModel->getIdAtRow(idx.row()); - if(!jobId) + if (!jobId) return; - JobCategory jobCat = jobsModel->getShiftAnCatAtRow(idx.row()).second; - auto times = jobsModel->getOrigAndDestTimeAtRow(idx.row()); + JobCategory jobCat = jobsModel->getShiftAnCatAtRow(idx.row()).second; + auto times = jobsModel->getOrigAndDestTimeAtRow(idx.row()); OwningQPointer dlg = new NewJobSamePathDlg(this); dlg->setSourceJob(jobId, jobCat, times.first, times.second); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; const QTime newStart = dlg->getNewStartTime(); const int secsOffset = times.first.secsTo(newStart); - db_id newJobId = 0; - if(!JobsHelper::createNewJob(Session->m_Db, newJobId, jobCat)) + db_id newJobId = 0; + if (!JobsHelper::createNewJob(Session->m_Db, newJobId, jobCat)) return; - JobsHelper::copyStops(Session->m_Db, jobId, newJobId, secsOffset, - dlg->shouldCopyRs(), dlg->shouldReversePath()); + JobsHelper::copyStops(Session->m_Db, jobId, newJobId, secsOffset, dlg->shouldCopyRs(), + dlg->shouldReversePath()); - //Let user edit newly created job + // Let user edit newly created job Session->getViewManager()->requestJobEditor(newJobId); } @@ -174,16 +178,16 @@ void JobsManager::onEditJob() void JobsManager::onShowJobGraph() { QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; db_id jobId = jobsModel->getIdAtRow(idx.row()); - if(!jobId) + if (!jobId) return; Session->getViewManager()->requestJobSelection(jobId, true, true); - //Minimize JobsManager to make graph visible + // Minimize JobsManager to make graph visible showMinimized(); } diff --git a/src/jobs/jobsmanager/model/joblistmodel.cpp b/src/jobs/jobsmanager/model/joblistmodel.cpp index 23661a8..8d73801 100644 --- a/src/jobs/jobsmanager/model/joblistmodel.cpp +++ b/src/jobs/jobsmanager/model/joblistmodel.cpp @@ -46,9 +46,9 @@ JobListModel::JobListModel(sqlite3pp::database &db, QObject *parent) : QVariant JobListModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (section) { @@ -84,16 +84,16 @@ QVariant JobListModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const JobItem& item = cache.at(row - cacheFirstRow); + const JobItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -122,7 +122,7 @@ QVariant JobListModel::data(const QModelIndex &idx, int role) const } case Qt::TextAlignmentRole: { - if(idx.column() == IdCol) + if (idx.column() == IdCol) { return Qt::AlignVCenter + Qt::AlignRight; } @@ -135,14 +135,14 @@ QVariant JobListModel::data(const QModelIndex &idx, int role) const void JobListModel::setSortingColumn(int col) { - if(sortColumn == col || col == OriginSt || col == DestinationSt || col >= NCols) + if (sortColumn == col || col == OriginSt || col == DestinationSt || col >= NCols) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -167,8 +167,8 @@ bool JobListModel::setFilterAtCol(int col, const QString &str) { case IdCol: { - if(isNull) - return false; //Cannot have NULL Job ID + if (isNull) + return false; // Cannot have NULL Job ID m_jobIdFilter = str; break; } @@ -187,7 +187,7 @@ bool JobListModel::setFilterAtCol(int col, const QString &str) void JobListModel::onJobAddedOrRemoved() { - refreshData(); //Recalc row count + refreshData(); // Recalc row count } qint64 JobListModel::recalcTotalItemCount() @@ -203,7 +203,7 @@ qint64 JobListModel::recalcTotalItemCount() void JobListModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool fullData) { QByteArray sql; - if(fullData) + if (fullData) { sql = "SELECT jobs.id, jobs.category, jobs.shift_id, jobshifts.name," "MIN(s1.departure), s1.station_id, MAX(s2.arrival), s2.station_id" @@ -216,44 +216,44 @@ void JobListModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool sql = "SELECT COUNT(1) FROM jobs"; } - //If counting but filtering by shift name (not null) we need to JOIN jobshifts + // If counting but filtering by shift name (not null) we need to JOIN jobshifts bool shiftFilterIsNull = m_shiftFilter.startsWith(nullFilterStr, Qt::CaseInsensitive); - if(fullData || (!shiftFilterIsNull && !m_shiftFilter.isEmpty())) + if (fullData || (!shiftFilterIsNull && !m_shiftFilter.isEmpty())) sql += " LEFT JOIN jobshifts ON jobshifts.id=jobs.shift_id"; bool whereClauseAdded = false; - if(!m_jobIdFilter.isEmpty()) + if (!m_jobIdFilter.isEmpty()) { sql.append(" WHERE jobs.id LIKE ?3"); whereClauseAdded = true; } - if(!m_shiftFilter.isEmpty()) + if (!m_shiftFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); - if(shiftFilterIsNull) + if (shiftFilterIsNull) sql.append("jobs.shift_id IS NULL"); else sql.append("jobshifts.name LIKE ?4"); } - if(fullData) + if (fullData) { - //Group by Job + // Group by Job sql.append(" GROUP BY jobs.id"); - //Apply sorting + // Apply sorting const char *sortColExpr = nullptr; switch (sortCol) { case IdCol: { - sortColExpr = "jobs.id"; //Order by 1 column, no where clause + sortColExpr = "jobs.id"; // Order by 1 column, no where clause break; } case Category: @@ -282,23 +282,23 @@ void JobListModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool sql += sortColExpr; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; } q.prepare(sql); - if(fullData) + if (fullData) { - //Apply offset and batch size + // Apply offset and batch size q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); } - //Apply filters + // Apply filters QByteArray jobFilter; - if(!m_jobIdFilter.isEmpty()) + if (!m_jobIdFilter.isEmpty()) { jobFilter.reserve(m_jobIdFilter.size() + 2); jobFilter.append('%'); @@ -308,7 +308,7 @@ void JobListModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool } QByteArray shiftFilter; - if(!m_shiftFilter.isEmpty() && !shiftFilterIsNull) + if (!m_shiftFilter.isEmpty() && !shiftFilterIsNull) { shiftFilter.reserve(m_shiftFilter.size() + 2); shiftFilter.append('%'); @@ -318,7 +318,7 @@ void JobListModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool } } -void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant &/*val*/) +void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant & /*val*/) { query q(mDb); @@ -331,29 +331,29 @@ void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const Q QVector vec(BatchSize); - //QString are implicitly shared, use QHash to temporary store them instead - //of creating new ones for each JobItem + // QString are implicitly shared, use QHash to temporary store them instead + // of creating new ones for each JobItem QHash shiftHash; QHash stationHash; - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = 0; + int i = 0; const int increment = 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; + auto r = *it; JobItem &item = vec[i]; - item.jobId = r.get(0); + item.jobId = r.get(0); item.category = JobCategory(r.get(1)); - item.shiftId = r.get(2); + item.shiftId = r.get(2); - if(item.shiftId) + if (item.shiftId) { auto shift = shiftHash.constFind(item.shiftId); - if(shift == shiftHash.constEnd()) + if (shift == shiftHash.constEnd()) { shift = shiftHash.insert(item.shiftId, r.get(3)); } @@ -362,13 +362,13 @@ void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const Q item.originTime = r.get(4); item.originStId = r.get(5); - item.destTime = r.get(6); - item.destStId = r.get(7); + item.destTime = r.get(6); + item.destStId = r.get(7); - if(item.originStId) + if (item.originStId) { auto st = stationHash.constFind(item.originStId); - if(st == stationHash.constEnd()) + if (st == stationHash.constEnd()) { q_stationName.bind(1, item.originStId); q_stationName.step(); @@ -378,10 +378,10 @@ void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const Q item.origStName = st.value(); } - if(item.destStId) + if (item.destStId) { auto st = stationHash.constFind(item.destStId); - if(st == stationHash.constEnd()) + if (st == stationHash.constEnd()) { q_stationName.bind(1, item.destStId); q_stationName.step(); @@ -394,7 +394,7 @@ void JobListModel::internalFetch(int first, int sortCol, int /*valRow*/, const Q i += increment; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/jobs/jobsmanager/model/joblistmodel.h b/src/jobs/jobsmanager/model/joblistmodel.h index 562df5b..dd7d308 100644 --- a/src/jobs/jobsmanager/model/joblistmodel.h +++ b/src/jobs/jobsmanager/model/joblistmodel.h @@ -48,9 +48,13 @@ class JobListModel : public IPagedItemModelImpl { Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; - enum Columns { + enum Columns + { IdCol = 0, Category, ShiftCol, @@ -69,7 +73,8 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; @@ -77,35 +82,35 @@ public: virtual void setSortingColumn(int col) override; - //Filter + // Filter std::pair getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // Convinience inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const JobItem& item = cache.at(row - cacheFirstRow); + const JobItem &item = cache.at(row - cacheFirstRow); return item.jobId; } inline QPair getShiftAnCatAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return {0, JobCategory::NCategories}; //Invalid + return {0, JobCategory::NCategories}; // Invalid - const JobItem& item = cache.at(row - cacheFirstRow); + const JobItem &item = cache.at(row - cacheFirstRow); return {item.shiftId, item.category}; } inline QPair getOrigAndDestTimeAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return {}; //Invalid + return {}; // Invalid - const JobItem& item = cache.at(row - cacheFirstRow); + const JobItem &item = cache.at(row - cacheFirstRow); return {item.originTime, item.destTime}; } diff --git a/src/jobs/jobsmanager/model/jobmatchmodel.cpp b/src/jobs/jobsmanager/model/jobmatchmodel.cpp index 2c66b52..9073612 100644 --- a/src/jobs/jobsmanager/model/jobmatchmodel.cpp +++ b/src/jobs/jobsmanager/model/jobmatchmodel.cpp @@ -38,11 +38,11 @@ JobMatchModel::JobMatchModel(database &db, QObject *parent) : int JobMatchModel::columnCount(const QModelIndex &p) const { - if(p.isValid()) + if (p.isValid()) return 0; - if(!m_stopStationId) - return NCols - 1; //Hide stop arrival if no station filter is set + if (!m_stopStationId) + return NCols - 1; // Hide stop arrival if no station filter is set return NCols; } @@ -59,7 +59,7 @@ QVariant JobMatchModel::data(const QModelIndex &idx, int role) const { case JobCategoryCol: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { break; } @@ -67,7 +67,7 @@ QVariant JobMatchModel::data(const QModelIndex &idx, int role) const } case JobNumber: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -75,8 +75,8 @@ QVariant JobMatchModel::data(const QModelIndex &idx, int role) const } case StopArrivalCol: { - if(!m_stopStationId) - break; //Do not show stop arrival if not filtering by station + if (!m_stopStationId) + break; // Do not show stop arrival if not filtering by station return items[idx.row()].stopArrival; } @@ -85,7 +85,7 @@ QVariant JobMatchModel::data(const QModelIndex &idx, int role) const } case Qt::ForegroundRole: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { break; } @@ -124,7 +124,7 @@ QVariant JobMatchModel::data(const QModelIndex &idx, int role) const void JobMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.reserve(text.size() + 2); mQuery.append('%'); @@ -137,36 +137,36 @@ void JobMatchModel::autoSuggest(const QString &text) void JobMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); - if(m_exceptJobId) + if (m_exceptJobId) q_getMatches.bind(2, m_exceptJobId); - if(m_stopStationId) + if (m_stopStationId) { q_getMatches.bind(3, m_stopStationId); - if(!m_maxStopArrival.isNull()) + if (!m_maxStopArrival.isNull()) q_getMatches.bind(4, m_maxStopArrival); } auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { - items[i].stop.jobId = (*it).get(0); + items[i].stop.jobId = (*it).get(0); items[i].stop.category = JobCategory((*it).get(1)); - if(m_stopStationId) + if (m_stopStationId) { items[i].stop.stopId = (*it).get(2); items[i].stopArrival = (*it).get(3); @@ -176,13 +176,13 @@ void JobMatchModel::refreshData() } size = i; - if(hasEmptyRow) - size++; //Items + Empty, add 1 row + if (hasEmptyRow) + size++; // Items + Empty, add 1 row - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -193,12 +193,12 @@ void JobMatchModel::refreshData() QString JobMatchModel::getName(db_id jobId) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT category FROM jobs WHERE id=?"); q.bind(1, jobId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return QString(); JobCategory jobCat = JobCategory(q.getRows().get(0)); @@ -207,32 +207,31 @@ QString JobMatchModel::getName(db_id jobId) const db_id JobMatchModel::getIdAtRow(int row) const { - if(m_defaultId == StopId) + if (m_defaultId == StopId) return items[row].stop.stopId; return items[row].stop.jobId; } QString JobMatchModel::getNameAtRow(int row) const { - return JobCategoryName::jobName(items[row].stop.jobId, - items[row].stop.category); + return JobCategoryName::jobName(items[row].stop.jobId, items[row].stop.category); } void JobMatchModel::setFilter(db_id exceptJobId, db_id stopsInStationId, const QTime &maxStopArr) { - m_exceptJobId = exceptJobId; - m_stopStationId = stopsInStationId; + m_exceptJobId = exceptJobId; + m_stopStationId = stopsInStationId; m_maxStopArrival = maxStopArr; QByteArray sql; - if(m_stopStationId) + if (m_stopStationId) { - //Filter by stopping station + // Filter by stopping station sql = "SELECT stops.job_id, jobs.category, stops.id, stops.arrival" " FROM stops JOIN jobs ON jobs.id=stops.job_id" " WHERE stops.station_id=?3 AND"; - if(!m_maxStopArrival.isNull()) + if (!m_maxStopArrival.isNull()) sql += " stops.arrival < ?4 AND"; } else @@ -240,18 +239,18 @@ void JobMatchModel::setFilter(db_id exceptJobId, db_id stopsInStationId, const Q sql = "SELECT jobs.id, jobs.category FROM jobs WHERE"; } - if(exceptJobId) + if (exceptJobId) { - //Filter out unwanted job ID + // Filter out unwanted job ID sql += " jobs.id<>?2 AND"; } - //Filter by name (job ID number) - //FIXME: filter also by category with regexp + // Filter by name (job ID number) + // FIXME: filter also by category with regexp sql += " jobs.id LIKE ?1"; sql += " ORDER BY "; - if(m_stopStationId) + if (m_stopStationId) { sql += "stops.arrival, "; } diff --git a/src/jobs/jobsmanager/model/jobmatchmodel.h b/src/jobs/jobsmanager/model/jobmatchmodel.h index 043746e..151b9f0 100644 --- a/src/jobs/jobsmanager/model/jobmatchmodel.h +++ b/src/jobs/jobsmanager/model/jobmatchmodel.h @@ -29,8 +29,8 @@ #include using namespace sqlite3pp; -//TODO: share common code with SearchResultModel -//TODO: allow filter byy job category +// TODO: share common code with SearchResultModel +// TODO: allow filter byy job category /*! * \brief Match model for Jobs @@ -67,7 +67,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id jobId) const override; @@ -75,7 +75,7 @@ public: QString getNameAtRow(int row) const override; // JobMatchModel: - void setFilter(db_id exceptJobId, db_id stopsInStationId, const QTime& maxStopArr); + void setFilter(db_id exceptJobId, db_id stopsInStationId, const QTime &maxStopArr); void setDefaultId(DefaultId defaultId); diff --git a/src/jobs/jobsmanager/model/jobshelper.cpp b/src/jobs/jobsmanager/model/jobshelper.cpp index c4da8bf..5c0eb68 100644 --- a/src/jobs/jobsmanager/model/jobshelper.cpp +++ b/src/jobs/jobsmanager/model/jobshelper.cpp @@ -28,20 +28,20 @@ bool JobsHelper::createNewJob(sqlite3pp::database &db, db_id &outJobId, JobCategory cat) { sqlite3pp::command q_newJob(db, "INSERT INTO jobs(id,category,shift_id) VALUES(?,?,NULL)"); - if(outJobId) + if (outJobId) q_newJob.bind(1, outJobId); else - q_newJob.bind(1); //Bind NULL + q_newJob.bind(1); // Bind NULL q_newJob.bind(2, int(cat)); sqlite3_mutex *mutex = sqlite3_db_mutex(db.db()); sqlite3_mutex_enter(mutex); - int rc = q_newJob.execute(); + int rc = q_newJob.execute(); db_id jobId = db.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newJob.reset(); - if(rc != SQLITE_OK) + if (rc != SQLITE_OK) { qWarning() << rc << db.error_msg(); outJobId = 0; @@ -59,44 +59,45 @@ bool JobsHelper::removeJob(sqlite3pp::database &db, db_id jobId) { sqlite3pp::query q(db, "SELECT shift_id FROM jobs WHERE id=?"); q.bind(1, jobId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) { - return false; //Job doesn't exist + return false; // Job doesn't exist } db_id shiftId = q.getRows().get(0); q.reset(); - if(shiftId != 0) + if (shiftId != 0) { - //Remove job from shift + // Remove job from shift emit Session->shiftJobsChanged(shiftId, jobId); } - //Get stations in which job stopped or transited + // Get stations in which job stopped or transited QSet stationsToUpdate; q.prepare("SELECT station_id FROM stops WHERE job_id=?" " UNION " "SELECT station_id FROM old_stops WHERE job_id=?"); q.bind(1, jobId); - for(auto st : q) + for (auto st : q) { stationsToUpdate.insert(st.get(0)); } - //Get Rollingstock used by job + // Get Rollingstock used by job QSet rsToUpdate; q.prepare("SELECT coupling.rs_id FROM stops JOIN coupling ON coupling.stop_id=stops.id" " WHERE stops.job_id=?" " UNION " - "SELECT old_coupling.rs_id FROM old_stops JOIN old_coupling ON old_coupling.stop_id=old_stops.id" + "SELECT old_coupling.rs_id FROM old_stops JOIN old_coupling ON " + "old_coupling.stop_id=old_stops.id" " WHERE old_stops.job_id=?"); q.bind(1, jobId); - for(auto rs : q) + for (auto rs : q) { rsToUpdate.insert(rs.get(0)); } - //Remove job + // Remove job db.execute("BEGIN TRANSACTION"); q.prepare("DELETE FROM stops WHERE job_id=?"); @@ -105,16 +106,16 @@ bool JobsHelper::removeJob(sqlite3pp::database &db, db_id jobId) int ret = q.step(); q.reset(); - if(ret == SQLITE_OK || ret == SQLITE_DONE) + if (ret == SQLITE_OK || ret == SQLITE_DONE) { - //Remove possible left over from editing + // Remove possible left over from editing q.prepare("DELETE FROM old_stops WHERE job_id=?"); q.bind(1, jobId); ret = q.step(); q.reset(); } - if(ret == SQLITE_OK || ret == SQLITE_DONE) + if (ret == SQLITE_OK || ret == SQLITE_DONE) { q.prepare("DELETE FROM jobs WHERE id=?"); q.bind(1, jobId); @@ -122,23 +123,24 @@ bool JobsHelper::removeJob(sqlite3pp::database &db, db_id jobId) q.reset(); } - if(ret == SQLITE_OK || ret == SQLITE_DONE) + if (ret == SQLITE_OK || ret == SQLITE_DONE) { db.execute("COMMIT"); } else { - qDebug() << "Error while removing Job:" << jobId << ret << db.error_msg() << db.extended_error_code(); + qDebug() << "Error while removing Job:" << jobId << ret << db.error_msg() + << db.extended_error_code(); db.execute("ROLLBACK"); return false; } emit Session->jobRemoved(jobId); - //Refresh graphs and station views + // Refresh graphs and station views emit Session->stationJobsPlanChanged(stationsToUpdate); - //Refresh Rollingstock views + // Refresh Rollingstock views emit Session->rollingStockPlanChanged(rsToUpdate); return true; @@ -146,21 +148,21 @@ bool JobsHelper::removeJob(sqlite3pp::database &db, db_id jobId) bool JobsHelper::removeAllJobs(sqlite3pp::database &db) { - //Old + // Old sqlite3pp::command cmd(db, "DELETE FROM old_coupling"); cmd.execute(); cmd.prepare("DELETE FROM old_stops"); cmd.execute(); - //Current + // Current cmd.prepare("DELETE FROM coupling"); cmd.execute(); cmd.prepare("DELETE FROM stops"); cmd.execute(); - //Delete jobs + // Delete jobs cmd.prepare("DELETE FROM jobs"); cmd.execute(); @@ -169,13 +171,14 @@ bool JobsHelper::removeAllJobs(sqlite3pp::database &db) return true; } -QTime calcReversedTime(const QTime& start, const QTime& end, const QTime& value) +QTime calcReversedTime(const QTime &start, const QTime &end, const QTime &value) { const int msecsFromStart = start.msecsTo(value); return end.addMSecs(-msecsFromStart); } -bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJobId, int secsOffset, bool copyRsOps, bool reversePath) +bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJobId, int secsOffset, + bool copyRsOps, bool reversePath) { query q_getStops(db, "SELECT id,station_id,arrival,departure,type," "description,in_gate_conn,out_gate_conn,next_segment_conn_id" @@ -191,9 +194,9 @@ bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJob QSet rsToUpdate; QTime start, end; - if(reversePath) + if (reversePath) { - //Get first departure and last arrival to compute reversed time + // Get first departure and last arrival to compute reversed time query q(db, "SELECT MIN(departure) FROM stops WHERE job_id=?"); q.bind(1, fromJobId); q.step(); @@ -205,54 +208,54 @@ bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJob end = q.getRows().get(0); } - //Store last next segment when reversing path + // Store last next segment when reversing path db_id lastNextSegmentConn = 0; q_getStops.bind(1, fromJobId); - for(auto stop : q_getStops) + for (auto stop : q_getStops) { db_id origStopId = stop.get(0); - db_id stationId = stop.get(1); - QTime arrival = stop.get(2); - QTime departure = stop.get(3); - int type = stop.get(4); + db_id stationId = stop.get(1); + QTime arrival = stop.get(2); + QTime departure = stop.get(3); + int type = stop.get(4); - //Avoid memory copy + // Avoid memory copy const unsigned char *description = sqlite3_column_text(q_getStops.stmt(), 5); - const int descrLen = sqlite3_column_bytes(q_getStops.stmt(), 5); + const int descrLen = sqlite3_column_bytes(q_getStops.stmt(), 5); - db_id in_gate_conn = stop.get(6); - db_id out_gate_conn = stop.get(7); - db_id next_seg_conn = stop.get(8); + db_id in_gate_conn = stop.get(6); + db_id out_gate_conn = stop.get(7); + db_id next_seg_conn = stop.get(8); - if(reversePath) + if (reversePath) { - //Calculate reversed time + // Calculate reversed time const QTime origArr = arrival; const QTime origDep = departure; - //Arrival and departure get swapped - arrival = calcReversedTime(start, end, origDep); + // Arrival and departure get swapped + arrival = calcReversedTime(start, end, origDep); departure = calcReversedTime(start, end, origArr); - //Swap current next segment with the one of previous stop + // Swap current next segment with the one of previous stop qSwap(lastNextSegmentConn, next_seg_conn); - //Swap gate connections + // Swap gate connections qSwap(in_gate_conn, out_gate_conn); - //First stop, set in_gate = out_gate so track matches - //TODO: this shouldn't be needed but seems to not cause harm - if(!in_gate_conn) + // First stop, set in_gate = out_gate so track matches + // TODO: this shouldn't be needed but seems to not cause harm + if (!in_gate_conn) in_gate_conn = out_gate_conn; - //If we do not go past this station (Last stop) then we do not set out gate - if(!next_seg_conn) + // If we do not go past this station (Last stop) then we do not set out gate + if (!next_seg_conn) out_gate_conn = 0; } - //Apply time shift - arrival = arrival.addSecs(secsOffset); + // Apply time shift + arrival = arrival.addSecs(secsOffset); departure = departure.addSecs(secsOffset); q_setStop.bind(1, toJobId); @@ -260,34 +263,35 @@ bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJob q_setStop.bind(3, arrival); q_setStop.bind(4, departure); q_setStop.bind(5, type); - //Pass SQLITE_STATIC because description is valid until next loop cycle, so avoid copy - sqlite3_bind_text(q_setStop.stmt(), 6, reinterpret_cast(description), descrLen, SQLITE_STATIC); + // Pass SQLITE_STATIC because description is valid until next loop cycle, so avoid copy + sqlite3_bind_text(q_setStop.stmt(), 6, reinterpret_cast(description), + descrLen, SQLITE_STATIC); q_setStop.bindOrNull(7, in_gate_conn); q_setStop.bindOrNull(8, out_gate_conn); q_setStop.bindOrNull(9, next_seg_conn); - if(q_setStop.execute() != SQLITE_OK) + if (q_setStop.execute() != SQLITE_OK) { - qWarning() << "JobsHelper::copyStops() error setting stop" << origStopId << "To:" << toJobId << secsOffset - << db.error_msg(); - continue; //Skip stop + qWarning() << "JobsHelper::copyStops() error setting stop" << origStopId + << "To:" << toJobId << secsOffset << db.error_msg(); + continue; // Skip stop } db_id newStopId = db.last_insert_rowid(); q_setStop.reset(); - if(copyRsOps) + if (copyRsOps) { q_getRsOp.bind(1, origStopId); - for(auto rs : q_getRsOp) + for (auto rs : q_getRsOp) { db_id rsId = rs.get(0); - RsOp op = RsOp(rs.get(1)); + RsOp op = RsOp(rs.get(1)); - if(reversePath) + if (reversePath) { - //Reverse operations (Couple -> Uncouple and viceversa) - if(op == RsOp::Coupled) + // Reverse operations (Couple -> Uncouple and viceversa) + if (op == RsOp::Coupled) op = RsOp::Uncoupled; - else if(op == RsOp::Uncoupled) + else if (op == RsOp::Uncoupled) op = RsOp::Coupled; } @@ -297,20 +301,20 @@ bool JobsHelper::copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJob q_setRsOp.execute(); q_setRsOp.reset(); - //Store rollingstock ID to update it later + // Store rollingstock ID to update it later rsToUpdate.insert(rsId); } q_getRsOp.reset(); } - //Store station to update it later + // Store station to update it later stationsToUpdate.insert(stationId); } - //Refresh graphs and station views + // Refresh graphs and station views emit Session->stationJobsPlanChanged(stationsToUpdate); - //Refresh Rollingstock views + // Refresh Rollingstock views emit Session->rollingStockPlanChanged(rsToUpdate); return true; @@ -333,7 +337,7 @@ JobStopDirectionHelper::JobStopDirectionHelper(sqlite3pp::database &db) : " LEFT JOIN station_gates g1 ON g1.id=c1.gate_id" " LEFT JOIN station_gates g2 ON g2.id=c2.gate_id" " WHERE stops.id=?"); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) qWarning() << "JobStopDirectionHelper cannot prepare query"; } @@ -346,27 +350,27 @@ JobStopDirectionHelper::~JobStopDirectionHelper() utils::Side JobStopDirectionHelper::getStopOutSide(db_id stopId) { m_query->bind(1, stopId); - if(m_query->step() != SQLITE_ROW) + if (m_query->step() != SQLITE_ROW) { - //Stop doesn't exist + // Stop doesn't exist return utils::Side::NSides; } - utils::Side in_side = utils::Side::NSides; + utils::Side in_side = utils::Side::NSides; utils::Side out_side = utils::Side::NSides; - auto r = m_query->getRows(); - if(r.column_type(0) != SQLITE_NULL) + auto r = m_query->getRows(); + if (r.column_type(0) != SQLITE_NULL) in_side = utils::Side(r.get(0)); - if(r.column_type(1) != SQLITE_NULL) + if (r.column_type(1) != SQLITE_NULL) out_side = utils::Side(r.get(1)); - //Prefer out side - if(out_side != utils::Side::NSides) + // Prefer out side + if (out_side != utils::Side::NSides) return out_side; - //We only have in side, invert it - if(in_side == utils::Side::NSides) + // We only have in side, invert it + if (in_side == utils::Side::NSides) return in_side; return in_side == utils::Side::East ? utils::Side::West : utils::Side::East; diff --git a/src/jobs/jobsmanager/model/jobshelper.h b/src/jobs/jobsmanager/model/jobshelper.h index 5addae1..a01cf5b 100644 --- a/src/jobs/jobsmanager/model/jobshelper.h +++ b/src/jobs/jobsmanager/model/jobshelper.h @@ -26,7 +26,7 @@ namespace sqlite3pp { class database; class query; -} +} // namespace sqlite3pp class JobsHelper { @@ -42,12 +42,13 @@ public: * If the Job ID is already in use, the function fails and no new Job is created. * If 0 is passed, the function creates a new Job with arbitrary free ID from database */ - static bool createNewJob(sqlite3pp::database &db, db_id &outJobId, JobCategory cat = JobCategory::FREIGHT); + static bool createNewJob(sqlite3pp::database &db, db_id &outJobId, + JobCategory cat = JobCategory::FREIGHT); static bool removeJob(sqlite3pp::database &db, db_id jobId); static bool removeAllJobs(sqlite3pp::database &db); - static bool copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJobId, - int secsOffset, bool copyRsOps, bool reversePath); + static bool copyStops(sqlite3pp::database &db, db_id fromJobId, db_id toJobId, int secsOffset, + bool copyRsOps, bool reversePath); static bool checkShiftsExist(sqlite3pp::database &db); }; diff --git a/src/jobs/jobsmanager/newjobsamepathdlg.cpp b/src/jobs/jobsmanager/newjobsamepathdlg.cpp index 2918b1b..7023620 100644 --- a/src/jobs/jobsmanager/newjobsamepathdlg.cpp +++ b/src/jobs/jobsmanager/newjobsamepathdlg.cpp @@ -33,7 +33,7 @@ NewJobSamePathDlg::NewJobSamePathDlg(QWidget *parent) : QDialog(parent) { QVBoxLayout *lay = new QVBoxLayout(this); - label = new QLabel; + label = new QLabel; label->setTextFormat(Qt::RichText); lay->addWidget(label); @@ -41,11 +41,11 @@ NewJobSamePathDlg::NewJobSamePathDlg(QWidget *parent) : lay->addWidget(startTimeEdit); copyRsCheck = new QCheckBox(tr("Copy Rollingstock items")); - copyRsCheck->setChecked(true); //Enabled by default + copyRsCheck->setChecked(true); // Enabled by default lay->addWidget(copyRsCheck); reversePathCheck = new QCheckBox(tr("Reverse path")); - reversePathCheck->setChecked(false); //Disabled by default + reversePathCheck->setChecked(false); // Disabled by default lay->addWidget(reversePathCheck); QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); @@ -60,21 +60,21 @@ NewJobSamePathDlg::NewJobSamePathDlg(QWidget *parent) : setWindowTitle(tr("New Job With Same Path")); } -void NewJobSamePathDlg::setSourceJob(db_id jobId, JobCategory cat, const QTime &start, const QTime &end) +void NewJobSamePathDlg::setSourceJob(db_id jobId, JobCategory cat, const QTime &start, + const QTime &end) { - sourceJobId = jobId; + sourceJobId = jobId; sourceJobCat = cat; - sourceStart = start; - sourceEnd = end; + sourceStart = start; + sourceEnd = end; label->setText(tr("Create a new job with same path of %1.
" "Original job starts at %2 and ends at %3.
" "Please select below when the new job should start.") - .arg(JobCategoryName::jobName(sourceJobId, sourceJobCat), - sourceStart.toString("HH:mm"), - sourceEnd.toString("HH:mm"))); + .arg(JobCategoryName::jobName(sourceJobId, sourceJobCat), + sourceStart.toString("HH:mm"), sourceEnd.toString("HH:mm"))); - //Prevent calling checkTimeIsValid() + // Prevent calling checkTimeIsValid() QSignalBlocker blk(startTimeEdit); startTimeEdit->setTime(sourceStart); } @@ -96,21 +96,21 @@ bool NewJobSamePathDlg::shouldReversePath() const void NewJobSamePathDlg::checkTimeIsValid() { - const QTime lastValidTime = QTime(23, 59); + const QTime lastValidTime = QTime(23, 59); const int travelDurationMsecs = sourceStart.msecsTo(sourceEnd); - QTime newStart = startTimeEdit->time(); - int msecsToMidnight = newStart.msecsTo(lastValidTime); - if(travelDurationMsecs > msecsToMidnight) + QTime newStart = startTimeEdit->time(); + int msecsToMidnight = newStart.msecsTo(lastValidTime); + if (travelDurationMsecs > msecsToMidnight) { - //New job would end after midnigth + // New job would end after midnigth QMessageBox::warning(this, tr("Invalid Start Time"), tr("New job would end past midnight.")); - //Go back from midnight to get maximum start value + // Go back from midnight to get maximum start value newStart = lastValidTime.addMSecs(-travelDurationMsecs); - //Prevent recursion + // Prevent recursion QSignalBlocker blk(startTimeEdit); startTimeEdit->setTime(newStart); } diff --git a/src/jobs/jobsmanager/newjobsamepathdlg.h b/src/jobs/jobsmanager/newjobsamepathdlg.h index 89fecad..fb016ee 100644 --- a/src/jobs/jobsmanager/newjobsamepathdlg.h +++ b/src/jobs/jobsmanager/newjobsamepathdlg.h @@ -35,7 +35,7 @@ class NewJobSamePathDlg : public QDialog public: explicit NewJobSamePathDlg(QWidget *parent = nullptr); - void setSourceJob(db_id jobId, JobCategory cat, const QTime& start, const QTime& end); + void setSourceJob(db_id jobId, JobCategory cat, const QTime &start, const QTime &end); QTime getNewStartTime() const; bool shouldCopyRs() const; @@ -50,7 +50,7 @@ private: QCheckBox *copyRsCheck; QCheckBox *reversePathCheck; - db_id sourceJobId = 0; + db_id sourceJobId = 0; JobCategory sourceJobCat = JobCategory::NCategories; QTime sourceStart; QTime sourceEnd; diff --git a/src/odt_export/common/jobwriter.cpp b/src/odt_export/common/jobwriter.cpp index f84aa77..4bcf01f 100644 --- a/src/odt_export/common/jobwriter.cpp +++ b/src/odt_export/common/jobwriter.cpp @@ -29,66 +29,62 @@ #include - -void writeJobSummary(QXmlStreamWriter& xml, - const QString& from, const QString& dep, - const QString& to, const QString& arr, - int axes) +void writeJobSummary(QXmlStreamWriter &xml, const QString &from, const QString &dep, + const QString &to, const QString &arr, int axes) { - //Table 'job_summary' + // Table 'job_summary' xml.writeStartElement("table:table"); xml.writeAttribute("table:name", "job_summary"); xml.writeAttribute("table:style-name", "job_5f_summary"); - xml.writeEmptyElement("table:table-column"); //A + xml.writeEmptyElement("table:table-column"); // A xml.writeAttribute("table:style-name", "job_5f_summary.A"); - xml.writeEmptyElement("table:table-column"); //B + xml.writeEmptyElement("table:table-column"); // B xml.writeAttribute("table:style-name", "job_5f_summary.B"); - xml.writeEmptyElement("table:table-column"); //C + xml.writeEmptyElement("table:table-column"); // C xml.writeAttribute("table:style-name", "job_5f_summary.C"); - xml.writeEmptyElement("table:table-column"); //D + xml.writeEmptyElement("table:table-column"); // D xml.writeAttribute("table:style-name", "job_5f_summary.D"); - //Row + // Row xml.writeStartElement("table:table-row"); - //Cells + // Cells writeCell(xml, "job_5f_summary_cell", "P2", Odt::text(Odt::jobSummaryFrom)); writeCell(xml, "job_5f_summary_cell", "P3", from); writeCell(xml, "job_5f_summary_cell", "P2", Odt::text(Odt::jobSummaryDep)); writeCell(xml, "job_5f_summary_cell", "P3", dep); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row - //Row 2 + // Row 2 xml.writeStartElement("table:table-row"); - //Cells + // Cells writeCell(xml, "job_5f_summary_cell", "P2", Odt::text(Odt::jobSummaryTo)); writeCell(xml, "job_5f_summary_cell", "P3", to); writeCell(xml, "job_5f_summary_cell", "P2", Odt::text(Odt::jobSummaryArr)); writeCell(xml, "job_5f_summary_cell", "P3", arr); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row - //Row 3 + // Row 3 xml.writeStartElement("table:table-row"); - //Cells + // Cells writeCell(xml, "job_5f_summary_cell", "P2", Odt::text(Odt::jobSummaryAxes)); writeCell(xml, "job_5f_summary_cell", "P3", QString::number(axes)); writeCell(xml, "job_5f_summary_cell", "P2", QString()); writeCell(xml, "job_5f_summary_cell", "P3", QString()); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row - xml.writeEndElement(); //table:table END + xml.writeEndElement(); // table:table END } - JobWriter::JobWriter(database &db) : mDb(db), q_getJobStops(mDb, "SELECT stops.id," @@ -128,7 +124,8 @@ JobWriter::JobWriter(database &db) : "stops.arrival,stops.departure" " FROM stops" " JOIN jobs ON jobs.id=stops.job_id" - " WHERE stops.station_id=? AND stops.departure>=? AND stops.arrival<=? AND stops.job_id<>?"), + " WHERE stops.station_id=? AND stops.departure>=? AND stops.arrival<=? " + "AND stops.job_id<>?"), q_getStopCouplings(mDb, "SELECT coupling.rs_id," "rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" @@ -141,21 +138,21 @@ JobWriter::JobWriter(database &db) : void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) { - //job_summary columns + // job_summary columns writeColumnStyle(xml, "job_5f_summary.A", "1.60cm"); writeColumnStyle(xml, "job_5f_summary.B", "8.30cm"); writeColumnStyle(xml, "job_5f_summary.C", "2.90cm"); writeColumnStyle(xml, "job_5f_summary.D", "4.20cm"); - //job_stops columns - writeColumnStyle(xml, "job_5f_stops.A", "2.60cm"); //Station (IT: Stazione) - writeColumnStyle(xml, "job_5f_stops.B", "1.60cm"); //Arrival (IT: Arrivo) - writeColumnStyle(xml, "job_5f_stops.C", "2.10cm"); //Departure (IT: Partenza) - writeColumnStyle(xml, "job_5f_stops.D", "1.cm"); //Platorm 'Platf' (IT: Binario 'Bin') - writeColumnStyle(xml, "job_5f_stops.E", "3.00cm"); //Rollingstock (IT: Rotabili) - writeColumnStyle(xml, "job_5f_stops.F", "2.30cm"); //Crossings - writeColumnStyle(xml, "job_5f_stops.G", "2.30cm"); //Passings - writeColumnStyle(xml, "job_5f_stops.H", "3.20cm"); //Description (IT: Note) + // job_stops columns + writeColumnStyle(xml, "job_5f_stops.A", "2.60cm"); // Station (IT: Stazione) + writeColumnStyle(xml, "job_5f_stops.B", "1.60cm"); // Arrival (IT: Arrivo) + writeColumnStyle(xml, "job_5f_stops.C", "2.10cm"); // Departure (IT: Partenza) + writeColumnStyle(xml, "job_5f_stops.D", "1.cm"); // Platorm 'Platf' (IT: Binario 'Bin') + writeColumnStyle(xml, "job_5f_stops.E", "3.00cm"); // Rollingstock (IT: Rotabili) + writeColumnStyle(xml, "job_5f_stops.F", "2.30cm"); // Crossings + writeColumnStyle(xml, "job_5f_stops.G", "2.30cm"); // Passings + writeColumnStyle(xml, "job_5f_stops.H", "3.20cm"); // Description (IT: Note) /* Style: job_5f_stops.A1 * @@ -181,8 +178,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-right", "none"); xml.writeAttribute("fo:border-top", "0.05pt solid #000000"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_stops.H1 * @@ -206,8 +203,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:padding-bottom", "0.15cm"); xml.writeAttribute("fo:border", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_stops.A2 * @@ -230,8 +227,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_stops.H2 * @@ -254,10 +251,10 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style - //job_5f_asset columns + // job_5f_asset columns writeColumnStyle(xml, "job_5f_asset.A", "3.0cm"); writeColumnStyle(xml, "job_5f_asset.B", "14.0cm"); @@ -281,8 +278,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-right", "none"); xml.writeAttribute("fo:border-top", "0.05pt solid #000000"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_asset.B1 * @@ -302,8 +299,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:padding", "0.049cm"); xml.writeAttribute("fo:border", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_asset.A2 * @@ -326,8 +323,8 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_asset.B2 * @@ -350,11 +347,11 @@ void JobWriter::writeJobAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style } -void JobWriter::writeJobStyles(QXmlStreamWriter& xml) +void JobWriter::writeJobStyles(QXmlStreamWriter &xml) { /* Style: job_5f_summary * @@ -374,8 +371,8 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeAttribute("style:shadow", "none"); xml.writeAttribute("table:align", "left"); xml.writeAttribute("style:width", "8.0cm"); - xml.writeEndElement(); //style:table-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-properties + xml.writeEndElement(); // style /* Style: job_5f_summary_cell * @@ -393,8 +390,8 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:table-cell-properties"); xml.writeAttribute("fo:border", "none"); xml.writeAttribute("fo:padding", "0.097cm"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: job_5f_stops * @@ -414,19 +411,19 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeAttribute("table:align", "left"); xml.writeAttribute("style:width", "16.0cm"); - xml.writeEndElement(); //style:table-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-properties + xml.writeEndElement(); // style /* Style: job_5f_asset - * - * Type: table - * Display name: job_asset - * Align: left - * Width: 16.0cm - * - * Usage: - * - job_stops table: displays job rollingstock asset summary - */ + * + * Type: table + * Display name: job_asset + * Align: left + * Width: 16.0cm + * + * Usage: + * - job_stops table: displays job rollingstock asset summary + */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "table"); xml.writeAttribute("style:name", "job_5f_asset"); @@ -435,8 +432,8 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeAttribute("table:align", "left"); xml.writeAttribute("style:width", "16.0cm"); - xml.writeEndElement(); //style:table-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-properties + xml.writeEndElement(); // style /* Style P2 * type: paragraph @@ -454,14 +451,14 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "start"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "16pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P3 * type: paragraph @@ -481,13 +478,13 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "start"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "16pt"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P5 * type: paragraph @@ -498,7 +495,8 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) * Like P4 but not bold * * Usages: - * - job_stops: stop cell text for normal stops and transit Rollingstock/Crossings/Passings/Description + * - job_stops: stop cell text for normal stops and transit + * Rollingstock/Crossings/Passings/Description */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); @@ -507,13 +505,13 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "12pt"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P6 * type: paragraph @@ -526,7 +524,8 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) * (P4 + Italic, not bold) * * Usages: - * - job_stops: stop cell text for transit stops except for Rollingstock/Crossings/Passings/Description columns which have P5 + * - job_stops: stop cell text for transit stops except for + * Rollingstock/Crossings/Passings/Description columns which have P5 */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); @@ -535,18 +534,17 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "12pt"); xml.writeAttribute("fo:font-style", "italic"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style - - //stile interruzione di pagina - //TODO: quando useremo 'Page master style' vedere se vanno in conflitto + // stile interruzione di pagina + // TODO: quando useremo 'Page master style' vedere se vanno in conflitto xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); xml.writeAttribute("style:name", "interruzione"); @@ -554,16 +552,16 @@ void JobWriter::writeJobStyles(QXmlStreamWriter& xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "start"); xml.writeAttribute("fo:break-after", "page"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "1pt"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } -void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) +void JobWriter::writeJob(QXmlStreamWriter &xml, db_id jobId, JobCategory jobCat) { query q_getRSInfo(mDb, "SELECT rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" " FROM rs_list" @@ -572,33 +570,34 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) QList>> stopsRS; - //Title + // Title xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeCharacters(JobCategoryName::jobNameSpaced(jobId, jobCat)); xml.writeEndElement(); - //Vertical space + // Vertical space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeEndElement(); db_id firstStopId = 0; - db_id lastStopId = 0; + db_id lastStopId = 0; QTime start, end; QString fromStation, toStation; int axesCount = 0; - //Job summary + // Job summary q_getFirstStop.bind(1, jobId); - if(q_getFirstStop.step() == SQLITE_ROW && q_getFirstStop.getRows().column_type(0) != SQLITE_NULL) + if (q_getFirstStop.step() == SQLITE_ROW + && q_getFirstStop.getRows().column_type(0) != SQLITE_NULL) { - auto r = q_getFirstStop.getRows(); + auto r = q_getFirstStop.getRows(); firstStopId = r.get(0); fromStation = r.get(1); - start = r.get(2); + start = r.get(2); q_initialJobAxes.bind(1, firstStopId); q_initialJobAxes.step(); @@ -608,21 +607,19 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) q_getFirstStop.reset(); q_getLastStop.bind(1, jobId); - if(q_getLastStop.step() == SQLITE_ROW && q_getLastStop.getRows().column_type(0) != SQLITE_NULL) + if (q_getLastStop.step() == SQLITE_ROW && q_getLastStop.getRows().column_type(0) != SQLITE_NULL) { - auto r = q_getLastStop.getRows(); + auto r = q_getLastStop.getRows(); lastStopId = r.get(0); - toStation = r.get(1); - end = r.get(2); + toStation = r.get(1); + end = r.get(2); } q_getLastStop.reset(); - if(firstStopId && lastStopId) + if (firstStopId && lastStopId) { - writeJobSummary(xml, - fromStation, start.toString("HH:mm"), - toStation, end.toString("HH:mm"), + writeJobSummary(xml, fromStation, start.toString("HH:mm"), toStation, end.toString("HH:mm"), axesCount); } else @@ -633,41 +630,41 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) writeJobSummary(xml, err, err, err, err, 0); } - //Vertical space + // Vertical space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeEndElement(); - //Table 'job_stops' + // Table 'job_stops' xml.writeStartElement("table:table"); xml.writeAttribute("table:name", "job_stops"); xml.writeAttribute("table:style-name", "job_5f_stops"); - xml.writeEmptyElement("table:table-column"); //Station + xml.writeEmptyElement("table:table-column"); // Station xml.writeAttribute("table:style-name", "job_5f_stops.A"); - xml.writeEmptyElement("table:table-column"); //Arrival + xml.writeEmptyElement("table:table-column"); // Arrival xml.writeAttribute("table:style-name", "job_5f_stops.B"); - xml.writeEmptyElement("table:table-column"); //Departure + xml.writeEmptyElement("table:table-column"); // Departure xml.writeAttribute("table:style-name", "job_5f_stops.C"); - xml.writeEmptyElement("table:table-column"); //Platform (Platf) + xml.writeEmptyElement("table:table-column"); // Platform (Platf) xml.writeAttribute("table:style-name", "job_5f_stops.D"); - xml.writeEmptyElement("table:table-column"); //Rollingstock + xml.writeEmptyElement("table:table-column"); // Rollingstock xml.writeAttribute("table:style-name", "job_5f_stops.E"); - xml.writeEmptyElement("table:table-column"); //Crossings + xml.writeEmptyElement("table:table-column"); // Crossings xml.writeAttribute("table:style-name", "job_5f_stops.F"); - xml.writeEmptyElement("table:table-column"); //Passings + xml.writeEmptyElement("table:table-column"); // Passings xml.writeAttribute("table:style-name", "job_5f_stops.G"); - xml.writeEmptyElement("table:table-column"); //Description + xml.writeEmptyElement("table:table-column"); // Description xml.writeAttribute("table:style-name", "job_5f_stops.H"); - //Row 1 (Heading) + // Row 1 (Heading) xml.writeStartElement("table:table-header-rows"); xml.writeStartElement("table:table-row"); @@ -679,40 +676,41 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) writeCell(xml, "job_5f_stops.A1", P4_Style, Odt::text(Odt::rollingstock)); writeCell(xml, "job_5f_stops.A1", P4_Style, Odt::text(Odt::jobStopCross)); writeCell(xml, "job_5f_stops.A1", P4_Style, Odt::text(Odt::jobStopPassings)); - writeCell(xml, "job_5f_stops.H1", P4_Style, Odt::text(Odt::notes)); //Description + writeCell(xml, "job_5f_stops.H1", P4_Style, Odt::text(Odt::notes)); // Description - xml.writeEndElement(); //end of row - xml.writeEndElement(); //header section + xml.writeEndElement(); // end of row + xml.writeEndElement(); // header section QList rsAsset; const QString P5_style = "P5"; - //Fill stops table + // Fill stops table q_getJobStops.bind(1, jobId); - for(auto stop : q_getJobStops) + for (auto stop : q_getJobStops) { - db_id stopId = stop.get(0); - db_id stationId = stop.get(1); + db_id stopId = stop.get(0); + db_id stationId = stop.get(1); QString stationName = stop.get(2); - QTime arr = stop.get(3); - QTime dep = stop.get(4); - const int stopType = stop.get(5); - QString descr = stop.get(6); + QTime arr = stop.get(3); + QTime dep = stop.get(4); + const int stopType = stop.get(5); + QString descr = stop.get(6); - QString trackName = stop.get(7); - if(trackName.isEmpty()) - trackName = stop.get(8); //Use out gate to get track name + QString trackName = stop.get(7); + if (trackName.isEmpty()) + trackName = stop.get(8); // Use out gate to get track name utils::Side entranceSide = utils::Side(stop.get(9)); - utils::Side exitSide = utils::Side(stop.get(10)); + utils::Side exitSide = utils::Side(stop.get(10)); - if(entranceSide == exitSide && stop.column_type(9) != SQLITE_NULL && stop.column_type(10) != SQLITE_NULL) + if (entranceSide == exitSide && stop.column_type(9) != SQLITE_NULL + && stop.column_type(10) != SQLITE_NULL) { - //Train enters and leaves from same track side, add reversal to description + // Train enters and leaves from same track side, add reversal to description QString descr2 = Odt::text(Odt::jobReverseDirection); - if(!descr.isEmpty()) - descr2.append('\n'); //Separate from manually set description + if (!descr.isEmpty()) + descr2.append('\n'); // Separate from manually set description descr2.append(descr); descr = descr2; } @@ -721,58 +719,59 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) qDebug() << "(Loop) Job:" << jobId << "Stop:" << stopId; - xml.writeStartElement("table:table-row"); //start new row + xml.writeStartElement("table:table-row"); // start new row - const QString styleName = isTransit ? "P6" : P5_style; //If it's transit use italic style + const QString styleName = isTransit ? "P6" : P5_style; // If it's transit use italic style - //Station + // Station writeCell(xml, "job_5f_stops.A2", styleName, stationName); - //Arrival - writeCell(xml, "job_5f_stops.A2", styleName, stopId == firstStopId ? QString() : arr.toString("HH:mm")); + // Arrival + writeCell(xml, "job_5f_stops.A2", styleName, + stopId == firstStopId ? QString() : arr.toString("HH:mm")); - //Departure - //If it's transit then and arrival is equal to departure (should be always but if is different show both to warn user about the error) - //then show only arrival - writeCell(xml, "job_5f_stops.A2", styleName, (stopId == lastStopId || (isTransit && arr == dep)) ? QString() : dep.toString("HH:mm")); + // Departure + // If it's transit then and arrival is equal to departure (should be always but if is + // different show both to warn user about the error) then show only arrival + writeCell(xml, "job_5f_stops.A2", styleName, + (stopId == lastStopId || (isTransit && arr == dep)) ? QString() + : dep.toString("HH:mm")); - //Platform + // Platform writeCell(xml, "job_5f_stops.A2", styleName, trackName); - //Rollingstock + // Rollingstock sqlite3_stmt *stmt = q_getStopCouplings.stmt(); writeCellListStart(xml, "job_5f_stops.A2", P5_style); - //Coupled rollingstock + // Coupled rollingstock bool firstCoupRow = true; q_getStopCouplings.bind(1, stopId); q_getStopCouplings.bind(2, int(RsOp::Coupled)); - for(auto coup : q_getStopCouplings) + for (auto coup : q_getStopCouplings) { db_id rsId = coup.get(0); rsAsset.append(rsId); - int number = coup.get(1); - int modelNameLen = sqlite3_column_bytes(stmt, 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); + int number = coup.get(1); + int modelNameLen = sqlite3_column_bytes(stmt, 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); - RsType type = RsType(sqlite3_column_int(stmt, 4)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); + RsType type = RsType(sqlite3_column_int(stmt, 4)); - const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, + modelSuffix, modelSuffixLen, type); - if(firstCoupRow) + if (firstCoupRow) { firstCoupRow = false; - //Use bold font + // Use bold font xml.writeStartElement("text:span"); xml.writeAttribute("text:style-name", "T1"); xml.writeCharacters(Odt::text(Odt::CoupledAbbr)); - xml.writeEndElement(); //test:span + xml.writeEndElement(); // test:span } xml.writeEmptyElement("text:line-break"); @@ -780,38 +779,36 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) } q_getStopCouplings.reset(); - //Unoupled rollingstock + // Unoupled rollingstock bool firstUncoupRow = true; q_getStopCouplings.bind(1, stopId); q_getStopCouplings.bind(2, int(RsOp::Uncoupled)); - for(auto coup : q_getStopCouplings) + for (auto coup : q_getStopCouplings) { db_id rsId = coup.get(0); rsAsset.removeAll(rsId); - int number = coup.get(1); - int modelNameLen = sqlite3_column_bytes(stmt, 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); + int number = coup.get(1); + int modelNameLen = sqlite3_column_bytes(stmt, 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); - RsType type = RsType(sqlite3_column_int(stmt, 4)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); + RsType type = RsType(sqlite3_column_int(stmt, 4)); - const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, + modelSuffix, modelSuffixLen, type); - if(firstUncoupRow) + if (firstUncoupRow) { - if(!firstCoupRow) //Not first row, there were coupled rs - xml.writeEmptyElement("text:line-break"); //Separate from coupled + if (!firstCoupRow) // Not first row, there were coupled rs + xml.writeEmptyElement("text:line-break"); // Separate from coupled firstUncoupRow = false; - //Use bold font + // Use bold font xml.writeStartElement("text:span"); xml.writeAttribute("text:style-name", "T1"); xml.writeCharacters(Odt::text(Odt::UncoupledAbbr)); - xml.writeEndElement(); //test:span + xml.writeEndElement(); // test:span } xml.writeEmptyElement("text:line-break"); @@ -822,7 +819,7 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) stopsRS.append({stationName, rsAsset}); - //Crossings / Passings + // Crossings / Passings JobStopDirectionHelper dirHelper(mDb); @@ -835,25 +832,25 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) q_selectPassings.bind(3, dep); q_selectPassings.bind(4, jobId); - //Incroci + // Incroci firstCoupRow = true; writeCellListStart(xml, "job_5f_stops.A2", P5_style); - for(auto pass : q_selectPassings) + for (auto pass : q_selectPassings) { - db_id otherStopId = pass.get(0); - db_id otherJobId = pass.get(1); + db_id otherStopId = pass.get(0); + db_id otherJobId = pass.get(1); JobCategory otherJobCat = JobCategory(pass.get(2)); - //QTime otherArr = pass.get(3); - //QTime otherDep = pass.get(4); + // QTime otherArr = pass.get(3); + // QTime otherDep = pass.get(4); utils::Side otherDir = dirHelper.getStopOutSide(otherStopId); - if(myDir == otherDir) + if (myDir == otherDir) passings.append({otherJobId, otherJobCat}); else { - if(firstCoupRow) + if (firstCoupRow) firstCoupRow = false; else xml.writeEmptyElement("text:line-break"); @@ -863,12 +860,12 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) q_selectPassings.reset(); writeCellListEnd(xml); - //Passings + // Passings firstCoupRow = true; writeCellListStart(xml, "job_5f_stops.A2", P5_style); - for(auto entry : passings) + for (auto entry : passings) { - if(firstCoupRow) + if (firstCoupRow) firstCoupRow = false; else xml.writeEmptyElement("text:line-break"); @@ -876,107 +873,105 @@ void JobWriter::writeJob(QXmlStreamWriter& xml, db_id jobId, JobCategory jobCat) } writeCellListEnd(xml); - //Description + // Description writeCellListStart(xml, "job_5f_stops.H2", P5_style); - if(!descr.isEmpty()) + if (!descr.isEmpty()) { - //Split in lines + // Split in lines int lastIdx = 0; - while(true) + while (true) { - int idx = descr.indexOf('\n', lastIdx); + int idx = descr.indexOf('\n', lastIdx); QString line = descr.mid(lastIdx, idx == -1 ? idx : idx - lastIdx); xml.writeCharacters(line.simplified()); - if(idx < 0) - break; //Last line + if (idx < 0) + break; // Last line lastIdx = idx + 1; xml.writeEmptyElement("text:line-break"); } } writeCellListEnd(xml); - xml.writeEndElement(); //end of row + xml.writeEndElement(); // end of row } q_getJobStops.reset(); - xml.writeEndElement(); //table:table END + xml.writeEndElement(); // table:table END - //text:p as separator + // text:p as separator xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeEndElement(); - //Table 'job_asset' + // Table 'job_asset' xml.writeStartElement("table:table"); xml.writeAttribute("table:name", "job_asset"); xml.writeAttribute("table:style-name", "job_5f_asset"); - xml.writeEmptyElement("table:table-column"); //Stazione + xml.writeEmptyElement("table:table-column"); // Stazione xml.writeAttribute("table:style-name", "job_5f_asset.A"); - xml.writeEmptyElement("table:table-column"); //Assetto + xml.writeEmptyElement("table:table-column"); // Assetto xml.writeAttribute("table:style-name", "job_5f_asset.B"); - //Duplicate second-last asset to last stop because last stop would be always empty - if(stopsRS.size() >= 2) + // Duplicate second-last asset to last stop because last stop would be always empty + if (stopsRS.size() >= 2) { - int i = stopsRS.size() - 2; //Get second-last (IT: penultima fermata) + int i = stopsRS.size() - 2; // Get second-last (IT: penultima fermata) stopsRS[i + 1].second = stopsRS[i].second; } else { - //Error! + // Error! qWarning() << __FUNCTION__ << "At least 2 stops required!"; } bool firstRow = true; - for(auto &s : qAsConst(stopsRS)) + for (auto &s : qAsConst(stopsRS)) { - xml.writeStartElement("table:table-row"); //start new row + xml.writeStartElement("table:table-row"); // start new row writeCell(xml, firstRow ? "job_5f_asset.A1" : "job_5f_asset.A2", P5_style, s.first); writeCellListStart(xml, firstRow ? "job_5f_asset.B1" : "job_5f_asset.B2", P5_style); - for(int i = 0; i < s.second.size(); i++) + for (int i = 0; i < s.second.size(); i++) { q_getRSInfo.reset(); q_getRSInfo.bind(1, s.second.at(i)); int ret = q_getRSInfo.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - //Error: RS does not exist! + // Error: RS does not exist! continue; } - sqlite3_stmt *stmt = q_getRSInfo.stmt(); - int number = sqlite3_column_int(stmt, 0); - int modelNameLen = sqlite3_column_bytes(stmt, 1); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 1)); + sqlite3_stmt *stmt = q_getRSInfo.stmt(); + int number = sqlite3_column_int(stmt, 0); + int modelNameLen = sqlite3_column_bytes(stmt, 1); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 1)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 2); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 2)); - RsType type = RsType(sqlite3_column_int(stmt, 3)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 2); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 2)); + RsType type = RsType(sqlite3_column_int(stmt, 3)); - const QString name = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString name = rs_utils::formatNameRef(modelName, modelNameLen, number, + modelSuffix, modelSuffixLen, type); xml.writeCharacters(name); - if(i < s.second.size() - 1) + if (i < s.second.size() - 1) xml.writeCharacters(" + "); } writeCellListEnd(xml); - xml.writeEndElement(); //end of row + xml.writeEndElement(); // end of row - if(firstRow) + if (firstRow) firstRow = false; } xml.writeEndElement(); - //Interruzione pagina TODO: see style 'interruzione' + // Interruzione pagina TODO: see style 'interruzione' xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "interruzione"); xml.writeEndElement(); diff --git a/src/odt_export/common/jobwriter.h b/src/odt_export/common/jobwriter.h index 07c76a4..b041fd0 100644 --- a/src/odt_export/common/jobwriter.h +++ b/src/odt_export/common/jobwriter.h @@ -30,9 +30,9 @@ class QXmlStreamWriter; class JobWriter { public: - JobWriter(database& db); + JobWriter(database &db); - static void writeJobAutomaticStyles(QXmlStreamWriter& xml); + static void writeJobAutomaticStyles(QXmlStreamWriter &xml); static void writeJobStyles(QXmlStreamWriter &xml); void writeJob(QXmlStreamWriter &xml, db_id jobId, JobCategory jobCat); diff --git a/src/odt_export/common/odtdocument.cpp b/src/odt_export/common/odtdocument.cpp index 9a5f3bf..b3bc20a 100644 --- a/src/odt_export/common/odtdocument.cpp +++ b/src/odt_export/common/odtdocument.cpp @@ -25,54 +25,58 @@ #include -#include "info.h" //Fot App constants +#include "info.h" //Fot App constants #include "app/session.h" //For settings #include "db_metadata/metadatamanager.h" #include "odtutils.h" -//content.xml +// content.xml static constexpr char contentFileStr[] = "content.xml"; -static constexpr QLatin1String contentFileName = QLatin1String(contentFileStr, sizeof (contentFileStr) - 1); +static constexpr QLatin1String contentFileName = + QLatin1String(contentFileStr, sizeof(contentFileStr) - 1); -//styles.xml +// styles.xml static constexpr char stylesFileStr[] = "styles.xml"; -static constexpr QLatin1String stylesFileName = QLatin1String(stylesFileStr, sizeof (stylesFileStr) - 1); +static constexpr QLatin1String stylesFileName = + QLatin1String(stylesFileStr, sizeof(stylesFileStr) - 1); -//meta.xml -static constexpr char metaFileStr[] = "meta.xml"; -static constexpr QLatin1String metaFileName = QLatin1String(metaFileStr, sizeof (metaFileStr) - 1); +// meta.xml +static constexpr char metaFileStr[] = "meta.xml"; +static constexpr QLatin1String metaFileName = QLatin1String(metaFileStr, sizeof(metaFileStr) - 1); -//META-INF/manifest.xml +// META-INF/manifest.xml static constexpr char manifestFileNameStr[] = "manifest.xml"; -static constexpr QLatin1String manifestFileName = QLatin1String(manifestFileNameStr, sizeof (manifestFileNameStr) - 1); +static constexpr QLatin1String manifestFileName = + QLatin1String(manifestFileNameStr, sizeof(manifestFileNameStr) - 1); static constexpr char metaInfPathStr[] = "/META-INF"; -static constexpr QLatin1String metaInfDirPath = QLatin1String(metaInfPathStr, sizeof (metaInfPathStr) - 1); +static constexpr QLatin1String metaInfDirPath = + QLatin1String(metaInfPathStr, sizeof(metaInfPathStr) - 1); static constexpr char manifestFilePathStr[] = "META-INF/manifest.xml"; -static constexpr QLatin1String manifestFilePath = QLatin1String(manifestFilePathStr, sizeof (manifestFilePathStr) - 1); +static constexpr QLatin1String manifestFilePath = + QLatin1String(manifestFilePathStr, sizeof(manifestFilePathStr) - 1); OdtDocument::OdtDocument() { - } bool OdtDocument::initDocument() { - if(!dir.isValid()) + if (!dir.isValid()) return false; content.setFileName(dir.filePath(contentFileName)); - if(!content.open(QFile::WriteOnly | QFile::Truncate)) + if (!content.open(QFile::WriteOnly | QFile::Truncate)) return false; styles.setFileName(dir.filePath(stylesFileName)); - if(!styles.open(QFile::WriteOnly | QFile::Truncate)) + if (!styles.open(QFile::WriteOnly | QFile::Truncate)) return false; contentXml.setDevice(&content); stylesXml.setDevice(&styles); - //Init content.xml + // Init content.xml writeStartDoc(contentXml); contentXml.writeStartElement("office:document-content"); contentXml.writeNamespace("urn:oasis:names:tc:opendocument:xmlns:office:1.0", "office"); @@ -85,7 +89,7 @@ bool OdtDocument::initDocument() contentXml.writeNamespace("http://www.w3.org/1999/xlink", "xlink"); contentXml.writeAttribute("office:version", "1.2"); - //Init styles.xml + // Init styles.xml writeStartDoc(stylesXml); stylesXml.writeStartElement("office:document-styles"); stylesXml.writeNamespace("urn:oasis:names:tc:opendocument:xmlns:office:1.0", "office"); @@ -100,31 +104,32 @@ bool OdtDocument::initDocument() return true; } -void OdtDocument::startBody() //TODO: start body manually, remove this function +void OdtDocument::startBody() // TODO: start body manually, remove this function { - contentXml.writeEndElement(); //office:automatic-styles + contentXml.writeEndElement(); // office:automatic-styles contentXml.writeStartElement("office:body"); contentXml.writeStartElement("office:text"); } -bool OdtDocument::saveTo(const QString& fileName) +bool OdtDocument::saveTo(const QString &fileName) { - int err = 0; + int err = 0; zip_t *zipper = zip_open(fileName.toUtf8(), ZIP_CREATE | ZIP_TRUNCATE, &err); if (zipper == nullptr) { zip_error_t ziperror; zip_error_init_with_code(&ziperror, err); - qDebug() << "Failed to open output file" << fileName << "Err:" << zip_error_strerror(&ziperror); + qDebug() << "Failed to open output file" << fileName + << "Err:" << zip_error_strerror(&ziperror); zip_error_fini(&ziperror); return false; } - //Add mimetype file NOTE: must be the first file in archive + // Add mimetype file NOTE: must be the first file in archive const char mimetype[] = "application/vnd.oasis.opendocument.text"; - zip_source_t *source = zip_source_buffer(zipper, mimetype, sizeof (mimetype) - 1, 0); + zip_source_t *source = zip_source_buffer(zipper, mimetype, sizeof(mimetype) - 1, 0); if (source == nullptr) { qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); @@ -136,10 +141,10 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - //Add META-INF/manifest.xml + // Add META-INF/manifest.xml QString fileToCompress = dir.filePath(manifestFilePath); - source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); + source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); if (source == nullptr) { qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); @@ -151,10 +156,10 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - //Add styles.xml + // Add styles.xml fileToCompress = dir.filePath(stylesFileName); - source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); + source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); if (source == nullptr) { qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); @@ -166,10 +171,10 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - //Add content.xml + // Add content.xml fileToCompress = dir.filePath(contentFileName); - source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); + source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); if (source == nullptr) { qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); @@ -181,10 +186,10 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - //Add meta.xml + // Add meta.xml fileToCompress = dir.filePath(metaFileName); - source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); + source = zip_source_file(zipper, fileToCompress.toUtf8(), 0, 0); if (source == nullptr) { qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); @@ -196,10 +201,10 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - //Add possible images - QString imgBasePath = dir.filePath("Pictures") + QLatin1String("/%1"); + // Add possible images + QString imgBasePath = dir.filePath("Pictures") + QLatin1String("/%1"); QString imgNewBasePath = QLatin1String("Pictures/%1"); - for(const auto& img : qAsConst(imageList)) + for (const auto &img : qAsConst(imageList)) { source = zip_source_file(zipper, imgBasePath.arg(img.first).toUtf8(), 0, 0); if (source == nullptr) @@ -207,14 +212,15 @@ bool OdtDocument::saveTo(const QString& fileName) qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } - if (zip_file_add(zipper, imgNewBasePath.arg(img.first).toUtf8(), source, ZIP_FL_ENC_UTF_8) < 0) + if (zip_file_add(zipper, imgNewBasePath.arg(img.first).toUtf8(), source, ZIP_FL_ENC_UTF_8) + < 0) { zip_source_free(source); qDebug() << "Failed to add file to zip:" << zip_strerror(zipper); } } - if(zip_close(zipper) != 0) + if (zip_close(zipper) != 0) { qDebug() << "Failed to close zip:" << zip_strerror(zipper); } @@ -236,11 +242,11 @@ void OdtDocument::endDocument() QString OdtDocument::addImage(const QString &name, const QString &mediaType) { - if(imageList.isEmpty()) + if (imageList.isEmpty()) { - //First image added, create Pictures folder + // First image added, create Pictures folder QDir pictures(dir.path()); - if(!pictures.mkdir("Pictures")) + if (!pictures.mkdir("Pictures")) qWarning() << "OdtDocument: cannot create Pictures folder"; } imageList.append({name, mediaType}); @@ -251,12 +257,12 @@ void OdtDocument::writeStartDoc(QXmlStreamWriter &xml) { xml.setAutoFormatting(true); xml.setAutoFormattingIndent(-1); - //xml.writeStartDocument(QStringLiteral("1.0"), true); + // xml.writeStartDocument(QStringLiteral("1.0"), true); xml.writeStartDocument(QStringLiteral("1.0")); } -void OdtDocument::writeFileEntry(QXmlStreamWriter& xml, - const QString& fullPath, const QString& mediaType) +void OdtDocument::writeFileEntry(QXmlStreamWriter &xml, const QString &fullPath, + const QString &mediaType) { xml.writeStartElement("manifest:file-entry"); xml.writeAttribute("manifest:full-path", fullPath); @@ -264,12 +270,12 @@ void OdtDocument::writeFileEntry(QXmlStreamWriter& xml, xml.writeEndElement(); } -void OdtDocument::saveManifest(const QString& path) +void OdtDocument::saveManifest(const QString &path) { const QString xmlMime = QLatin1String("text/xml"); QDir manifestDir(path + metaInfDirPath); - if(!manifestDir.exists()) + if (!manifestDir.exists()) manifestDir.mkpath("."); QFile manifest(manifestDir.filePath(manifestFileName)); @@ -281,30 +287,30 @@ void OdtDocument::saveManifest(const QString& path) xml.writeNamespace("urn:oasis:names:tc:opendocument:xmlns:manifest:1.0", "manifest"); xml.writeAttribute("manifest:version", "1.2"); - //Root + // Root writeFileEntry(xml, "/", "application/vnd.oasis.opendocument.text"); - //styles.xml + // styles.xml writeFileEntry(xml, stylesFileName, xmlMime); - //content.xml + // content.xml writeFileEntry(xml, contentFileName, xmlMime); - //meta.xml + // meta.xml writeFileEntry(xml, metaFileName, xmlMime); - //Add possible images - for(const auto& img : qAsConst(imageList)) + // Add possible images + for (const auto &img : qAsConst(imageList)) { writeFileEntry(xml, "Pictures/" + img.first, img.second); } - xml.writeEndElement(); //manifest:manifest + xml.writeEndElement(); // manifest:manifest xml.writeEndDocument(); } -void OdtDocument::saveMeta(const QString& path) +void OdtDocument::saveMeta(const QString &path) { QDir metaDir(path); @@ -323,122 +329,122 @@ void OdtDocument::saveMeta(const QString& path) xml.writeStartElement("office:meta"); - MetaDataManager *meta = Session->getMetaDataManager(); + MetaDataManager *meta = Session->getMetaDataManager(); const bool storeLocationAndDate = AppSettings.getSheetStoreLocationDateInMeta(); - //Title - if(!documentTitle.isEmpty()) + // Title + if (!documentTitle.isEmpty()) { xml.writeStartElement("dc:title"); xml.writeCharacters(documentTitle); - xml.writeEndElement(); //dc:title + xml.writeEndElement(); // dc:title } - //Subject + // Subject xml.writeStartElement("dc:subject"); xml.writeCharacters(AppDisplayName); - xml.writeCharacters(" Session Meeting"); //Do not translate, so it's standard for everyone - xml.writeEndElement(); //dc:subject + xml.writeCharacters(" Session Meeting"); // Do not translate, so it's standard for everyone + xml.writeEndElement(); // dc:subject - //Description + // Description QString meetingLocation; - if(storeLocationAndDate) + if (storeLocationAndDate) { meta->getString(meetingLocation, MetaDataKey::MeetingLocation); QDate start, end; qint64 tmp = 0; - if(meta->getInt64(tmp, MetaDataKey::MeetingStartDate) == MetaDataKey::ValueFound) + if (meta->getInt64(tmp, MetaDataKey::MeetingStartDate) == MetaDataKey::ValueFound) start = QDate::fromJulianDay(tmp); - if(meta->getInt64(tmp, MetaDataKey::MeetingEndDate) == MetaDataKey::ValueFound) + if (meta->getInt64(tmp, MetaDataKey::MeetingEndDate) == MetaDataKey::ValueFound) end = QDate::fromJulianDay(tmp); - if(!end.isValid() || end < start) + if (!end.isValid() || end < start) end = start; - if(!meetingLocation.isEmpty() && start.isValid()) + if (!meetingLocation.isEmpty() && start.isValid()) { - //Store description only if metadata is valid - //Example: Meeting in CORNUDA from 07/11/2020 to 09/11/2020 + // Store description only if metadata is valid + // Example: Meeting in CORNUDA from 07/11/2020 to 09/11/2020 QString description; - if(start != end) + if (start != end) { - description = Odt::text(Odt::meetingFromTo) - .arg(meetingLocation, - start.toString("dd/MM/yyyy"), - end.toString("dd/MM/yyyy")); + description = + Odt::text(Odt::meetingFromTo) + .arg(meetingLocation, start.toString("dd/MM/yyyy"), end.toString("dd/MM/yyyy")); } else { - description = Odt::text(Odt::meetingOnDate) - .arg(meetingLocation, - start.toString("dd/MM/yyyy")); + description = + Odt::text(Odt::meetingOnDate).arg(meetingLocation, start.toString("dd/MM/yyyy")); } xml.writeStartElement("dc:description"); xml.writeCharacters(description); - xml.writeEndElement(); //dc:description + xml.writeEndElement(); // dc:description } } - //Language + // Language xml.writeStartElement("dc:language"); xml.writeCharacters(Session->getSheetExportLocale().bcp47Name()); - xml.writeEndElement(); //dc:language + xml.writeEndElement(); // dc:language - //Generator + // Generator xml.writeStartElement("meta:generator"); xml.writeCharacters(AppProduct); xml.writeCharacters("/"); xml.writeCharacters(AppVersion); xml.writeCharacters("-"); xml.writeCharacters(AppBuildDate); - xml.writeEndElement(); //meta:generator + xml.writeEndElement(); // meta:generator - //Initial creator + // Initial creator xml.writeStartElement("meta:initial-creator"); xml.writeCharacters(AppDisplayName); - xml.writeEndElement(); //meta:initial-creator + xml.writeEndElement(); // meta:initial-creator - //Creation date + // Creation date xml.writeStartElement("meta:creation-date"); - //NOTE: date must be in ISO 8601 format but without time zone offset (LibreOffice doesn't recognize it) - // so do not use Qt::ISODate otherwise there is the risk of adding time zone offset to string + // NOTE: date must be in ISO 8601 format but without time zone offset (LibreOffice doesn't + // recognize it) + // so do not use Qt::ISODate otherwise there is the risk of adding time zone offset to + // string xml.writeCharacters(QDateTime::currentDateTime().toString("yyyy-MM-ddTHH:mm:ss")); - xml.writeEndElement(); //meta:creation-date + xml.writeEndElement(); // meta:creation-date - //Keywords + // Keywords xml.writeStartElement("meta:keyword"); xml.writeCharacters(AppDisplayName); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword xml.writeStartElement("meta:keyword"); xml.writeCharacters(AppProduct); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword xml.writeStartElement("meta:keyword"); xml.writeCharacters(AppCompany); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword xml.writeStartElement("meta:keyword"); xml.writeCharacters(Odt::text(Odt::meeting)); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword - //Untranslated version + // Untranslated version xml.writeStartElement("meta:keyword"); xml.writeCharacters(QString::fromUtf8(Odt::meeting.sourceText)); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword - if(storeLocationAndDate && !meetingLocation.isEmpty()) + if (storeLocationAndDate && !meetingLocation.isEmpty()) { xml.writeStartElement("meta:keyword"); xml.writeCharacters(meetingLocation); - xml.writeEndElement(); //meta:keyword + xml.writeEndElement(); // meta:keyword } - //End - xml.writeEndElement(); //office:meta - xml.writeEndElement(); //office:document-meta + // End + xml.writeEndElement(); // office:meta + xml.writeEndElement(); // office:document-meta xml.writeEndDocument(); } diff --git a/src/odt_export/common/odtdocument.h b/src/odt_export/common/odtdocument.h index 7e61727..3e93d8f 100644 --- a/src/odt_export/common/odtdocument.h +++ b/src/odt_export/common/odtdocument.h @@ -35,10 +35,13 @@ public: void startBody(); void endDocument(); - //Returns a 'path + file name' where you must save the image - QString addImage(const QString& name, const QString& mediaType); + // Returns a 'path + file name' where you must save the image + QString addImage(const QString &name, const QString &mediaType); - inline void setTitle(const QString& title) { documentTitle = title; } + inline void setTitle(const QString &title) + { + documentTitle = title; + } public: QTemporaryDir dir; @@ -57,7 +60,7 @@ private: private: QString documentTitle; - //pair: fileName, mediaType + // pair: fileName, mediaType QList> imageList; }; diff --git a/src/odt_export/common/odtutils.cpp b/src/odt_export/common/odtutils.cpp index 14757cf..0c6c757 100644 --- a/src/odt_export/common/odtutils.cpp +++ b/src/odt_export/common/odtutils.cpp @@ -34,29 +34,31 @@ void writeColumnStyle(QXmlStreamWriter &xml, const QString &name, const QString xml.writeStartElement("style:table-column-properties"); xml.writeAttribute("style:column-width", width); - xml.writeEndElement(); //style:table-column-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-column-properties + xml.writeEndElement(); // style } /* writeCell * * Helper function to write table cell - * Sets up the cell style and paragraph style, writes single line text and closes xml opened elements + * Sets up the cell style and paragraph style, writes single line text and closes xml opened + * elements */ -void writeCell(QXmlStreamWriter &xml, const QString &cellStyle, const QString ¶graphStyle, const QString &text) +void writeCell(QXmlStreamWriter &xml, const QString &cellStyle, const QString ¶graphStyle, + const QString &text) { - //Cell + // Cell xml.writeStartElement("table:table-cell"); xml.writeAttribute("office:value-type", "string"); xml.writeAttribute("table:style-name", cellStyle); - //text:p + // text:p xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", paragraphStyle); xml.writeCharacters(text); - xml.writeEndElement(); //text:p + xml.writeEndElement(); // text:p - xml.writeEndElement(); //table-cell + xml.writeEndElement(); // table-cell } /* writeCellListStart @@ -66,14 +68,15 @@ void writeCell(QXmlStreamWriter &xml, const QString &cellStyle, const QString &p * Then you have full control on cell contents * Then call writeCellListEnd */ -void writeCellListStart(QXmlStreamWriter &xml, const QString &cellStyle, const QString ¶graphStyle) +void writeCellListStart(QXmlStreamWriter &xml, const QString &cellStyle, + const QString ¶graphStyle) { - //Cell + // Cell xml.writeStartElement("table:table-cell"); xml.writeAttribute("office:value-type", "string"); xml.writeAttribute("table:style-name", cellStyle); - //text:p + // text:p xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", paragraphStyle); } @@ -84,8 +87,8 @@ void writeCellListStart(QXmlStreamWriter &xml, const QString &cellStyle, const Q */ void writeCellListEnd(QXmlStreamWriter &xml) { - xml.writeEndElement(); //text:p - xml.writeEndElement(); //table-cell + xml.writeEndElement(); // text:p + xml.writeEndElement(); // table-cell } void writeStandardStyle(QXmlStreamWriter &xml) @@ -96,7 +99,7 @@ void writeStandardStyle(QXmlStreamWriter &xml) xml.writeAttribute("style:family", "paragraph"); xml.writeAttribute("style:class", "text"); - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } void writeGraphicsStyle(QXmlStreamWriter &xml) @@ -113,9 +116,9 @@ void writeGraphicsStyle(QXmlStreamWriter &xml) xml.writeAttribute("style:vertical-rel", "paragraph"); xml.writeAttribute("style:horizontal-pos", "center"); xml.writeAttribute("style:horizontal-rel", "paragraph"); - xml.writeEndElement(); //style:graphic-properties + xml.writeEndElement(); // style:graphic-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } void writeCommonStyles(QXmlStreamWriter &xml) @@ -154,14 +157,14 @@ void writeCommonStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "18pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P4 * type: paragraph style @@ -199,14 +202,14 @@ void writeCommonStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "12pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style T1 * type: text style @@ -225,14 +228,14 @@ void writeCommonStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } void writeFooterStyle(QXmlStreamWriter &xml) { - //Base style for MP1 style used in header/footer + // Base style for MP1 style used in header/footer xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); @@ -250,33 +253,33 @@ void writeFooterStyle(QXmlStreamWriter &xml) xml.writeStartElement("style:tab-stop"); xml.writeAttribute("style:position", "8.5cm"); xml.writeAttribute("style:type", "center"); - xml.writeEndElement(); //style:tab-stop + xml.writeEndElement(); // style:tab-stop xml.writeStartElement("style:tab-stop"); xml.writeAttribute("style:position", "17cm"); xml.writeAttribute("style:type", "right"); - xml.writeEndElement(); //style:tab-stop + xml.writeEndElement(); // style:tab-stop - xml.writeEndElement(); //style:tab-stops + xml.writeEndElement(); // style:tab-stops - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } void writePageLayout(QXmlStreamWriter &xml) { - //Footer style + // Footer style xml.writeStartElement("style:style"); xml.writeAttribute("style:name", "MP1"); xml.writeAttribute("style:family", "paragraph"); xml.writeAttribute("style:parent-style-name", "Footer"); xml.writeStartElement("style:text-properties"); xml.writeAttribute("style:font-name", "Liberation Sans"); - xml.writeEndElement(); //style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:text-properties + xml.writeEndElement(); // style:style - //Page Layout + // Page Layout xml.writeStartElement("style:page-layout"); xml.writeAttribute("style:name", "Mpm1"); @@ -286,25 +289,25 @@ void writePageLayout(QXmlStreamWriter &xml) xml.writeAttribute("fo:margin-bottom", "2cm"); xml.writeAttribute("fo:margin-left", "2cm"); xml.writeAttribute("fo:margin-right", "2cm"); - xml.writeEndElement(); //style:page-layout-properties + xml.writeEndElement(); // style:page-layout-properties xml.writeStartElement("style:header-style"); - xml.writeEndElement(); //style:header-style + xml.writeEndElement(); // style:header-style xml.writeStartElement("style:footer-style"); - xml.writeEndElement(); //style:footer-style + xml.writeEndElement(); // style:footer-style - xml.writeEndElement(); //style:page-layout + xml.writeEndElement(); // style:page-layout } -void writeHeaderFooter(QXmlStreamWriter &xml, const QString& headerText, const QString& footerText) +void writeHeaderFooter(QXmlStreamWriter &xml, const QString &headerText, const QString &footerText) { xml.writeStartElement("style:master-page"); xml.writeAttribute("style:name", "Standard"); - xml.writeAttribute("style:page-layout-name", "Mpm1"); //TODO + xml.writeAttribute("style:page-layout-name", "Mpm1"); // TODO - //Header + // Header xml.writeStartElement("style:header"); xml.writeStartElement("text:p"); @@ -313,10 +316,10 @@ void writeHeaderFooter(QXmlStreamWriter &xml, const QString& headerText, const Q xml.writeCharacters(headerText); xml.writeStartElement("text:tab"); - xml.writeEndElement(); //text:tab + xml.writeEndElement(); // text:tab xml.writeStartElement("text:tab"); - xml.writeEndElement(); //text:tab + xml.writeEndElement(); // text:tab const QString pageStr = Odt::text(Odt::headerPage); @@ -324,13 +327,13 @@ void writeHeaderFooter(QXmlStreamWriter &xml, const QString& headerText, const Q xml.writeStartElement("text:page-number"); xml.writeAttribute("text:select-page", "current"); - xml.writeEndElement(); //text:page-number + xml.writeEndElement(); // text:page-number - xml.writeEndElement(); //text:p + xml.writeEndElement(); // text:p - xml.writeEndElement(); //style:header + xml.writeEndElement(); // style:header - //Header for left pages (mirrored) + // Header for left pages (mirrored) xml.writeStartElement("style:header-left"); xml.writeStartElement("text:p"); @@ -340,21 +343,21 @@ void writeHeaderFooter(QXmlStreamWriter &xml, const QString& headerText, const Q xml.writeStartElement("text:page-number"); xml.writeAttribute("text:select-page", "current"); - xml.writeEndElement(); //text:page-number + xml.writeEndElement(); // text:page-number xml.writeStartElement("text:tab"); - xml.writeEndElement(); //text:tab + xml.writeEndElement(); // text:tab xml.writeStartElement("text:tab"); - xml.writeEndElement(); //text:tab + xml.writeEndElement(); // text:tab xml.writeCharacters(headerText); - xml.writeEndElement(); //text:p + xml.writeEndElement(); // text:p - xml.writeEndElement(); //style:header-left + xml.writeEndElement(); // style:header-left - //Footer + // Footer xml.writeStartElement("style:footer"); xml.writeStartElement("text:p"); @@ -362,19 +365,19 @@ void writeHeaderFooter(QXmlStreamWriter &xml, const QString& headerText, const Q xml.writeCharacters(footerText); - xml.writeEndElement(); //text:p + xml.writeEndElement(); // text:p - xml.writeEndElement(); //style:footer + xml.writeEndElement(); // style:footer - xml.writeEndElement(); //style:master-page + xml.writeEndElement(); // style:master-page } void writeLiberationFontFaces(QXmlStreamWriter &xml) { - const QString variablePitch = QStringLiteral("variable"); + const QString variablePitch = QStringLiteral("variable"); const QString liberationSerif = QStringLiteral("Liberation Serif"); - const QString liberationSans = QStringLiteral("Liberation Sans"); - const QString liberationMono = QStringLiteral("Liberation Mono"); + const QString liberationSans = QStringLiteral("Liberation Sans"); + const QString liberationMono = QStringLiteral("Liberation Mono"); writeFontFace(xml, liberationSerif, liberationSerif, "roman", variablePitch); writeFontFace(xml, liberationSans, liberationSans, "swiss", variablePitch); @@ -386,18 +389,18 @@ QString Odt::text(const Text &t) QTranslator *translator = Session->getSheetExportTranslator(); QString result; - if(translator) + if (translator) { - //Prefer selected language + // Prefer selected language result = translator->translate("Odt", t.sourceText, t.disambiguation); } - else if(Session->getSheetExportLocale() == MeetingSession::embeddedLocale) + else if (Session->getSheetExportLocale() == MeetingSession::embeddedLocale) { - //Bypass any translation and use hardcoded string literals + // Bypass any translation and use hardcoded string literals return QString::fromUtf8(t.sourceText); } - if(result.isNull()) //Fallback to application language + if (result.isNull()) // Fallback to application language result = tr(t.sourceText, t.disambiguation); return result; } diff --git a/src/odt_export/common/odtutils.h b/src/odt_export/common/odtutils.h index fd67e88..d5196d5 100644 --- a/src/odt_export/common/odtutils.h +++ b/src/odt_export/common/odtutils.h @@ -24,16 +24,14 @@ #include -//small util -void writeColumnStyle(QXmlStreamWriter& xml, const QString& name, const QString& width); +// small util +void writeColumnStyle(QXmlStreamWriter &xml, const QString &name, const QString &width); -void writeCell(QXmlStreamWriter &xml, - const QString& cellStyle, - const QString& paragraphStyle, - const QString& text); +void writeCell(QXmlStreamWriter &xml, const QString &cellStyle, const QString ¶graphStyle, + const QString &text); - -void writeCellListStart(QXmlStreamWriter &xml, const QString &cellStyle, const QString ¶graphStyle); +void writeCellListStart(QXmlStreamWriter &xml, const QString &cellStyle, + const QString ¶graphStyle); void writeCellListEnd(QXmlStreamWriter &xml); void writeStandardStyle(QXmlStreamWriter &xml); @@ -46,37 +44,34 @@ void writeFooterStyle(QXmlStreamWriter &xml); void writePageLayout(QXmlStreamWriter &xml); -void writeHeaderFooter(QXmlStreamWriter &xml, - const QString& headerText, - const QString& footerText); +void writeHeaderFooter(QXmlStreamWriter &xml, const QString &headerText, const QString &footerText); -inline void writeFontFace(QXmlStreamWriter &xml, - const QString& name, const QString& family, - const QString& genericFamily, const QString& pitch) +inline void writeFontFace(QXmlStreamWriter &xml, const QString &name, const QString &family, + const QString &genericFamily, const QString &pitch) { xml.writeStartElement("style:font-face"); xml.writeAttribute("style:name", name); - if(!family.isEmpty()) + if (!family.isEmpty()) { QString familyQuoted; familyQuoted.reserve(family.size() + 2); - bool needsQuotes = family.contains(' '); //If family name contains blanks - if(needsQuotes) //Enclose in single quotes + bool needsQuotes = family.contains(' '); // If family name contains blanks + if (needsQuotes) // Enclose in single quotes familyQuoted.append('\''); familyQuoted.append(family); - if(needsQuotes) + if (needsQuotes) familyQuoted.append('\''); xml.writeAttribute("svg:font-family", familyQuoted); } - if(!genericFamily.isEmpty()) + if (!genericFamily.isEmpty()) { xml.writeAttribute("svg:font-family-generic", genericFamily); } - if(!pitch.isEmpty()) + if (!pitch.isEmpty()) { xml.writeAttribute("svg:font-pitch", pitch); } - xml.writeEndElement(); //style:font-face + xml.writeEndElement(); // style:font-face } void writeLiberationFontFaces(QXmlStreamWriter &xml); @@ -91,72 +86,90 @@ public: const char *disambiguation; }; - static QString text(const Text& t); + static QString text(const Text &t); public: - //Header/Footer - static constexpr Text headerPage = QT_TRANSLATE_NOOP3("Odt", "Page ", - "Header page, leave space at end, page number will be added"); + // Header/Footer + static constexpr Text headerPage = QT_TRANSLATE_NOOP3( + "Odt", "Page ", "Header page, leave space at end, page number will be added"); - //Meeting + // Meeting static constexpr Text meeting = QT_TRANSLATE_NOOP3("Odt", "Meeting", "Document keywords"); - static constexpr Text meetingFromTo = QT_TRANSLATE_NOOP3("Odt", "Meeting in %1 from %2 to %3", - "Document description, where, from date, to date"); - static constexpr Text meetingOnDate = QT_TRANSLATE_NOOP3("Odt", "Meeting in %1 on %2", - "Document description, where, when"); - static constexpr Text meetingFromToShort = QT_TRANSLATE_NOOP3("Odt", "From %1 to %2", - "Shift cover, meeting from date, to date"); + static constexpr Text meetingFromTo = QT_TRANSLATE_NOOP3( + "Odt", "Meeting in %1 from %2 to %3", "Document description, where, from date, to date"); + static constexpr Text meetingOnDate = + QT_TRANSLATE_NOOP3("Odt", "Meeting in %1 on %2", "Document description, where, when"); + static constexpr Text meetingFromToShort = + QT_TRANSLATE_NOOP3("Odt", "From %1 to %2", "Shift cover, meeting from date, to date"); - //Rollingstock - static constexpr Text CoupledAbbr = QT_TRANSLATE_NOOP3("Odt", "Cp:", "Job stop coupled RS"); - static constexpr Text UncoupledAbbr = QT_TRANSLATE_NOOP3("Odt", "Unc:", "Job stop uncoupled RS"); + // Rollingstock + static constexpr Text CoupledAbbr = QT_TRANSLATE_NOOP3("Odt", "Cp:", "Job stop coupled RS"); + static constexpr Text UncoupledAbbr = + QT_TRANSLATE_NOOP3("Odt", "Unc:", "Job stop uncoupled RS"); static constexpr Text genericRSOwner = QT_TRANSLATE_NOOP3("Odt", "Owner", "Rollingstock Owner"); - static constexpr Text rsSessionTitle = QT_TRANSLATE_NOOP3("Odt", "Rollingstock by %1 at %2 of session", - "Rollingstock Session title, 1 is Owner/Station and 2 is start/end"); - static constexpr Text rsSessionStart = QT_TRANSLATE_NOOP3("Odt", "start", "Rollingstock Session start"); - static constexpr Text rsSessionEnd = QT_TRANSLATE_NOOP3("Odt", "end", "Rollingstock Session end"); + static constexpr Text rsSessionTitle = + QT_TRANSLATE_NOOP3("Odt", "Rollingstock by %1 at %2 of session", + "Rollingstock Session title, 1 is Owner/Station and 2 is start/end"); + static constexpr Text rsSessionStart = + QT_TRANSLATE_NOOP3("Odt", "start", "Rollingstock Session start"); + static constexpr Text rsSessionEnd = + QT_TRANSLATE_NOOP3("Odt", "end", "Rollingstock Session end"); - //Job Summary - static constexpr Text jobSummaryFrom = QT_TRANSLATE_NOOP3("Odt", "From:", "Job summary"); - static constexpr Text jobSummaryTo = QT_TRANSLATE_NOOP3("Odt", "To:", "Job summary"); + // Job Summary + static constexpr Text jobSummaryFrom = QT_TRANSLATE_NOOP3("Odt", "From:", "Job summary"); + static constexpr Text jobSummaryTo = QT_TRANSLATE_NOOP3("Odt", "To:", "Job summary"); static constexpr Text jobSummaryDep = QT_TRANSLATE_NOOP3("Odt", "Departure:", "Job summary"); - static constexpr Text jobSummaryArr = QT_TRANSLATE_NOOP3("Odt", "Arrival:", "Job summary"); - static constexpr Text jobSummaryAxes = QT_TRANSLATE_NOOP3("Odt", "Axes:", "Job summary"); + static constexpr Text jobSummaryArr = QT_TRANSLATE_NOOP3("Odt", "Arrival:", "Job summary"); + static constexpr Text jobSummaryAxes = QT_TRANSLATE_NOOP3("Odt", "Axes:", "Job summary"); - //Job Stops Header - static constexpr Text station = QT_TRANSLATE_NOOP3("Odt", "Station", "Job stop table"); - static constexpr Text stationPageTitle = QT_TRANSLATE_NOOP3("Odt", "Station: %1", "Station title in station sheet"); - static constexpr Text stationDocTitle = QT_TRANSLATE_NOOP3("Odt", "%1 station", "Station sheet title in document metadata"); - static constexpr Text rollingstock = QT_TRANSLATE_NOOP3("Odt", "Rollingstock", "Job stop table"); - static constexpr Text jobNr = QT_TRANSLATE_NOOP3("Odt", "Job Nr", "Job column"); + // Job Stops Header + static constexpr Text station = QT_TRANSLATE_NOOP3("Odt", "Station", "Job stop table"); + static constexpr Text stationPageTitle = + QT_TRANSLATE_NOOP3("Odt", "Station: %1", "Station title in station sheet"); + static constexpr Text stationDocTitle = + QT_TRANSLATE_NOOP3("Odt", "%1 station", "Station sheet title in document metadata"); + static constexpr Text rollingstock = + QT_TRANSLATE_NOOP3("Odt", "Rollingstock", "Job stop table"); + static constexpr Text jobNr = QT_TRANSLATE_NOOP3("Odt", "Job Nr", "Job column"); - static constexpr Text arrival = QT_TRANSLATE_NOOP3("Odt", "Arrival", "Job stop table"); - static constexpr Text departure = QT_TRANSLATE_NOOP3("Odt", "Departure", "Job stop table"); - static constexpr Text arrivalShort = QT_TRANSLATE_NOOP3("Odt", "Arr.", "Arrival abbreviated"); - static constexpr Text departureShort = QT_TRANSLATE_NOOP3("Odt", "Dep.", "Departure abbreviated"); + static constexpr Text arrival = QT_TRANSLATE_NOOP3("Odt", "Arrival", "Job stop table"); + static constexpr Text departure = QT_TRANSLATE_NOOP3("Odt", "Departure", "Job stop table"); + static constexpr Text arrivalShort = QT_TRANSLATE_NOOP3("Odt", "Arr.", "Arrival abbreviated"); + static constexpr Text departureShort = + QT_TRANSLATE_NOOP3("Odt", "Dep.", "Departure abbreviated"); - static constexpr Text stationFromCol = QT_TRANSLATE_NOOP3("Odt", "From", "Station stop table, From previous station column"); - static constexpr Text stationToCol = QT_TRANSLATE_NOOP3("Odt", "To", "Station stop table, To next station column"); + static constexpr Text stationFromCol = + QT_TRANSLATE_NOOP3("Odt", "From", "Station stop table, From previous station column"); + static constexpr Text stationToCol = + QT_TRANSLATE_NOOP3("Odt", "To", "Station stop table, To next station column"); - static constexpr Text jobStopPlatf = QT_TRANSLATE_NOOP3("Odt", "Platf", "Job stop table, platform abbreviated"); - static constexpr Text jobStopIsTransit = QT_TRANSLATE_NOOP3("Odt", "Transit", "Job stop table, notes column"); - static constexpr Text jobStopIsFirst = QT_TRANSLATE_NOOP3("Odt", "START", - "Station stop table, notes column for first job stop, " - "keep in English it's the same for every sheet"); + static constexpr Text jobStopPlatf = + QT_TRANSLATE_NOOP3("Odt", "Platf", "Job stop table, platform abbreviated"); + static constexpr Text jobStopIsTransit = + QT_TRANSLATE_NOOP3("Odt", "Transit", "Job stop table, notes column"); + static constexpr Text jobStopIsFirst = + QT_TRANSLATE_NOOP3("Odt", "START", + "Station stop table, notes column for first job stop, " + "keep in English it's the same for every sheet"); - static constexpr Text jobStopCross = QT_TRANSLATE_NOOP3("Odt", "Crossings", "Job stop table"); - static constexpr Text jobStopPassings = QT_TRANSLATE_NOOP3("Odt", "Passings", "Job stop table"); - static constexpr Text jobStopCrossShort = QT_TRANSLATE_NOOP3("Odt", "Cross", "Job stop crossings abbreviated column"); - static constexpr Text jobStopPassingsShort = QT_TRANSLATE_NOOP3("Odt", "Passes", "Job stop passings abbreviated column"); + static constexpr Text jobStopCross = QT_TRANSLATE_NOOP3("Odt", "Crossings", "Job stop table"); + static constexpr Text jobStopPassings = QT_TRANSLATE_NOOP3("Odt", "Passings", "Job stop table"); + static constexpr Text jobStopCrossShort = + QT_TRANSLATE_NOOP3("Odt", "Cross", "Job stop crossings abbreviated column"); + static constexpr Text jobStopPassingsShort = + QT_TRANSLATE_NOOP3("Odt", "Passes", "Job stop passings abbreviated column"); static constexpr Text notes = QT_TRANSLATE_NOOP3("Odt", "Notes", "Job stop table"); - //Job stops - static constexpr Text jobReverseDirection = QT_TRANSLATE_NOOP3("Odt", "Reverse direction", "Job stop table"); + // Job stops + static constexpr Text jobReverseDirection = + QT_TRANSLATE_NOOP3("Odt", "Reverse direction", "Job stop table"); - //Shift - static constexpr Text shiftCoverTitle = QT_TRANSLATE_NOOP3("Odt", "SHIFT %1", "Shift title in shift sheet cover"); - static constexpr Text shiftDocTitle = QT_TRANSLATE_NOOP3("Odt", "Shift %1", "Shift sheet document title for metadata"); + // Shift + static constexpr Text shiftCoverTitle = + QT_TRANSLATE_NOOP3("Odt", "SHIFT %1", "Shift title in shift sheet cover"); + static constexpr Text shiftDocTitle = + QT_TRANSLATE_NOOP3("Odt", "Shift %1", "Shift sheet document title for metadata"); }; #endif // ODTUTILS_H diff --git a/src/odt_export/common/sessionrswriter.cpp b/src/odt_export/common/sessionrswriter.cpp index 5ff7686..1c0069e 100644 --- a/src/odt_export/common/sessionrswriter.cpp +++ b/src/odt_export/common/sessionrswriter.cpp @@ -33,43 +33,39 @@ SessionRSWriter::SessionRSWriter(database &db, SessionRSMode mode, SessionRSOrde m_mode(mode), m_order(order) { - //TODO: fetch departure instead of arrival for start session - const auto sql = QStringLiteral("SELECT %1," - " %2, %3, %4," - " rs_list.id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type," - " t1.name,t2.name," - " stops.job_id, jobs.category, coupling.operation" - " FROM rs_list" - " JOIN coupling ON coupling.rs_id=rs_list.id" - " JOIN stops ON stops.id=coupling.stop_id" - " JOIN jobs ON jobs.id=stops.job_id" - " JOIN rs_models ON rs_models.id=rs_list.model_id" - " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" - " LEFT JOIN station_gate_connections g2 ON g2.id=stops.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" - " JOIN %5" - " GROUP BY rs_list.id" - " ORDER BY %6, stops.arrival, stops.job_id, rs_list.model_id"); + // TODO: fetch departure instead of arrival for start session + const auto sql = QStringLiteral( + "SELECT %1," + " %2, %3, %4," + " rs_list.id, rs_list.number, rs_models.name, rs_models.suffix, rs_models.type," + " t1.name,t2.name," + " stops.job_id, jobs.category, coupling.operation" + " FROM rs_list" + " JOIN coupling ON coupling.rs_id=rs_list.id" + " JOIN stops ON stops.id=coupling.stop_id" + " JOIN jobs ON jobs.id=stops.job_id" + " JOIN rs_models ON rs_models.id=rs_list.model_id" + " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" + " LEFT JOIN station_gate_connections g2 ON g2.id=stops.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" + " JOIN %5" + " GROUP BY rs_list.id" + " ORDER BY %6, stops.arrival, stops.job_id, rs_list.model_id"); - QString temp = sql.arg(m_mode == SessionRSMode::StartOfSession ? "MIN(stops.arrival)" : "MAX(stops.departure)"); - if(m_order == SessionRSOrder::ByStation) + QString temp = sql.arg(m_mode == SessionRSMode::StartOfSession ? "MIN(stops.arrival)" + : "MAX(stops.departure)"); + if (m_order == SessionRSOrder::ByStation) { - temp = temp.arg("rs_list.owner_id", - "rs_owners.name", - "stops.station_id", - "rs_owners ON rs_owners.id=rs_list.owner_id", - "stops.station_id"); + temp = temp.arg("rs_list.owner_id", "rs_owners.name", "stops.station_id", + "rs_owners ON rs_owners.id=rs_list.owner_id", "stops.station_id"); q_getParentName.prepare("SELECT name FROM stations WHERE id=?"); } else { - temp = temp.arg("stops.station_id", - "stations.name", - "rs_list.owner_id", - "stations ON stations.id=stops.station_id", - "rs_list.owner_id"); + temp = temp.arg("stops.station_id", "stations.name", "rs_list.owner_id", + "stations ON stations.id=stops.station_id", "rs_list.owner_id"); q_getParentName.prepare("SELECT name FROM rs_owners WHERE id=?"); } @@ -91,7 +87,8 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) * Like P4 but not bold, and Sans Serif * * Usages: - * - job_stops: stop cell text for normal stops and transit Rollingstock/Crossings/Passings/Description + * - job_stops: stop cell text for normal stops and transit + * Rollingstock/Crossings/Passings/Description */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); @@ -100,27 +97,26 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("style:font-name", "Liberation Sans"); xml.writeAttribute("fo:font-size", "12pt"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style - - //rs_table Table + // rs_table Table /* Style: rs_5f_table - * - * Type: table - * Display name: rollingstock - * Align: left - * Width: 16.0cm - * - * Usage: - * - SessionRSWriter: main table for Rollingstock Owners/Stations - */ + * + * Type: table + * Display name: rollingstock + * Align: left + * Width: 16.0cm + * + * Usage: + * - SessionRSWriter: main table for Rollingstock Owners/Stations + */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "table"); xml.writeAttribute("style:name", "rs_5f_table"); @@ -129,15 +125,15 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeAttribute("style:shadow", "none"); xml.writeAttribute("table:align", "left"); xml.writeAttribute("style:width", "16.0cm"); - xml.writeEndElement(); //style:table-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-properties + xml.writeEndElement(); // style - //rs_table columns - writeColumnStyle(xml, "rs_5f_table.A", "3.00cm"); //RS Name - writeColumnStyle(xml, "rs_5f_table.B", "4.45cm"); //Job - writeColumnStyle(xml, "rs_5f_table.C", "2.21cm"); //Platf - writeColumnStyle(xml, "rs_5f_table.D", "3.17cm"); //Departure or Arrival - writeColumnStyle(xml, "rs_5f_table.E", "4.00cm"); //Station or Owner + // rs_table columns + writeColumnStyle(xml, "rs_5f_table.A", "3.00cm"); // RS Name + writeColumnStyle(xml, "rs_5f_table.B", "4.45cm"); // Job + writeColumnStyle(xml, "rs_5f_table.C", "2.21cm"); // Platf + writeColumnStyle(xml, "rs_5f_table.D", "3.17cm"); // Departure or Arrival + writeColumnStyle(xml, "rs_5f_table.E", "4.00cm"); // Station or Owner /* Style: rs_5f_table.A1 * @@ -158,8 +154,8 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-right", "none"); xml.writeAttribute("fo:border-top", "0.05pt solid #000000"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: rs_5f_table.E1 * @@ -177,8 +173,8 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:table-cell-properties"); xml.writeAttribute("fo:padding", "0.049cm"); xml.writeAttribute("fo:border", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: rs_5f_table.A2 * @@ -199,8 +195,8 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-right", "none"); xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: rs_5f_table.E2 * @@ -221,90 +217,93 @@ void SessionRSWriter::writeStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-right", "0.05pt solid #000000"); xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style } -db_id SessionRSWriter::writeTable(QXmlStreamWriter &xml, const QString& parentName) +db_id SessionRSWriter::writeTable(QXmlStreamWriter &xml, const QString &parentName) { - //Table '???_table' where ??? is the station/owner name without spaces + // Table '???_table' where ??? is the station/owner name without spaces QString tableName = parentName; - tableName.replace(' ', '_'); //Replace spaces with underscores + tableName.replace(' ', '_'); // Replace spaces with underscores tableName.append("_table"); xml.writeStartElement("table:table"); xml.writeAttribute("table:name", tableName); xml.writeAttribute("table:style-name", "rs_5f_table"); - //Columns - xml.writeEmptyElement("table:table-column"); //A - RS Name + // Columns + xml.writeEmptyElement("table:table-column"); // A - RS Name xml.writeAttribute("table:style-name", "rs_5f_table.A"); - xml.writeEmptyElement("table:table-column"); //B - Job + xml.writeEmptyElement("table:table-column"); // B - Job xml.writeAttribute("table:style-name", "rs_5f_table.B"); - xml.writeEmptyElement("table:table-column"); //C - Platf + xml.writeEmptyElement("table:table-column"); // C - Platf xml.writeAttribute("table:style-name", "rs_5f_table.C"); - xml.writeEmptyElement("table:table-column"); //D - Departure + xml.writeEmptyElement("table:table-column"); // D - Departure xml.writeAttribute("table:style-name", "rs_5f_table.D"); - xml.writeEmptyElement("table:table-column"); //E - Station or Owner + xml.writeEmptyElement("table:table-column"); // E - Station or Owner xml.writeAttribute("table:style-name", "rs_5f_table.E"); - //Row 1 (Heading) + // Row 1 (Heading) xml.writeStartElement("table:table-header-rows"); xml.writeStartElement("table:table-row"); const QString P4_style = QStringLiteral("P4"); const QString P5_style = QStringLiteral("P5"); - //Cells (column names, headings) + // Cells (column names, headings) writeCell(xml, "rs_5f_table.A1", P4_style, Odt::text(Odt::rollingstock)); writeCell(xml, "rs_5f_table.A1", P4_style, Odt::text(Odt::jobNr)); writeCell(xml, "rs_5f_table.A1", P4_style, Odt::text(Odt::jobStopPlatf)); - writeCell(xml, "rs_5f_table.A1", P4_style, Odt::text(m_mode == SessionRSMode::StartOfSession ? Odt::departure : Odt::arrival)); - writeCell(xml, "rs_5f_table.E1", P4_style, Odt::text(m_order == SessionRSOrder::ByStation ? Odt::genericRSOwner : Odt::station)); + writeCell(xml, "rs_5f_table.A1", P4_style, + Odt::text(m_mode == SessionRSMode::StartOfSession ? Odt::departure : Odt::arrival)); + writeCell(xml, "rs_5f_table.E1", P4_style, + Odt::text(m_order == SessionRSOrder::ByStation ? Odt::genericRSOwner : Odt::station)); - xml.writeEndElement(); //end of row - xml.writeEndElement(); //header section + xml.writeEndElement(); // end of row + xml.writeEndElement(); // header section - //Fill the table - for(; it != q_getSessionRS.end(); ++it) + // Fill the table + for (; it != q_getSessionRS.end(); ++it) { - auto rs = *it; - QTime time = rs.get(0); //Departure or arrival + auto rs = *it; + QTime time = rs.get(0); // Departure or arrival - //db_id stationOrOwnerId = rs.get(1); - QString name = rs.get(2); //Name of the station or owner - db_id parentId = rs.get(3); //ownerOrStation (opposite of stationOrOwner) + // db_id stationOrOwnerId = rs.get(1); + QString name = rs.get(2); // Name of the station or owner + db_id parentId = rs.get(3); // ownerOrStation (opposite of stationOrOwner) - //db_id rsId = rs.get(4); - int number = rs.get(5); - sqlite3_stmt *stmt = q_getSessionRS.stmt(); - int modelNameLen = sqlite3_column_bytes(stmt, 6); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 6)); + // db_id rsId = rs.get(4); + int number = rs.get(5); + sqlite3_stmt *stmt = q_getSessionRS.stmt(); + int modelNameLen = sqlite3_column_bytes(stmt, 6); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 6)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 7); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 7)); - RsType type = RsType(rs.get(8)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 7); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 7)); + RsType type = RsType(rs.get(8)); - QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, modelSuffixLen, type); + QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); QString platform = rs.get(9); - if(platform.isEmpty()) - platform = rs.get(10); //Use out gate to get track name + if (platform.isEmpty()) + platform = rs.get(10); // Use out gate to get track name - db_id jobId = rs.get(11); + db_id jobId = rs.get(11); JobCategory jobCat = JobCategory(rs.get(12)); - if(parentId != lastParentId) + if (parentId != lastParentId) { - xml.writeEndElement(); //table:table + xml.writeEndElement(); // table:table return parentId; } - xml.writeStartElement("table:table-row"); //start new row + xml.writeStartElement("table:table-row"); // start new row writeCell(xml, "rs_5f_table.A2", P5_style, rsName); writeCell(xml, "rs_5f_table.A2", P5_style, JobCategoryName::jobName(jobId, jobCat)); @@ -312,18 +311,18 @@ db_id SessionRSWriter::writeTable(QXmlStreamWriter &xml, const QString& parentNa writeCell(xml, "rs_5f_table.A2", P5_style, time.toString("HH:mm")); writeCell(xml, "rs_5f_table.E2", P5_style, name); - xml.writeEndElement(); //end of row + xml.writeEndElement(); // end of row } - xml.writeEndElement(); //table:table + xml.writeEndElement(); // table:table - return 0; //End of document, no more tables + return 0; // End of document, no more tables } void SessionRSWriter::writeContent(QXmlStreamWriter &xml) { it = q_getSessionRS.begin(); - if(it == q_getSessionRS.end()) + if (it == q_getSessionRS.end()) return; lastParentId = (*it).get(3); @@ -334,7 +333,7 @@ void SessionRSWriter::writeContent(QXmlStreamWriter &xml) QString name = q_getParentName.getRows().get(0); q_getParentName.reset(); - //Write Station or Rollingstock Owner name + // Write Station or Rollingstock Owner name xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeCharacters(name); @@ -342,7 +341,7 @@ void SessionRSWriter::writeContent(QXmlStreamWriter &xml) lastParentId = writeTable(xml, name); - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeEndElement(); @@ -351,8 +350,10 @@ void SessionRSWriter::writeContent(QXmlStreamWriter &xml) QString SessionRSWriter::generateTitle() const { - QString title = Odt::text(Odt::rsSessionTitle).arg( - Odt::text(m_order == SessionRSOrder::ByStation ? Odt::genericRSOwner : Odt::station), - Odt::text(m_mode == SessionRSMode::StartOfSession ? Odt::rsSessionStart : Odt::rsSessionEnd)); + QString title = + Odt::text(Odt::rsSessionTitle) + .arg(Odt::text(m_order == SessionRSOrder::ByStation ? Odt::genericRSOwner : Odt::station), + Odt::text(m_mode == SessionRSMode::StartOfSession ? Odt::rsSessionStart + : Odt::rsSessionEnd)); return title; } diff --git a/src/odt_export/common/sessionrswriter.h b/src/odt_export/common/sessionrswriter.h index 658537b..d3d27bc 100644 --- a/src/odt_export/common/sessionrswriter.h +++ b/src/odt_export/common/sessionrswriter.h @@ -35,7 +35,7 @@ public: static void writeStyles(QXmlStreamWriter &xml); - db_id writeTable(QXmlStreamWriter& xml, const QString& parentName); + db_id writeTable(QXmlStreamWriter &xml, const QString &parentName); void writeContent(QXmlStreamWriter &xml); diff --git a/src/odt_export/common/stationwriter.cpp b/src/odt_export/common/stationwriter.cpp index bad92a6..dce65ce 100644 --- a/src/odt_export/common/stationwriter.cpp +++ b/src/odt_export/common/stationwriter.cpp @@ -30,46 +30,48 @@ #include -//first == true for the first time the stop is writter -//the second time it should be false to skip the repetition of Arrival, Crossings, Passings -void StationWriter::insertStop(QXmlStreamWriter &xml, const Stop& stop, bool first, bool transit) +// first == true for the first time the stop is writter +// the second time it should be false to skip the repetition of Arrival, Crossings, Passings +void StationWriter::insertStop(QXmlStreamWriter &xml, const Stop &stop, bool first, bool transit) { const QString P3_style = "P3"; - //Row + // Row xml.writeStartElement("table:table-row"); - //Cells, hide Arrival the second time - if(first) + // Cells, hide Arrival the second time + if (first) { - //Arrival in bold, if transit bold + italic + // Arrival in bold, if transit bold + italic writeCell(xml, "stationtable.A2", transit ? "P5" : "P4", stop.arrival.toString("HH:mm")); - //Departure, if transit don't repeat it - writeCell(xml, "stationtable.A2", P3_style, transit ? "-/-" : stop.departure.toString("HH:mm")); + // Departure, if transit don't repeat it + writeCell(xml, "stationtable.A2", P3_style, + transit ? "-/-" : stop.departure.toString("HH:mm")); } else { - writeCell(xml, "stationtable.A2", P3_style, QString()); //Don't repeat Arrival - writeCell(xml, "stationtable.A2", "P4", stop.departure.toString("HH:mm")); //Departure in bold + writeCell(xml, "stationtable.A2", P3_style, QString()); // Don't repeat Arrival + writeCell(xml, "stationtable.A2", "P4", + stop.departure.toString("HH:mm")); // Departure in bold } - //Job N + // Job N writeCell(xml, "stationtable.A2", P3_style, JobCategoryName::jobName(stop.jobId, stop.jobCat)); - writeCell(xml, "stationtable.A2", P3_style, stop.platform); //Platform + writeCell(xml, "stationtable.A2", P3_style, stop.platform); // Platform - //From Previous Station, write only first time + // From Previous Station, write only first time writeCell(xml, "stationtable.A2", P3_style, first ? stop.prevSt : QString()); writeCell(xml, "stationtable.A2", P3_style, stop.nextSt); - if(!first) + if (!first) { - //Fill with empty cells, needed to keep the order - writeCell(xml, "stationtable.A2", P3_style, QString()); //Rollingstock - writeCell(xml, "stationtable.A2", P3_style, QString()); //Crossings - writeCell(xml, "stationtable.A2", P3_style, QString()); //Passings + // Fill with empty cells, needed to keep the order + writeCell(xml, "stationtable.A2", P3_style, QString()); // Rollingstock + writeCell(xml, "stationtable.A2", P3_style, QString()); // Crossings + writeCell(xml, "stationtable.A2", P3_style, QString()); // Passings - //Notes, description, repaeat to user the arrival to better link the 2 rows + // Notes, description, repaeat to user the arrival to better link the 2 rows writeCell(xml, "stationtable.L2", P3_style, stop.arrival.toString("HH:mm")); } } @@ -97,7 +99,8 @@ StationWriter::StationWriter(database &db) : q_selectPassings(mDb, "SELECT stops.id,stops.job_id,jobs.category" " FROM stops" " JOIN jobs ON jobs.id=stops.job_id" - " WHERE stops.station_id=? AND stops.departure>=? AND stops.arrival<=? AND stops.job_id<>?"), + " WHERE stops.station_id=? AND stops.departure>=? AND stops.arrival<=? " + "AND stops.job_id<>?"), q_getStopCouplings(mDb, "SELECT coupling.rs_id," "rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" " FROM coupling" @@ -105,22 +108,21 @@ StationWriter::StationWriter(database &db) : " JOIN rs_models ON rs_models.id=rs_list.model_id" " WHERE coupling.stop_id=? AND coupling.operation=?") { - } -//TODO: common styles with JobWriter should go in common +// TODO: common styles with JobWriter should go in common void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) { /* Style: stationtable - * - * Type: table - * Display name: Station Table - * Align: center - * Width: 20.0cm - * - * Usage: - * - StationWriter: station sheet main table showing jobs that stop in this station - */ + * + * Type: table + * Display name: Station Table + * Align: center + * Width: 20.0cm + * + * Usage: + * - StationWriter: station sheet main table showing jobs that stop in this station + */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "table"); xml.writeAttribute("style:name", "stationtable"); @@ -129,20 +131,20 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("style:shadow", "none"); xml.writeAttribute("table:align", "center"); xml.writeAttribute("style:width", "20.0cm"); - xml.writeEndElement(); //style:table-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-properties + xml.writeEndElement(); // style - //stationtable columns - writeColumnStyle(xml, "stationtable.A", "1.74cm"); //1 Arrival - writeColumnStyle(xml, "stationtable.B", "1.80cm"); //2 Departure - writeColumnStyle(xml, "stationtable.C", "1.93cm"); //3 Job N - writeColumnStyle(xml, "stationtable.D", "1.00cm"); //4 Platform (Platf) - writeColumnStyle(xml, "stationtable.E", "3.09cm"); //5 From (Previous Station) - writeColumnStyle(xml, "stationtable.F", "3.11cm"); //6 To (Next Station) - writeColumnStyle(xml, "stationtable.G", "3.00cm"); //7 Rollingstock - writeColumnStyle(xml, "stationtable.H", "2.10cm"); //8 Crossings - writeColumnStyle(xml, "stationtable.I", "2.10cm"); //9 Passings - writeColumnStyle(xml, "stationtable.L", "2.21cm"); //10 Description + // stationtable columns + writeColumnStyle(xml, "stationtable.A", "1.74cm"); // 1 Arrival + writeColumnStyle(xml, "stationtable.B", "1.80cm"); // 2 Departure + writeColumnStyle(xml, "stationtable.C", "1.93cm"); // 3 Job N + writeColumnStyle(xml, "stationtable.D", "1.00cm"); // 4 Platform (Platf) + writeColumnStyle(xml, "stationtable.E", "3.09cm"); // 5 From (Previous Station) + writeColumnStyle(xml, "stationtable.F", "3.11cm"); // 6 To (Next Station) + writeColumnStyle(xml, "stationtable.G", "3.00cm"); // 7 Rollingstock + writeColumnStyle(xml, "stationtable.H", "2.10cm"); // 8 Crossings + writeColumnStyle(xml, "stationtable.I", "2.10cm"); // 9 Passings + writeColumnStyle(xml, "stationtable.L", "2.21cm"); // 10 Description /* Style: stationtable.A1 * @@ -165,8 +167,8 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "0.05pt solid #000000"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: stationtable.L1 * @@ -186,8 +188,8 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border", "0.05pt solid #000000"); xml.writeAttribute("fo:padding", "0.097cm"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: stationtable.A2 * @@ -210,8 +212,8 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style: stationtable.L2 * @@ -234,8 +236,8 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeAttribute("fo:border-top", "none"); xml.writeAttribute("fo:border-bottom", "0.05pt solid #000000"); xml.writeAttribute("style:vertical-align", "middle"); - xml.writeEndElement(); //style:table-cell-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:table-cell-properties + xml.writeEndElement(); // style /* Style P2 * type: paragraph @@ -253,14 +255,14 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "13pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P3 * type: paragraph @@ -277,15 +279,15 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "10pt"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style - //P5 - Bold, Italics, for Transits + // P5 - Bold, Italics, for Transits /* Style P5 * type: paragraph * text-align: center @@ -294,7 +296,8 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) * font-style: italic * * Usages: - * - stationtable table: Arrival for transit jobs (Normal stops have bold Arrival, transits have Bold + Italic) + * - stationtable table: Arrival for transit jobs (Normal stops have bold Arrival, transits have + * Bold + Italic) */ xml.writeStartElement("style:style"); xml.writeAttribute("style:family", "paragraph"); @@ -303,20 +306,20 @@ void StationWriter::writeStationAutomaticStyles(QXmlStreamWriter &xml) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("fo:font-size", "12pt"); xml.writeAttribute("fo:font-weight", "bold"); xml.writeAttribute("fo:font-style", "italic"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString *stNameOut) { - QMap stops; //Order by Departure ASC + QMap stops; // Order by Departure ASC query q_getStName(mDb, "SELECT name,short_name FROM stations WHERE id=?"); @@ -328,71 +331,71 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString QString stationName; QString shortName; q_getStName.bind(1, stationId); - if(q_getStName.step() == SQLITE_ROW) + if (q_getStName.step() == SQLITE_ROW) { - auto r = q_getStName.getRows(); + auto r = q_getStName.getRows(); stationName = r.get(0); - shortName = r.get(1); + shortName = r.get(1); } q_getStName.reset(); - if(stNameOut) + if (stNameOut) *stNameOut = stationName; QString stationNameStr = stationName; - if(!shortName.isEmpty()) + if (!shortName.isEmpty()) { stationNameStr.append(QLatin1String(" (")); stationNameStr.append(shortName); stationNameStr.append(')'); } - //Title + // Title xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeCharacters(Odt::text(Odt::stationPageTitle).arg(stationNameStr)); xml.writeEndElement(); - //Vertical space + // Vertical space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); xml.writeEndElement(); - //stationtable + // stationtable xml.writeStartElement("table:table"); - //xml.writeAttribute("table:name", "stationtable"); + // xml.writeAttribute("table:name", "stationtable"); xml.writeAttribute("table:style-name", "stationtable"); - xml.writeEmptyElement("table:table-column"); //Arrival + xml.writeEmptyElement("table:table-column"); // Arrival xml.writeAttribute("table:style-name", "stationtable.A"); - xml.writeEmptyElement("table:table-column"); //Departure + xml.writeEmptyElement("table:table-column"); // Departure xml.writeAttribute("table:style-name", "stationtable.B"); - xml.writeEmptyElement("table:table-column"); //Job N + xml.writeEmptyElement("table:table-column"); // Job N xml.writeAttribute("table:style-name", "stationtable.C"); - xml.writeEmptyElement("table:table-column"); //Platform (Bin) + xml.writeEmptyElement("table:table-column"); // Platform (Bin) xml.writeAttribute("table:style-name", "stationtable.D"); - xml.writeEmptyElement("table:table-column"); //Comes From + xml.writeEmptyElement("table:table-column"); // Comes From xml.writeAttribute("table:style-name", "stationtable.E"); - xml.writeEmptyElement("table:table-column"); //Goes To + xml.writeEmptyElement("table:table-column"); // Goes To xml.writeAttribute("table:style-name", "stationtable.F"); - xml.writeEmptyElement("table:table-column"); //Rollingstock + xml.writeEmptyElement("table:table-column"); // Rollingstock xml.writeAttribute("table:style-name", "stationtable.G"); - xml.writeEmptyElement("table:table-column"); //Crossings + xml.writeEmptyElement("table:table-column"); // Crossings xml.writeAttribute("table:style-name", "stationtable.H"); - xml.writeEmptyElement("table:table-column"); //Passings + xml.writeEmptyElement("table:table-column"); // Passings xml.writeAttribute("table:style-name", "stationtable.I"); - xml.writeEmptyElement("table:table-column"); //Notes + xml.writeEmptyElement("table:table-column"); // Notes xml.writeAttribute("table:style-name", "stationtable.L"); - //Row 1 (Heading) + // Row 1 (Heading) xml.writeStartElement("table:table-header-rows"); xml.writeStartElement("table:table-row"); @@ -405,54 +408,55 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString writeCell(xml, "stationtable.A1", "P2", Odt::text(Odt::rollingstock)); writeCell(xml, "stationtable.A1", "P2", Odt::text(Odt::jobStopCrossShort)); writeCell(xml, "stationtable.A1", "P2", Odt::text(Odt::jobStopPassingsShort)); - writeCell(xml, "stationtable.L1", "P2", Odt::text(Odt::notes)); //Description + writeCell(xml, "stationtable.L1", "P2", Odt::text(Odt::notes)); // Description - xml.writeEndElement(); //end of row - xml.writeEndElement(); //header section + xml.writeEndElement(); // end of row + xml.writeEndElement(); // header section - //Stops + // Stops q_getJobsByStation.bind(1, stationId); - for(auto r : q_getJobsByStation) + for (auto r : q_getJobsByStation) { db_id stopId = r.get(0); Stop stop; - stop.jobId = r.get(1); - stop.jobCat = JobCategory(r.get(2)); - stop.arrival = r.get(3); - stop.departure = r.get(4); + stop.jobId = r.get(1); + stop.jobCat = JobCategory(r.get(2)); + stop.arrival = r.get(3); + stop.departure = r.get(4); const int stopType = r.get(5); - stop.description = r.get(6); + stop.description = r.get(6); - stop.platform = r.get(7); - if(stop.platform.isEmpty()) - stop.platform = r.get(8); //Use out gate to get track name + stop.platform = r.get(7); + if (stop.platform.isEmpty()) + stop.platform = r.get(8); // Use out gate to get track name utils::Side entranceSide = utils::Side(r.get(9)); - utils::Side exitSide = utils::Side(r.get(10)); + utils::Side exitSide = utils::Side(r.get(10)); - if(entranceSide == exitSide && r.column_type(9) != SQLITE_NULL && r.column_type(10) != SQLITE_NULL) + if (entranceSide == exitSide && r.column_type(9) != SQLITE_NULL + && r.column_type(10) != SQLITE_NULL) { - //Train enters and leaves from same track side, add reversal to description + // Train enters and leaves from same track side, add reversal to description QString descr2 = Odt::text(Odt::jobReverseDirection); - if(!stop.description.isEmpty()) - descr2.append('\n'); //Separate from manually set description + if (!stop.description.isEmpty()) + descr2.append('\n'); // Separate from manually set description descr2.append(stop.description); stop.description = descr2; } const bool isTransit = stopType == 1; - //BIG TODO: if this is First or Last stop of this job - //then it shouldn't be duplicated in 2 rows + // BIG TODO: if this is First or Last stop of this job + // then it shouldn't be duplicated in 2 rows - //Comes from station + // Comes from station q_getPrevStop.bind(1, stop.jobId); q_getPrevStop.bind(2, stop.arrival); - if(q_getPrevStop.step() == SQLITE_ROW) + if (q_getPrevStop.step() == SQLITE_ROW) { db_id prevStId = q_getPrevStop.getRows().get(1); q_getStName.bind(1, prevStId); - if(q_getStName.step() == SQLITE_ROW) + if (q_getStName.step() == SQLITE_ROW) { stop.prevSt = q_getStName.getRows().get(0); } @@ -460,14 +464,14 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString } q_getPrevStop.reset(); - //Goes to station + // Goes to station q_getNextStop.bind(1, stop.jobId); q_getNextStop.bind(2, stop.arrival); - if(q_getNextStop.step() == SQLITE_ROW) + if (q_getNextStop.step() == SQLITE_ROW) { db_id nextStId = q_getNextStop.getRows().get(1); q_getStName.bind(1, nextStId); - if(q_getStName.step() == SQLITE_ROW) + if (q_getStName.step() == SQLITE_ROW) { stop.nextSt = q_getStName.getRows().get(0); } @@ -475,62 +479,60 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString } q_getNextStop.reset(); - for(auto s = stops.begin(); s != stops.end(); /*nothing because of erase*/) + for (auto s = stops.begin(); s != stops.end(); /*nothing because of erase*/) { - //If 's' departs after 'stop' arrives then skip 's' for now - if(s->departure >= stop.arrival) + // If 's' departs after 'stop' arrives then skip 's' for now + if (s->departure >= stop.arrival) { ++s; continue; } //'s' departs before 'stop' arrives so we - //insert it again to remind station master (IT: capostazione) + // insert it again to remind station master (IT: capostazione) insertStop(xml, s.value(), false, false); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row - //Then remove from the list otherwise it gets inserted infinite times + // Then remove from the list otherwise it gets inserted infinite times s = stops.erase(s); } - //Fill with basic data + // Fill with basic data insertStop(xml, stop, true, isTransit); - //First time this stop is written, fill with other data + // First time this stop is written, fill with other data - //Rollingstock + // Rollingstock sqlite3_stmt *stmt = q_getStopCouplings.stmt(); writeCellListStart(xml, "stationtable.A2", "P3"); - //Coupled rollingstock + // Coupled rollingstock bool firstCoupRow = true; q_getStopCouplings.bind(1, stopId); q_getStopCouplings.bind(2, int(RsOp::Coupled)); - for(auto coup : q_getStopCouplings) + for (auto coup : q_getStopCouplings) { - //db_id rsId = coup.get(0); + // db_id rsId = coup.get(0); - int number = coup.get(1); - int modelNameLen = sqlite3_column_bytes(stmt, 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); + int number = coup.get(1); + int modelNameLen = sqlite3_column_bytes(stmt, 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); - RsType type = RsType(sqlite3_column_int(stmt, 4)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); + RsType type = RsType(sqlite3_column_int(stmt, 4)); - const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, + modelSuffix, modelSuffixLen, type); - if(firstCoupRow) + if (firstCoupRow) { firstCoupRow = false; - //Use bold font + // Use bold font xml.writeStartElement("text:span"); xml.writeAttribute("text:style-name", "T1"); xml.writeCharacters(Odt::text(Odt::CoupledAbbr)); - xml.writeEndElement(); //test:span + xml.writeEndElement(); // test:span } xml.writeEmptyElement("text:line-break"); @@ -538,38 +540,36 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString } q_getStopCouplings.reset(); - //Unoupled rollingstock + // Unoupled rollingstock bool firstUncoupRow = true; q_getStopCouplings.bind(1, stopId); q_getStopCouplings.bind(2, int(RsOp::Uncoupled)); - for(auto coup : q_getStopCouplings) + for (auto coup : q_getStopCouplings) { - //db_id rsId = coup.get(0); + // db_id rsId = coup.get(0); - int number = coup.get(1); - int modelNameLen = sqlite3_column_bytes(stmt, 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); + int number = coup.get(1); + int modelNameLen = sqlite3_column_bytes(stmt, 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 2)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); - RsType type = RsType(sqlite3_column_int(stmt, 4)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 3)); + RsType type = RsType(sqlite3_column_int(stmt, 4)); - const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, + modelSuffix, modelSuffixLen, type); - if(firstUncoupRow) + if (firstUncoupRow) { - if(!firstCoupRow) //Not first row, there were coupled rs - xml.writeEmptyElement("text:line-break"); //Separate from coupled + if (!firstCoupRow) // Not first row, there were coupled rs + xml.writeEmptyElement("text:line-break"); // Separate from coupled firstUncoupRow = false; - //Use bold font + // Use bold font xml.writeStartElement("text:span"); xml.writeAttribute("text:style-name", "T1"); xml.writeCharacters(Odt::text(Odt::UncoupledAbbr)); - xml.writeEndElement(); //test:span + xml.writeEndElement(); // test:span } xml.writeEmptyElement("text:line-break"); @@ -578,7 +578,7 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString q_getStopCouplings.reset(); writeCellListEnd(xml); - //Crossings, Passings + // Crossings, Passings QVector passings; JobStopDirectionHelper dirHelper(mDb); utils::Side myDirection = dirHelper.getStopOutSide(stopId); @@ -589,24 +589,24 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString q_selectPassings.bind(4, stop.jobId); firstCoupRow = true; - //Incroci + // Incroci writeCellListStart(xml, "stationtable.A2", "P3"); - for(auto pass : q_selectPassings) + for (auto pass : q_selectPassings) { - db_id otherStopId = pass.get(0); - db_id otherJobId = pass.get(1); + db_id otherStopId = pass.get(0); + db_id otherJobId = pass.get(1); JobCategory otherJobCat = JobCategory(pass.get(2)); - //QTime otherArr = pass.get(3); - //QTime otherDep = pass.get(4); + // QTime otherArr = pass.get(3); + // QTime otherDep = pass.get(4); utils::Side otherDir = dirHelper.getStopOutSide(otherStopId); - if(myDirection == otherDir) + if (myDirection == otherDir) passings.append({otherJobId, otherJobCat}); else { - if(firstCoupRow) + if (firstCoupRow) firstCoupRow = false; else xml.writeEmptyElement("text:line-break"); @@ -616,12 +616,12 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString q_selectPassings.reset(); writeCellListEnd(xml); - //Passings + // Passings firstCoupRow = true; writeCellListStart(xml, "stationtable.A2", "P3"); - for(auto entry : passings) + for (auto entry : passings) { - if(firstCoupRow) + if (firstCoupRow) firstCoupRow = false; else xml.writeEmptyElement("text:line-break"); @@ -629,66 +629,66 @@ void StationWriter::writeStation(QXmlStreamWriter &xml, db_id stationId, QString } writeCellListEnd(xml); - //Description, Notes + // Description, Notes writeCellListStart(xml, "stationtable.L2", "P3"); bool needsLineBreak = false; - if(isTransit) + if (isTransit) { xml.writeCharacters(Odt::text(Odt::jobStopIsTransit)); needsLineBreak = true; } - if(stop.prevSt.isEmpty()) + if (stop.prevSt.isEmpty()) { - if(needsLineBreak) + if (needsLineBreak) xml.writeEmptyElement("text:line-break"); - //This is Origin (First stop), use Bold font + // This is Origin (First stop), use Bold font xml.writeStartElement("text:span"); xml.writeAttribute("text:style-name", "T1"); xml.writeCharacters(Odt::text(Odt::jobStopIsFirst)); - xml.writeEndElement(); //test:span + xml.writeEndElement(); // test:span needsLineBreak = true; } - if(!stop.description.isEmpty()) + if (!stop.description.isEmpty()) { - if(needsLineBreak) //go to new line after 'Transit' word + if (needsLineBreak) // go to new line after 'Transit' word xml.writeEmptyElement("text:line-break"); - //Split in lines + // Split in lines int lastIdx = 0; - while(true) + while (true) { - int idx = stop.description.indexOf('\n', lastIdx); + int idx = stop.description.indexOf('\n', lastIdx); QString line = stop.description.mid(lastIdx, idx == -1 ? idx : idx - lastIdx); xml.writeCharacters(line.simplified()); - if(idx < 0) - break; //Last line + if (idx < 0) + break; // Last line lastIdx = idx + 1; xml.writeEmptyElement("text:line-break"); } } writeCellListEnd(xml); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row - if(!isTransit && !stop.prevSt.isEmpty() && !stop.nextSt.isEmpty()) + if (!isTransit && !stop.prevSt.isEmpty() && !stop.nextSt.isEmpty()) { - //If it is a normal stop (not a transit and not first stop or last stop) - //insert two rows: one for arrival and another - //that reminds the station master (capostazione) - //the departure of that train - //In order to achieve this we put the stop in a list - //and write it again before another arrival (see above) + // If it is a normal stop (not a transit and not first stop or last stop) + // insert two rows: one for arrival and another + // that reminds the station master (capostazione) + // the departure of that train + // In order to achieve this we put the stop in a list + // and write it again before another arrival (see above) stops.insert(stop.departure, stop); } } q_getJobsByStation.reset(); - for(const Stop& s : stops) + for (const Stop &s : stops) { insertStop(xml, s, false, false); - xml.writeEndElement(); //table-row + xml.writeEndElement(); // table-row } - xml.writeEndElement(); //stationtable end + xml.writeEndElement(); // stationtable end } diff --git a/src/odt_export/common/stationwriter.h b/src/odt_export/common/stationwriter.h index 81041cb..3eff53e 100644 --- a/src/odt_export/common/stationwriter.h +++ b/src/odt_export/common/stationwriter.h @@ -31,9 +31,9 @@ class QXmlStreamWriter; class StationWriter { public: - StationWriter(database& db); + StationWriter(database &db); - static void writeStationAutomaticStyles(QXmlStreamWriter& xml); + static void writeStationAutomaticStyles(QXmlStreamWriter &xml); void writeStation(QXmlStreamWriter &xml, db_id stationId, QString *stNameOut = nullptr); @@ -54,7 +54,7 @@ private: JobCategory jobCat; }; - void insertStop(QXmlStreamWriter &xml, const Stop& stop, bool first, bool transit); + void insertStop(QXmlStreamWriter &xml, const Stop &stop, bool first, bool transit); private: database &mDb; diff --git a/src/odt_export/jobsheetexport.cpp b/src/odt_export/jobsheetexport.cpp index 68bc377..e27e683 100644 --- a/src/odt_export/jobsheetexport.cpp +++ b/src/odt_export/jobsheetexport.cpp @@ -30,7 +30,6 @@ JobSheetExport::JobSheetExport(db_id jobId, JobCategory cat) : m_jobId(jobId), m_jobCat(cat) { - } void JobSheetExport::write() @@ -38,27 +37,27 @@ void JobSheetExport::write() qDebug() << "TEMP:" << odt.dir.path(); odt.initDocument(); - //styles.xml font declarations + // styles.xml font declarations odt.stylesXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.stylesXml); - odt.stylesXml.writeEndElement(); //office:font-face-decls + odt.stylesXml.writeEndElement(); // office:font-face-decls - //Content font declarations + // Content font declarations odt.contentXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.contentXml); - odt.contentXml.writeEndElement(); //office:font-face-decls + odt.contentXml.writeEndElement(); // office:font-face-decls - //Content Automatic styles + // Content Automatic styles odt.contentXml.writeStartElement("office:automatic-styles"); JobWriter::writeJobAutomaticStyles(odt.contentXml); - //Styles + // Styles odt.stylesXml.writeStartElement("office:styles"); writeCommonStyles(odt.stylesXml); JobWriter::writeJobStyles(odt.stylesXml); odt.stylesXml.writeEndElement(); - //Body + // Body odt.startBody(); JobWriter w(Session->m_Db); diff --git a/src/odt_export/jobsheetexport.h b/src/odt_export/jobsheetexport.h index 5d41aaa..e829a77 100644 --- a/src/odt_export/jobsheetexport.h +++ b/src/odt_export/jobsheetexport.h @@ -24,14 +24,13 @@ #include "utils/types.h" - class JobSheetExport { public: JobSheetExport(db_id jobId, JobCategory cat); void write(); - void save(const QString& fileName); + void save(const QString &fileName); private: OdtDocument odt; diff --git a/src/odt_export/sessionrsexport.cpp b/src/odt_export/sessionrsexport.cpp index bae2141..911dfb2 100644 --- a/src/odt_export/sessionrsexport.cpp +++ b/src/odt_export/sessionrsexport.cpp @@ -31,7 +31,6 @@ SessionRSExport::SessionRSExport(SessionRSMode mode, SessionRSOrder order) : m_mode(mode), m_order(order) { - } void SessionRSExport::write() @@ -39,55 +38,56 @@ void SessionRSExport::write() qDebug() << "TEMP:" << odt.dir.path(); odt.initDocument(); - //styles.xml font declarations + // styles.xml font declarations odt.stylesXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.stylesXml); - odt.stylesXml.writeEndElement(); //office:font-face-decls + odt.stylesXml.writeEndElement(); // office:font-face-decls - //Styles + // Styles odt.stylesXml.writeStartElement("office:styles"); writeStandardStyle(odt.stylesXml); writeCommonStyles(odt.stylesXml); - //JobWriter::writeJobStyles(odt.stylesXml); TODO + // JobWriter::writeJobStyles(odt.stylesXml); TODO writeFooterStyle(odt.stylesXml); odt.stylesXml.writeEndElement(); - //Automatic styles + // Automatic styles odt.stylesXml.writeStartElement("office:automatic-styles"); writePageLayout(odt.stylesXml); odt.stylesXml.writeEndElement(); MetaDataManager *meta = Session->getMetaDataManager(); - //Retrive header and footer: give precedence to database metadata and then fallback to global application settings - //If the text was explicitly set to empty in metadata no header/footer will be displayed + // Retrive header and footer: give precedence to database metadata and then fallback to global + // application settings If the text was explicitly set to empty in metadata no header/footer + // will be displayed QString header; - if(meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) + if (meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) { header = AppSettings.getSheetHeader(); } QString footer; - if(meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) + if (meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) { footer = AppSettings.getSheetFooter(); } - //Master styles + // Master styles odt.stylesXml.writeStartElement("office:master-styles"); writeHeaderFooter(odt.stylesXml, header, footer); odt.stylesXml.writeEndElement(); - //Content font declarations + // Content font declarations odt.contentXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.contentXml); - odt.contentXml.writeEndElement(); //office:font-face-decls + odt.contentXml.writeEndElement(); // office:font-face-decls - //Content Automatic styles + // Content Automatic styles odt.contentXml.writeStartElement("office:automatic-styles"); SessionRSWriter::writeStyles(odt.contentXml); - //Body + // Body odt.startBody(); SessionRSWriter w(Session->m_Db, m_mode, m_order); diff --git a/src/odt_export/sessionrsexport.h b/src/odt_export/sessionrsexport.h index 2a00264..61ee167 100644 --- a/src/odt_export/sessionrsexport.h +++ b/src/odt_export/sessionrsexport.h @@ -31,7 +31,7 @@ public: SessionRSExport(SessionRSMode mode, SessionRSOrder order); void write(); - void save(const QString& fileName); + void save(const QString &fileName); private: OdtDocument odt; diff --git a/src/odt_export/shiftsheetexport.cpp b/src/odt_export/shiftsheetexport.cpp index 3c22352..0f3fe46 100644 --- a/src/odt_export/shiftsheetexport.cpp +++ b/src/odt_export/shiftsheetexport.cpp @@ -43,7 +43,6 @@ ShiftSheetExport::ShiftSheetExport(sqlite3pp::database &db, db_id shiftId) : logoWidthCm(0), logoHeightCm(0) { - } void ShiftSheetExport::write() @@ -51,12 +50,12 @@ void ShiftSheetExport::write() qDebug() << "TEMP:" << odt.dir.path(); odt.initDocument(); - //styles.xml font declarations + // styles.xml font declarations odt.stylesXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.stylesXml); - odt.stylesXml.writeEndElement(); //office:font-face-decls + odt.stylesXml.writeEndElement(); // office:font-face-decls - //Styles + // Styles odt.stylesXml.writeStartElement("office:styles"); writeStandardStyle(odt.stylesXml); writeGraphicsStyle(odt.stylesXml); @@ -65,57 +64,58 @@ void ShiftSheetExport::write() writeFooterStyle(odt.stylesXml); odt.stylesXml.writeEndElement(); - //Automatic styles + // Automatic styles odt.stylesXml.writeStartElement("office:automatic-styles"); writePageLayout(odt.stylesXml); odt.stylesXml.writeEndElement(); MetaDataManager *meta = Session->getMetaDataManager(); - //Retrive header and footer: give precedence to database metadata and then fallback to global application settings - //If the text was explicitly set to empty in metadata no header/footer will be displayed + // Retrive header and footer: give precedence to database metadata and then fallback to global + // application settings If the text was explicitly set to empty in metadata no header/footer + // will be displayed QString header; - if(meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) + if (meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) { header = AppSettings.getSheetHeader(); } QString footer; - if(meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) + if (meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) { footer = AppSettings.getSheetFooter(); } - //Master styles + // Master styles odt.stylesXml.writeStartElement("office:master-styles"); writeHeaderFooter(odt.stylesXml, header, footer); odt.stylesXml.writeEndElement(); - //Content font declarations + // Content font declarations odt.contentXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.contentXml); - odt.contentXml.writeEndElement(); //office:font-face-decls + odt.contentXml.writeEndElement(); // office:font-face-decls - //Content Automatic styles + // Content Automatic styles odt.contentXml.writeStartElement("office:automatic-styles"); JobWriter::writeJobAutomaticStyles(odt.contentXml); bool hasLogo = (meta->hasKey(MetaDataKey::MeetingLogoPicture) == MetaDataKey::ValueFound); - if(hasLogo) + if (hasLogo) { - //Save image + // Save image saveLogoPicture(); } writeCoverStyles(odt.contentXml, hasLogo); - //Body + // Body odt.startBody(); QString shiftName; query q(mDb, "SELECT name FROM jobshifts WHERE id=?"); q.bind(1, m_shiftId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) qWarning() << "ShiftSheetExport: shift does not exist, id" << m_shiftId; shiftName = q.getRows().get(0); @@ -133,9 +133,9 @@ void ShiftSheetExport::write() " GROUP BY jobs.id" " ORDER BY s1.arrival ASC"); q.bind(1, m_shiftId); - for(auto r : q) + for (auto r : q) { - db_id jobId = r.get(0); + db_id jobId = r.get(0); JobCategory cat = JobCategory(r.get(1)); w.writeJob(odt.contentXml, jobId, cat); } @@ -150,7 +150,7 @@ void ShiftSheetExport::save(const QString &fileName) void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) { - if(hasImage) + if (hasImage) { /* Style logo_style * @@ -182,8 +182,8 @@ void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) xml.writeAttribute("draw:luminance", "0%"); xml.writeAttribute("draw:image-opacity", "100%"); xml.writeAttribute("fo:clip", "rect(0cm, 0cm, 0cm, 0cm)"); - xml.writeEndElement(); //style:graphic-properties - xml.writeEndElement(); //style + xml.writeEndElement(); // style:graphic-properties + xml.writeEndElement(); // style } /* Style P7 @@ -203,16 +203,16 @@ void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("style:font-name", "Liberation Serif"); xml.writeAttribute("fo:font-size", "24pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style P8 * type: paragraph @@ -234,16 +234,16 @@ void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("style:font-name", "Liberation Sans"); xml.writeAttribute("fo:font-size", "24pt"); xml.writeAttribute("fo:font-weight", "bold"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style /* Style shift_name_style * type: paragraph @@ -264,7 +264,7 @@ void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) xml.writeStartElement("style:paragraph-properties"); xml.writeAttribute("fo:text-align", "center"); xml.writeAttribute("style:justify-single-word", "false"); - xml.writeEndElement(); //style:paragraph-properties + xml.writeEndElement(); // style:paragraph-properties xml.writeStartElement("style:text-properties"); xml.writeAttribute("style:font-name", "Liberation Sans"); @@ -277,46 +277,46 @@ void ShiftSheetExport::writeCoverStyles(QXmlStreamWriter &xml, bool hasImage) xml.writeAttribute("fo:padding-bottom", "0.15cm"); xml.writeAttribute("fo:border", "0.05pt solid #000000"); - xml.writeEndElement(); //style:text-properties + xml.writeEndElement(); // style:text-properties - xml.writeEndElement(); //style:style + xml.writeEndElement(); // style:style } bool ShiftSheetExport::calculateLogoSize(QIODevice *dev) { QImageReader reader(dev, "PNG"); - if(!reader.canRead()) + if (!reader.canRead()) { qWarning() << "ShiftSheetExport: cannot read picture," << reader.errorString(); return false; } QImage img; - if(!reader.read(&img)) + if (!reader.read(&img)) { qWarning() << "ShiftSheetExport: cannot read picture," << reader.errorString(); return false; } - const int widthPx = img.width(); + const int widthPx = img.width(); const int heightPx = img.height(); const double dotsX = img.dotsPerMeterX(); const double dotsY = img.dotsPerMeterY(); - logoWidthCm = 100.0 * double(widthPx) / dotsX; - logoHeightCm = 100.0 * double(heightPx) / dotsY; + logoWidthCm = 100.0 * double(widthPx) / dotsX; + logoHeightCm = 100.0 * double(heightPx) / dotsY; - if(logoWidthCm > 20.0 || logoWidthCm < 2.0) + if (logoWidthCm > 20.0 || logoWidthCm < 2.0) { - //Try with 15 cm wide - logoWidthCm = 15.0; - logoHeightCm = 15.0 * double(heightPx)/double(widthPx); + // Try with 15 cm wide + logoWidthCm = 15.0; + logoHeightCm = 15.0 * double(heightPx) / double(widthPx); } - if(logoHeightCm > 10.0) + if (logoHeightCm > 10.0) { - //Maximum 10 cm tall - logoWidthCm = 10.0 * double(widthPx)/double(heightPx); + // Maximum 10 cm tall + logoWidthCm = 10.0 * double(widthPx) / double(heightPx); logoHeightCm = 10.0; } @@ -327,20 +327,20 @@ void ShiftSheetExport::saveLogoPicture() { 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)) { qWarning() << "ShiftSheetExport: error query image," << Session->m_Db.error_msg(); return; } - if(!calculateLogoSize(imageIO.get())) - return; //Image is not valid + if (!calculateLogoSize(imageIO.get())) + return; // Image is not valid - imageIO->seek(0); //Reset device + imageIO->seek(0); // Reset device QString fileNamePath = odt.addImage("logo.png", "image/png"); QFile f(fileNamePath); - if(!f.open(QFile::WriteOnly | QFile::Truncate)) + if (!f.open(QFile::WriteOnly | QFile::Truncate)) { qWarning() << "ShiftSheetExport: error saving image," << f.errorString(); return; @@ -352,25 +352,25 @@ void ShiftSheetExport::saveLogoPicture() while (!imageIO->atEnd() || size < 0) { size = imageIO->read(buf, bufSize); - if(f.write(buf, size) != size) + if (f.write(buf, size) != size) qWarning() << "ShiftSheetExport: error witing image," << f.errorString(); } f.close(); } -void ShiftSheetExport::writeCover(QXmlStreamWriter& xml, const QString& shiftName, bool hasLogo) +void ShiftSheetExport::writeCover(QXmlStreamWriter &xml, const QString &shiftName, bool hasLogo) { MetaDataManager *meta = Session->getMetaDataManager(); - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P4"); xml.writeEndElement(); - //Host association + // Host association QString str; meta->getString(str, MetaDataKey::MeetingHostAssociation); - if(!str.isEmpty()) + if (!str.isEmpty()) { xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P7"); @@ -379,13 +379,13 @@ void ShiftSheetExport::writeCover(QXmlStreamWriter& xml, const QString& shiftNam str.clear(); } - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P4"); xml.writeEndElement(); - //Logo - if(hasLogo && !qFuzzyIsNull(logoWidthCm)) + // Logo + if (hasLogo && !qFuzzyIsNull(logoWidthCm)) { xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); @@ -405,54 +405,54 @@ void ShiftSheetExport::writeCover(QXmlStreamWriter& xml, const QString& shiftNam xml.writeAttribute("xlink:type", "simple"); xml.writeAttribute("xlink:show", "embed"); xml.writeAttribute("xlink:actuate", "onLoad"); - xml.writeEndElement(); //draw:image + xml.writeEndElement(); // draw:image - xml.writeEndElement(); //draw:frame + xml.writeEndElement(); // draw:frame - xml.writeEndElement(); //text:p + xml.writeEndElement(); // text:p } - //Meeting dates + // Meeting dates qint64 showDates = 1; meta->getInt64(showDates, MetaDataKey::MeetingShowDates); - if(showDates) + if (showDates) { QDate start, end; qint64 tmp = 0; - if(meta->getInt64(tmp, MetaDataKey::MeetingStartDate) == MetaDataKey::ValueFound) + if (meta->getInt64(tmp, MetaDataKey::MeetingStartDate) == MetaDataKey::ValueFound) { start = QDate::fromJulianDay(tmp); } - if(meta->getInt64(tmp, MetaDataKey::MeetingEndDate) == MetaDataKey::ValueFound) + if (meta->getInt64(tmp, MetaDataKey::MeetingEndDate) == MetaDataKey::ValueFound) { end = QDate::fromJulianDay(tmp); - if(!end.isValid() || end < start) + if (!end.isValid() || end < start) end = start; } - if(start.isValid()) + if (start.isValid()) { xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); - if(start == end) + if (start == end) xml.writeCharacters(start.toString("dd/MM/yyyy")); else - xml.writeCharacters(Odt::text(Odt::meetingFromToShort) - .arg(start.toString("dd/MM/yyyy"), - end.toString("dd/MM/yyyy"))); + xml.writeCharacters( + Odt::text(Odt::meetingFromToShort) + .arg(start.toString("dd/MM/yyyy"), end.toString("dd/MM/yyyy"))); xml.writeEndElement(); } } - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P4"); xml.writeEndElement(); - //Location + // Location meta->getString(str, MetaDataKey::MeetingLocation); - if(!str.isEmpty()) + if (!str.isEmpty()) { xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P8"); @@ -461,27 +461,27 @@ void ShiftSheetExport::writeCover(QXmlStreamWriter& xml, const QString& shiftNam str.clear(); } - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P4"); xml.writeEndElement(); - //Description + // Description meta->getString(str, MetaDataKey::MeetingDescription); - if(!str.isEmpty()) + if (!str.isEmpty()) { xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P1"); - //Split in lines + // Split in lines int lastIdx = 0; - while(true) + while (true) { - int idx = str.indexOf('\n', lastIdx); + int idx = str.indexOf('\n', lastIdx); QString line = str.mid(lastIdx, idx == -1 ? idx : idx - lastIdx); xml.writeCharacters(line.simplified()); - if(idx < 0) - break; //Last line + if (idx < 0) + break; // Last line lastIdx = idx + 1; xml.writeEmptyElement("text:line-break"); } @@ -489,19 +489,19 @@ void ShiftSheetExport::writeCover(QXmlStreamWriter& xml, const QString& shiftNam str.clear(); } - //Add some space + // Add some space xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "P4"); xml.writeEndElement(); - //Shift name + // Shift name xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "shift_name_style"); xml.writeCharacters(Odt::text(Odt::shiftCoverTitle).arg(shiftName)); xml.writeEndElement(); str.clear(); - //Interruzione pagina TODO: see style 'interruzione' + // Interruzione pagina TODO: see style 'interruzione' xml.writeStartElement("text:p"); xml.writeAttribute("text:style-name", "interruzione"); xml.writeEndElement(); diff --git a/src/odt_export/shiftsheetexport.h b/src/odt_export/shiftsheetexport.h index 9b7bfcd..e8b269a 100644 --- a/src/odt_export/shiftsheetexport.h +++ b/src/odt_export/shiftsheetexport.h @@ -34,9 +34,12 @@ public: ShiftSheetExport(sqlite3pp::database &db, db_id shiftId); void write(); - void save(const QString& fileName); + void save(const QString &fileName); - inline void setShiftId(db_id shiftId) { m_shiftId = shiftId; } + inline void setShiftId(db_id shiftId) + { + m_shiftId = shiftId; + } private: void writeCoverStyles(QXmlStreamWriter &xml, bool hasImage); diff --git a/src/odt_export/stationsheetexport.cpp b/src/odt_export/stationsheetexport.cpp index d54e0f8..f25585e 100644 --- a/src/odt_export/stationsheetexport.cpp +++ b/src/odt_export/stationsheetexport.cpp @@ -31,7 +31,6 @@ StationSheetExport::StationSheetExport(db_id stationId) : m_stationId(stationId) { - } void StationSheetExport::write() @@ -39,54 +38,55 @@ void StationSheetExport::write() qDebug() << "TEMP:" << odt.dir.path(); odt.initDocument(); - //styles.xml font declarations + // styles.xml font declarations odt.stylesXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.stylesXml); - odt.stylesXml.writeEndElement(); //office:font-face-decls + odt.stylesXml.writeEndElement(); // office:font-face-decls - //Styles + // Styles odt.stylesXml.writeStartElement("office:styles"); writeStandardStyle(odt.stylesXml); writeFooterStyle(odt.stylesXml); odt.stylesXml.writeEndElement(); - //Automatic styles + // Automatic styles odt.stylesXml.writeStartElement("office:automatic-styles"); writePageLayout(odt.stylesXml); odt.stylesXml.writeEndElement(); MetaDataManager *meta = Session->getMetaDataManager(); - //Retrive header and footer: give precedence to database metadata and then fallback to global application settings - //If the text was explicitly set to empty in metadata no header/footer will be displayed + // Retrive header and footer: give precedence to database metadata and then fallback to global + // application settings If the text was explicitly set to empty in metadata no header/footer + // will be displayed QString header; - if(meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) + if (meta->getString(header, MetaDataKey::SheetHeaderText) != MetaDataKey::Result::ValueFound) { header = AppSettings.getSheetHeader(); } QString footer; - if(meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) + if (meta->getString(footer, MetaDataKey::SheetFooterText) != MetaDataKey::Result::ValueFound) { footer = AppSettings.getSheetFooter(); } - //Master styles + // Master styles odt.stylesXml.writeStartElement("office:master-styles"); writeHeaderFooter(odt.stylesXml, header, footer); odt.stylesXml.writeEndElement(); - //Content font declarations + // Content font declarations odt.contentXml.writeStartElement("office:font-face-decls"); writeLiberationFontFaces(odt.contentXml); - odt.contentXml.writeEndElement(); //office:font-face-decls + odt.contentXml.writeEndElement(); // office:font-face-decls - //Content Automatic styles + // Content Automatic styles odt.contentXml.writeStartElement("office:automatic-styles"); writeCommonStyles(odt.contentXml); StationWriter::writeStationAutomaticStyles(odt.contentXml); - //Body + // Body odt.startBody(); StationWriter w(Session->m_Db); diff --git a/src/odt_export/stationsheetexport.h b/src/odt_export/stationsheetexport.h index fbc380c..48b26f2 100644 --- a/src/odt_export/stationsheetexport.h +++ b/src/odt_export/stationsheetexport.h @@ -30,7 +30,7 @@ public: StationSheetExport(db_id stationId); void write(); - void save(const QString& fileName); + void save(const QString &fileName); private: OdtDocument odt; diff --git a/src/printing/helper/model/igraphscenecollection.cpp b/src/printing/helper/model/igraphscenecollection.cpp index d78acc9..4a2e349 100644 --- a/src/printing/helper/model/igraphscenecollection.cpp +++ b/src/printing/helper/model/igraphscenecollection.cpp @@ -21,10 +21,8 @@ IGraphSceneCollection::IGraphSceneCollection() { - } IGraphSceneCollection::~IGraphSceneCollection() { - } diff --git a/src/printing/helper/model/igraphscenecollection.h b/src/printing/helper/model/igraphscenecollection.h index 376bf99..bd0984a 100644 --- a/src/printing/helper/model/igraphscenecollection.h +++ b/src/printing/helper/model/igraphscenecollection.h @@ -32,15 +32,14 @@ class IGraphScene; class IGraphSceneCollection { public: - /*! * \brief The SceneItem struct */ struct SceneItem { IGraphScene *scene = nullptr; //! pointer to scene - QString name; //! scene title - QString type; //! scene type name + QString name; //! scene title + QString type; //! scene type name }; IGraphSceneCollection(); diff --git a/src/printing/helper/model/printdefs.h b/src/printing/helper/model/printdefs.h index e540eb1..599f5a6 100644 --- a/src/printing/helper/model/printdefs.h +++ b/src/printing/helper/model/printdefs.h @@ -27,25 +27,26 @@ class QPrinter; namespace Print { -enum class OutputType { +enum class OutputType +{ Native = 0, Pdf, Svg, NTypes }; -//Implemented in printwizard.cpp +// Implemented in printwizard.cpp QString getOutputTypeName(OutputType type); -//Place holders for file names +// Place holders for file names const QLatin1String phNameUnderscore = QLatin1String("%n"); const QLatin1String phNameKeepSpaces = QLatin1String("%N"); -const QLatin1String phType = QLatin1String("%t"); -const QLatin1String phProgressive = QLatin1String("%i"); +const QLatin1String phType = QLatin1String("%t"); +const QLatin1String phProgressive = QLatin1String("%i"); -//Implemented in printing/wizard/printwizard.cpp -QString getFileName(const QString& baseDir, const QString& pattern, const QString& extension, - const QString& name, const QString &type, int i); +// Implemented in printing/wizard/printwizard.cpp +QString getFileName(const QString &baseDir, const QString &pattern, const QString &extension, + const QString &name, const QString &type, int i); struct PrintBasicOptions { @@ -53,18 +54,18 @@ struct PrintBasicOptions QString fileNamePattern; QString filePath; bool useOneFileForEachScene = true; - bool printSceneInOnePage = false; + bool printSceneInOnePage = false; }; -//Implemented in printing/wizard/printwizard.cpp -void validatePrintOptions(PrintBasicOptions& printOpt, QPrinter *printer); +// Implemented in printing/wizard/printwizard.cpp +void validatePrintOptions(PrintBasicOptions &printOpt, QPrinter *printer); -//Implemented in printing/wizard/printwizard.cpp +// Implemented in printing/wizard/printwizard.cpp bool askUserToAbortPrinting(bool wasAlreadyStarted, QWidget *parent); -//Implemented in printing/wizard/printwizard.cpp -bool askUserToTryAgain(const QString& errMsg, QWidget *parent); +// Implemented in printing/wizard/printwizard.cpp +bool askUserToTryAgain(const QString &errMsg, QWidget *parent); -} +} // namespace Print #endif // DEFS_H diff --git a/src/printing/helper/model/printhelper.cpp b/src/printing/helper/model/printhelper.cpp index ebba606..fd5e5a1 100644 --- a/src/printing/helper/model/printhelper.cpp +++ b/src/printing/helper/model/printhelper.cpp @@ -27,221 +27,242 @@ QPageSize PrintHelper::fixPageSize(const QPageSize &pageSz, QPageLayout::Orientation &orient) { - //NOTE: Sometimes QPageSetupDialog messes up page size - //To express A4 Landascape, it swaps height and width - //But now the page size is no longer recognized as "A4" - //And other dialogs might show "Custom", try to fix it. + // NOTE: Sometimes QPageSetupDialog messes up page size + // To express A4 Landascape, it swaps height and width + // But now the page size is no longer recognized as "A4" + // And other dialogs might show "Custom", try to fix it. - if(pageSz.id() != QPageSize::Custom) - return pageSz; //Already correct value, use it directly + if (pageSz.id() != QPageSize::Custom) + return pageSz; // Already correct value, use it directly const QSizeF defSize = pageSz.definitionSize(); - QPageSize possibleMatchSwapped(defSize.transposed(), - pageSz.definitionUnits()); - if(possibleMatchSwapped.id() != QPageSize::Custom) - return possibleMatchSwapped; //Found a match + QPageSize possibleMatchSwapped(defSize.transposed(), pageSz.definitionUnits()); + if (possibleMatchSwapped.id() != QPageSize::Custom) + return possibleMatchSwapped; // Found a match - //No match found, at least check orientation - if(defSize.width() > defSize.height()) + // No match found, at least check orientation + if (defSize.width() > defSize.height()) orient = QPageLayout::Landscape; else orient = QPageLayout::Portrait; return pageSz; } -void PrintHelper::applyPageSize(const QPageSize &pageSz, const QPageLayout::Orientation &orient, Print::PageLayoutOpt &pageLay) +void PrintHelper::applyPageSize(const QPageSize &pageSz, const QPageLayout::Orientation &orient, + Print::PageLayoutOpt &pageLay) { QRect pointsRect = pageSz.rectPoints(); - const bool shouldTranspose = (orient == QPageLayout::Portrait && pointsRect.width() > pointsRect.height()) - || (orient == QPageLayout::Landscape && pointsRect.width() < pointsRect.height()); + const bool shouldTranspose = + (orient == QPageLayout::Portrait && pointsRect.width() > pointsRect.height()) + || (orient == QPageLayout::Landscape && pointsRect.width() < pointsRect.height()); - if(shouldTranspose) + if (shouldTranspose) pointsRect = pointsRect.transposed(); pageLay.pageRectPoints = pointsRect; } -void PrintHelper::initScaledLayout(Print::PageLayoutScaled &scaledPageLay, const Print::PageLayoutOpt &pageLay) +void PrintHelper::initScaledLayout(Print::PageLayoutScaled &scaledPageLay, + const Print::PageLayoutOpt &pageLay) { scaledPageLay.lay = pageLay; - //Update printer resolution + // Update printer resolution double resolutionFactor = scaledPageLay.printerResolution / Print::PrinterDefaultResolution; scaledPageLay.realScaleFactor = pageLay.sourceScaleFactor * resolutionFactor; - //Inverse scale for margins and pen to keep them independent + // Inverse scale for margins and pen to keep them independent scaledPageLay.overlapMarginWidthScaled = pageLay.marginWidthPoints / pageLay.sourceScaleFactor; - scaledPageLay.pageMarginsPen.setWidthF(pageLay.pageMarginsPenWidthPoints / pageLay.sourceScaleFactor); + scaledPageLay.pageMarginsPen.setWidthF(pageLay.pageMarginsPenWidthPoints + / pageLay.sourceScaleFactor); } void PrintHelper::calculatePageCount(IGraphScene *scene, Print::PageLayoutOpt &pageLay, QSizeF &outEffectivePageSizePoints) { QSizeF srcContentsSize; - if(scene) + if (scene) srcContentsSize = scene->getContentsSize() * pageLay.sourceScaleFactor; - //NOTE: do not shift by top left margin here - //This is because it should not be counted when calculating page count - //as it is out of effective page size (= page inside margins) - //Overall size is then computed from page count so it's always correct + // NOTE: do not shift by top left margin here + // This is because it should not be counted when calculating page count + // as it is out of effective page size (= page inside margins) + // Overall size is then computed from page count so it's always correct - //Apply overlap margin - //Each page has 2 margin (left and right) and other 2 margins (top and bottom) - //Calculate effective content size inside margins - const double sizeShrink = 2 * pageLay.marginWidthPoints; + // Apply overlap margin + // Each page has 2 margin (left and right) and other 2 margins (top and bottom) + // Calculate effective content size inside margins + const double sizeShrink = 2 * pageLay.marginWidthPoints; outEffectivePageSizePoints = pageLay.pageRectPoints.size(); outEffectivePageSizePoints.rwidth() -= sizeShrink; outEffectivePageSizePoints.rheight() -= sizeShrink; - //Calculate page count, at least 1 page - pageLay.pageCountHoriz = qMax(1, qCeil(srcContentsSize.width() / outEffectivePageSizePoints.width())); - pageLay.pageCountVert = qMax(1, qCeil(srcContentsSize.height() / outEffectivePageSizePoints.height())); + // Calculate page count, at least 1 page + pageLay.pageCountHoriz = + qMax(1, qCeil(srcContentsSize.width() / outEffectivePageSizePoints.width())); + pageLay.pageCountVert = + qMax(1, qCeil(srcContentsSize.height() / outEffectivePageSizePoints.height())); } -bool PrintHelper::printPagedScene(QPainter *painter, Print::IPagedPaintDevice *dev, IGraphScene *scene, Print::IProgress *progress, - Print::PageLayoutScaled &pageLay, Print::PageNumberOpt &pageNumOpt) +bool PrintHelper::printPagedScene(QPainter *painter, Print::IPagedPaintDevice *dev, + IGraphScene *scene, Print::IProgress *progress, + Print::PageLayoutScaled &pageLay, + Print::PageNumberOpt &pageNumOpt) { QSizeF effectivePageSize; calculatePageCount(scene, pageLay.lay, effectivePageSize); - //NOTE: effectivePageSize is in points, we need to scale by inverse of source scene + // NOTE: effectivePageSize is in points, we need to scale by inverse of source scene effectivePageSize /= pageLay.lay.sourceScaleFactor; - //Fix margins by half pen with so pen does not draw on over contents + // Fix margins by half pen with so pen does not draw on over contents const double marginCorrection = pageLay.pageMarginsPen.widthF() / 2.0; - //Page info rect above top margin to draw page numbers + // Page info rect above top margin to draw page numbers QRectF pageNumbersRect(QPointF(pageLay.overlapMarginWidthScaled, 0), QSizeF(effectivePageSize.width(), pageLay.overlapMarginWidthScaled)); - if(pageLay.lay.marginWidthPoints < 8) - pageNumbersRect.setHeight(8.0 / pageLay.lay.sourceScaleFactor); //Minimum height + if (pageLay.lay.marginWidthPoints < 8) + pageNumbersRect.setHeight(8.0 / pageLay.lay.sourceScaleFactor); // Minimum height - //Avoid overflowing text outside margins + // Avoid overflowing text outside margins double fontSizePt = qMin(pageNumOpt.fontSizePt, pageLay.lay.marginWidthPoints * 0.8); - if(fontSizePt < 5) - fontSizePt = 5; //Minimum font size + if (fontSizePt < 5) + fontSizePt = 5; // Minimum font size pageNumOpt.font.setPointSizeF(fontSizePt / pageLay.realScaleFactor); const QSizeF headerSize = scene->getHeaderSize(); - //Set maximum progress (= total page count) - if(progress && !progress->reportProgressAndContinue(Print::IProgress::ProgressSetMaximum, - pageLay.lay.pageCountHoriz * pageLay.lay.pageCountVert)) + // Set maximum progress (= total page count) + if (progress + && !progress->reportProgressAndContinue(Print::IProgress::ProgressSetMaximum, + pageLay.lay.pageCountHoriz + * pageLay.lay.pageCountVert)) return false; - //Rect to paint on each page (inverse scale of source) - QRectF sourceRect = QRectF(QPointF(), pageLay.lay.pageRectPoints.size() / pageLay.lay.sourceScaleFactor); + // Rect to paint on each page (inverse scale of source) + QRectF sourceRect = + QRectF(QPointF(), pageLay.lay.pageRectPoints.size() / pageLay.lay.sourceScaleFactor); - //Shift by top left page margins + // Shift by top left page margins const QPointF origin(pageLay.overlapMarginWidthScaled, pageLay.overlapMarginWidthScaled); sourceRect.moveTopLeft(sourceRect.topLeft() - origin); - for(int y = 0; y < pageLay.lay.pageCountVert; y++) + for (int y = 0; y < pageLay.lay.pageCountVert; y++) { - for(int x = 0; x < pageLay.lay.pageCountHoriz; x++) + for (int x = 0; x < pageLay.lay.pageCountHoriz; x++) { const bool onFirstPage = x + y == 0; - //To avoid calling newPage() at end of loop - //which would result in an empty extra page after last drawn page + // To avoid calling newPage() at end of loop + // which would result in an empty extra page after last drawn page dev->newPage(painter, pageLay.devicePageRectPixels, onFirstPage); - if(dev->needsInitForEachPage() || onFirstPage) + if (dev->needsInitForEachPage() || onFirstPage) { - //If on first page of current scene or need init for every page - //Reset painter transform because device might be already inited + // If on first page of current scene or need init for every page + // Reset painter transform because device might be already inited painter->resetTransform(); - //Apply scaling + // Apply scaling painter->scale(pageLay.realScaleFactor, pageLay.realScaleFactor); - //Shift by inverse of top left page margins + // Shift by inverse of top left page margins painter->translate(origin); } - //Clipping must be set on every new page - //Since clipping works in logical (QPainter) coordinates - //we use sourceRect which is already transformed + // Clipping must be set on every new page + // Since clipping works in logical (QPainter) coordinates + // we use sourceRect which is already transformed painter->setClipRect(sourceRect); QRectF sceneRect = sourceRect; - if(sceneRect.left() < 0) + if (sceneRect.left() < 0) sceneRect.setLeft(0); - if(sceneRect.top() < 0) + if (sceneRect.top() < 0) sceneRect.setTop(0); - //Render scene contets + // Render scene contets scene->renderContents(painter, sceneRect); - //Render horizontal header + // Render horizontal header QRectF horizHeaderRect = sceneRect; horizHeaderRect.moveTop(0); horizHeaderRect.setBottom(headerSize.height()); scene->renderHeader(painter, horizHeaderRect, Qt::Horizontal, 0); - //Render vertical header + // Render vertical header QRectF vertHeaderRect = sceneRect; vertHeaderRect.moveLeft(0); vertHeaderRect.setRight(headerSize.width()); scene->renderHeader(painter, vertHeaderRect, Qt::Vertical, 0); - if(pageLay.lay.drawPageMargins) + if (pageLay.lay.drawPageMargins) { - //Draw a frame to help align printed pages + // Draw a frame to help align printed pages painter->setPen(pageLay.pageMarginsPen); QLineF arr[4] = { - //Top - QLineF(sourceRect.left(), sourceRect.top() + pageLay.overlapMarginWidthScaled - marginCorrection, - sourceRect.right(), sourceRect.top() + pageLay.overlapMarginWidthScaled - marginCorrection), - //Bottom - QLineF(sourceRect.left(), sourceRect.bottom() - pageLay.overlapMarginWidthScaled + marginCorrection, - sourceRect.right(), sourceRect.bottom() - pageLay.overlapMarginWidthScaled + marginCorrection), - //Left - QLineF(sourceRect.left() + pageLay.overlapMarginWidthScaled - marginCorrection, sourceRect.top(), - sourceRect.left() + pageLay.overlapMarginWidthScaled - marginCorrection, sourceRect.bottom()), - //Right - QLineF(sourceRect.right() - pageLay.overlapMarginWidthScaled + marginCorrection, sourceRect.top(), - sourceRect.right() - pageLay.overlapMarginWidthScaled + marginCorrection, sourceRect.bottom()) - }; + // Top + QLineF(sourceRect.left(), + sourceRect.top() + pageLay.overlapMarginWidthScaled - marginCorrection, + sourceRect.right(), + sourceRect.top() + pageLay.overlapMarginWidthScaled - marginCorrection), + // Bottom + QLineF(sourceRect.left(), + sourceRect.bottom() - pageLay.overlapMarginWidthScaled + marginCorrection, + sourceRect.right(), + sourceRect.bottom() - pageLay.overlapMarginWidthScaled + marginCorrection), + // Left + QLineF(sourceRect.left() + pageLay.overlapMarginWidthScaled - marginCorrection, + sourceRect.top(), + sourceRect.left() + pageLay.overlapMarginWidthScaled - marginCorrection, + sourceRect.bottom()), + // Right + QLineF(sourceRect.right() - pageLay.overlapMarginWidthScaled + marginCorrection, + sourceRect.top(), + sourceRect.right() - pageLay.overlapMarginWidthScaled + marginCorrection, + sourceRect.bottom())}; painter->drawLines(arr, 4); } - if(pageNumOpt.enable) + if (pageNumOpt.enable) { - //Draw page numbers to help laying out printed pages - //Add +1 because loop starts from 0 - const QString str = pageNumOpt.fmt - .arg(y + 1).arg(pageLay.lay.pageCountVert) - .arg(x + 1).arg(pageLay.lay.pageCountHoriz); + // Draw page numbers to help laying out printed pages + // Add +1 because loop starts from 0 + const QString str = pageNumOpt.fmt.arg(y + 1) + .arg(pageLay.lay.pageCountVert) + .arg(x + 1) + .arg(pageLay.lay.pageCountHoriz); - //Move to top left but separate a bit from left margin + // Move to top left but separate a bit from left margin pageNumbersRect.moveTop(sourceRect.top()); - pageNumbersRect.moveLeft(sourceRect.left() + pageLay.overlapMarginWidthScaled * 1.5); + pageNumbersRect.moveLeft(sourceRect.left() + + pageLay.overlapMarginWidthScaled * 1.5); painter->setFont(pageNumOpt.font); painter->drawText(pageNumbersRect, Qt::AlignVCenter | Qt::AlignLeft, str); } - //Go left + // Go left sourceRect.moveLeft(sourceRect.left() + effectivePageSize.width()); painter->translate(-effectivePageSize.width(), 0); - //Report progress - if(progress && !progress->reportProgressAndContinue(y * pageLay.lay.pageCountHoriz + x, - pageLay.lay.pageCountHoriz * pageLay.lay.pageCountVert)) + // Report progress + if (progress + && !progress->reportProgressAndContinue(y * pageLay.lay.pageCountHoriz + x, + pageLay.lay.pageCountHoriz + * pageLay.lay.pageCountVert)) return false; } - //Go down and back to left most column + // Go down and back to left most column sourceRect.moveTop(sourceRect.top() + effectivePageSize.height()); painter->translate(sourceRect.left() + origin.x(), -effectivePageSize.height()); sourceRect.moveLeft(-origin.x()); } - //Reset to top most and left most + // Reset to top most and left most painter->translate(sourceRect.topLeft()); sourceRect.moveTopLeft(QPointF()); diff --git a/src/printing/helper/model/printhelper.h b/src/printing/helper/model/printhelper.h index 5428530..8f78124 100644 --- a/src/printing/helper/model/printhelper.h +++ b/src/printing/helper/model/printhelper.h @@ -28,59 +28,62 @@ class IGraphScene; namespace Print { -//Standard resolution, set to all printers to calculate page size +// Standard resolution, set to all printers to calculate page size static constexpr const double PrinterDefaultResolution = 72.0; -//Page Layout +// Page Layout struct PageLayoutOpt { QRectF pageRectPoints; - int pageCountHoriz = 0; - int pageCountVert = 0; + int pageCountHoriz = 0; + int pageCountVert = 0; - double sourceScaleFactor = 0.5; - double marginWidthPoints = 20; + double sourceScaleFactor = 0.5; + double marginWidthPoints = 20; double pageMarginsPenWidthPoints = 7; - bool drawPageMargins = true; + bool drawPageMargins = true; }; -//Scaled values useful for printing +// Scaled values useful for printing struct PageLayoutScaled { PageLayoutOpt lay; - //Device page rect is multiplied by printerResolution + // Device page rect is multiplied by printerResolution QRectF devicePageRectPixels; double printerResolution = PrinterDefaultResolution; - //Premultiplied originalScaleFactor for PrinterDefaultResolution/printerResolution - //This is needed to compensate devicePageRect which depends on printer resolution - double realScaleFactor = 1; + // Premultiplied originalScaleFactor for PrinterDefaultResolution/printerResolution + // This is needed to compensate devicePageRect which depends on printer resolution + double realScaleFactor = 1; double overlapMarginWidthScaled = 20; QPen pageMarginsPen; }; -//Page Numbers +// Page Numbers struct PageNumberOpt { QFont font; QString fmt; double fontSizePt = 20; - bool enable = true; + bool enable = true; }; -//Device +// Device class IPagedPaintDevice { public: - virtual ~IPagedPaintDevice() {}; - virtual bool newPage(QPainter *painter, const QRectF& brect, bool isFirstPage) = 0; + virtual ~IPagedPaintDevice(){}; + virtual bool newPage(QPainter *painter, const QRectF &brect, bool isFirstPage) = 0; - inline bool needsInitForEachPage() const { return m_needsInitForEachPage; } + inline bool needsInitForEachPage() const + { + return m_needsInitForEachPage; + } protected: bool m_needsInitForEachPage; @@ -89,29 +92,31 @@ protected: class IProgress { public: - virtual ~IProgress() {}; + virtual ~IProgress(){}; virtual bool reportProgressAndContinue(int current, int max) = 0; - static const int ProgressSetMaximum = -1; + static const int ProgressSetMaximum = -1; }; -} //namespace Print - +} // namespace Print class PrintHelper { public: - static QPageSize fixPageSize(const QPageSize& pageSz, QPageLayout::Orientation &orient); + static QPageSize fixPageSize(const QPageSize &pageSz, QPageLayout::Orientation &orient); - static void applyPageSize(const QPageSize& pageSz, const QPageLayout::Orientation &orient, Print::PageLayoutOpt &pageLay); + static void applyPageSize(const QPageSize &pageSz, const QPageLayout::Orientation &orient, + Print::PageLayoutOpt &pageLay); - static void initScaledLayout(Print::PageLayoutScaled &scaledPageLay, const Print::PageLayoutOpt &pageLay); + static void initScaledLayout(Print::PageLayoutScaled &scaledPageLay, + const Print::PageLayoutOpt &pageLay); - static void calculatePageCount(IGraphScene *scene, Print::PageLayoutOpt& pageLay, + static void calculatePageCount(IGraphScene *scene, Print::PageLayoutOpt &pageLay, QSizeF &outEffectivePageSizePoints); - static bool printPagedScene(QPainter *painter, Print::IPagedPaintDevice *dev, IGraphScene *scene, Print::IProgress *progress, - Print::PageLayoutScaled &pageLay, Print::PageNumberOpt& pageNumOpt); + static bool printPagedScene(QPainter *painter, Print::IPagedPaintDevice *dev, + IGraphScene *scene, Print::IProgress *progress, + Print::PageLayoutScaled &pageLay, Print::PageNumberOpt &pageNumOpt); }; #endif // PRINTHELPER_H diff --git a/src/printing/helper/model/printpreviewsceneproxy.cpp b/src/printing/helper/model/printpreviewsceneproxy.cpp index 16574b3..582746f 100644 --- a/src/printing/helper/model/printpreviewsceneproxy.cpp +++ b/src/printing/helper/model/printpreviewsceneproxy.cpp @@ -38,63 +38,63 @@ void PrintPreviewSceneProxy::renderContents(QPainter *painter, const QRectF &sce { const QTransform originalTransform = painter->worldTransform(); - if(m_sourceScene) + if (m_sourceScene) { - //Map coordinates to source scene + // Map coordinates to source scene QRectF sourceRect = sceneRect; - //Shift contents by our headers size and top left page margin + // Shift contents by our headers size and top left page margin QPointF origin(m_cachedHeaderSize.width() + m_pageLay.marginWidthPoints, m_cachedHeaderSize.height() + m_pageLay.marginWidthPoints); sourceRect.moveTopLeft(sourceRect.topLeft() - origin); - //Apply scale factor + // Apply scale factor sourceRect = QRectF(sourceRect.topLeft() / m_pageLay.sourceScaleFactor, sourceRect.size() / m_pageLay.sourceScaleFactor); - //Cut negative part which would go under our headers - //This will reduce a bit the rect size - if(sourceRect.left() < 0) + // Cut negative part which would go under our headers + // This will reduce a bit the rect size + if (sourceRect.left() < 0) sourceRect.setLeft(0); - if(sourceRect.top() < 0) + if (sourceRect.top() < 0) sourceRect.setTop(0); - //Cut possible extra parts + // Cut possible extra parts QSizeF contentsSize = m_sourceScene->getContentsSize(); - if(sourceRect.right() > contentsSize.width()) + if (sourceRect.right() > contentsSize.width()) sourceRect.setRight(contentsSize.width()); - if(sourceRect.bottom() > contentsSize.height()) + if (sourceRect.bottom() > contentsSize.height()) sourceRect.setBottom(contentsSize.height()); painter->translate(origin); painter->scale(m_pageLay.sourceScaleFactor, m_pageLay.sourceScaleFactor); - //Draw source contents + // Draw source contents m_sourceScene->renderContents(painter, sourceRect); QSizeF headerSize = m_sourceScene->getHeaderSize(); - //If on top draw horizontal header - if(sourceRect.top() < headerSize.height()) + // If on top draw horizontal header + if (sourceRect.top() < headerSize.height()) { QRectF horizHeaderRect = sourceRect; horizHeaderRect.setBottom(headerSize.height()); m_sourceScene->renderHeader(painter, horizHeaderRect, Qt::Horizontal, 0); } - //If on left draw vertical header - if(sourceRect.left() < headerSize.width()) + // If on left draw vertical header + if (sourceRect.left() < headerSize.width()) { QRectF vertHeaderRect = sourceRect; vertHeaderRect.setRight(headerSize.width()); m_sourceScene->renderHeader(painter, vertHeaderRect, Qt::Vertical, 0); } - //Wash out a bit to make page borders more visible + // Wash out a bit to make page borders more visible painter->fillRect(sourceRect, QColor(40, 255, 40, 100)); } - //Reset transorm to previous + // Reset transorm to previous painter->setWorldTransform(originalTransform); drawPageBorders(painter, sceneRect, false); @@ -103,48 +103,50 @@ void PrintPreviewSceneProxy::renderContents(QPainter *painter, const QRectF &sce void PrintPreviewSceneProxy::renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient, double scroll) { - double vertScroll = scroll; + double vertScroll = scroll; double horizScroll = 0; - if(orient == Qt::Horizontal) + if (orient == Qt::Horizontal) qSwap(vertScroll, horizScroll); - //Do not overlap the 2 headers in the top left corner for background and separator lines + // Do not overlap the 2 headers in the top left corner for background and separator lines QRectF nonOverlappingingRect = sceneRect; - if(nonOverlappingingRect.left() < m_cachedHeaderSize.width() + horizScroll) + if (nonOverlappingingRect.left() < m_cachedHeaderSize.width() + horizScroll) nonOverlappingingRect.setLeft(m_cachedHeaderSize.width() + horizScroll); - if(nonOverlappingingRect.top() < m_cachedHeaderSize.width() + vertScroll) + if (nonOverlappingingRect.top() < m_cachedHeaderSize.width() + vertScroll) nonOverlappingingRect.setTop(m_cachedHeaderSize.width() + vertScroll); - //Draw a ligth gray background to tell it's a header + // Draw a ligth gray background to tell it's a header QRectF backGroundRect = sceneRect; - if(orient == Qt::Vertical) + if (orient == Qt::Vertical) { - //Do not draw corner, it's already drawn by horizontal header + // Do not draw corner, it's already drawn by horizontal header backGroundRect = nonOverlappingingRect; - backGroundRect.setLeft(sceneRect.left()); //Keep original left edge + backGroundRect.setLeft(sceneRect.left()); // Keep original left edge } painter->fillRect(backGroundRect, QColor(101, 101, 101, 128)); - //Draw a separation line of fixed size + // Draw a separation line of fixed size QPen separatorPen(Qt::darkGreen, 5.0 / viewScaleFactor, Qt::SolidLine, Qt::FlatCap); painter->setPen(separatorPen); - if(orient == Qt::Horizontal) + if (orient == Qt::Horizontal) { - //Horizontal line + // Horizontal line painter->drawLine(QLineF(sceneRect.left(), m_cachedHeaderSize.height(), nonOverlappingingRect.right(), m_cachedHeaderSize.height())); - //Vertical line + // Vertical line painter->drawLine(QLineF(m_cachedHeaderSize.width() + horizScroll, sceneRect.top(), - m_cachedHeaderSize.width() + horizScroll, nonOverlappingingRect.bottom())); + m_cachedHeaderSize.width() + horizScroll, + nonOverlappingingRect.bottom())); } else { - //Horizontal line + // Horizontal line painter->drawLine(QLineF(sceneRect.left(), m_cachedHeaderSize.height() + vertScroll, - nonOverlappingingRect.right(), m_cachedHeaderSize.height() + vertScroll)); - //Vertical line + nonOverlappingingRect.right(), + m_cachedHeaderSize.height() + vertScroll)); + // Vertical line painter->drawLine(QLineF(m_cachedHeaderSize.width(), nonOverlappingingRect.top(), m_cachedHeaderSize.width(), nonOverlappingingRect.bottom())); } @@ -159,28 +161,28 @@ IGraphScene *PrintPreviewSceneProxy::getSourceScene() const void PrintPreviewSceneProxy::setSourceScene(IGraphScene *newSourceScene) { - //Connect to size and content changes to forward them to view - //Since this is a print preview we are not interested - //in sceneActivated() and requestShowRect() signals + // Connect to size and content changes to forward them to view + // Since this is a print preview we are not interested + // in sceneActivated() and requestShowRect() signals - if(m_sourceScene) + if (m_sourceScene) { disconnect(m_sourceScene, &QObject::destroyed, this, &PrintPreviewSceneProxy::onSourceSceneDestroyed); - disconnect(m_sourceScene, &IGraphScene::redrawGraph, - this, &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); - disconnect(m_sourceScene, &IGraphScene::headersSizeChanged, - this, &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); + disconnect(m_sourceScene, &IGraphScene::redrawGraph, this, + &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); + disconnect(m_sourceScene, &IGraphScene::headersSizeChanged, this, + &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); } m_sourceScene = newSourceScene; - if(m_sourceScene) + if (m_sourceScene) { connect(m_sourceScene, &QObject::destroyed, this, &PrintPreviewSceneProxy::onSourceSceneDestroyed); - connect(m_sourceScene, &IGraphScene::redrawGraph, - this, &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); - connect(m_sourceScene, &IGraphScene::headersSizeChanged, - this, &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); + connect(m_sourceScene, &IGraphScene::redrawGraph, this, + &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); + connect(m_sourceScene, &IGraphScene::headersSizeChanged, this, + &PrintPreviewSceneProxy::updateSourceSizeAndRedraw); } updateSourceSizeAndRedraw(); @@ -193,11 +195,11 @@ double PrintPreviewSceneProxy::getViewScaleFactor() const void PrintPreviewSceneProxy::setViewScaleFactor(double newViewScaleFactor) { - //Keep header of same size, independently of view zoom - viewScaleFactor = newViewScaleFactor; + // Keep header of same size, independently of view zoom + viewScaleFactor = newViewScaleFactor; const QSizeF newHeaderSize = originalHeaderSize / viewScaleFactor; - if(newHeaderSize != m_cachedHeaderSize) + if (newHeaderSize != m_cachedHeaderSize) { m_cachedHeaderSize = newHeaderSize; emit headersSizeChanged(); @@ -226,73 +228,74 @@ void PrintPreviewSceneProxy::updateSourceSizeAndRedraw() { PrintHelper::calculatePageCount(m_sourceScene, m_pageLay, effectivePageSize); - //Calculate total size + // Calculate total size QSizeF printedSize(m_pageLay.pageCountHoriz * m_pageLay.pageRectPoints.width(), m_pageLay.pageCountVert * m_pageLay.pageRectPoints.height()); - //Adjust by substracting overlapped edges ((2 * n) - 2) + // Adjust by substracting overlapped edges ((2 * n) - 2) printedSize -= QSizeF((2 * m_pageLay.pageCountHoriz - 2) * m_pageLay.marginWidthPoints, - (2 * m_pageLay.pageCountVert - 2)* m_pageLay.marginWidthPoints); + (2 * m_pageLay.pageCountVert - 2) * m_pageLay.marginWidthPoints); - //Add our headers and store + // Add our headers and store m_cachedContentsSize = printedSize + m_cachedHeaderSize; emit redrawGraph(); emit pageCountChanged(); } -void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sceneRect, bool isHeader, Qt::Orientation orient) +void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sceneRect, + bool isHeader, Qt::Orientation orient) { const qreal fixedOffsetX = m_cachedHeaderSize.width() + m_pageLay.marginWidthPoints; const qreal fixedOffsetY = m_cachedHeaderSize.height() + m_pageLay.marginWidthPoints; - //Theese are effective page sizes (so inside margins) + // Theese are effective page sizes (so inside margins) int firstPageVertBorder = qCeil((sceneRect.left() - fixedOffsetX) / effectivePageSize.width()); int lastPageVertBorder = qFloor((sceneRect.right() - fixedOffsetX) / effectivePageSize.width()); - //For N pages there are N + 1 borders, but we count from 0 so last border is N + // For N pages there are N + 1 borders, but we count from 0 so last border is N - //Vertical border, horizontal page count - if(lastPageVertBorder > m_pageLay.pageCountHoriz) + // Vertical border, horizontal page count + if (lastPageVertBorder > m_pageLay.pageCountHoriz) lastPageVertBorder = m_pageLay.pageCountHoriz; - if(firstPageVertBorder > lastPageVertBorder) + if (firstPageVertBorder > lastPageVertBorder) firstPageVertBorder = lastPageVertBorder; - if(firstPageVertBorder < 0) + if (firstPageVertBorder < 0) firstPageVertBorder = 0; int firstPageHorizBorder = qCeil((sceneRect.top() - fixedOffsetY) / effectivePageSize.height()); - int lastPageHorizBorder = qFloor((sceneRect.bottom() - fixedOffsetY) / effectivePageSize.height()); + int lastPageHorizBorder = + qFloor((sceneRect.bottom() - fixedOffsetY) / effectivePageSize.height()); - //Horizontal border, vertical page count - if(lastPageHorizBorder > m_pageLay.pageCountVert) + // Horizontal border, vertical page count + if (lastPageHorizBorder > m_pageLay.pageCountVert) lastPageHorizBorder = m_pageLay.pageCountVert; - if(firstPageHorizBorder > lastPageHorizBorder) + if (firstPageHorizBorder > lastPageHorizBorder) firstPageHorizBorder = lastPageHorizBorder; - if(firstPageHorizBorder < 0) + if (firstPageHorizBorder < 0) firstPageHorizBorder = 0; qreal pageBordersLeft = sceneRect.left(); - qreal pageBordersTop = sceneRect.top(); + qreal pageBordersTop = sceneRect.top(); - if(!isHeader) + if (!isHeader) { - //Do not go under headers when drawing contents + // Do not go under headers when drawing contents pageBordersLeft = qMax(m_cachedHeaderSize.width(), sceneRect.left()); - pageBordersTop = qMax(m_cachedHeaderSize.height(), sceneRect.top()); + pageBordersTop = qMax(m_cachedHeaderSize.height(), sceneRect.top()); } - - //Do not exceed scene proxy size - const qreal pageBordersRight = qMin(m_cachedContentsSize.width(), sceneRect.right()); + // Do not exceed scene proxy size + const qreal pageBordersRight = qMin(m_cachedContentsSize.width(), sceneRect.right()); const qreal pageBordersBottom = qMin(m_cachedContentsSize.height(), sceneRect.bottom()); QPen pageMarginsPen(Qt::red, m_pageLay.pageMarginsPenWidthPoints, Qt::SolidLine, Qt::FlatCap); - if(isHeader) + if (isHeader) { - //Keep width independent of view scale but with limits + // Keep width independent of view scale but with limits qreal wt = m_pageLay.pageMarginsPenWidthPoints / viewScaleFactor; - wt = qBound(2.0, wt, 20.0); + wt = qBound(2.0, wt, 20.0); pageMarginsPen.setWidthF(wt); } @@ -300,7 +303,7 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc QFont pageNumFont; pageNumFont.setBold(true); - if(isHeader) + if (isHeader) { setFontPointSizeDPI(pageNumFont, m_cachedHeaderSize.height() * 0.6, painter); } @@ -313,14 +316,14 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc QVector marginsVec; - int nLinesVert = lastPageVertBorder - firstPageVertBorder + 1; + int nLinesVert = lastPageVertBorder - firstPageVertBorder + 1; int nLinesHoriz = lastPageHorizBorder - firstPageHorizBorder + 1; - if(!isHeader) + if (!isHeader) { - //Draw real page borders (outside margins) + // Draw real page borders (outside margins) - //Set pen for page numbers + // Set pen for page numbers painter->setPen(pageMarginsPen); /* Divide them in 3 color groups @@ -335,68 +338,69 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc * +---+---+---+---+ */ - const double borderPenWidth = m_pageLay.pageMarginsPenWidthPoints * 0.7; + const double borderPenWidth = m_pageLay.pageMarginsPenWidthPoints * 0.7; - constexpr const int NPageColors = 3; + constexpr const int NPageColors = 3; QPen pagesBorderPen[NPageColors] = { - QPen(Qt::blue, borderPenWidth, Qt::DashLine, Qt::FlatCap), - QPen(Qt::magenta, borderPenWidth, Qt::DashLine, Qt::FlatCap), - QPen(Qt::black, borderPenWidth, Qt::DashLine, Qt::FlatCap) - }; + QPen(Qt::blue, borderPenWidth, Qt::DashLine, Qt::FlatCap), + QPen(Qt::magenta, borderPenWidth, Qt::DashLine, Qt::FlatCap), + QPen(Qt::black, borderPenWidth, Qt::DashLine, Qt::FlatCap)}; QVector pageBordersVec[NPageColors]; - //Try to allocate memory in advance + // Try to allocate memory in advance int allocCount = 4 * nLinesHoriz * nLinesVert / NPageColors; - if(allocCount < 4) + if (allocCount < 4) allocCount = 4; - for(int i = 0; i < NPageColors; i++) + for (int i = 0; i < NPageColors; i++) pageBordersVec[i].reserve(allocCount); - int vertPageColorGroup = firstPageVertBorder % NPageColors; + int vertPageColorGroup = firstPageVertBorder % NPageColors; int horizPageColorGroup = 0; - //Get page rect, move out of header + // Get page rect, move out of header QRectF pageRect = m_pageLay.pageRectPoints; - //Try also previous than first or next of last - //This is because maybe real border is shown but not the effective margin - for(int x = -1; x < nLinesVert + 1; x++) + // Try also previous than first or next of last + // This is because maybe real border is shown but not the effective margin + for (int x = -1; x < nLinesVert + 1; x++) { - //Increment vertical page color group - vertPageColorGroup = (vertPageColorGroup + 1) % NPageColors; + // Increment vertical page color group + vertPageColorGroup = (vertPageColorGroup + 1) % NPageColors; const int pageBorderCol = firstPageVertBorder + x; - if(pageBorderCol < 0 || pageBorderCol >= m_pageLay.pageCountHoriz) - continue; //Before first or after last, skip + if (pageBorderCol < 0 || pageBorderCol >= m_pageLay.pageCountHoriz) + continue; // Before first or after last, skip - pageRect.moveLeft(m_cachedHeaderSize.width() + effectivePageSize.width() * (pageBorderCol)); + pageRect.moveLeft(m_cachedHeaderSize.width() + + effectivePageSize.width() * (pageBorderCol)); - //Reset column to original value for every row + // Reset column to original value for every row horizPageColorGroup = firstPageHorizBorder % NPageColors; - for(int y = -1; y < nLinesHoriz + 1; y++) + for (int y = -1; y < nLinesHoriz + 1; y++) { - //Increment horizontal page color group - horizPageColorGroup = (horizPageColorGroup + 1) % NPageColors; + // Increment horizontal page color group + horizPageColorGroup = (horizPageColorGroup + 1) % NPageColors; const int pageBorderRow = firstPageHorizBorder + y; - if(pageBorderRow < 0 || pageBorderRow >= m_pageLay.pageCountVert) - continue; //Before first or after last, skip + if (pageBorderRow < 0 || pageBorderRow >= m_pageLay.pageCountVert) + continue; // Before first or after last, skip - pageRect.moveTop(m_cachedHeaderSize.height() + effectivePageSize.height() * (pageBorderRow)); + pageRect.moveTop(m_cachedHeaderSize.height() + + effectivePageSize.height() * (pageBorderRow)); - //Draw page number + // Draw page number const int pageNumber = pageBorderRow * m_pageLay.pageCountHoriz + pageBorderCol + 1; painter->drawText(pageRect, QString::number(pageNumber), pageNumTextOpt); - //Calculate page borders - QLineF topBorder = QLineF(pageRect.topLeft(), pageRect.topRight()); + // Calculate page borders + QLineF topBorder = QLineF(pageRect.topLeft(), pageRect.topRight()); QLineF bottomBorder = QLineF(pageRect.bottomLeft(), pageRect.bottomRight()); - QLineF leftBorder = QLineF(pageRect.topLeft(), pageRect.bottomLeft()); - QLineF rightBorder = QLineF(pageRect.topRight(), pageRect.bottomRight()); + QLineF leftBorder = QLineF(pageRect.topLeft(), pageRect.bottomLeft()); + QLineF rightBorder = QLineF(pageRect.topRight(), pageRect.bottomRight()); - const int group = (vertPageColorGroup + horizPageColorGroup) % NPageColors; + const int group = (vertPageColorGroup + horizPageColorGroup) % NPageColors; pageBordersVec[group].append(topBorder); pageBordersVec[group].append(bottomBorder); @@ -405,25 +409,25 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc } } - //Draw lines - for(int i = 0; i < NPageColors; i++) + // Draw lines + for (int i = 0; i < NPageColors; i++) { painter->setPen(pagesBorderPen[i]); painter->drawLines(pageBordersVec[i]); } } - //Set pen for page margins + // Set pen for page margins painter->setPen(pageMarginsPen); - //Draw effective page borders - if(!isHeader || orient == Qt::Horizontal) + // Draw effective page borders + if (!isHeader || orient == Qt::Horizontal) { - //Horizontal header draws vertical borders + // Horizontal header draws vertical borders marginsVec.reserve(nLinesVert); qreal borderX = fixedOffsetX + firstPageVertBorder * effectivePageSize.width(); - for(int i = 0; i < nLinesVert; i++) + for (int i = 0; i < nLinesVert; i++) { QLineF line(borderX, pageBordersTop, borderX, pageBordersBottom); marginsVec.append(line); @@ -431,24 +435,24 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc } painter->drawLines(marginsVec); - if(isHeader) + if (isHeader) { - //Draw page numbers + // Draw page numbers int firstPageNumber = firstPageVertBorder; - if(firstPageVertBorder > 0) - firstPageNumber--; //Draw also previous page + if (firstPageVertBorder > 0) + firstPageNumber--; // Draw also previous page - //If there are N pages, there are (N + 1) margins - //So last margin and last but one margin both belong to last page + // If there are N pages, there are (N + 1) margins + // So last margin and last but one margin both belong to last page int lastPageNumberPlusOne = lastPageVertBorder; - if(lastPageVertBorder < m_pageLay.pageCountHoriz) - lastPageNumberPlusOne++; //Draw also next page + if (lastPageVertBorder < m_pageLay.pageCountHoriz) + lastPageNumberPlusOne++; // Draw also next page borderX = fixedOffsetX + firstPageNumber * effectivePageSize.width(); QRectF textRect(borderX, 0, effectivePageSize.width(), m_cachedHeaderSize.height()); - for(int i = firstPageNumber; i < lastPageNumberPlusOne; i++) + for (int i = firstPageNumber; i < lastPageNumberPlusOne; i++) { - //Column index starts from 0 so add +1 + // Column index starts from 0 so add +1 painter->drawText(textRect, QString::number(i + 1), pageNumTextOpt); textRect.moveLeft(textRect.left() + effectivePageSize.width()); } @@ -457,13 +461,13 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc marginsVec.clear(); - if(!isHeader || orient == Qt::Vertical) + if (!isHeader || orient == Qt::Vertical) { - //Vertical header draws horizontal borders + // Vertical header draws horizontal borders marginsVec.reserve(nLinesHoriz); qreal borderY = fixedOffsetY + firstPageHorizBorder * effectivePageSize.height(); - for(int i = 0; i < nLinesHoriz; i++) + for (int i = 0; i < nLinesHoriz; i++) { QLineF line(pageBordersLeft, borderY, pageBordersRight, borderY); marginsVec.append(line); @@ -471,29 +475,29 @@ void PrintPreviewSceneProxy::drawPageBorders(QPainter *painter, const QRectF &sc } painter->drawLines(marginsVec); - if(isHeader) + if (isHeader) { - //Draw page numbers + // Draw page numbers int firstPageNumber = firstPageHorizBorder; - if(firstPageHorizBorder > 0) - firstPageNumber--; //Draw also previous page + if (firstPageHorizBorder > 0) + firstPageNumber--; // Draw also previous page int lastPageNumberPlusOne = lastPageHorizBorder; - if(lastPageHorizBorder < m_pageLay.pageCountVert) - lastPageNumberPlusOne++; //Draw also next page + if (lastPageHorizBorder < m_pageLay.pageCountVert) + lastPageNumberPlusOne++; // Draw also next page borderY = fixedOffsetY + firstPageNumber * effectivePageSize.height(); QRectF textRect(0, borderY, m_cachedHeaderSize.width(), effectivePageSize.height()); - for(int i = firstPageNumber; i < lastPageNumberPlusOne; i++) + for (int i = firstPageNumber; i < lastPageNumberPlusOne; i++) { - //Row index starts from 0 so add +1 + // Row index starts from 0 so add +1 painter->drawText(textRect, QString::number(i + 1), pageNumTextOpt); textRect.moveTop(textRect.top() + effectivePageSize.height()); } } } - //Free memory + // Free memory marginsVec.clear(); marginsVec.squeeze(); } diff --git a/src/printing/helper/model/printpreviewsceneproxy.h b/src/printing/helper/model/printpreviewsceneproxy.h index c212ccb..8fb3f52 100644 --- a/src/printing/helper/model/printpreviewsceneproxy.h +++ b/src/printing/helper/model/printpreviewsceneproxy.h @@ -30,9 +30,9 @@ class PrintPreviewSceneProxy : public IGraphScene public: PrintPreviewSceneProxy(QObject *parent = nullptr); - virtual void renderContents(QPainter *painter, const QRectF& sceneRect) override; - virtual void renderHeader(QPainter *painter, const QRectF& sceneRect, - Qt::Orientation orient, double scroll) override; + virtual void renderContents(QPainter *painter, const QRectF &sceneRect) override; + virtual void renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient, + double scroll) override; IGraphScene *getSourceScene() const; void setSourceScene(IGraphScene *newSourceScene); @@ -41,7 +41,7 @@ public: void setViewScaleFactor(double newViewScaleFactor); Print::PageLayoutOpt getPageLay() const; - void setPageLay(const Print::PageLayoutOpt& newPageLay); + void setPageLay(const Print::PageLayoutOpt &newPageLay); signals: void pageCountChanged(); @@ -51,8 +51,8 @@ private slots: void updateSourceSizeAndRedraw(); private: - void drawPageBorders(QPainter *painter, const QRectF& sceneRect, - bool isHeader, Qt::Orientation orient = Qt::Horizontal); + void drawPageBorders(QPainter *painter, const QRectF &sceneRect, bool isHeader, + Qt::Orientation orient = Qt::Horizontal); private: IGraphScene *m_sourceScene; diff --git a/src/printing/helper/model/printworker.cpp b/src/printing/helper/model/printworker.cpp index 388bbef..408dd6e 100644 --- a/src/printing/helper/model/printworker.cpp +++ b/src/printing/helper/model/printworker.cpp @@ -38,16 +38,16 @@ #include -bool testFileIsWriteable(const QString& fileName, QString &errOut) +bool testFileIsWriteable(const QString &fileName, QString &errOut) { QFile tmp(fileName); const bool existed = tmp.exists(); - bool writable = tmp.open(QFile::WriteOnly); - errOut = tmp.errorString(); + bool writable = tmp.open(QFile::WriteOnly); + errOut = tmp.errorString(); - if(tmp.isOpen()) + if (tmp.isOpen()) tmp.close(); - if(!existed) + if (!existed) tmp.remove(); return writable; @@ -59,7 +59,6 @@ PrintProgressEvent::PrintProgressEvent(QRunnable *self, int pr, const QString &d progress(pr), descriptionOrError(descrOrErr) { - } PrintWorker::PrintWorker(sqlite3pp::database &db, QObject *receiver) : @@ -67,12 +66,10 @@ PrintWorker::PrintWorker(sqlite3pp::database &db, QObject *receiver) : m_printer(nullptr), m_collection(nullptr) { - } PrintWorker::~PrintWorker() { - } void PrintWorker::setPrinter(QPrinter *printer) @@ -84,8 +81,8 @@ void PrintWorker::setPrintOpt(const Print::PrintBasicOptions &newPrintOpt) { printOpt = newPrintOpt; - if(printOpt.filePath.endsWith('/')) - printOpt.filePath.chop(1); //Remove last slash + if (printOpt.filePath.endsWith('/')) + printOpt.filePath.chop(1); // Remove last slash } void PrintWorker::setCollection(IGraphSceneCollection *newCollection) @@ -131,12 +128,11 @@ void PrintWorker::run() break; } - if(success) + if (success) { - //Send 'Finished' and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressMaxFinished, - QString()), true); + // Send 'Finished' and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressMaxFinished, QString()), + true); } } @@ -144,11 +140,10 @@ bool PrintWorker::printInternal(BeginPaintFunc func, bool endPaintingEveryPage) { QPainter painter; - if(!m_collection->startIteration()) + if (!m_collection->startIteration()) { - //Send error and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressError, + // Send error and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressError, PrintWizard::tr("Cannot iterate items.\n" "Check database connection.")), true); @@ -159,72 +154,72 @@ bool PrintWorker::printInternal(BeginPaintFunc func, bool endPaintingEveryPage) while (true) { - if(wasStopped()) + if (wasStopped()) { - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressAbortedByUser, - QString()), true); + sendEvent( + new PrintProgressEvent(this, PrintProgressEvent::ProgressAbortedByUser, QString()), + true); return false; } - //Lock to access 'm_collection' + // Lock to access 'm_collection' lockTask(); - if(!m_collection) + if (!m_collection) { unlockTask(); - //Task cannot proceed without collection. Abort - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressAbortedByUser, - QString()), true); + // Task cannot proceed without collection. Abort + sendEvent( + new PrintProgressEvent(this, PrintProgressEvent::ProgressAbortedByUser, QString()), + true); return false; } const IGraphSceneCollection::SceneItem item = m_collection->getNextItem(); unlockTask(); - if(!item.scene) - break; //Finished + if (!item.scene) + break; // Finished QScopedPointer scenPtr(item.scene); const QRectF sourceRect(QPointF(), scenPtr->getContentsSize()); - //Send progress and description - sendEvent(new PrintProgressEvent(this, progressiveNum * ProgressStepsForScene, item.name), false); + // Send progress and description + sendEvent(new PrintProgressEvent(this, progressiveNum * ProgressStepsForScene, item.name), + false); - if(func) + if (func) { bool valid = true; - //Callback might access 'this' pointer so lock + // Callback might access 'this' pointer so lock lockTask(); - valid = func(&painter, item.name, sourceRect, - item.type, progressiveNum); + valid = func(&painter, item.name, sourceRect, item.type, progressiveNum); unlockTask(); - if(!valid) + if (!valid) return false; } else { - //Fake success to trigger sending finished event + // Fake success to trigger sending finished event return true; } - //Render scene contets + // Render scene contets scenPtr->renderContents(&painter, sourceRect); - //Render horizontal header + // Render horizontal header QRectF horizHeaderRect = sourceRect; horizHeaderRect.moveTop(0); horizHeaderRect.setBottom(item.scene->getHeaderSize().height()); scenPtr->renderHeader(&painter, horizHeaderRect, Qt::Horizontal, 0); - //Render vertical header + // Render vertical header QRectF vertHeaderRect = sourceRect; vertHeaderRect.moveLeft(0); vertHeaderRect.setRight(item.scene->getHeaderSize().width()); scenPtr->renderHeader(&painter, vertHeaderRect, Qt::Vertical, 0); - if(endPaintingEveryPage) + if (endPaintingEveryPage) painter.end(); progressiveNum++; @@ -238,23 +233,25 @@ class PrintWorkerProgress : public Print::IProgress public: bool reportProgressAndContinue(int current, int max) override { - if(current == Print::IProgress::ProgressSetMaximum) + if (current == Print::IProgress::ProgressSetMaximum) { - //Begin a new scene + // Begin a new scene totalPages = max; - pageNum = 0; + pageNum = 0; } else { - //Add 1 because curren page is already finished + // Add 1 because curren page is already finished pageNum = current + 1; } - //Calculate fraction of current scene - const double sceneFraction = double(pageNum * PrintWorker::ProgressStepsForScene) / double(totalPages); + // Calculate fraction of current scene + const double sceneFraction = + double(pageNum * PrintWorker::ProgressStepsForScene) / double(totalPages); - //Calculate progress, completed scenes + fraction of current scene - const int progress = sceneNumber * PrintWorker::ProgressStepsForScene + qFloor(sceneFraction); + // Calculate progress, completed scenes + fraction of current scene + const int progress = + sceneNumber * PrintWorker::ProgressStepsForScene + qFloor(sceneFraction); return m_task->sendProgressOrAbort(progress, name); } @@ -262,23 +259,28 @@ public: public: PrintWorker *m_task = nullptr; - int pageNum = 0; - int totalPages = 0; - int sceneNumber = 0; + int pageNum = 0; + int totalPages = 0; + int sceneNumber = 0; QString name; }; class PagedDevImpl : public Print::IPagedPaintDevice { public: - PagedDevImpl() :m_dev(nullptr) { m_needsInitForEachPage = false; } - - bool newPage(QPainter *painter, const QRectF& brect, bool isFirstPage) override + PagedDevImpl() : + m_dev(nullptr) { - if(!isFirstPage) + m_needsInitForEachPage = false; + } + + bool newPage(QPainter *painter, const QRectF &brect, bool isFirstPage) override + { + if (!isFirstPage) return m_dev->newPage(); return true; } + public: QPagedPaintDevice *m_dev; }; @@ -286,29 +288,28 @@ public: bool PrintWorker::printInternalPaged(BeginPaintFunc func, bool endPaintingEveryPage) { PrintWorkerProgress progress; - progress.m_task = this; + progress.m_task = this; progress.sceneNumber = 0; PagedDevImpl devImpl; QPainter painter; - if(!m_collection->startIteration()) + if (!m_collection->startIteration()) { - //Send error and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressError, + // Send error and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressError, PrintWizard::tr("Cannot iterate items.\n" "Check database connection.")), true); return false; } - scenePageLay.drawPageMargins = true; + scenePageLay.drawPageMargins = true; scenePageLay.pageMarginsPenWidthPoints = 3; Print::PageNumberOpt pageNumberOpt; - pageNumberOpt.enable = true; + pageNumberOpt.enable = true; pageNumberOpt.fontSizePt = 20; pageNumberOpt.font.setBold(true); pageNumberOpt.fmt = QStringLiteral("Row: %1/%2 Col: %3/%4"); @@ -318,50 +319,51 @@ bool PrintWorker::printInternalPaged(BeginPaintFunc func, bool endPaintingEveryP while (true) { - if(wasStopped()) + if (wasStopped()) { - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressAbortedByUser, - QString()), true); + sendEvent( + new PrintProgressEvent(this, PrintProgressEvent::ProgressAbortedByUser, QString()), + true); return false; } const IGraphSceneCollection::SceneItem item = m_collection->getNextItem(); - if(!item.scene) - break; //Finished + if (!item.scene) + break; // Finished QScopedPointer scenPtr(item.scene); progress.name = item.name; - //Send progress and description - sendEvent(new PrintProgressEvent(this, - progress.sceneNumber * ProgressStepsForScene, - item.name), false); + // Send progress and description + sendEvent( + new PrintProgressEvent(this, progress.sceneNumber * ProgressStepsForScene, item.name), + false); const QRectF sceneRect(QPointF(), scenPtr->getContentsSize()); bool valid = true; - if(func) - valid = func(&painter, item.name, sceneRect, - item.type, progress.sceneNumber * ProgressStepsForScene); - if(!valid) + if (func) + valid = func(&painter, item.name, sceneRect, item.type, + progress.sceneNumber * ProgressStepsForScene); + if (!valid) return false; devImpl.m_dev = static_cast(painter.device()); - //Update printer resolution + // Update printer resolution scenePageLayScale.printerResolution = painter.device()->logicalDpiY(); - scenePageLayScale.devicePageRectPixels = QRectF(0, 0, painter.device()->width(), painter.device()->height()); + scenePageLayScale.devicePageRectPixels = + QRectF(0, 0, painter.device()->width(), painter.device()->height()); PrintHelper::initScaledLayout(scenePageLayScale, scenePageLay); - if(!PrintHelper::printPagedScene(&painter, &devImpl, scenPtr.data(), &progress, + if (!PrintHelper::printPagedScene(&painter, &devImpl, scenPtr.data(), &progress, scenePageLayScale, pageNumberOpt)) return false; - //Reset transform after evert + // Reset transform after evert painter.resetTransform(); - if(endPaintingEveryPage) + if (endPaintingEveryPage) painter.end(); progress.sceneNumber++; @@ -372,12 +374,11 @@ bool PrintWorker::printInternalPaged(BeginPaintFunc func, bool endPaintingEveryP bool PrintWorker::sendProgressOrAbort(int progress, const QString &msg) { - if(wasStopped()) + if (wasStopped()) { - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressAbortedByUser, - QString()), true); - //Quit + sendEvent( + new PrintProgressEvent(this, PrintProgressEvent::ProgressAbortedByUser, QString()), true); + // Quit return false; } @@ -389,14 +390,15 @@ bool PrintWorker::printSvg() { std::unique_ptr svg; const QString docTitle = QStringLiteral("Timetable Session (%1)"); - const QString descr = QStringLiteral("Generated by %1").arg(AppDisplayName); + const QString descr = QStringLiteral("Generated by %1").arg(AppDisplayName); - auto beginPaint = [this, &svg, &docTitle, &descr](QPainter *painter, - const QString& title, const QRectF& sourceRect, - const QString& type, int progressiveNum) -> bool + auto beginPaint = [this, &svg, &docTitle, &descr](QPainter *painter, const QString &title, + const QRectF &sourceRect, const QString &type, + int progressiveNum) -> bool { - const QString fileName = Print::getFileName(printOpt.filePath, printOpt.fileNamePattern, QLatin1String(".svg"), - title, type, progressiveNum); + const QString fileName = + Print::getFileName(printOpt.filePath, printOpt.fileNamePattern, QLatin1String(".svg"), + title, type, progressiveNum); svg.reset(new QSvgGenerator); svg->setTitle(docTitle.arg(title)); svg->setDescription(descr); @@ -404,28 +406,27 @@ bool PrintWorker::printSvg() svg->setSize(sourceRect.size().toSize()); svg->setViewBox(sourceRect); - if(!painter->begin(svg.get())) + if (!painter->begin(svg.get())) { qWarning() << "PrintWorker::printSvg(): cannot begin QPainter"; QString fileErr; bool writable = testFileIsWriteable(fileName, fileErr); QString msg; - if(!writable) + if (!writable) { msg = PrintWizard::tr("SVG Error: cannot open output file.\n" - "Path: \"%1\"\n" - "Error: %2").arg(fileName, fileErr); + "Path: \"%1\"\n" + "Error: %2") + .arg(fileName, fileErr); } else { msg = PrintWizard::tr("SVG Error: generic error."); } - //Send error and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressError, - msg), true); + // Send error and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressError, msg), true); return false; } @@ -439,47 +440,48 @@ bool PrintWorker::printPdf() { std::unique_ptr writer; - auto beginPaint = [this, &writer](QPainter *painter, - const QString& title, const QRectF& sourceRect, - const QString& type, int progressiveNum) -> bool + auto beginPaint = [this, &writer](QPainter *painter, const QString &title, + const QRectF &sourceRect, const QString &type, + int progressiveNum) -> bool { QString fileName = printOpt.filePath; - if(printOpt.useOneFileForEachScene) + if (printOpt.useOneFileForEachScene) { - //File path is the base directory, build file name - fileName = Print::getFileName(printOpt.filePath, printOpt.fileNamePattern, QLatin1String(".pdf"), - title, type, progressiveNum); + // File path is the base directory, build file name + fileName = Print::getFileName(printOpt.filePath, printOpt.fileNamePattern, + QLatin1String(".pdf"), title, type, progressiveNum); } - if(printOpt.useOneFileForEachScene || progressiveNum == 0) + if (printOpt.useOneFileForEachScene || progressiveNum == 0) { - //First page of new scene, create a new PDF + // First page of new scene, create a new PDF writer.reset(new QPdfWriter(fileName)); writer->setCreator(AppDisplayName); writer->setTitle(title); - //If page layout is need set it before begin painting - //When printing each scene on single page we do not set a layout here - if(!printOpt.printSceneInOnePage) + // If page layout is need set it before begin painting + // When printing each scene on single page we do not set a layout here + if (!printOpt.printSceneInOnePage) writer->setPageLayout(m_printer->pageLayout()); qDebug() << "LAYOUT:" << writer->pageLayout(); } - //If custom page is needed set it before begin painting or adding page - if(printOpt.printSceneInOnePage) + // If custom page is needed set it before begin painting or adding page + if (printOpt.printSceneInOnePage) { - //Calculate custom page size (inverse scale factor: Pixel -> Points) - QSizeF newSize = sourceRect.size() * Print::PrinterDefaultResolution / writer->resolution(); + // Calculate custom page size (inverse scale factor: Pixel -> Points) + QSizeF newSize = + sourceRect.size() * Print::PrinterDefaultResolution / writer->resolution(); QPageSize ps(newSize, QPageSize::Point); writer->setPageSize(ps); writer->setPageMargins(QMarginsF()); } - if(printOpt.useOneFileForEachScene || progressiveNum == 0) + if (printOpt.useOneFileForEachScene || progressiveNum == 0) { - //First page of new scene, begin painting - if(!painter->begin(writer.get())) + // First page of new scene, begin painting + if (!painter->begin(writer.get())) { qWarning() << "PrintWorker::printPdf(): cannot begin QPainter"; @@ -487,88 +489,86 @@ bool PrintWorker::printPdf() bool writable = testFileIsWriteable(fileName, fileErr); QString msg; - if(!writable) + if (!writable) { msg = PrintWizard::tr("PDF Error: cannot open output file.\n" "Path: \"%1\"\n" - "Error: %2").arg(fileName, fileErr); + "Error: %2") + .arg(fileName, fileErr); } else { msg = PrintWizard::tr("PDF Error: generic error."); } - //Send error and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressError, - msg), true); + // Send error and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressError, msg), + true); return false; } } else { - //New scene on same file, add page - if(!writer->newPage()) + // New scene on same file, add page + if (!writer->newPage()) { qWarning() << "PrintWorker::printPdf(): cannot add page"; return false; } } - if(printOpt.printSceneInOnePage) + if (printOpt.printSceneInOnePage) { - //Scale painter to fix possible custom page size problems - int wt = writer->width(); - int ht = writer->height(); + // Scale painter to fix possible custom page size problems + int wt = writer->width(); + int ht = writer->height(); const double scaleX = wt / sourceRect.width(); const double scaleY = ht / sourceRect.height(); - const double scale = qMin(scaleX, scaleY); + const double scale = qMin(scaleX, scaleY); painter->scale(scale, scale); } return true; }; - if(printOpt.printSceneInOnePage) + if (printOpt.printSceneInOnePage) return printInternal(beginPaint, printOpt.useOneFileForEachScene); return printInternalPaged(beginPaint, printOpt.useOneFileForEachScene); } bool PrintWorker::printPaged() { - auto beginPaint = [this](QPainter *painter, - const QString& title, const QRectF& sourceRect, - const QString& type, int progressiveNum) -> bool + auto beginPaint = [this](QPainter *painter, const QString &title, const QRectF &sourceRect, + const QString &type, int progressiveNum) -> bool { bool success = true; QString errMsg; - if(progressiveNum == 0) + if (progressiveNum == 0) { - //First page - if(!painter->begin(m_printer)) + // First page + if (!painter->begin(m_printer)) { qWarning() << "PrintWorker::printPaged(): cannot begin QPainter"; - errMsg = PrintWizard::tr("Cannot begin painting"); + errMsg = PrintWizard::tr("Cannot begin painting"); success = false; } } else { - if(!m_printer->newPage()) + if (!m_printer->newPage()) { qWarning() << "PrintWorker::printPaged(): cannot add new page"; - errMsg = PrintWizard::tr("Cannot create new page"); + errMsg = PrintWizard::tr("Cannot create new page"); success = false; } } - if(!success) + if (!success) { - //Send error and quit - sendEvent(new PrintProgressEvent(this, - PrintProgressEvent::ProgressError, - errMsg), true); + // Send error and quit + sendEvent(new PrintProgressEvent(this, PrintProgressEvent::ProgressError, errMsg), + true); return false; } diff --git a/src/printing/helper/model/printworker.h b/src/printing/helper/model/printworker.h index fc2ae6a..f257855 100644 --- a/src/printing/helper/model/printworker.h +++ b/src/printing/helper/model/printworker.h @@ -43,14 +43,14 @@ class PrintProgressEvent : public QEvent public: enum { - ProgressError = -1, + ProgressError = -1, ProgressAbortedByUser = -2, - ProgressMaxFinished = -3 + ProgressMaxFinished = -3 }; static constexpr Type _Type = Type(CustomEvents::PrintProgress); - PrintProgressEvent(QRunnable *self, int pr, const QString& descrOrErr); + PrintProgressEvent(QRunnable *self, int pr, const QString &descrOrErr); public: QRunnable *task; @@ -58,7 +58,6 @@ public: QString descriptionOrError; }; - class PrintWorker : public IQuittableTask { public: @@ -67,15 +66,18 @@ public: void setPrinter(QPrinter *printer); - inline Print::PrintBasicOptions getPrintOpt() const { return printOpt; }; + inline Print::PrintBasicOptions getPrintOpt() const + { + return printOpt; + }; void setPrintOpt(const Print::PrintBasicOptions &newPrintOpt); void setCollection(IGraphSceneCollection *newCollection); int getMaxProgress() const; - void setScenePageLay(const Print::PageLayoutOpt& pageLay); + void setScenePageLay(const Print::PageLayoutOpt &pageLay); - //IQuittableTask + // IQuittableTask void run() override; private: @@ -84,18 +86,18 @@ private: bool printPaged(); private: - typedef std::function BeginPaintFunc; + typedef std::function + BeginPaintFunc; bool printInternal(BeginPaintFunc func, bool endPaintingEveryPage); bool printInternalPaged(BeginPaintFunc func, bool endPaintingEveryPage); public: - //For each scene, count 10 steps + // For each scene, count 10 steps static constexpr int ProgressStepsForScene = 10; - bool sendProgressOrAbort(int progress, const QString& msg); + bool sendProgressOrAbort(int progress, const QString &msg); private: QPrinter *m_printer; diff --git a/src/printing/helper/model/printworkerhandler.cpp b/src/printing/helper/model/printworkerhandler.cpp index 6323ea4..c9aee86 100644 --- a/src/printing/helper/model/printworkerhandler.cpp +++ b/src/printing/helper/model/printworkerhandler.cpp @@ -28,7 +28,6 @@ PrintWorkerHandler::PrintWorkerHandler(sqlite3pp::database &db, QObject *parent) printTask(nullptr), isStoppingTask(false) { - } void PrintWorkerHandler::setOptions(const Print::PrintBasicOptions &opt, QPrinter *printer) @@ -39,35 +38,35 @@ void PrintWorkerHandler::setOptions(const Print::PrintBasicOptions &opt, QPrinte bool PrintWorkerHandler::event(QEvent *e) { - if(e->type() == PrintProgressEvent::_Type) + if (e->type() == PrintProgressEvent::_Type) { PrintProgressEvent *ev = static_cast(e); ev->setAccepted(true); - if(ev->task == printTask) + if (ev->task == printTask) { - if(ev->progress < 0) + if (ev->progress < 0) { - //Task finished, delete it + // Task finished, delete it delete printTask; printTask = nullptr; } QString description; - if(ev->progress == PrintProgressEvent::ProgressError) + if (ev->progress == PrintProgressEvent::ProgressError) description = tr("Error"); - else if(ev->progress == PrintProgressEvent::ProgressAbortedByUser) + else if (ev->progress == PrintProgressEvent::ProgressAbortedByUser) description = tr("Canceled"); - else if(ev->progress == PrintProgressEvent::ProgressMaxFinished) + else if (ev->progress == PrintProgressEvent::ProgressMaxFinished) description = tr("Done!"); else description = tr("Printing %1...").arg(ev->descriptionOrError); emit progressChanged(ev->progress, description); - if(ev->progress < 0) + if (ev->progress < 0) { - //Consider Abort succesful, on error send error message + // Consider Abort succesful, on error send error message bool success = ev->progress != PrintProgressEvent::ProgressError; emit progressFinished(success, success ? description : ev->descriptionOrError); } @@ -93,14 +92,14 @@ void PrintWorkerHandler::startPrintTask(QPrinter *printer, IGraphSceneCollection QThreadPool::globalInstance()->start(printTask); - //Start progress + // Start progress emit progressMaxChanged(printTask->getMaxProgress()); emit progressChanged(0, tr("Starting...")); } void PrintWorkerHandler::abortPrintTask() { - if(printTask) + if (printTask) { printTask->stop(); printTask->cleanup(); @@ -110,13 +109,13 @@ void PrintWorkerHandler::abortPrintTask() void PrintWorkerHandler::stopTaskGracefully() { - if(printTask) + if (printTask) { - //If printing was already started, stop it. + // If printing was already started, stop it. printTask->stop(); - //Set this flag to wait a bit before print task is really stopped - //This also prevents asking user to Abort a second time + // Set this flag to wait a bit before print task is really stopped + // This also prevents asking user to Abort a second time isStoppingTask = true; emit progressChanged(0, tr("Aborting...")); diff --git a/src/printing/helper/model/printworkerhandler.h b/src/printing/helper/model/printworkerhandler.h index 5839cde..4913597 100644 --- a/src/printing/helper/model/printworkerhandler.h +++ b/src/printing/helper/model/printworkerhandler.h @@ -38,21 +38,36 @@ class PrintWorkerHandler : public QObject public: explicit PrintWorkerHandler(sqlite3pp::database &db, QObject *parent = nullptr); - inline Print::PrintBasicOptions getOptions() const { return printOpt; } - void setOptions(const Print::PrintBasicOptions& opt, QPrinter *printer); + inline Print::PrintBasicOptions getOptions() const + { + return printOpt; + } + void setOptions(const Print::PrintBasicOptions &opt, QPrinter *printer); - inline Print::PageLayoutOpt getScenePageLay() const { return scenePageLay; } - inline void setScenePageLay(const Print::PageLayoutOpt& lay) { scenePageLay = lay; } + inline Print::PageLayoutOpt getScenePageLay() const + { + return scenePageLay; + } + inline void setScenePageLay(const Print::PageLayoutOpt &lay) + { + scenePageLay = lay; + } bool event(QEvent *e) override; - inline bool taskIsRunning() const { return printTask != nullptr; } - inline bool waitingForTaskToStop() const { return isStoppingTask; } + inline bool taskIsRunning() const + { + return printTask != nullptr; + } + inline bool waitingForTaskToStop() const + { + return isStoppingTask; + } signals: void progressMaxChanged(int max); - void progressChanged(int val, const QString& msg); - void progressFinished(bool success, const QString& msg); + void progressChanged(int val, const QString &msg); + void progressFinished(bool success, const QString &msg); public: void startPrintTask(QPrinter *printer, IGraphSceneCollection *collection); diff --git a/src/printing/helper/view/custompagesetupdlg.cpp b/src/printing/helper/view/custompagesetupdlg.cpp index 7e191d8..5f765d8 100644 --- a/src/printing/helper/view/custompagesetupdlg.cpp +++ b/src/printing/helper/view/custompagesetupdlg.cpp @@ -32,22 +32,22 @@ CustomPageSetupDlg::CustomPageSetupDlg(QWidget *parent) : m_pageSize(QPageSize::A4), m_pageOrient(QPageLayout::Portrait) { - QVBoxLayout *mainLay = new QVBoxLayout(this); + QVBoxLayout *mainLay = new QVBoxLayout(this); QGroupBox *pageSizeBox = new QGroupBox(tr("Page Size")); - QVBoxLayout *lay1 = new QVBoxLayout(pageSizeBox); + QVBoxLayout *lay1 = new QVBoxLayout(pageSizeBox); - pageSizeCombo = new QComboBox; + pageSizeCombo = new QComboBox; - PageSizeModel *m = new PageSizeModel(this); + PageSizeModel *m = new PageSizeModel(this); pageSizeCombo->setModel(m); lay1->addWidget(pageSizeCombo); QGroupBox *pageOrientBox = new QGroupBox(tr("Page Orientation")); - QVBoxLayout *lay2 = new QVBoxLayout(pageOrientBox); + QVBoxLayout *lay2 = new QVBoxLayout(pageOrientBox); - portraitRadioBut = new QRadioButton(tr("Portrait")); + portraitRadioBut = new QRadioButton(tr("Portrait")); lay2->addWidget(portraitRadioBut); landscapeRadioBut = new QRadioButton(tr("Landscape")); @@ -56,17 +56,18 @@ CustomPageSetupDlg::CustomPageSetupDlg(QWidget *parent) : mainLay->addWidget(pageSizeBox); mainLay->addWidget(pageOrientBox); - QDialogButtonBox *buttBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + QDialogButtonBox *buttBox = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); mainLay->addWidget(buttBox); - //Default to A4 Portrait + // Default to A4 Portrait portraitRadioBut->setChecked(true); pageSizeCombo->setCurrentIndex(int(m_pageSize.id())); - connect(pageSizeCombo, qOverload(&QComboBox::activated), - this, &CustomPageSetupDlg::onPageComboActivated); - connect(portraitRadioBut, &QRadioButton::toggled, - this, &CustomPageSetupDlg::onPagePortraitToggled); + connect(pageSizeCombo, qOverload(&QComboBox::activated), this, + &CustomPageSetupDlg::onPageComboActivated); + connect(portraitRadioBut, &QRadioButton::toggled, this, + &CustomPageSetupDlg::onPagePortraitToggled); connect(buttBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttBox, &QDialogButtonBox::rejected, this, &QDialog::reject); @@ -74,21 +75,21 @@ CustomPageSetupDlg::CustomPageSetupDlg(QWidget *parent) : void CustomPageSetupDlg::setPageSize(const QPageSize &pageSz) { - if(m_pageSize == pageSz) + if (m_pageSize == pageSz) return; m_pageSize = pageSz; - int idx = int(m_pageSize.id()); + int idx = int(m_pageSize.id()); pageSizeCombo->setCurrentIndex(idx); } void CustomPageSetupDlg::setPageOrient(QPageLayout::Orientation orient) { - if(m_pageOrient == orient) + if (m_pageOrient == orient) return; m_pageOrient = orient; - if(m_pageOrient == QPageLayout::Portrait) + if (m_pageOrient == QPageLayout::Portrait) portraitRadioBut->setChecked(true); else landscapeRadioBut->setChecked(true); diff --git a/src/printing/helper/view/custompagesetupdlg.h b/src/printing/helper/view/custompagesetupdlg.h index 11f2219..eab2d2a 100644 --- a/src/printing/helper/view/custompagesetupdlg.h +++ b/src/printing/helper/view/custompagesetupdlg.h @@ -41,11 +41,17 @@ class CustomPageSetupDlg : public QDialog public: explicit CustomPageSetupDlg(QWidget *parent = nullptr); - void setPageSize(const QPageSize& pageSz); - inline QPageSize getPageSize() const { return m_pageSize; } + void setPageSize(const QPageSize &pageSz); + inline QPageSize getPageSize() const + { + return m_pageSize; + } void setPageOrient(QPageLayout::Orientation orient); - inline QPageLayout::Orientation getPageOrient() const { return m_pageOrient; } + inline QPageLayout::Orientation getPageOrient() const + { + return m_pageOrient; + } private slots: void onPageComboActivated(int idx); diff --git a/src/printing/helper/view/printeroptionswidget.cpp b/src/printing/helper/view/printeroptionswidget.cpp index aef8a5f..d324329 100644 --- a/src/printing/helper/view/printeroptionswidget.cpp +++ b/src/printing/helper/view/printeroptionswidget.cpp @@ -58,16 +58,16 @@ PrinterOptionsWidget::PrinterOptionsWidget(QWidget *parent) : outputTypeCombo = new QComboBox; QStringList items; items.reserve(int(Print::OutputType::NTypes)); - for(int i = 0; i < int(Print::OutputType::NTypes); i++) + for (int i = 0; i < int(Print::OutputType::NTypes); i++) items.append(Print::getOutputTypeName(Print::OutputType(i))); outputTypeCombo->addItems(items); outputTypeCombo->setCurrentIndex(int(Print::OutputType::Pdf)); - connect(outputTypeCombo, qOverload(&QComboBox::activated), - this, &PrinterOptionsWidget::updateOutputType); + connect(outputTypeCombo, qOverload(&QComboBox::activated), this, + &PrinterOptionsWidget::updateOutputType); QLabel *typeLabel = new QLabel(tr("Output Type:")); - QGridLayout *lay = new QGridLayout(this); + QGridLayout *lay = new QGridLayout(this); lay->addWidget(typeLabel, 0, 0); lay->addWidget(outputTypeCombo, 0, 1); lay->addWidget(fileBox, 1, 0, 1, 2); @@ -83,7 +83,7 @@ void PrinterOptionsWidget::setOptions(const Print::PrintBasicOptions &printOpt) outputTypeCombo->setCurrentIndex(int(printOpt.outputType)); updateOutputType(); - if(printOpt.filePath.isEmpty()) + if (printOpt.filePath.isEmpty()) { pathEdit->setText(RecentDirStore::getDir(recentDirKey, RecentDirStore::Documents)); } @@ -92,33 +92,33 @@ void PrinterOptionsWidget::setOptions(const Print::PrintBasicOptions &printOpt) Print::PrintBasicOptions PrinterOptionsWidget::getOptions() const { Print::PrintBasicOptions printOpt; - printOpt.filePath = pathEdit->text(); - printOpt.fileNamePattern = patternEdit->text(); + printOpt.filePath = pathEdit->text(); + printOpt.fileNamePattern = patternEdit->text(); printOpt.useOneFileForEachScene = differentFilesCheckBox->isChecked(); - printOpt.printSceneInOnePage = sceneInOnePageCheckBox->isChecked(); - printOpt.outputType = Print::OutputType(outputTypeCombo->currentIndex()); + printOpt.printSceneInOnePage = sceneInOnePageCheckBox->isChecked(); + printOpt.outputType = Print::OutputType(outputTypeCombo->currentIndex()); return printOpt; } bool PrinterOptionsWidget::validateOptions() { - if(outputTypeCombo->currentIndex() != int(Print::OutputType::Native)) + if (outputTypeCombo->currentIndex() != int(Print::OutputType::Native)) { - //Check files + // Check files const QString path = pathEdit->text(); - if(path.isEmpty()) + if (path.isEmpty()) { return false; } const QString pattern = patternEdit->text(); - if(pattern.isEmpty() && differentFilesCheckBox->isChecked()) + if (pattern.isEmpty() && differentFilesCheckBox->isChecked()) { return false; } } - if(!pathEdit->text().isEmpty()) + if (!pathEdit->text().isEmpty()) { RecentDirStore::setPath(recentDirKey, pathEdit->text()); } @@ -128,11 +128,11 @@ bool PrinterOptionsWidget::validateOptions() bool PrinterOptionsWidget::isComplete() const { - if(outputTypeCombo->currentIndex() == int(Print::OutputType::Native)) - return true; //No need to check files + if (outputTypeCombo->currentIndex() == int(Print::OutputType::Native)) + return true; // No need to check files bool complete = !pathEdit->text().isEmpty(); - if(complete && differentFilesCheckBox->isChecked()) + if (complete && differentFilesCheckBox->isChecked()) complete = !patternEdit->text().isEmpty(); return complete; } @@ -171,33 +171,31 @@ void PrinterOptionsWidget::onChooseFile() { QString path = pathEdit->text(); - if(!path.isEmpty()) + if (!path.isEmpty()) { - //Check if file or dir is valid + // Check if file or dir is valid QFileInfo info(path); - if(differentFilesCheckBox->isChecked()) + if (differentFilesCheckBox->isChecked()) { - if(!info.isDir() || !info.exists()) + if (!info.isDir() || !info.exists()) path.clear(); } else { - if(info.isFile() && !info.absoluteDir().exists()) + if (info.isFile() && !info.absoluteDir().exists()) path.clear(); } } - //Default to Documents folder - if(path.isEmpty()) + // Default to Documents folder + if (path.isEmpty()) path = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); - if(differentFilesCheckBox->isChecked()) + if (differentFilesCheckBox->isChecked()) { - path = QFileDialog::getExistingDirectory(this, - tr("Choose Folder"), - path); + path = QFileDialog::getExistingDirectory(this, tr("Choose Folder"), path); - if(path.isEmpty()) //User canceled dialog + if (path.isEmpty()) // User canceled dialog return; } else @@ -207,25 +205,22 @@ void PrinterOptionsWidget::onChooseFile() switch (Print::OutputType(outputTypeCombo->currentIndex())) { case Print::OutputType::Pdf: - ext = QStringLiteral(".pdf"); + ext = QStringLiteral(".pdf"); fullName = FileFormats::tr(FileFormats::pdfFile); break; case Print::OutputType::Svg: - ext = QStringLiteral(".svg"); + ext = QStringLiteral(".svg"); fullName = FileFormats::tr(FileFormats::svgFile); break; default: break; } - path = QFileDialog::getSaveFileName(this, - tr("Choose file"), - path, - fullName); - if(path.isEmpty()) //User canceled dialog + path = QFileDialog::getSaveFileName(this, tr("Choose file"), path, fullName); + if (path.isEmpty()) // User canceled dialog return; - if(!path.endsWith(ext)) + if (!path.endsWith(ext)) path.append(ext); } @@ -234,14 +229,14 @@ void PrinterOptionsWidget::onChooseFile() void PrinterOptionsWidget::updateDifferentFiles() { - //Pattern is applicable only if printing multiple files + // Pattern is applicable only if printing multiple files patternEdit->setEnabled(differentFilesCheckBox->isChecked()); - //If pathEdit contains a file but user checks 'Different Files' - //We go up to file directory and use that + // If pathEdit contains a file but user checks 'Different Files' + // We go up to file directory and use that QString path = pathEdit->text(); - if(path.isEmpty()) + if (path.isEmpty()) return; QString ext; @@ -257,18 +252,18 @@ void PrinterOptionsWidget::updateDifferentFiles() break; } - if(differentFilesCheckBox->isChecked()) + if (differentFilesCheckBox->isChecked()) { - if(path.endsWith(ext)) + if (path.endsWith(ext)) { path = path.left(path.lastIndexOf('/')); } } else { - if(!path.endsWith(ext)) + if (!path.endsWith(ext)) { - if(path.endsWith('/')) + if (path.endsWith('/')) path.append(QStringLiteral("file%1").arg(ext)); else path.append(QStringLiteral("/file%1").arg(ext)); @@ -280,47 +275,47 @@ void PrinterOptionsWidget::updateDifferentFiles() void PrinterOptionsWidget::onOpenPageSetup() { - if(!m_printer) + if (!m_printer) return; QPageLayout pageLay; - if(m_printer->outputFormat() == QPrinter::NativeFormat) + if (m_printer->outputFormat() == QPrinter::NativeFormat) { - //Native dialog for native printer + // Native dialog for native printer OwningQPointer dlg = new QPrintDialog(m_printer, this); dlg->exec(); - //Get after dialog finished + // Get after dialog finished pageLay = m_printer->pageLayout(); - //Fix possible wrong page size - QPageSize pageSz = pageLay.pageSize(); + // Fix possible wrong page size + QPageSize pageSz = pageLay.pageSize(); QPageLayout::Orientation orient = pageLay.orientation(); - pageSz = PrintHelper::fixPageSize(pageSz, orient); + pageSz = PrintHelper::fixPageSize(pageSz, orient); pageLay.setPageSize(pageSz); pageLay.setOrientation(orient); } else { - //Custom dialog for PDF printer + // Custom dialog for PDF printer OwningQPointer dlg = new CustomPageSetupDlg(this); - pageLay = m_printer->pageLayout(); + pageLay = m_printer->pageLayout(); dlg->setPageSize(pageLay.pageSize()); dlg->setPageOrient(pageLay.orientation()); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; - //Update layout page size + // Update layout page size pageLay.setPageSize(dlg->getPageSize()); pageLay.setOrientation(dlg->getPageOrient()); } - //Update printer layout + // Update printer layout m_printer->setPageLayout(pageLay); - //Apply page size to scene layout + // Apply page size to scene layout PrintHelper::applyPageSize(pageLay.pageSize(), pageLay.orientation(), scenePageLay); } @@ -334,12 +329,12 @@ void PrinterOptionsWidget::onShowPreviewDlg() dlg->exec(); - if(!dlg) + if (!dlg) return; - if(m_printer && m_printer->outputFormat() == QPrinter::PdfFormat) + if (m_printer && m_printer->outputFormat() == QPrinter::PdfFormat) { - //Update page layout + // Update page layout m_printer->setPageLayout(dlg->getPrinterPageLay()); } @@ -353,15 +348,16 @@ void PrinterOptionsWidget::updateOutputType() fileBox->setEnabled(type != Print::OutputType::Native); pageLayoutBox->setEnabled(type != Print::OutputType::Svg); - pageSetupDlgBut->setText(type == Print::OutputType::Native ? tr("Printer Options") : tr("Page Setup")); + pageSetupDlgBut->setText(type == Print::OutputType::Native ? tr("Printer Options") + : tr("Page Setup")); - if(type == Print::OutputType::Svg) + if (type == Print::OutputType::Svg) { - //Svg can only be printed in multiple files + // Svg can only be printed in multiple files differentFilesCheckBox->setChecked(true); differentFilesCheckBox->setEnabled(false); - //Svg will always be on single page + // Svg will always be on single page sceneInOnePageCheckBox->setChecked(true); sceneInOnePageCheckBox->setEnabled(false); } @@ -369,8 +365,8 @@ void PrinterOptionsWidget::updateOutputType() { differentFilesCheckBox->setEnabled(true); - //Printers always need to split in multiple pages - if(type == Print::OutputType::Native) + // Printers always need to split in multiple pages + if (type == Print::OutputType::Native) { sceneInOnePageCheckBox->setChecked(false); sceneInOnePageCheckBox->setEnabled(false); @@ -381,38 +377,40 @@ void PrinterOptionsWidget::updateOutputType() } } - if(m_printer) + if (m_printer) { - m_printer->setOutputFormat(type == Print::OutputType::Native ? QPrinter::NativeFormat : QPrinter::PdfFormat); + m_printer->setOutputFormat(type == Print::OutputType::Native ? QPrinter::NativeFormat + : QPrinter::PdfFormat); } - //Check if new otptions are valid + // Check if new otptions are valid emit completeChanged(); } void PrinterOptionsWidget::createFilesBox() { - fileBox = new QGroupBox(tr("Files")); + fileBox = new QGroupBox(tr("Files")); differentFilesCheckBox = new QCheckBox(tr("Different Files")); - connect(differentFilesCheckBox, &QCheckBox::toggled, - this, &PrinterOptionsWidget::updateDifferentFiles); + connect(differentFilesCheckBox, &QCheckBox::toggled, this, + &PrinterOptionsWidget::updateDifferentFiles); sceneInOnePageCheckBox = new QCheckBox(tr("Whole scene in one page")); - sceneInOnePageCheckBox->setToolTip(tr("This will print a custom page size to fit everything in one page.\n" - "Not available on native printer.")); + sceneInOnePageCheckBox->setToolTip( + tr("This will print a custom page size to fit everything in one page.\n" + "Not available on native printer.")); pathEdit = new QLineEdit; connect(pathEdit, &QLineEdit::textChanged, this, &PrinterOptionsWidget::completeChanged); patternEdit = new QLineEdit; connect(patternEdit, &QLineEdit::textChanged, this, &PrinterOptionsWidget::completeChanged); - patternEdit->setEnabled(false); //Initially different files is not checked + patternEdit->setEnabled(false); // Initially different files is not checked fileBut = new QPushButton(tr("Choose")); connect(fileBut, &QPushButton::clicked, this, &PrinterOptionsWidget::onChooseFile); - QLabel *label = new QLabel(tr("File(s)")); + QLabel *label = new QLabel(tr("File(s)")); QGridLayout *l = new QGridLayout; l->addWidget(differentFilesCheckBox, 0, 0, 1, 2); @@ -433,9 +431,9 @@ void PrinterOptionsWidget::createFilesBox() void PrinterOptionsWidget::createPageLayoutBox() { - pageLayoutBox = new QGroupBox(tr("Page Layout")); + pageLayoutBox = new QGroupBox(tr("Page Layout")); - pageSetupDlgBut = new QPushButton; //Text is set in updateOutputType() + pageSetupDlgBut = new QPushButton; // Text is set in updateOutputType() connect(pageSetupDlgBut, &QPushButton::clicked, this, &PrinterOptionsWidget::onOpenPageSetup); previewDlgBut = new QPushButton(tr("Preview")); diff --git a/src/printing/helper/view/sceneprintpreviewdlg.cpp b/src/printing/helper/view/sceneprintpreviewdlg.cpp index 8ac3a59..4d9f271 100644 --- a/src/printing/helper/view/sceneprintpreviewdlg.cpp +++ b/src/printing/helper/view/sceneprintpreviewdlg.cpp @@ -40,7 +40,7 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : QDialog(parent), m_printer(nullptr) { - QVBoxLayout *lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); QToolBar *toolBar = new QToolBar; lay->addWidget(toolBar); @@ -52,8 +52,7 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : zoomSlider->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred); zoomSlider->setValue(100); zoomSlider->setToolTip(tr("Double click to reset zoom")); - connect(zoomSlider, &QSlider::valueChanged, this, - &ScenePrintPreviewDlg::updateZoomLevel); + connect(zoomSlider, &QSlider::valueChanged, this, &ScenePrintPreviewDlg::updateZoomLevel); zoomSlider->installEventFilter(this); QAction *zoomAct = toolBar->addWidget(zoomSlider); zoomAct->setText(tr("Zoom:")); @@ -63,8 +62,8 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : zoomSpinBox->setValue(100); zoomSpinBox->setSuffix(QChar('%')); zoomSpinBox->setToolTip(tr("Zoom")); - connect(zoomSpinBox, qOverload(&QSpinBox::valueChanged), - this, &ScenePrintPreviewDlg::updateZoomLevel); + connect(zoomSpinBox, qOverload(&QSpinBox::valueChanged), this, + &ScenePrintPreviewDlg::updateZoomLevel); toolBar->addWidget(zoomSpinBox); toolBar->addSeparator(); @@ -74,18 +73,18 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : sceneScaleSpinBox->setValue(100); sceneScaleSpinBox->setSuffix(QChar('%')); sceneScaleSpinBox->setToolTip(tr("Source scale factor")); - connect(sceneScaleSpinBox, qOverload(&QDoubleSpinBox::valueChanged), - this, &ScenePrintPreviewDlg::onScaleChanged); + connect(sceneScaleSpinBox, qOverload(&QDoubleSpinBox::valueChanged), this, + &ScenePrintPreviewDlg::onScaleChanged); QAction *scaleAct = toolBar->addWidget(sceneScaleSpinBox); scaleAct->setText(tr("Scale:")); marginSpinBox = new QDoubleSpinBox; marginSpinBox->setRange(0, 200); marginSpinBox->setValue(20); - marginSpinBox->setSuffix(QLatin1String(" pt")); //Points + marginSpinBox->setSuffix(QLatin1String(" pt")); // Points marginSpinBox->setToolTip(tr("Margins")); - connect(marginSpinBox, qOverload(&QDoubleSpinBox::valueChanged), - this, &ScenePrintPreviewDlg::setMarginsWidth); + connect(marginSpinBox, qOverload(&QDoubleSpinBox::valueChanged), this, + &ScenePrintPreviewDlg::setMarginsWidth); QAction *marginsAct = toolBar->addWidget(marginSpinBox); marginsAct->setText(tr("Margins:")); @@ -101,10 +100,10 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : previewScene = new PrintPreviewSceneProxy(this); graphView->setScene(previewScene); - connect(previewScene, &PrintPreviewSceneProxy::pageCountChanged, - this, &ScenePrintPreviewDlg::updatePageCount); + connect(previewScene, &PrintPreviewSceneProxy::pageCountChanged, this, + &ScenePrintPreviewDlg::updatePageCount); - //Default to A4 Portraint page + // Default to A4 Portraint page printerPageLay.setPageSize(QPageSize(QPageSize::A4)); printerPageLay.setOrientation(QPageLayout::Portrait); updateModelPageSize(); @@ -114,9 +113,9 @@ ScenePrintPreviewDlg::ScenePrintPreviewDlg(QWidget *parent) : bool ScenePrintPreviewDlg::eventFilter(QObject *watched, QEvent *ev) { - 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); } @@ -131,7 +130,7 @@ void ScenePrintPreviewDlg::setSourceScene(IGraphScene *sourceScene) void ScenePrintPreviewDlg::setSceneScale(double scaleFactor) { Print::PageLayoutOpt pageLay = previewScene->getPageLay(); - if(qFuzzyCompare(pageLay.sourceScaleFactor, scaleFactor)) + if (qFuzzyCompare(pageLay.sourceScaleFactor, scaleFactor)) return; sceneScaleSpinBox->setValue(scaleFactor * 100); @@ -148,9 +147,9 @@ void ScenePrintPreviewDlg::setPrinter(QPrinter *newPrinter) { m_printer = newPrinter; - if(m_printer) + if (m_printer) { - //Update page rect + // Update page rect QPageLayout printerLay = m_printer->pageLayout(); printerLay.setMargins(QMarginsF()); setPrinterPageLay(printerLay); @@ -160,7 +159,7 @@ void ScenePrintPreviewDlg::setPrinter(QPrinter *newPrinter) void ScenePrintPreviewDlg::setPrinterPageLay(const QPageLayout &pageLay) { printerPageLay = pageLay; - if(m_printer) + if (m_printer) m_printer->setPageLayout(printerPageLay); updateModelPageSize(); } @@ -180,10 +179,10 @@ void ScenePrintPreviewDlg::setScenePageLay(const Print::PageLayoutOpt &newSceneP void ScenePrintPreviewDlg::updateZoomLevel(int zoom) { - if(graphView->getZoomLevel() == zoom) + if (graphView->getZoomLevel() == zoom) return; - //Set for view first because it checks minimum and mazimum values + // Set for view first because it checks minimum and mazimum values graphView->setZoomLevel(zoom); zoom = graphView->getZoomLevel(); @@ -194,14 +193,14 @@ void ScenePrintPreviewDlg::updateZoomLevel(int zoom) void ScenePrintPreviewDlg::onScaleChanged(double zoom) { - //Convert from 0%-100% to 0-1 + // Convert from 0%-100% to 0-1 setSceneScale(zoom / 100); } void ScenePrintPreviewDlg::setMarginsWidth(double margins) { Print::PageLayoutOpt pageLay = previewScene->getPageLay(); - if(qFuzzyCompare(pageLay.marginWidthPoints, margins)) + if (qFuzzyCompare(pageLay.marginWidthPoints, margins)) return; marginSpinBox->setValue(margins); @@ -211,38 +210,38 @@ void ScenePrintPreviewDlg::setMarginsWidth(double margins) void ScenePrintPreviewDlg::showPageSetupDlg() { - if(m_printer && m_printer->outputFormat() == QPrinter::NativeFormat) + if (m_printer && m_printer->outputFormat() == QPrinter::NativeFormat) { - //For native printers use standard page dialog + // For native printers use standard page dialog OwningQPointer dlg = new QPageSetupDialog(m_printer, this); dlg->exec(); - //Fix possible wrong page size - QPageLayout pageLay = m_printer->pageLayout(); - QPageSize pageSz = pageLay.pageSize(); + // Fix possible wrong page size + QPageLayout pageLay = m_printer->pageLayout(); + QPageSize pageSz = pageLay.pageSize(); QPageLayout::Orientation orient = pageLay.orientation(); - pageSz = PrintHelper::fixPageSize(pageSz, orient); + pageSz = PrintHelper::fixPageSize(pageSz, orient); pageLay.setPageSize(pageSz); pageLay.setOrientation(orient); - pageLay.setMargins(QMarginsF()); //Reset margins + pageLay.setMargins(QMarginsF()); // Reset margins m_printer->setPageLayout(pageLay); - //Update page rect + // Update page rect setPrinterPageLay(m_printer->pageLayout()); } else { - //Show custom dialog + // Show custom dialog OwningQPointer dlg = new CustomPageSetupDlg(this); dlg->setPageSize(printerPageLay.pageSize()); dlg->setPageOrient(printerPageLay.orientation()); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; printerPageLay.setPageSize(dlg->getPageSize()); printerPageLay.setOrientation(dlg->getPageOrient()); - //Update page rect + // Update page rect setPrinterPageLay(printerPageLay); } } @@ -250,16 +249,18 @@ void ScenePrintPreviewDlg::showPageSetupDlg() void ScenePrintPreviewDlg::updatePageCount() { Print::PageLayoutOpt pageLay = previewScene->getPageLay(); - const int totalCount = pageLay.pageCountVert * pageLay.pageCountHoriz; + const int totalCount = pageLay.pageCountVert * pageLay.pageCountHoriz; pageCountLabel->setText(tr("Rows: %1, Cols: %2, Total Pages: %3") - .arg(pageLay.pageCountVert).arg(pageLay.pageCountHoriz).arg(totalCount)); + .arg(pageLay.pageCountVert) + .arg(pageLay.pageCountHoriz) + .arg(totalCount)); } void ScenePrintPreviewDlg::updateModelPageSize() { - Print::PageLayoutOpt pageLay = previewScene->getPageLay(); + Print::PageLayoutOpt pageLay = previewScene->getPageLay(); - QPageSize pageSize = printerPageLay.pageSize(); + QPageSize pageSize = printerPageLay.pageSize(); QPageLayout::Orientation pageOrient = printerPageLay.orientation(); PrintHelper::applyPageSize(pageSize, pageOrient, pageLay); diff --git a/src/printing/helper/view/sceneprintpreviewdlg.h b/src/printing/helper/view/sceneprintpreviewdlg.h index 558c8e7..b4a2e8d 100644 --- a/src/printing/helper/view/sceneprintpreviewdlg.h +++ b/src/printing/helper/view/sceneprintpreviewdlg.h @@ -57,8 +57,11 @@ public: QPrinter *printer() const; void setPrinter(QPrinter *newPrinter); - inline QPageLayout getPrinterPageLay() const { return printerPageLay; } - void setPrinterPageLay(const QPageLayout& pageLay); + inline QPageLayout getPrinterPageLay() const + { + return printerPageLay; + } + void setPrinterPageLay(const QPageLayout &pageLay); Print::PageLayoutOpt getScenePageLay() const; void setScenePageLay(const Print::PageLayoutOpt &newScenePageLay); diff --git a/src/printing/wizard/printoptionspage.cpp b/src/printing/wizard/printoptionspage.cpp index 135da2d..f5b1da4 100644 --- a/src/printing/wizard/printoptionspage.cpp +++ b/src/printing/wizard/printoptionspage.cpp @@ -26,39 +26,38 @@ #include "utils/scene/igraphscene.h" - PrintOptionsPage::PrintOptionsPage(PrintWizard *w, QWidget *parent) : - QWizardPage (parent), + QWizardPage(parent), mWizard(w), m_scene(nullptr) { QVBoxLayout *lay = new QVBoxLayout(this); - optionsWidget = new PrinterOptionsWidget; + optionsWidget = new PrinterOptionsWidget; lay->addWidget(optionsWidget); - connect(optionsWidget, &PrinterOptionsWidget::completeChanged, - this, &QWizardPage::completeChanged); + connect(optionsWidget, &PrinterOptionsWidget::completeChanged, this, + &QWizardPage::completeChanged); setTitle(tr("Print Options")); setCommitPage(true); - //Change 'Commit' to 'Print' so user understands better + // Change 'Commit' to 'Print' so user understands better setButtonText(QWizard::CommitButton, tr("Print")); } PrintOptionsPage::~PrintOptionsPage() { - //Reset scene + // Reset scene setScene(nullptr); } bool PrintOptionsPage::validatePage() { - if(!optionsWidget->validateOptions()) + if (!optionsWidget->validateOptions()) return false; - //Update options + // Update options mWizard->setPrintOpt(optionsWidget->getOptions()); mWizard->setScenePageLay(optionsWidget->getScenePageLay()); return true; @@ -79,7 +78,7 @@ void PrintOptionsPage::setupPage() void PrintOptionsPage::setScene(IGraphScene *scene) { - if(m_scene) + if (m_scene) delete m_scene; m_scene = scene; optionsWidget->setSourceScene(m_scene); diff --git a/src/printing/wizard/printwizard.cpp b/src/printing/wizard/printwizard.cpp index f6752b1..4a344c4 100644 --- a/src/printing/wizard/printwizard.cpp +++ b/src/printing/wizard/printwizard.cpp @@ -49,13 +49,13 @@ QString Print::getOutputTypeName(Print::OutputType type) return QString(); } -QString Print::getFileName(const QString& baseDir, const QString& pattern, const QString& extension, - const QString& name, const QString &type, int i) +QString Print::getFileName(const QString &baseDir, const QString &pattern, const QString &extension, + const QString &name, const QString &type, int i) { QString result = pattern; - if(result.contains(phNameUnderscore)) + if (result.contains(phNameUnderscore)) { - //Replace spaces with underscores + // Replace spaces with underscores QString nameUnderscores = name; nameUnderscores.replace(' ', '_'); result.replace(phNameUnderscore, nameUnderscores); @@ -65,7 +65,7 @@ QString Print::getFileName(const QString& baseDir, const QString& pattern, const result.replace(phType, type); result.replace(phProgressive, QString::number(i).rightJustified(2, '0')); - if(!baseDir.endsWith('/')) + if (!baseDir.endsWith('/')) result.prepend('/'); result.prepend(baseDir); @@ -74,26 +74,28 @@ QString Print::getFileName(const QString& baseDir, const QString& pattern, const return result; } -void Print::validatePrintOptions(Print::PrintBasicOptions& printOpt, QPrinter *printer) +void Print::validatePrintOptions(Print::PrintBasicOptions &printOpt, QPrinter *printer) { - if(printOpt.outputType == Print::OutputType::Svg) + if (printOpt.outputType == Print::OutputType::Svg) { - //Svg can only be printed in multiple files + // Svg can only be printed in multiple files printOpt.useOneFileForEachScene = true; - //Svg will always be on single page + // Svg will always be on single page printOpt.printSceneInOnePage = true; } - else if(printOpt.outputType == Print::OutputType::Native) + else if (printOpt.outputType == Print::OutputType::Native) { - //Printers always need to split in multiple pages + // Printers always need to split in multiple pages printOpt.printSceneInOnePage = false; } - if(printer) + if (printer) { - //Update printer output format - printer->setOutputFormat(printOpt.outputType == Print::OutputType::Native ? QPrinter::NativeFormat : QPrinter::PdfFormat); + // Update printer output format + printer->setOutputFormat(printOpt.outputType == Print::OutputType::Native + ? QPrinter::NativeFormat + : QPrinter::PdfFormat); } } @@ -104,7 +106,7 @@ bool Print::askUserToAbortPrinting(bool wasAlreadyStarted, QWidget *parent) msgBox->setWindowTitle(PrintWizard::tr("Abort Printing?")); QString msg; - if(wasAlreadyStarted) + if (wasAlreadyStarted) msg = PrintWizard::tr("Do you want to abort printing?\n" "Some items may have already be printed."); else @@ -112,15 +114,15 @@ bool Print::askUserToAbortPrinting(bool wasAlreadyStarted, QWidget *parent) msgBox->setText(msg); QPushButton *abortBut = msgBox->addButton(QMessageBox::Abort); - QPushButton *noBut = msgBox->addButton(QMessageBox::No); + QPushButton *noBut = msgBox->addButton(QMessageBox::No); msgBox->setDefaultButton(noBut); - msgBox->setEscapeButton(noBut); //Do not Abort if dialog is closed by Esc or X window button + msgBox->setEscapeButton(noBut); // Do not Abort if dialog is closed by Esc or X window button msgBox->exec(); bool abortClicked = msgBox && msgBox->clickedButton() == abortBut; return abortClicked; } -bool Print::askUserToTryAgain(const QString& errMsg, QWidget *parent) +bool Print::askUserToTryAgain(const QString &errMsg, QWidget *parent) { OwningQPointer msgBox = new QMessageBox(parent); msgBox->setIcon(QMessageBox::Warning); @@ -131,7 +133,7 @@ bool Print::askUserToTryAgain(const QString& errMsg, QWidget *parent) msgBox->setWindowTitle(PrintWizard::tr("Print Error")); msgBox->exec(); - if(!msgBox) + if (!msgBox) return false; bool shouldTryAgain = msgBox->clickedButton() == tryAgainBut; @@ -139,35 +141,36 @@ bool Print::askUserToTryAgain(const QString& errMsg, QWidget *parent) } PrintWizard::PrintWizard(sqlite3pp::database &db, QWidget *parent) : - QWizard (parent), + QWizard(parent), mDb(db), m_printer(nullptr) { printTaskHandler = new PrintWorkerHandler(mDb, this); - connect(printTaskHandler, &PrintWorkerHandler::progressMaxChanged, - this, &PrintWizard::progressMaxChanged); - connect(printTaskHandler, &PrintWorkerHandler::progressChanged, - this, &PrintWizard::progressChanged); - connect(printTaskHandler, &PrintWorkerHandler::progressFinished, - this, &PrintWizard::handleProgressFinished); + connect(printTaskHandler, &PrintWorkerHandler::progressMaxChanged, this, + &PrintWizard::progressMaxChanged); + connect(printTaskHandler, &PrintWorkerHandler::progressChanged, this, + &PrintWizard::progressChanged); + connect(printTaskHandler, &PrintWorkerHandler::progressFinished, this, + &PrintWizard::handleProgressFinished); m_printer = new QPrinter; m_printer->setOutputFormat(QPrinter::PdfFormat); - //Initialize to a default pattern + // Initialize to a default pattern Print::PrintBasicOptions printOpt; printOpt.fileNamePattern = Print::phType + QLatin1Char('_') + Print::phNameUnderscore; printTaskHandler->setOptions(printOpt, m_printer); - //Remove page margins + // Remove page margins QPageLayout printerPageLay = m_printer->pageLayout(); printerPageLay.setMode(QPageLayout::FullPageMode); printerPageLay.setMargins(QMarginsF()); m_printer->setPageLayout(printerPageLay); - //Apply page size to scene layout + // Apply page size to scene layout Print::PageLayoutOpt scenePageLay; - PrintHelper::applyPageSize(printerPageLay.pageSize(), printerPageLay.orientation(), scenePageLay); + PrintHelper::applyPageSize(printerPageLay.pageSize(), printerPageLay.orientation(), + scenePageLay); printTaskHandler->setScenePageLay(scenePageLay); selectionModel = new SceneSelectionModel(mDb, this); @@ -189,25 +192,25 @@ PrintWizard::~PrintWizard() bool PrintWizard::validateCurrentPage() { QWizardPage *curPage = currentPage(); - if(!curPage) + if (!curPage) return true; - if(!curPage->validatePage()) + if (!curPage->validatePage()) return false; - //NOTE: needed because when going back and then again forward - //initializePage() is not called again - //So we need to manually initialize again next page + // NOTE: needed because when going back and then again forward + // initializePage() is not called again + // So we need to manually initialize again next page int id = currentId(); - if(id == 0) + if (id == 0) { - //Setup PrintOptionsPage + // Setup PrintOptionsPage PrintOptionsPage *optionsPage = static_cast(page(1)); optionsPage->setupPage(); } - else if(id == 1) + else if (id == 1) { - //After PrintOptionsPage start task + // After PrintOptionsPage start task printTaskHandler->startPrintTask(m_printer, selectionModel); } @@ -222,7 +225,7 @@ QPrinter *PrintWizard::getPrinter() const void PrintWizard::setOutputType(Print::OutputType type) { Print::PrintBasicOptions printOpt = printTaskHandler->getOptions(); - printOpt.outputType = type; + printOpt.outputType = type; printTaskHandler->setOptions(printOpt, m_printer); } @@ -248,14 +251,14 @@ void PrintWizard::setPrintOpt(const Print::PrintBasicOptions &newPrintOpt) IGraphScene *PrintWizard::getFirstScene() { - if(!selectionModel->startIteration()) + if (!selectionModel->startIteration()) return nullptr; IGraphSceneCollection::SceneItem item = selectionModel->getNextItem(); - if(!item.scene) + if (!item.scene) return nullptr; - //Caller is responsible for deleting + // Caller is responsible for deleting return item.scene; } @@ -266,20 +269,20 @@ bool PrintWizard::taskRunning() const void PrintWizard::done(int result) { - //When we finish, we disable Cancel button - //If finished do not prompt about aborting printing - //Tasks is already cleaned up + // When we finish, we disable Cancel button + // If finished do not prompt about aborting printing + // Tasks is already cleaned up const bool printingFinished = !button(CancelButton)->isEnabled(); - if(result == QDialog::Rejected && !printingFinished) + if (result == QDialog::Rejected && !printingFinished) { - if(!printTaskHandler->waitingForTaskToStop()) + if (!printTaskHandler->waitingForTaskToStop()) { - //Ask user if he wants to abort printing - if(!Print::askUserToAbortPrinting(printTaskHandler->taskIsRunning(), this)) + // Ask user if he wants to abort printing + if (!Print::askUserToAbortPrinting(printTaskHandler->taskIsRunning(), this)) return; - if(printTaskHandler->taskIsRunning()) + if (printTaskHandler->taskIsRunning()) { printTaskHandler->stopTaskGracefully(); return; @@ -287,8 +290,8 @@ void PrintWizard::done(int result) } else { - if(printTaskHandler->taskIsRunning()) - return; //Already sent 'stop', just wait + if (printTaskHandler->taskIsRunning()) + return; // Already sent 'stop', just wait } } @@ -307,16 +310,16 @@ void PrintWizard::progressChanged(int val, const QString &msg) void PrintWizard::handleProgressFinished(bool success, const QString &errMsg) { - if(!success) + if (!success) { - if(Print::askUserToTryAgain(errMsg, this)) + if (Print::askUserToTryAgain(errMsg, this)) { - //Go back to options page + // Go back to options page back(); return; } } - //When finished, disable Cancel button. + // When finished, disable Cancel button. button(CancelButton)->setEnabled(false); } diff --git a/src/printing/wizard/printwizard.h b/src/printing/wizard/printwizard.h index 5f57856..b9d7f19 100644 --- a/src/printing/wizard/printwizard.h +++ b/src/printing/wizard/printwizard.h @@ -60,12 +60,18 @@ public: Print::PrintBasicOptions getPrintOpt() const; void setPrintOpt(const Print::PrintBasicOptions &newPrintOpt); - //Get first selected scene, ownership is passed to the caller + // Get first selected scene, ownership is passed to the caller IGraphScene *getFirstScene(); - inline sqlite3pp::database& getDb() const { return mDb; } + inline sqlite3pp::database &getDb() const + { + return mDb; + } - inline SceneSelectionModel* getSelectionModel() const { return selectionModel; } + inline SceneSelectionModel *getSelectionModel() const + { + return selectionModel; + } bool taskRunning() const; @@ -74,8 +80,8 @@ protected: private slots: void progressMaxChanged(int max); - void progressChanged(int val, const QString& msg); - void handleProgressFinished(bool success, const QString& errMsg); + void progressChanged(int val, const QString &msg); + void handleProgressFinished(bool success, const QString &errMsg); private: sqlite3pp::database &mDb; diff --git a/src/printing/wizard/progresspage.cpp b/src/printing/wizard/progresspage.cpp index 5360653..029bdc6 100644 --- a/src/printing/wizard/progresspage.cpp +++ b/src/printing/wizard/progresspage.cpp @@ -28,7 +28,7 @@ PrintProgressPage::PrintProgressPage(PrintWizard *w, QWidget *parent) : QWizardPage(parent), mWizard(w) { - m_label = new QLabel(tr("Printing...")); + m_label = new QLabel(tr("Printing...")); m_progressBar = new QProgressBar; m_progressBar->setMinimum(0); @@ -49,24 +49,24 @@ bool PrintProgressPage::isComplete() const void PrintProgressPage::handleProgressStart(int max) { - //We are starting new progress - //Enable progress bar and set maximum + // We are starting new progress + // Enable progress bar and set maximum m_progressBar->setMaximum(max); m_progressBar->setEnabled(true); emit completeChanged(); } -void PrintProgressPage::handleProgress(int val, const QString& text) +void PrintProgressPage::handleProgress(int val, const QString &text) { const bool finished = val < 0; - if(val == m_progressBar->maximum() && !finished) - m_progressBar->setMaximum(val + 1); //Increase maximum + if (val == m_progressBar->maximum() && !finished) + m_progressBar->setMaximum(val + 1); // Increase maximum m_label->setText(text); - if(finished) + if (finished) { - //Set progress to max and set disabled + // Set progress to max and set disabled m_progressBar->setValue(m_progressBar->maximum()); m_progressBar->setEnabled(false); emit completeChanged(); diff --git a/src/printing/wizard/sceneselectionmodel.cpp b/src/printing/wizard/sceneselectionmodel.cpp index d66b51f..24fd6dc 100644 --- a/src/printing/wizard/sceneselectionmodel.cpp +++ b/src/printing/wizard/sceneselectionmodel.cpp @@ -34,7 +34,7 @@ SceneSelectionModel::SceneSelectionModel(sqlite3pp::database &db, QObject *paren QVariant SceneSelectionModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -70,7 +70,7 @@ QVariant SceneSelectionModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= entries.size() || role != Qt::DisplayRole) return QVariant(); - const Entry& entry = entries.at(idx.row()); + const Entry &entry = entries.at(idx.row()); switch (idx.column()) { @@ -89,13 +89,13 @@ QVariant SceneSelectionModel::data(const QModelIndex &idx, int role) const bool SceneSelectionModel::addEntry(const Entry &entry) { - if(selectionMode == AllOfTypeExceptSelected && entry.type != selectedType) - return false; //Not the right type + if (selectionMode == AllOfTypeExceptSelected && entry.type != selectedType) + return false; // Not the right type - for(const Entry& e : qAsConst(entries)) + for (const Entry &e : qAsConst(entries)) { - if(e.objectId == entry.objectId && e.type == entry.type) - return false; //Already added + if (e.objectId == entry.objectId && e.type == entry.type) + return false; // Already added } const int row = entries.size(); @@ -121,9 +121,9 @@ void SceneSelectionModel::removeAt(int row) void SceneSelectionModel::moveRow(int row, bool up) { - if(row == 0 && !up) + if (row == 0 && !up) return; - if(row == entries.size() - 1 && up) + if (row == entries.size() - 1 && up) return; const int dest = up ? row + 2 : row - 1; @@ -135,18 +135,18 @@ void SceneSelectionModel::moveRow(int row, bool up) void SceneSelectionModel::setMode(SelectionMode mode, LineGraphType type) { - if(mode == UseSelectedEntries) + if (mode == UseSelectedEntries) type = LineGraphType::NoGraph; - else if(type == LineGraphType::NoGraph) - return; //Must set a valid type + else if (type == LineGraphType::NoGraph) + return; // Must set a valid type - if(selectionMode == mode && selectedType == type) + if (selectionMode == mode && selectedType == type) return; selectionMode = mode; - selectedType = type; + selectedType = type; - if(selectionMode == AllOfTypeExceptSelected) + if (selectionMode == AllOfTypeExceptSelected) keepOnlyType(selectedType); emit selectionModeChanged(int(mode), int(type)); @@ -157,10 +157,10 @@ void SceneSelectionModel::setMode(SelectionMode mode, LineGraphType type) qint64 SceneSelectionModel::getItemCount() { - if(cachedCount >= 0) + if (cachedCount >= 0) return cachedCount; - if(selectionMode == UseSelectedEntries) + if (selectionMode == UseSelectedEntries) { cachedCount = entries.size(); } @@ -179,16 +179,16 @@ qint64 SceneSelectionModel::getItemCount() sql.append("lines"); break; default: - return -1; //Error + return -1; // Error } sqlite3pp::query q(mDb); - if(q.prepare(sql) != SQLITE_OK || q.step() != SQLITE_ROW) + if (q.prepare(sql) != SQLITE_OK || q.step() != SQLITE_ROW) return -1; qint64 totalCount = q.getRows().get(0); totalCount -= entries.size(); // "Except" selected - if(totalCount < 0) + if (totalCount < 0) totalCount = 0; cachedCount = totalCount; @@ -199,7 +199,7 @@ qint64 SceneSelectionModel::getItemCount() bool SceneSelectionModel::startIteration() { - if(selectionMode == UseSelectedEntries) + if (selectionMode == UseSelectedEntries) { iterationIdx = 0; return true; @@ -218,7 +218,7 @@ bool SceneSelectionModel::startIteration() sql.append("lines"); break; default: - return false; //Error + return false; // Error } int ret = mQuery.prepare(sql); @@ -230,16 +230,16 @@ IGraphSceneCollection::SceneItem SceneSelectionModel::getNextItem() SceneItem item; Entry entry = getNextEntry(); - if(!entry.objectId) + if (!entry.objectId) return item; - //Create new scene without parent so ownership is passed to caller + // Create new scene without parent so ownership is passed to caller LineGraphScene *lineScene = new LineGraphScene(mDb); lineScene->loadGraph(entry.objectId, entry.type); item.scene = lineScene; - item.name = lineScene->getGraphObjectName(); - item.type = utils::getLineGraphTypeName(entry.type); + item.name = lineScene->getGraphObjectName(); + item.type = utils::getLineGraphTypeName(entry.type); return item; } @@ -272,45 +272,45 @@ SceneSelectionModel::Entry SceneSelectionModel::getNextEntry() { Entry entry{0, QString(), selectedType}; - if(selectionMode == UseSelectedEntries) + if (selectionMode == UseSelectedEntries) { - if(iterationIdx < 0 || iterationIdx >= entries.size()) + if (iterationIdx < 0 || iterationIdx >= entries.size()) return entry; entry = entries.at(iterationIdx); iterationIdx++; - if(iterationIdx == entries.size()) - iterationIdx = -1; //End iteration + if (iterationIdx == entries.size()) + iterationIdx = -1; // End iteration } else { - if(!mQuery.stmt()) - return entry; //Error: not iteration not started + if (!mQuery.stmt()) + return entry; // Error: not iteration not started while (true) { int ret = mQuery.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - if(ret == SQLITE_OK || ret == SQLITE_DONE) - mQuery.finish(); //End iteration + if (ret == SQLITE_OK || ret == SQLITE_DONE) + mQuery.finish(); // End iteration return entry; } entry.objectId = mQuery.getRows().get(0); - bool exclude = false; - for(const Entry& e : qAsConst(entries)) + bool exclude = false; + for (const Entry &e : qAsConst(entries)) { - if(e.objectId == entry.objectId) + if (e.objectId == entry.objectId) { exclude = true; break; } } - if(!exclude) + if (!exclude) break; } } @@ -325,7 +325,7 @@ void SceneSelectionModel::keepOnlyType(LineGraphType type) auto it = entries.begin(); while (it != entries.end()) { - if(it->type != type) + if (it->type != type) it = entries.erase(it); else it++; diff --git a/src/printing/wizard/sceneselectionmodel.h b/src/printing/wizard/sceneselectionmodel.h index 7889e74..6402e33 100644 --- a/src/printing/wizard/sceneselectionmodel.h +++ b/src/printing/wizard/sceneselectionmodel.h @@ -59,7 +59,8 @@ public: SceneSelectionModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -67,13 +68,19 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; - bool addEntry(const Entry& entry); + bool addEntry(const Entry &entry); void removeAt(int row); void moveRow(int row, bool up); void setMode(SelectionMode mode, LineGraphType type); - inline SelectionMode getMode() const { return selectionMode; } - inline LineGraphType getSelectedType() const { return selectedType; } + inline SelectionMode getMode() const + { + return selectionMode; + } + inline LineGraphType getSelectedType() const + { + return selectedType; + } // IGraphSceneCollection qint64 getItemCount() override; diff --git a/src/printing/wizard/selectionpage.cpp b/src/printing/wizard/selectionpage.cpp index 2c69465..9c4f8f2 100644 --- a/src/printing/wizard/selectionpage.cpp +++ b/src/printing/wizard/selectionpage.cpp @@ -37,15 +37,15 @@ #include "sceneselectionmodel.h" PrintSelectionPage::PrintSelectionPage(PrintWizard *w, QWidget *parent) : - QWizardPage (parent), + QWizardPage(parent), mWizard(w) { SceneSelectionModel *model = mWizard->getSelectionModel(); setupComboBoxes(); - addBut = new QPushButton(tr("Add")); - remBut = new QPushButton(tr("Remove")); + addBut = new QPushButton(tr("Add")); + remBut = new QPushButton(tr("Remove")); removeAllBut = new QPushButton(tr("Unselect All")); connect(addBut, &QPushButton::clicked, this, &PrintSelectionPage::onAddItem); @@ -56,7 +56,8 @@ PrintSelectionPage::PrintSelectionPage(PrintWizard *w, QWidget *parent) : view->setModel(model); statusLabel = new QLabel; - connect(model, &SceneSelectionModel::selectionCountChanged, this, &PrintSelectionPage::updateSelectionCount); + connect(model, &SceneSelectionModel::selectionCountChanged, this, + &PrintSelectionPage::updateSelectionCount); updateSelectionCount(); QVBoxLayout *lay = new QVBoxLayout(this); @@ -84,23 +85,23 @@ bool PrintSelectionPage::isComplete() const void PrintSelectionPage::comboBoxesChanged() { - SceneSelectionModel *model = mWizard->getSelectionModel(); + SceneSelectionModel *model = mWizard->getSelectionModel(); - const int modeIdx = modeCombo->currentIndex(); + const int modeIdx = modeCombo->currentIndex(); const SceneSelectionModel::SelectionMode mode = SceneSelectionModel::SelectionMode(modeIdx); - LineGraphType type = LineGraphType(typeCombo->currentIndex()); + LineGraphType type = LineGraphType(typeCombo->currentIndex()); - if(mode == SceneSelectionModel::AllOfTypeExceptSelected) + if (mode == SceneSelectionModel::AllOfTypeExceptSelected) { - //Type cannot be NoGraph - if(type == LineGraphType::NoGraph) + // Type cannot be NoGraph + if (type == LineGraphType::NoGraph) type = model->getSelectedType(); - //Default to RailwayLine if still NoGraph - if(type == LineGraphType::NoGraph) + // Default to RailwayLine if still NoGraph + if (type == LineGraphType::NoGraph) type = LineGraphType::RailwayLine; - //Update combo box + // Update combo box typeCombo->setCurrentIndex(int(type)); } @@ -109,10 +110,10 @@ void PrintSelectionPage::comboBoxesChanged() void PrintSelectionPage::updateComboBoxesFromModel() { - SceneSelectionModel *model = mWizard->getSelectionModel(); + SceneSelectionModel *model = mWizard->getSelectionModel(); const SceneSelectionModel::SelectionMode mode = model->getMode(); - const LineGraphType type = model->getSelectedType(); + const LineGraphType type = model->getSelectedType(); modeCombo->setCurrentIndex(int(mode)); typeCombo->setCurrentIndex(int(type)); @@ -130,12 +131,12 @@ void PrintSelectionPage::updateSelectionCount() void PrintSelectionPage::onAddItem() { - SceneSelectionModel *model = mWizard->getSelectionModel(); + SceneSelectionModel *model = mWizard->getSelectionModel(); - const LineGraphType requestedType = model->getSelectedType(); + const LineGraphType requestedType = model->getSelectedType(); - OwningQPointer dlg = new QDialog(this); - QVBoxLayout *lay = new QVBoxLayout(dlg); + OwningQPointer dlg = new QDialog(this); + QVBoxLayout *lay = new QVBoxLayout(dlg); LineGraphSelectionWidget *selectionWidget = new LineGraphSelectionWidget; selectionWidget->setGraphType(requestedType); @@ -149,7 +150,7 @@ void PrintSelectionPage::onAddItem() auto updateDlg = [selectionWidget, box, requestedType]() { LineGraphType type = selectionWidget->getGraphType(); - if(requestedType != LineGraphType::NoGraph && type != requestedType) + if (requestedType != LineGraphType::NoGraph && type != requestedType) { selectionWidget->setGraphType(requestedType); return; @@ -161,24 +162,24 @@ void PrintSelectionPage::onAddItem() connect(selectionWidget, &LineGraphSelectionWidget::graphChanged, this, updateDlg); updateDlg(); - if(dlg->exec() != QDialog::Accepted) + if (dlg->exec() != QDialog::Accepted) return; SceneSelectionModel::Entry entry; entry.objectId = selectionWidget->getObjectId(); - entry.name = selectionWidget->getObjectName(); - entry.type = selectionWidget->getGraphType(); + entry.name = selectionWidget->getObjectName(); + entry.type = selectionWidget->getGraphType(); model->addEntry(entry); } void PrintSelectionPage::onRemoveItem() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; mWizard->getSelectionModel()->removeAt(idx.row()); @@ -188,15 +189,17 @@ void PrintSelectionPage::setupComboBoxes() { SceneSelectionModel *model = mWizard->getSelectionModel(); - modeCombo = new QComboBox; - typeCombo = new QComboBox; + modeCombo = new QComboBox; + typeCombo = new QComboBox; - connect(modeCombo, qOverload(&QComboBox::activated), this, &PrintSelectionPage::comboBoxesChanged); - connect(typeCombo, qOverload(&QComboBox::activated), this, &PrintSelectionPage::comboBoxesChanged); + connect(modeCombo, qOverload(&QComboBox::activated), this, + &PrintSelectionPage::comboBoxesChanged); + connect(typeCombo, qOverload(&QComboBox::activated), this, + &PrintSelectionPage::comboBoxesChanged); - QStringList items; + QStringList items; items.reserve(SceneSelectionModel::NModes); - for(int i = 0; i < SceneSelectionModel::NModes; i++) + for (int i = 0; i < SceneSelectionModel::NModes; i++) { items.append(SceneSelectionModel::getModeName(SceneSelectionModel::SelectionMode(i))); } @@ -204,10 +207,11 @@ void PrintSelectionPage::setupComboBoxes() items.clear(); 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))); typeCombo->addItems(items); - connect(model, &SceneSelectionModel::selectionModeChanged, this, &PrintSelectionPage::updateComboBoxesFromModel); + connect(model, &SceneSelectionModel::selectionModeChanged, this, + &PrintSelectionPage::updateComboBoxesFromModel); updateComboBoxesFromModel(); } diff --git a/src/rollingstock/importer/backends/importtask.cpp b/src/rollingstock/importer/backends/importtask.cpp index 653deea..2c7e368 100644 --- a/src/rollingstock/importer/backends/importtask.cpp +++ b/src/rollingstock/importer/backends/importtask.cpp @@ -36,45 +36,46 @@ void ImportTask::run() { sendEvent(new LoadProgressEvent(this, 0, 4), false); - //FIXME: do copy in batches like LoadSQLiteTask - //TODO: get only owners used really - sqlite3pp::query q(mDb, "SELECT imp.id,imp.name,imp.new_name FROM imported_rs_owners imp WHERE imp.import=1 AND imp.match_existing_id IS NULL"); + // FIXME: do copy in batches like LoadSQLiteTask + // TODO: get only owners used really + sqlite3pp::query q(mDb, "SELECT imp.id,imp.name,imp.new_name FROM imported_rs_owners imp WHERE " + "imp.import=1 AND imp.match_existing_id IS NULL"); sqlite3pp::command q_create(mDb, "INSERT INTO rs_owners(id, name) VALUES(NULL, ?)"); - sqlite3pp::command q_update(mDb, "UPDATE imported_rs_owners SET match_existing_id=? WHERE id=?"); + sqlite3pp::command q_update(mDb, + "UPDATE imported_rs_owners SET match_existing_id=? WHERE id=?"); - sqlite3_stmt *st = q.stmt(); + sqlite3_stmt *st = q.stmt(); sqlite3_stmt *create = q_create.stmt(); sqlite3_stmt *update = q_update.stmt(); - sqlite3 *db = mDb.db(); - sqlite3_mutex *m = sqlite3_db_mutex(db); + sqlite3 *db = mDb.db(); + sqlite3_mutex *m = sqlite3_db_mutex(db); - int n = 0; + int n = 0; while (q.step() == SQLITE_ROW) { - if(n % 8 == 0 && wasStopped()) + if (n % 8 == 0 && wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; } - //Get imported owner id + // Get imported owner id db_id importedOwnerId = sqlite3_column_int64(st, 0); - int len = 2; + int len = 2; - if(sqlite3_column_type(st, 2) == SQLITE_NULL) + if (sqlite3_column_type(st, 2) == SQLITE_NULL) { - len = 1; //Get original name instead of the custom one + len = 1; // Get original name instead of the custom one } - //Get its name (or new_name) + // Get its name (or new_name) const char *name = reinterpret_cast(sqlite3_column_text(st, len)); - len = sqlite3_column_bytes(st, len); + len = sqlite3_column_bytes(st, len); - //Create a real owner with this name and get its id + // Create a real owner with this name and get its id sqlite3_bind_text(create, 1, name, len, SQLITE_STATIC); sqlite3_mutex_enter(m); sqlite3_step(create); @@ -82,7 +83,7 @@ void ImportTask::run() sqlite3_mutex_leave(m); sqlite3_reset(create); - //Set the real owner id in the imported owner record to use it later + // Set the real owner id in the imported owner record to use it later sqlite3_bind_int64(update, 1, existingOwnerId); sqlite3_bind_int64(update, 2, importedOwnerId); sqlite3_step(update); @@ -93,71 +94,72 @@ void ImportTask::run() sendEvent(new LoadProgressEvent(this, 1, 4), false); - q.prepare("SELECT imp.id,imp.name,imp.suffix,imp.new_name,imp.max_speed,imp.axes,imp.type,imp.sub_type" - " FROM imported_rs_models imp WHERE imp.import=1 AND imp.match_existing_id IS NULL"); + q.prepare( + "SELECT imp.id,imp.name,imp.suffix,imp.new_name,imp.max_speed,imp.axes,imp.type,imp.sub_type" + " FROM imported_rs_models imp WHERE imp.import=1 AND imp.match_existing_id IS NULL"); st = q.stmt(); - q_create.prepare("INSERT INTO rs_models(id,name,suffix,max_speed,axes,type,sub_type) VALUES(NULL,?,?,?,?,?,?)"); //Create invalid engine + q_create.prepare("INSERT INTO rs_models(id,name,suffix,max_speed,axes,type,sub_type) " + "VALUES(NULL,?,?,?,?,?,?)"); // Create invalid engine create = q_create.stmt(); q_update.prepare("UPDATE imported_rs_models SET match_existing_id=? WHERE id=?"); update = q_update.stmt(); - n = 0; + n = 0; while (q.step() == SQLITE_ROW) { - if(n % 8 == 0 && wasStopped()) + if (n % 8 == 0 && wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; } - //Get imported model id + // Get imported model id db_id importedModelId = sqlite3_column_int64(st, 0); - int len = 3; - if(sqlite3_column_type(st, 3) == SQLITE_NULL) + int len = 3; + if (sqlite3_column_type(st, 3) == SQLITE_NULL) { - len = 1; //Get original name instead of the custom one ('name' instead of 'new_name' + len = 1; // Get original name instead of the custom one ('name' instead of 'new_name' } - //Get its name (or new_name) + // Get its name (or new_name) const char *name = reinterpret_cast(sqlite3_column_text(st, len)); - len = sqlite3_column_bytes(st, len); + len = sqlite3_column_bytes(st, len); sqlite3_bind_text(create, 1, name, len, SQLITE_STATIC); - //Get its suffix + // Get its suffix name = reinterpret_cast(sqlite3_column_text(st, 2)); - len = sqlite3_column_bytes(st, 2); + len = sqlite3_column_bytes(st, 2); sqlite3_bind_text(create, 2, name, len, SQLITE_STATIC); - //Get its max_speed + // Get its max_speed int val = sqlite3_column_int(st, 4); sqlite3_bind_int(create, 3, val); - //Get its axes count + // Get its axes count val = sqlite3_column_int(st, 5); sqlite3_bind_int(create, 4, val); - //Get its type + // Get its type val = sqlite3_column_int(st, 6); sqlite3_bind_int(create, 5, val); - //Get its sub_type + // Get its sub_type val = sqlite3_column_int(st, 7); sqlite3_bind_int(create, 6, val); - //Create a real model with this name and get its id + // Create a real model with this name and get its id sqlite3_mutex_enter(m); sqlite3_step(create); db_id existingModelId = sqlite3_last_insert_rowid(db); sqlite3_mutex_leave(m); sqlite3_reset(create); - //Set the real owner id in the imported model record to use it later + // Set the real owner id in the imported model record to use it later sqlite3_bind_int64(update, 1, existingModelId); sqlite3_bind_int64(update, 2, importedModelId); sqlite3_step(update); @@ -165,26 +167,28 @@ void ImportTask::run() n++; } - if(wasStopped()) + if (wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; - }else{ + } + else + { sendEvent(new LoadProgressEvent(this, 2, 4), false); } - //Finally import rollingstock + // Finally import rollingstock q_create.prepare("INSERT INTO rs_list(id, model_id, number, owner_id)" - " SELECT NULL, m.match_existing_id, (CASE WHEN imp.new_number IS NULL THEN imp.number ELSE imp.new_number END), o.match_existing_id" + " SELECT NULL, m.match_existing_id, (CASE WHEN imp.new_number IS NULL THEN " + "imp.number ELSE imp.new_number END), o.match_existing_id" " FROM imported_rs_list imp" " JOIN imported_rs_models m ON m.id=imp.model_id " " JOIN imported_rs_owners o ON o.id=imp.owner_id" " WHERE imp.import=1 AND m.import=1 AND o.import=1"); - q_create.execute(); //Long running + q_create.execute(); // Long running sendEvent(new LoadProgressEvent(this, 0, LoadProgressEvent::ProgressMaxFinished), true); } diff --git a/src/rollingstock/importer/backends/ioptionswidget.cpp b/src/rollingstock/importer/backends/ioptionswidget.cpp index 684249f..f9f7a9a 100644 --- a/src/rollingstock/importer/backends/ioptionswidget.cpp +++ b/src/rollingstock/importer/backends/ioptionswidget.cpp @@ -19,7 +19,7 @@ #include "ioptionswidget.h" -IOptionsWidget::IOptionsWidget(QWidget *parent) : QWidget(parent) +IOptionsWidget::IOptionsWidget(QWidget *parent) : + QWidget(parent) { - } diff --git a/src/rollingstock/importer/backends/ioptionswidget.h b/src/rollingstock/importer/backends/ioptionswidget.h index ab13411..429c7dd 100644 --- a/src/rollingstock/importer/backends/ioptionswidget.h +++ b/src/rollingstock/importer/backends/ioptionswidget.h @@ -30,8 +30,8 @@ class IOptionsWidget : public QWidget public: explicit IOptionsWidget(QWidget *parent = nullptr); - virtual void loadSettings(const QMap &settings) = 0; - virtual void saveSettings(QMap &settings) = 0; + virtual void loadSettings(const QMap &settings) = 0; + virtual void saveSettings(QMap &settings) = 0; virtual void getFileDialogOptions(QString &title, QStringList &fileFormats) = 0; }; diff --git a/src/rollingstock/importer/backends/loadprogressevent.cpp b/src/rollingstock/importer/backends/loadprogressevent.cpp index 8f379af..3a44c96 100644 --- a/src/rollingstock/importer/backends/loadprogressevent.cpp +++ b/src/rollingstock/importer/backends/loadprogressevent.cpp @@ -25,5 +25,4 @@ LoadProgressEvent::LoadProgressEvent(QRunnable *self, int pr, int m) : progress(pr), max(m) { - } diff --git a/src/rollingstock/importer/backends/loadprogressevent.h b/src/rollingstock/importer/backends/loadprogressevent.h index 1bd5f00..4f5689c 100644 --- a/src/rollingstock/importer/backends/loadprogressevent.h +++ b/src/rollingstock/importer/backends/loadprogressevent.h @@ -30,9 +30,9 @@ class LoadProgressEvent : public QEvent public: enum { - ProgressError = -1, + ProgressError = -1, ProgressAbortedByUser = -2, - ProgressMaxFinished = -3 + ProgressMaxFinished = -3 }; static constexpr Type _Type = Type(CustomEvents::RsImportLoadProgress); diff --git a/src/rollingstock/importer/backends/loadtaskutils.cpp b/src/rollingstock/importer/backends/loadtaskutils.cpp index e311b46..7d9dda7 100644 --- a/src/rollingstock/importer/backends/loadtaskutils.cpp +++ b/src/rollingstock/importer/backends/loadtaskutils.cpp @@ -19,11 +19,9 @@ #include "loadtaskutils.h" - ILoadRSTask::ILoadRSTask(sqlite3pp::database &db, const QString &fileName, QObject *receiver) : IQuittableTask(receiver), mDb(db), mFileName(fileName) { - } diff --git a/src/rollingstock/importer/backends/loadtaskutils.h b/src/rollingstock/importer/backends/loadtaskutils.h index 8644e6d..856b3b4 100644 --- a/src/rollingstock/importer/backends/loadtaskutils.h +++ b/src/rollingstock/importer/backends/loadtaskutils.h @@ -31,9 +31,12 @@ class database; class ILoadRSTask : public IQuittableTask { public: - ILoadRSTask(sqlite3pp::database &db, const QString& fileName, QObject *receiver); + ILoadRSTask(sqlite3pp::database &db, const QString &fileName, QObject *receiver); - inline QString getErrorText() const { return errText; } + inline QString getErrorText() const + { + return errText; + } protected: sqlite3pp::database &mDb; @@ -46,7 +49,10 @@ class LoadTaskUtils { Q_DECLARE_TR_FUNCTIONS(LoadTaskUtils) public: - enum { BatchSize = 50 }; + enum + { + BatchSize = 50 + }; }; #endif // LOADTASKUTILS_H diff --git a/src/rollingstock/importer/backends/ods/loadodstask.cpp b/src/rollingstock/importer/backends/ods/loadodstask.cpp index 7a79112..e5c1903 100644 --- a/src/rollingstock/importer/backends/ods/loadodstask.cpp +++ b/src/rollingstock/importer/backends/ods/loadodstask.cpp @@ -29,35 +29,34 @@ #include -LoadODSTask::LoadODSTask(const QMap &arguments, - sqlite3pp::database &db, int mode, int defSpeed, RsType defType, - const QString &fileName, QObject *receiver) : +LoadODSTask::LoadODSTask(const QMap &arguments, sqlite3pp::database &db, + int mode, int defSpeed, RsType defType, const QString &fileName, + QObject *receiver) : ILoadRSTask(db, fileName, receiver), importMode(mode), defaultSpeed(defSpeed), defaultType(defType) { - m_tblFirstRow = arguments.value(odsFirstRowKey, 3).toInt(); - m_tblRSNumberCol = arguments.value(odsNumColKey, 1).toInt(); + m_tblFirstRow = arguments.value(odsFirstRowKey, 3).toInt(); + m_tblRSNumberCol = arguments.value(odsNumColKey, 1).toInt(); m_tblModelNameCol = arguments.value(odsNameColKey, 3).toInt(); } void LoadODSTask::run() { - if(wasStopped()) + if (wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; } - int max = 4; + int max = 4; int progress = 0; sendEvent(new LoadProgressEvent(this, progress++, max), false); - int err = 0; + int err = 0; zip_t *zipper = zip_open(mFileName.toUtf8(), ZIP_RDONLY, &err); if (!zipper) @@ -68,27 +67,25 @@ void LoadODSTask::run() qDebug() << "Failed to open output file" << mFileName << "Err:" << msg; errText = QString::fromUtf8(msg); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; } - //Search for the file of given name + // Search for the file of given name const char *name = "content.xml"; struct zip_stat st; zip_stat_init(&st); - if(zip_stat(zipper, name, 0, &st) < 0) + if (zip_stat(zipper, name, 0, &st) < 0) { const char *msg = zip_strerror(zipper); - errText = QString::fromUtf8(msg); + errText = QString::fromUtf8(msg); - //Close archive + // Close archive zip_close(zipper); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; @@ -96,33 +93,31 @@ void LoadODSTask::run() QTemporaryFile mContentFile; - if(mContentFile.isOpen()) + if (mContentFile.isOpen()) mContentFile.close(); - if(!mContentFile.open() || !mContentFile.resize(qint64(st.size))) + if (!mContentFile.open() || !mContentFile.resize(qint64(st.size))) { errText = mContentFile.errorString(); - //Close archive + // Close archive zip_close(zipper); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; } - //Read the compressed file + // Read the compressed file zip_file *f = zip_fopen(zipper, name, 0); - if(!f) + if (!f) { const char *msg = zip_strerror(zipper); - errText = QString::fromUtf8(msg); - //Close archive + errText = QString::fromUtf8(msg); + // Close archive zip_close(zipper); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; @@ -136,13 +131,12 @@ void LoadODSTask::run() if (len < 0) { const char *msg = zip_file_strerror(f); - errText = QString::fromUtf8(msg); - //Close file and archive + errText = QString::fromUtf8(msg); + // Close file and archive zip_fclose(f); zip_close(zipper); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; @@ -151,14 +145,13 @@ void LoadODSTask::run() sum += zip_uint64_t(len); } - //Close file and archive + // Close file and archive zip_fclose(f); zip_close(zipper); - if(wasStopped()) + if (wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; @@ -166,43 +159,38 @@ void LoadODSTask::run() sendEvent(new LoadProgressEvent(this, progress++, max), false); - mContentFile.reset(); //Seek to start + mContentFile.reset(); // Seek to start QXmlStreamReader xml(&mContentFile); ODSImporter importer(importMode, m_tblFirstRow, m_tblRSNumberCol, m_tblModelNameCol, defaultSpeed, defaultType, mDb); - if(!importer.loadDocument(xml)) + if (!importer.loadDocument(xml)) { errText = xml.errorString(); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); return; } - do{ - if(wasStopped()) + do + { + if (wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; } sendEvent(new LoadProgressEvent(this, progress++, max++), false); - } - while (importer.readNextTable(xml)); + } while (importer.readNextTable(xml)); - if(xml.hasError()) + if (xml.hasError()) { progress = LoadProgressEvent::ProgressError; - errText = xml.errorString(); + errText = xml.errorString(); } - sendEvent(new LoadProgressEvent(this, - progress, - LoadProgressEvent::ProgressMaxFinished), - true); + sendEvent(new LoadProgressEvent(this, progress, LoadProgressEvent::ProgressMaxFinished), true); } diff --git a/src/rollingstock/importer/backends/ods/loadodstask.h b/src/rollingstock/importer/backends/ods/loadodstask.h index 6de7b5b..bfa87ac 100644 --- a/src/rollingstock/importer/backends/ods/loadodstask.h +++ b/src/rollingstock/importer/backends/ods/loadodstask.h @@ -37,16 +37,15 @@ class LoadODSTask : public ILoadRSTask { public: - LoadODSTask(const QMap& arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString& fileName, QObject *receiver); + LoadODSTask(const QMap &arguments, sqlite3pp::database &db, int mode, + int defSpeed, RsType defType, const QString &fileName, QObject *receiver); void run() override; private: - int m_tblFirstRow; //Start from 1 (not 0) - int m_tblRSNumberCol; //Start from 1 (not 0) - int m_tblModelNameCol; //Start from 1 (not 0) + int m_tblFirstRow; // Start from 1 (not 0) + int m_tblRSNumberCol; // Start from 1 (not 0) + int m_tblModelNameCol; // Start from 1 (not 0) int importMode; int defaultSpeed; diff --git a/src/rollingstock/importer/backends/ods/odsimporter.cpp b/src/rollingstock/importer/backends/ods/odsimporter.cpp index ece580c..766677d 100644 --- a/src/rollingstock/importer/backends/ods/odsimporter.cpp +++ b/src/rollingstock/importer/backends/ods/odsimporter.cpp @@ -27,18 +27,22 @@ #include -const QString offns = QStringLiteral("xmlns:office"); +const QString offns = QStringLiteral("xmlns:office"); const QString offvers = QStringLiteral("office:version"); -const QString tbl = QStringLiteral("table:table"); +const QString tbl = QStringLiteral("table:table"); const QString tblname = QStringLiteral("table:name"); const QString offbody = QStringLiteral("office:body"); -ODSImporter::ODSImporter(const int mode, const int firstRow, const int numColm, const int nameCol, int defSpeed, RsType defType, sqlite3pp::database &db) : +ODSImporter::ODSImporter(const int mode, const int firstRow, const int numColm, const int nameCol, + int defSpeed, RsType defType, sqlite3pp::database &db) : mDb(db), - q_addOwner(mDb, "INSERT INTO imported_rs_owners(id, name, import, new_name, match_existing_id, sheet_idx)" - " VALUES(NULL, ?, 1, NULL, ?, ?)"), + q_addOwner( + mDb, + "INSERT INTO imported_rs_owners(id, name, import, new_name, match_existing_id, sheet_idx)" + " VALUES(NULL, ?, 1, NULL, ?, ?)"), q_unsetImported(mDb, "UPDATE imported_rs_owners SET import=0 WHERE id=?"), - q_addModel(mDb, "INSERT INTO imported_rs_models(id, name, suffix, import, new_name, match_existing_id, max_speed, axes, type, sub_type)" + q_addModel(mDb, "INSERT INTO imported_rs_models(id, name, suffix, import, new_name, " + "match_existing_id, max_speed, axes, type, sub_type)" " VALUES(NULL, ?, '', 1, NULL, ?, ?, ?, ?, ?)"), q_addRS(mDb, "INSERT INTO imported_rs_list(id, import, model_id, owner_id, number, new_number)" " VALUES(NULL, 1, ?, ?, ?, NULL)"), @@ -62,48 +66,49 @@ ODSImporter::ODSImporter(const int mode, const int firstRow, const int numColm, mutex = sqlite3_db_mutex(mDb.db()); } -bool ODSImporter::loadDocument(QXmlStreamReader& xml) +bool ODSImporter::loadDocument(QXmlStreamReader &xml) { xml.setNamespaceProcessing(false); sheetIdx = 0; - if(!xml.readNextStartElement() || xml.qualifiedName() != QLatin1String("office:document-content")) + if (!xml.readNextStartElement() + || xml.qualifiedName() != QLatin1String("office:document-content")) return false; - bool offNsFound = false; - bool offVersFound = false; + bool offNsFound = false; + bool offVersFound = false; QXmlStreamAttributes attrs = xml.attributes(); - for(int i = 0; i < attrs.size(); i++) + for (int i = 0; i < attrs.size(); i++) { - const QXmlStreamAttribute& a = attrs[i]; - if(!offVersFound && a.qualifiedName() == offvers) + const QXmlStreamAttribute &a = attrs[i]; + if (!offVersFound && a.qualifiedName() == offvers) { - if(a.value().size() < 3 || a.value().at(1) != '.') + if (a.value().size() < 3 || a.value().at(1) != '.') { qWarning() << "WRONG OFFICE VERSION:" << a.value(); } int major = a.value().at(0).digitValue(); int minor = a.value().at(2).digitValue(); qDebug() << "FOUND VERSION:" << a.value(); - if(major != 1 || minor < 2) + if (major != 1 || minor < 2) { qDebug() << "Error: wrong office:version value"; } offVersFound = true; - if(offNsFound) + if (offNsFound) break; } - else if(!offNsFound && a.qualifiedName() == offns) + else if (!offNsFound && a.qualifiedName() == offns) { offNsFound = true; - if(offVersFound) + if (offVersFound) break; } } - if(!offVersFound || !offNsFound) + if (!offVersFound || !offNsFound) return false; while (xml.readNextStartElement() && xml.qualifiedName() != offbody) @@ -111,16 +116,16 @@ bool ODSImporter::loadDocument(QXmlStreamReader& xml) xml.skipCurrentElement(); } - if(xml.hasError()) + if (xml.hasError()) { qDebug() << "XML Error:" << xml.error() << xml.errorString(); return false; } - if(!xml.readNextStartElement() || xml.qualifiedName() != QLatin1String("office:spreadsheet")) + if (!xml.readNextStartElement() || xml.qualifiedName() != QLatin1String("office:spreadsheet")) return false; - if(xml.hasError()) + if (xml.hasError()) { return false; } @@ -128,14 +133,14 @@ bool ODSImporter::loadDocument(QXmlStreamReader& xml) return true; } -bool ODSImporter::readNextTable(QXmlStreamReader& xml) +bool ODSImporter::readNextTable(QXmlStreamReader &xml) { - while(xml.readNextStartElement()) + while (xml.readNextStartElement()) { - if(xml.qualifiedName() != tbl) + if (xml.qualifiedName() != tbl) { xml.skipCurrentElement(); - continue; //Skip unknown elements + continue; // Skip unknown elements } readTable(xml); @@ -148,59 +153,59 @@ bool ODSImporter::readNextTable(QXmlStreamReader& xml) void ODSImporter::readTable(QXmlStreamReader &xml) { - db_id importedOwnerId = 0; - if(importMode & RSImportMode::ImportRSOwners) + db_id importedOwnerId = 0; + if (importMode & RSImportMode::ImportRSOwners) { QString name; - for(const QXmlStreamAttribute& a : xml.attributes()) + for (const QXmlStreamAttribute &a : xml.attributes()) { - if(a.qualifiedName() == tblname) + if (a.qualifiedName() == tblname) { name = a.value().toString().simplified(); break; } } - //qDebug() << "OWNER:" << name; + // qDebug() << "OWNER:" << name; - //Try to match an existing owner, if returns 0 -> no match -> create new owner + // Try to match an existing owner, if returns 0 -> no match -> create new owner db_id existingOwnerId = 0; q_findOwner.bind(1, name); - if(q_findOwner.step() == SQLITE_ROW) + if (q_findOwner.step() == SQLITE_ROW) existingOwnerId = q_findOwner.getRows().get(0); q_findOwner.reset(); - if(name.isEmpty()) - q_addOwner.bind(1); //Bind NULL, will be handled by SelectOwnersPage + if (name.isEmpty()) + q_addOwner.bind(1); // Bind NULL, will be handled by SelectOwnersPage else q_addOwner.bind(1, name); - if(existingOwnerId) + if (existingOwnerId) q_addOwner.bind(2, existingOwnerId); else - q_addOwner.bind(2); //bind NULL + q_addOwner.bind(2); // bind NULL q_addOwner.bind(3, sheetIdx); sqlite3_mutex_enter(mutex); - int ret = q_addOwner.execute(); + int ret = q_addOwner.execute(); importedOwnerId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_addOwner.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - //FIXME: tell the user + // FIXME: tell the user qWarning() << "Error importing owner:" << name << "skipping..."; xml.skipCurrentElement(); return; } } - row = 0; - col = 0; + row = 0; + col = 0; - int rsCount = 0; + int rsCount = 0; bool finished = false; QByteArray model; @@ -212,51 +217,53 @@ void ODSImporter::readTable(QXmlStreamReader &xml) { case QXmlStreamReader::StartElement: { - if(importMode & RSImportMode::ImportRSModels && xml.qualifiedName() == QLatin1String("table:table-row")) + if (importMode & RSImportMode::ImportRSModels + && xml.qualifiedName() == QLatin1String("table:table-row")) { readRow(xml, model, number); - if(row < tableFirstRow || model.isEmpty() || number == -1) - break; //First n rows are table header / empty + if (row < tableFirstRow || model.isEmpty() || number == -1) + break; // First n rows are table header / empty - //qDebug() << "RS:" << model << number; + // qDebug() << "RS:" << model << number; db_id importedModelId = 0; - sqlite3_bind_text(q_findImportedModel.stmt(), 1, model, model.size(), SQLITE_STATIC); - if(q_findImportedModel.step() == SQLITE_ROW) + sqlite3_bind_text(q_findImportedModel.stmt(), 1, model, model.size(), + SQLITE_STATIC); + if (q_findImportedModel.step() == SQLITE_ROW) { importedModelId = q_findImportedModel.getRows().get(0); } q_findImportedModel.reset(); - if(!importedModelId) + if (!importedModelId) { - //Create new one - db_id existingModelId = 0; - int maxSpeedKm = defaultSpeed; - int axes = 4; - RsType type = defaultType; + // Create new one + db_id existingModelId = 0; + int maxSpeedKm = defaultSpeed; + int axes = 4; + RsType type = defaultType; RsEngineSubType subType = RsEngineSubType::Invalid; - //Try filling with matched name model infos + // Try filling with matched name model infos sqlite3_bind_text(q_findModel.stmt(), 1, model, model.size(), SQLITE_STATIC); - if(q_findModel.step() == SQLITE_ROW) + if (q_findModel.step() == SQLITE_ROW) { - auto m = q_findModel.getRows(); + auto m = q_findModel.getRows(); existingModelId = m.get(0); - maxSpeedKm = m.get(1); - axes = m.get(2); - type = RsType(m.get(3)); - subType = RsEngineSubType(m.get(4)); + maxSpeedKm = m.get(1); + axes = m.get(2); + type = RsType(m.get(3)); + subType = RsEngineSubType(m.get(4)); } q_findModel.reset(); sqlite3_bind_text(q_addModel.stmt(), 1, model, model.size(), SQLITE_STATIC); - if(existingModelId) + if (existingModelId) q_addModel.bind(2, existingModelId); else - q_addModel.bind(2); //bind NULL + q_addModel.bind(2); // bind NULL q_addModel.bind(3, maxSpeedKm); q_addModel.bind(4, axes); q_addModel.bind(5, int(type)); @@ -270,11 +277,11 @@ void ODSImporter::readTable(QXmlStreamReader &xml) q_addModel.reset(); } - if(importMode & RSImportMode::ImportRSPieces) + if (importMode & RSImportMode::ImportRSPieces) { - int num = number % 10000; //Cut at 4 digits + int num = number % 10000; // Cut at 4 digits - //Finally register RS + // Finally register RS q_addRS.bind(1, importedModelId); q_addRS.bind(2, importedOwnerId); q_addRS.bind(3, num); @@ -300,7 +307,7 @@ void ODSImporter::readTable(QXmlStreamReader &xml) } } - if(rsCount == 0 && importMode & RSImportMode::ImportRSPieces) + if (rsCount == 0 && importMode & RSImportMode::ImportRSPieces) { q_unsetImported.bind(1, importedOwnerId); q_unsetImported.execute(); @@ -308,14 +315,14 @@ void ODSImporter::readTable(QXmlStreamReader &xml) } } -void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& number) +void ODSImporter::readRow(QXmlStreamReader &xml, QByteArray &model, qint64 &number) { row++; col = 0; - for(const QXmlStreamAttribute& a : xml.attributes()) + for (const QXmlStreamAttribute &a : xml.attributes()) { - if(a.qualifiedName() == QLatin1String("table:number-rows-repeated")) + if (a.qualifiedName() == QLatin1String("table:number-rows-repeated")) { int rowsRepeated = a.value().toInt(); row += rowsRepeated - 1; @@ -329,14 +336,14 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb { case QXmlStreamReader::StartElement: { - if(xml.qualifiedName() == QLatin1String("table:table-cell")) + if (xml.qualifiedName() == QLatin1String("table:table-cell")) { int oldCol = col; col++; - for(const QXmlStreamAttribute& a : xml.attributes()) + for (const QXmlStreamAttribute &a : xml.attributes()) { - if(a.qualifiedName() == QLatin1String("table:number-columns-repeated")) + if (a.qualifiedName() == QLatin1String("table:number-columns-repeated")) { int colsRepeated = a.value().toInt(); col += colsRepeated - 1; @@ -344,9 +351,9 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb } } - //Read current cell - int depth = 1; - bool cellEmpty = true; + // Read current cell + int depth = 1; + bool cellEmpty = true; QXmlStreamReader::TokenType token = QXmlStreamReader::NoToken; while (depth && (token = xml.readNext()) != QXmlStreamReader::Invalid) { @@ -360,23 +367,26 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb break; case QXmlStreamReader::Characters: { - if(xml.isWhitespace()) + if (xml.isWhitespace()) break; - //Convert to QString immidiately because xml reader changes buffer contents when reading next token + // Convert to QString immidiately because xml reader changes buffer contents + // when reading next token QStringRef val = xml.text(); - cellEmpty = val.isEmpty(); - //qDebug() << "CELL:" << row << col << val; + cellEmpty = val.isEmpty(); + // qDebug() << "CELL:" << row << col << val; - //Avoid allocating a QString copy of QStringRef, directly convert to QByteArray - if(oldCol < tableRSNumberCol && col >= tableRSNumberCol && val.size()) + // Avoid allocating a QString copy of QStringRef, directly convert to + // QByteArray + if (oldCol < tableRSNumberCol && col >= tableRSNumberCol && val.size()) { - //Do not use toInt(), we must tolerate dashes and other non-digit characters in the middle + // Do not use toInt(), we must tolerate dashes and other non-digit + // characters in the middle qint64 tmp = 0; - for(int i = 0; i < val.size(); i++) + for (int i = 0; i < val.size(); i++) { int d = val.at(i).digitValue(); - if(d != -1) //-1 means it's not a digit so skip it + if (d != -1) //-1 means it's not a digit so skip it { tmp *= 10; tmp += d; @@ -385,7 +395,7 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb number = tmp; } - if(oldCol < tableModelNameCol && col >= tableModelNameCol) + if (oldCol < tableModelNameCol && col >= tableModelNameCol) model = val.toUtf8().simplified(); break; @@ -395,14 +405,13 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb } } - if(cellEmpty) + if (cellEmpty) { - if(oldCol < tableRSNumberCol && col >= tableRSNumberCol) + if (oldCol < tableRSNumberCol && col >= tableRSNumberCol) number = -1; - if(oldCol < tableModelNameCol && col >= tableModelNameCol) + if (oldCol < tableModelNameCol && col >= tableModelNameCol) model.clear(); } - } else { @@ -421,9 +430,9 @@ void ODSImporter::readRow(QXmlStreamReader& xml, QByteArray& model, qint64& numb QString ODSImporter::readCell(QXmlStreamReader &xml) { col++; - for(const QXmlStreamAttribute& a : xml.attributes()) + for (const QXmlStreamAttribute &a : xml.attributes()) { - if(a.qualifiedName() == QLatin1String("table:number-columns-repeated")) + if (a.qualifiedName() == QLatin1String("table:number-columns-repeated")) { int colsRepeated = a.value().toInt(); col += colsRepeated - 1; @@ -433,8 +442,8 @@ QString ODSImporter::readCell(QXmlStreamReader &xml) QString val; - //Read current cell - int depth = 1; + // Read current cell + int depth = 1; QXmlStreamReader::TokenType token = QXmlStreamReader::NoToken; while (depth && (token = xml.readNext()) != QXmlStreamReader::Invalid) { @@ -448,11 +457,12 @@ QString ODSImporter::readCell(QXmlStreamReader &xml) break; case QXmlStreamReader::Characters: { - if(xml.isWhitespace()) + if (xml.isWhitespace()) break; - val = xml.text().toString(); //Convert to QString immidiately because xml reader changes buffer contents when reading next token - //qDebug() << "CELL:" << row << col << val; + val = xml.text().toString(); // Convert to QString immidiately because xml reader + // changes buffer contents when reading next token + // qDebug() << "CELL:" << row << col << val; break; } default: diff --git a/src/rollingstock/importer/backends/ods/odsimporter.h b/src/rollingstock/importer/backends/ods/odsimporter.h index 49989f2..7f7a6f8 100644 --- a/src/rollingstock/importer/backends/ods/odsimporter.h +++ b/src/rollingstock/importer/backends/ods/odsimporter.h @@ -37,7 +37,7 @@ public: bool readNextTable(QXmlStreamReader &xml); private: - void readTable(QXmlStreamReader& xml); + void readTable(QXmlStreamReader &xml); void readRow(QXmlStreamReader &xml, QByteArray &model, qint64 &number); QString readCell(QXmlStreamReader &xml); @@ -53,9 +53,9 @@ private: sqlite3pp::query q_findModel; sqlite3pp::query q_findImportedModel; - const int tableFirstRow; //Start from 1 (not 0) - const int tableRSNumberCol; //Start from 1 (not 0) - const int tableModelNameCol; //Start from 1 (not 0) + const int tableFirstRow; // Start from 1 (not 0) + const int tableRSNumberCol; // Start from 1 (not 0) + const int tableModelNameCol; // Start from 1 (not 0) const int importMode; int sheetIdx; diff --git a/src/rollingstock/importer/backends/ods/odsoptionswidget.cpp b/src/rollingstock/importer/backends/ods/odsoptionswidget.cpp index cfeb176..6df94ed 100644 --- a/src/rollingstock/importer/backends/ods/odsoptionswidget.cpp +++ b/src/rollingstock/importer/backends/ods/odsoptionswidget.cpp @@ -31,14 +31,16 @@ ODSOptionsWidget::ODSOptionsWidget(QWidget *parent) : IOptionsWidget(parent) { - //ODS Option + // ODS Option QFormLayout *lay = new QFormLayout(this); - lay->addRow(new QLabel(tr("Import rollingstock pieces, models and owners from a spreadsheet file.\n" - "The file must be a valid Open Document Format Spreadsheet V1.2\n" - "Extension: (*.ods)"))); + lay->addRow( + new QLabel(tr("Import rollingstock pieces, models and owners from a spreadsheet file.\n" + "The file must be a valid Open Document Format Spreadsheet V1.2\n" + "Extension: (*.ods)"))); odsFirstRowSpin = new QSpinBox; odsFirstRowSpin->setRange(1, 9999); - lay->addRow(tr("First non-empty row that contains rollingstock piece information"), odsFirstRowSpin); + lay->addRow(tr("First non-empty row that contains rollingstock piece information"), + odsFirstRowSpin); odsNumColSpin = new QSpinBox; odsNumColSpin->setRange(1, 9999); lay->addRow(tr("Column from which item number is extracted"), odsNumColSpin); diff --git a/src/rollingstock/importer/backends/ods/options.h b/src/rollingstock/importer/backends/ods/options.h index e6eaf2b..095379d 100644 --- a/src/rollingstock/importer/backends/ods/options.h +++ b/src/rollingstock/importer/backends/ods/options.h @@ -21,7 +21,7 @@ #define OPTIONS_H constexpr const char *odsFirstRowKey = "odsFirstRow"; -constexpr const char *odsNumColKey = "odsNumCol"; -constexpr const char *odsNameColKey = "odsNameCol"; +constexpr const char *odsNumColKey = "odsNumCol"; +constexpr const char *odsNameColKey = "odsNameCol"; #endif // OPTIONS_H diff --git a/src/rollingstock/importer/backends/ods/rsimportodsbackend.cpp b/src/rollingstock/importer/backends/ods/rsimportodsbackend.cpp index e3b834b..44a025a 100644 --- a/src/rollingstock/importer/backends/ods/rsimportodsbackend.cpp +++ b/src/rollingstock/importer/backends/ods/rsimportodsbackend.cpp @@ -26,7 +26,6 @@ RSImportODSBackend::RSImportODSBackend() { - } QString RSImportODSBackend::getBackendName() @@ -39,9 +38,10 @@ IOptionsWidget *RSImportODSBackend::createOptionsWidget() return new ODSOptionsWidget; } -ILoadRSTask *RSImportODSBackend::createLoadTask(const QMap &arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString &fileName, QObject *receiver) +ILoadRSTask *RSImportODSBackend::createLoadTask(const QMap &arguments, + sqlite3pp::database &db, int mode, int defSpeed, + RsType defType, const QString &fileName, + QObject *receiver) { return new LoadODSTask(arguments, db, mode, defSpeed, defType, fileName, receiver); } diff --git a/src/rollingstock/importer/backends/ods/rsimportodsbackend.h b/src/rollingstock/importer/backends/ods/rsimportodsbackend.h index 6f17158..5fcc6df 100644 --- a/src/rollingstock/importer/backends/ods/rsimportodsbackend.h +++ b/src/rollingstock/importer/backends/ods/rsimportodsbackend.h @@ -31,9 +31,9 @@ public: IOptionsWidget *createOptionsWidget() override; - ILoadRSTask *createLoadTask(const QMap& arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString& fileName, QObject *receiver) override; + ILoadRSTask *createLoadTask(const QMap &arguments, sqlite3pp::database &db, + int mode, int defSpeed, RsType defType, const QString &fileName, + QObject *receiver) override; }; #endif // RSIMPORTODSBACKEND_H diff --git a/src/rollingstock/importer/backends/rsbackendsmodel.cpp b/src/rollingstock/importer/backends/rsbackendsmodel.cpp index f3185cb..197d537 100644 --- a/src/rollingstock/importer/backends/rsbackendsmodel.cpp +++ b/src/rollingstock/importer/backends/rsbackendsmodel.cpp @@ -22,7 +22,6 @@ RSImportBackendsModel::RSImportBackendsModel(QObject *parent) : QAbstractListModel(parent) { - } RSImportBackendsModel::~RSImportBackendsModel() @@ -38,11 +37,11 @@ int RSImportBackendsModel::rowCount(const QModelIndex &parent) const QVariant RSImportBackendsModel::data(const QModelIndex &idx, int role) const { - if(role != Qt::DisplayRole || idx.column() != 0) + if (role != Qt::DisplayRole || idx.column() != 0) return QVariant(); RSImportBackend *back = getBackend(idx.row()); - if(!back) + if (!back) return QVariant(); return back->getBackendName(); @@ -58,7 +57,7 @@ void RSImportBackendsModel::addBackend(RSImportBackend *backend) RSImportBackend *RSImportBackendsModel::getBackend(int idx) const { - if(idx < 0 || idx >= backends.size()) + if (idx < 0 || idx >= backends.size()) return nullptr; return backends.at(idx); } diff --git a/src/rollingstock/importer/backends/rsimportbackend.cpp b/src/rollingstock/importer/backends/rsimportbackend.cpp index 196cc00..d40b805 100644 --- a/src/rollingstock/importer/backends/rsimportbackend.cpp +++ b/src/rollingstock/importer/backends/rsimportbackend.cpp @@ -21,10 +21,8 @@ RSImportBackend::RSImportBackend() { - } RSImportBackend::~RSImportBackend() { - } diff --git a/src/rollingstock/importer/backends/rsimportbackend.h b/src/rollingstock/importer/backends/rsimportbackend.h index 134f92f..b6846d7 100644 --- a/src/rollingstock/importer/backends/rsimportbackend.h +++ b/src/rollingstock/importer/backends/rsimportbackend.h @@ -39,13 +39,14 @@ public: RSImportBackend(); virtual ~RSImportBackend(); - virtual QString getBackendName() = 0; + virtual QString getBackendName() = 0; - virtual IOptionsWidget *createOptionsWidget() = 0; + virtual IOptionsWidget *createOptionsWidget() = 0; - virtual ILoadRSTask *createLoadTask(const QMap& arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString& fileName, QObject *receiver) = 0; + virtual ILoadRSTask *createLoadTask(const QMap &arguments, + sqlite3pp::database &db, int mode, int defSpeed, + RsType defType, const QString &fileName, + QObject *receiver) = 0; }; #endif // RSIMPORTBACKEND_H diff --git a/src/rollingstock/importer/backends/sqlite/loadsqlitetask.cpp b/src/rollingstock/importer/backends/sqlite/loadsqlitetask.cpp index 4dd26d8..104b231 100644 --- a/src/rollingstock/importer/backends/sqlite/loadsqlitetask.cpp +++ b/src/rollingstock/importer/backends/sqlite/loadsqlitetask.cpp @@ -26,23 +26,22 @@ #include -LoadSQLiteTask::LoadSQLiteTask(sqlite3pp::database &db, int mode, const QString &fileName, QObject *receiver) : +LoadSQLiteTask::LoadSQLiteTask(sqlite3pp::database &db, int mode, const QString &fileName, + QObject *receiver) : ILoadRSTask(db, fileName, receiver), importMode(mode) { - } void LoadSQLiteTask::run() { currentProgress = 0; - localCount = 0; - localProgress = 0; + localCount = 0; + localProgress = 0; - if(wasStopped()) + if (wasStopped()) { - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return; @@ -50,27 +49,25 @@ void LoadSQLiteTask::run() sendEvent(new LoadProgressEvent(this, 0, MaxProgress), false); - if(!attachDB()) + if (!attachDB()) return; - if(!copyOwners()) + if (!copyOwners()) return; - if(!copyModels()) + if (!copyModels()) return; - if(!copyRS()) + if (!copyRS()) return; - //Cleanup + // Cleanup mDb.execute("DETACH rs_source"); - if(!unselectOwnersWithNoRS()) + if (!unselectOwnersWithNoRS()) return; - sendEvent(new LoadProgressEvent(this, - MaxProgress, - LoadProgressEvent::ProgressMaxFinished), + sendEvent(new LoadProgressEvent(this, MaxProgress, LoadProgressEvent::ProgressMaxFinished), true); } @@ -81,30 +78,29 @@ void LoadSQLiteTask::endWithDbError(const QString &text) errText = LoadTaskUtils::tr("%1\n" "Code: %2\n" "Message: %3") - .arg(text) - .arg(mDb.extended_error_code()) - .arg(mDb.error_msg()); + .arg(text) + .arg(mDb.extended_error_code()) + .arg(mDb.error_msg()); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressError, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressError, LoadProgressEvent::ProgressMaxFinished), true); } bool LoadSQLiteTask::attachDB() { - //ATTACH other database to this session + // ATTACH other database to this session localCount = 1; - sqlite3pp::command q(mDb, "ATTACH ? AS rs_source"); //TODO: use URI to pass 'readonly' + sqlite3pp::command q(mDb, "ATTACH ? AS rs_source"); // TODO: use URI to pass 'readonly' q.bind(1, mFileName); int ret = q.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Could not open session file correctly.")); return false; } - localProgress = 0; //Advance by 1 step, clear partial progress + localProgress = 0; // Advance by 1 step, clear partial progress currentProgress += StepSize; sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); return true; @@ -112,51 +108,52 @@ bool LoadSQLiteTask::attachDB() bool LoadSQLiteTask::copyOwners() { - if((importMode & RSImportMode::ImportRSOwners) == 0) - return true; //Skip owners importation + if ((importMode & RSImportMode::ImportRSOwners) == 0) + return true; // Skip owners importation sqlite3pp::query q(mDb); sqlite3pp::query q_getFirstIdGreaterThan(mDb); - //Calculate maximum number of batches + // Calculate maximum number of batches q.prepare("SELECT MAX(id) FROM rs_source.rs_owners"); q.step(); localCount = sqlite3_column_int(q.stmt(), 0); - localCount = localCount/LoadTaskUtils::BatchSize + (localCount % LoadTaskUtils::BatchSize != 0); //Round up - if(localCount < 1) - localCount = 1; //At least 1 batch + localCount = localCount / LoadTaskUtils::BatchSize + + (localCount % LoadTaskUtils::BatchSize != 0); // Round up + if (localCount < 1) + localCount = 1; // At least 1 batch - //Init query: get first id to import + // Init query: get first id to import int ret = q_getFirstIdGreaterThan.prepare("SELECT MIN(id) FROM rs_source.rs_owners WHERE id>?"); sqlite3_stmt *stmt = q_getFirstIdGreaterThan.stmt(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed A1.")); return false; } - ret = q.prepare("INSERT OR IGNORE INTO main.imported_rs_owners(id, name, import, new_name, match_existing_id, sheet_idx)" + ret = q.prepare("INSERT OR IGNORE INTO main.imported_rs_owners(id, name, import, new_name, " + "match_existing_id, sheet_idx)" " SELECT NULL,own1.name,1,NULL,own2.id,0" " FROM rs_source.rs_owners AS own1" " LEFT JOIN main.rs_owners own2 ON own1.name=own2.name" " WHERE own1.id BETWEEN ? AND ?"); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed A2.")); return false; } - int firstId = 0; + int firstId = 0; localProgress = 0; while (true) { - if(wasStopped()) + if (wasStopped()) { - q.prepare("DETACH rs_source"); //Cleanup + q.prepare("DETACH rs_source"); // Cleanup q.step(); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return false; @@ -164,8 +161,8 @@ bool LoadSQLiteTask::copyOwners() q_getFirstIdGreaterThan.bind(1, firstId); q_getFirstIdGreaterThan.step(); - if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) - break; //No more owners to import + if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) + break; // No more owners to import firstId = sqlite3_column_int(stmt, 0); q_getFirstIdGreaterThan.reset(); @@ -181,7 +178,7 @@ bool LoadSQLiteTask::copyOwners() sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); } - localProgress = 0; //Advance by 1 step, clear partial progress + localProgress = 0; // Advance by 1 step, clear partial progress currentProgress += StepSize; sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); return true; @@ -189,51 +186,54 @@ bool LoadSQLiteTask::copyOwners() bool LoadSQLiteTask::copyModels() { - if((importMode & RSImportMode::ImportRSModels) == 0) - return true; //Skip models importation + if ((importMode & RSImportMode::ImportRSModels) == 0) + return true; // Skip models importation sqlite3pp::query q(mDb); sqlite3pp::query q_getFirstIdGreaterThan(mDb); - //Calculate maximum number of batches + // Calculate maximum number of batches q.prepare("SELECT MAX(id) FROM rs_source.rs_models"); q.step(); localCount = sqlite3_column_int(q.stmt(), 0); - localCount = localCount/LoadTaskUtils::BatchSize + (localCount % LoadTaskUtils::BatchSize != 0); //Round up - if(localCount < 1) - localCount = 1; //At least 1 batch + localCount = localCount / LoadTaskUtils::BatchSize + + (localCount % LoadTaskUtils::BatchSize != 0); // Round up + if (localCount < 1) + localCount = 1; // At least 1 batch - //Init query: get first id to import + // Init query: get first id to import int ret = q_getFirstIdGreaterThan.prepare("SELECT MIN(id) FROM rs_source.rs_models WHERE id>?"); sqlite3_stmt *stmt = q_getFirstIdGreaterThan.stmt(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed B1.")); return false; } - ret = q.prepare("INSERT OR IGNORE INTO main.imported_rs_models(id, name, suffix, import, new_name, match_existing_id, max_speed, axes, type, sub_type)" - " SELECT NULL,mod1.name,mod1.suffix,1,NULL,mod2.id,mod1.max_speed,mod1.axes,mod1.type,mod1.sub_type" - " FROM rs_source.rs_models AS mod1" - " LEFT JOIN main.rs_models mod2 ON mod1.name=mod2.name AND mod1.suffix=mod2.suffix" - " WHERE mod1.id BETWEEN ? AND ?"); - if(ret != SQLITE_OK) + ret = q.prepare( + "INSERT OR IGNORE INTO main.imported_rs_models(id, name, suffix, import, new_name, " + "match_existing_id, max_speed, axes, type, sub_type)" + " SELECT " + "NULL,mod1.name,mod1.suffix,1,NULL,mod2.id,mod1.max_speed,mod1.axes,mod1.type,mod1.sub_type" + " FROM rs_source.rs_models AS mod1" + " LEFT JOIN main.rs_models mod2 ON mod1.name=mod2.name AND mod1.suffix=mod2.suffix" + " WHERE mod1.id BETWEEN ? AND ?"); + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed B2.")); return false; } - int firstId = 0; + int firstId = 0; localProgress = 0; while (true) { - if(wasStopped()) + if (wasStopped()) { - q.prepare("DETACH rs_source"); //Cleanup + q.prepare("DETACH rs_source"); // Cleanup q.step(); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return false; @@ -241,8 +241,8 @@ bool LoadSQLiteTask::copyModels() q_getFirstIdGreaterThan.bind(1, firstId); q_getFirstIdGreaterThan.step(); - if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) - break; //No more models to import + if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) + break; // No more models to import firstId = sqlite3_column_int(stmt, 0); q_getFirstIdGreaterThan.reset(); @@ -258,7 +258,7 @@ bool LoadSQLiteTask::copyModels() sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); } - localProgress = 0; //Advance by 1 step, clear partial progress + localProgress = 0; // Advance by 1 step, clear partial progress currentProgress += StepSize; sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); return true; @@ -266,54 +266,56 @@ bool LoadSQLiteTask::copyModels() bool LoadSQLiteTask::copyRS() { - if((importMode & RSImportMode::ImportRSPieces) == 0) - return true; //Skip RS importation + if ((importMode & RSImportMode::ImportRSPieces) == 0) + return true; // Skip RS importation sqlite3pp::query q(mDb); sqlite3pp::query q_getFirstIdGreaterThan(mDb); - //Calculate maximum number of batches + // Calculate maximum number of batches q.prepare("SELECT MAX(id) FROM rs_source.rs_models"); q.step(); localCount = sqlite3_column_int(q.stmt(), 0); - localCount = localCount/LoadTaskUtils::BatchSize + (localCount % LoadTaskUtils::BatchSize != 0); //Round up - if(localCount < 1) - localCount = 1; //At least 1 batch + localCount = localCount / LoadTaskUtils::BatchSize + + (localCount % LoadTaskUtils::BatchSize != 0); // Round up + if (localCount < 1) + localCount = 1; // At least 1 batch - //Init query: get first id to import + // Init query: get first id to import int ret = q_getFirstIdGreaterThan.prepare("SELECT MIN(id) FROM rs_source.rs_models WHERE id>?"); sqlite3_stmt *stmt = q_getFirstIdGreaterThan.stmt(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed C1.")); return false; } - ret = q.prepare("INSERT OR IGNORE INTO main.imported_rs_list(id, import, model_id, owner_id, number, new_number)" - " SELECT NULL,1,mod2.id,own2.id,rs.number % 10000,NULL" - " FROM rs_source.rs_list AS rs" - " LEFT JOIN rs_source.rs_models mod1 ON mod1.id=rs.model_id" - " LEFT JOIN main.imported_rs_models mod2 ON mod1.name=mod2.name AND mod1.suffix=mod2.suffix" - " LEFT JOIN rs_source.rs_owners own1 ON own1.id=rs.owner_id" - " LEFT JOIN main.imported_rs_owners own2 ON own1.name=own2.name" - " WHERE mod1.id BETWEEN ? AND ?"); - if(ret != SQLITE_OK) + ret = q.prepare( + "INSERT OR IGNORE INTO main.imported_rs_list(id, import, model_id, owner_id, number, " + "new_number)" + " SELECT NULL,1,mod2.id,own2.id,rs.number % 10000,NULL" + " FROM rs_source.rs_list AS rs" + " LEFT JOIN rs_source.rs_models mod1 ON mod1.id=rs.model_id" + " LEFT JOIN main.imported_rs_models mod2 ON mod1.name=mod2.name AND mod1.suffix=mod2.suffix" + " LEFT JOIN rs_source.rs_owners own1 ON own1.id=rs.owner_id" + " LEFT JOIN main.imported_rs_owners own2 ON own1.name=own2.name" + " WHERE mod1.id BETWEEN ? AND ?"); + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed C2.")); return false; } - int firstId = 0; + int firstId = 0; localProgress = 0; while (true) { - if(wasStopped()) + if (wasStopped()) { - q.prepare("DETACH rs_source"); //Cleanup + q.prepare("DETACH rs_source"); // Cleanup q.step(); - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return false; @@ -321,8 +323,8 @@ bool LoadSQLiteTask::copyRS() q_getFirstIdGreaterThan.bind(1, firstId); q_getFirstIdGreaterThan.step(); - if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) - break; //No more RS to import + if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) + break; // No more RS to import firstId = sqlite3_column_int(stmt, 0); q_getFirstIdGreaterThan.reset(); @@ -338,7 +340,7 @@ bool LoadSQLiteTask::copyRS() sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); } - localProgress = 0; //Advance by 1 step, clear partial progress + localProgress = 0; // Advance by 1 step, clear partial progress currentProgress += StepSize; sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); return true; @@ -349,18 +351,19 @@ bool LoadSQLiteTask::unselectOwnersWithNoRS() sqlite3pp::query q(mDb); sqlite3pp::query q_getFirstIdGreaterThan(mDb); - //Calculate maximum number of batches + // Calculate maximum number of batches q.prepare("SELECT MAX(id) FROM imported_rs_owners"); q.step(); localCount = sqlite3_column_int(q.stmt(), 0); - localCount = localCount/LoadTaskUtils::BatchSize + (localCount % LoadTaskUtils::BatchSize != 0); //Round up - if(localCount < 1) - localCount = 1; //At least 1 batch + localCount = localCount / LoadTaskUtils::BatchSize + + (localCount % LoadTaskUtils::BatchSize != 0); // Round up + if (localCount < 1) + localCount = 1; // At least 1 batch - //Init query: get first id to query + // Init query: get first id to query int ret = q_getFirstIdGreaterThan.prepare("SELECT MIN(id) FROM imported_rs_owners WHERE id>?"); sqlite3_stmt *stmt = q_getFirstIdGreaterThan.stmt(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed C1.")); return false; @@ -373,21 +376,20 @@ bool LoadSQLiteTask::unselectOwnersWithNoRS() " WHERE own.id BETWEEN ? AND ?" " GROUP BY own.id" " HAVING COUNT(rs.id)=0)"); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { endWithDbError(LoadTaskUtils::tr("Query preparation failed C2.")); return false; } - int firstId = 0; + int firstId = 0; localProgress = 0; while (true) { - if(wasStopped()) + if (wasStopped()) { - //No cleanup, already done after importing RS - sendEvent(new LoadProgressEvent(this, - LoadProgressEvent::ProgressAbortedByUser, + // No cleanup, already done after importing RS + sendEvent(new LoadProgressEvent(this, LoadProgressEvent::ProgressAbortedByUser, LoadProgressEvent::ProgressMaxFinished), true); return false; @@ -395,8 +397,8 @@ bool LoadSQLiteTask::unselectOwnersWithNoRS() q_getFirstIdGreaterThan.bind(1, firstId); q_getFirstIdGreaterThan.step(); - if(sqlite3_column_type(stmt, 0) == SQLITE_NULL) - break; //No more owners to edit + if (sqlite3_column_type(stmt, 0) == SQLITE_NULL) + break; // No more owners to edit firstId = sqlite3_column_int(stmt, 0); q_getFirstIdGreaterThan.reset(); @@ -412,7 +414,7 @@ bool LoadSQLiteTask::unselectOwnersWithNoRS() sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); } - localProgress = 0; //Advance by 1 step, clear partial progress + localProgress = 0; // Advance by 1 step, clear partial progress currentProgress += StepSize; sendEvent(new LoadProgressEvent(this, calcProgress(), MaxProgress), false); return true; diff --git a/src/rollingstock/importer/backends/sqlite/loadsqlitetask.h b/src/rollingstock/importer/backends/sqlite/loadsqlitetask.h index 33dcc88..2613265 100644 --- a/src/rollingstock/importer/backends/sqlite/loadsqlitetask.h +++ b/src/rollingstock/importer/backends/sqlite/loadsqlitetask.h @@ -30,18 +30,25 @@ class LoadSQLiteTask : public ILoadRSTask { public: - //5 steps - //Load DB, Load Owners, Load Models, Load RS, Unselect Owners - enum { StepSize = 100, MaxProgress = 5 * StepSize }; + // 5 steps + // Load DB, Load Owners, Load Models, Load RS, Unselect Owners + enum + { + StepSize = 100, + MaxProgress = 5 * StepSize + }; - LoadSQLiteTask(sqlite3pp::database &db, int mode, const QString& fileName, QObject *receiver); + LoadSQLiteTask(sqlite3pp::database &db, int mode, const QString &fileName, QObject *receiver); void run() override; private: - void endWithDbError(const QString& text); + void endWithDbError(const QString &text); - inline int calcProgress() const { return currentProgress + localProgress / localCount * StepSize; } + inline int calcProgress() const + { + return currentProgress + localProgress / localCount * StepSize; + } bool attachDB(); bool copyOwners(); diff --git a/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.cpp b/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.cpp index 8b79e20..0c715ae 100644 --- a/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.cpp +++ b/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.cpp @@ -26,7 +26,6 @@ RSImportSQLiteBackend::RSImportSQLiteBackend() { - } QString RSImportSQLiteBackend::getBackendName() @@ -39,9 +38,10 @@ IOptionsWidget *RSImportSQLiteBackend::createOptionsWidget() return new SQLiteOptionsWidget(nullptr); } -ILoadRSTask *RSImportSQLiteBackend::createLoadTask(const QMap &arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString &fileName, QObject *receiver) +ILoadRSTask *RSImportSQLiteBackend::createLoadTask(const QMap &arguments, + sqlite3pp::database &db, int mode, int defSpeed, + RsType defType, const QString &fileName, + QObject *receiver) { Q_UNUSED(arguments) Q_UNUSED(defSpeed) diff --git a/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.h b/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.h index 555eb67..17f43fb 100644 --- a/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.h +++ b/src/rollingstock/importer/backends/sqlite/rsimportsqlitebackend.h @@ -31,9 +31,9 @@ public: IOptionsWidget *createOptionsWidget() override; - ILoadRSTask *createLoadTask(const QMap& arguments, sqlite3pp::database &db, - int mode, int defSpeed, RsType defType, - const QString& fileName, QObject *receiver) override; + ILoadRSTask *createLoadTask(const QMap &arguments, sqlite3pp::database &db, + int mode, int defSpeed, RsType defType, const QString &fileName, + QObject *receiver) override; }; #endif // RSIMPORTSQLITEBACKEND_H diff --git a/src/rollingstock/importer/backends/sqlite/sqliteoptionswidget.cpp b/src/rollingstock/importer/backends/sqlite/sqliteoptionswidget.cpp index 6e8d47e..1671ace 100644 --- a/src/rollingstock/importer/backends/sqlite/sqliteoptionswidget.cpp +++ b/src/rollingstock/importer/backends/sqlite/sqliteoptionswidget.cpp @@ -27,22 +27,21 @@ SQLiteOptionsWidget::SQLiteOptionsWidget(QWidget *parent) : IOptionsWidget(parent) { - //SQLite Option + // SQLite Option QVBoxLayout *lay = new QVBoxLayout(this); - lay->addWidget(new QLabel(tr("Import rollingstock pieces, models and owners from another MRTPlanner session file.\n" - "The file must be a valid MRTPlanner session of recent version\n" - "Extension: (*.ttt)"))); + lay->addWidget(new QLabel( + tr("Import rollingstock pieces, models and owners from another MRTPlanner session file.\n" + "The file must be a valid MRTPlanner session of recent version\n" + "Extension: (*.ttt)"))); lay->setAlignment(Qt::AlignTop | Qt::AlignRight); } -void SQLiteOptionsWidget::loadSettings(const QMap &/*settings*/) +void SQLiteOptionsWidget::loadSettings(const QMap & /*settings*/) { - } -void SQLiteOptionsWidget::saveSettings(QMap &/*settings*/) +void SQLiteOptionsWidget::saveSettings(QMap & /*settings*/) { - } void SQLiteOptionsWidget::getFileDialogOptions(QString &title, QStringList &fileFormats) diff --git a/src/rollingstock/importer/intefaces/icheckname.cpp b/src/rollingstock/importer/intefaces/icheckname.cpp index 9757f82..293c4fb 100644 --- a/src/rollingstock/importer/intefaces/icheckname.cpp +++ b/src/rollingstock/importer/intefaces/icheckname.cpp @@ -21,7 +21,6 @@ ICheckName::~ICheckName() { - } bool ICheckName::checkCustomNameValid(db_id, const QString &, const QString &, QString *) @@ -29,7 +28,7 @@ bool ICheckName::checkCustomNameValid(db_id, const QString &, const QString &, Q return false; } -bool ICheckName::checkNewNumberIsValid(db_id, db_id, db_id, RsType , int, int, QString *) +bool ICheckName::checkNewNumberIsValid(db_id, db_id, db_id, RsType, int, int, QString *) { return false; } diff --git a/src/rollingstock/importer/intefaces/icheckname.h b/src/rollingstock/importer/intefaces/icheckname.h index 8af4c26..c4fbf02 100644 --- a/src/rollingstock/importer/intefaces/icheckname.h +++ b/src/rollingstock/importer/intefaces/icheckname.h @@ -28,11 +28,14 @@ class ICheckName public: virtual ~ICheckName(); - //For models and Owners - virtual bool checkCustomNameValid(db_id importedId, const QString& originalName, const QString& newCustomName, QString *errMsgOut); + // For models and Owners + virtual bool checkCustomNameValid(db_id importedId, const QString &originalName, + const QString &newCustomName, QString *errMsgOut); - //For RS - virtual bool checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, db_id matchExistingModelId, RsType rsType, int number, int newNumber, QString *errMsgOut); + // For RS + virtual bool checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, + db_id matchExistingModelId, RsType rsType, int number, + int newNumber, QString *errMsgOut); }; #endif // ICHECKNAME_H diff --git a/src/rollingstock/importer/intefaces/iduplicatesitemevent.cpp b/src/rollingstock/importer/intefaces/iduplicatesitemevent.cpp index 585eba5..8f37aa8 100644 --- a/src/rollingstock/importer/intefaces/iduplicatesitemevent.cpp +++ b/src/rollingstock/importer/intefaces/iduplicatesitemevent.cpp @@ -27,5 +27,4 @@ IDuplicatesItemEvent::IDuplicatesItemEvent(QRunnable *self, int pr, int m, int c ducplicatesCount(count), state(st) { - } diff --git a/src/rollingstock/importer/intefaces/iduplicatesitemevent.h b/src/rollingstock/importer/intefaces/iduplicatesitemevent.h index 09782a7..6d10c7c 100644 --- a/src/rollingstock/importer/intefaces/iduplicatesitemevent.h +++ b/src/rollingstock/importer/intefaces/iduplicatesitemevent.h @@ -32,9 +32,9 @@ public: enum { - ProgressError = -1, + ProgressError = -1, ProgressAbortedByUser = -2, - ProgressMaxFinished = -3 + ProgressMaxFinished = -3 }; static constexpr Type _Type = Type(CustomEvents::RsImportCheckDuplicates); diff --git a/src/rollingstock/importer/intefaces/iduplicatesitemmodel.cpp b/src/rollingstock/importer/intefaces/iduplicatesitemmodel.cpp index 992666e..a022110 100644 --- a/src/rollingstock/importer/intefaces/iduplicatesitemmodel.cpp +++ b/src/rollingstock/importer/intefaces/iduplicatesitemmodel.cpp @@ -34,12 +34,11 @@ IDuplicatesItemModel::IDuplicatesItemModel(sqlite3pp::database &db, QObject *par mState(Loaded), cachedCount(-1) { - } IDuplicatesItemModel::~IDuplicatesItemModel() { - if(mTask) + if (mTask) { mTask->stop(); mTask->cleanup(); @@ -49,22 +48,22 @@ IDuplicatesItemModel::~IDuplicatesItemModel() bool IDuplicatesItemModel::event(QEvent *e) { - if(e->type() == IDuplicatesItemEvent::_Type) + if (e->type() == IDuplicatesItemEvent::_Type) { IDuplicatesItemEvent *ev = static_cast(e); - if(mTask == ev->task) + if (mTask == ev->task) { QString errText; - if(ev->max == IDuplicatesItemEvent::ProgressMaxFinished) + if (ev->max == IDuplicatesItemEvent::ProgressMaxFinished) { - if(ev->progress == IDuplicatesItemEvent::ProgressError) + if (ev->progress == IDuplicatesItemEvent::ProgressError) { - //FIXME: add error QString in base IQuittableTask + // FIXME: add error QString in base IQuittableTask - //errText = loadTask->getErrorText(); + // errText = loadTask->getErrorText(); cachedCount = -1; } - else if(ev->progress != IDuplicatesItemEvent::ProgressAbortedByUser) + else if (ev->progress != IDuplicatesItemEvent::ProgressAbortedByUser) { handleResult(mTask); cachedCount = ev->ducplicatesCount; @@ -73,7 +72,7 @@ bool IDuplicatesItemModel::event(QEvent *e) mState = Loaded; emit stateChanged(mState); - if(ev->progress == IDuplicatesItemEvent::ProgressAbortedByUser) + if (ev->progress == IDuplicatesItemEvent::ProgressAbortedByUser) { emit processAborted(); } @@ -82,21 +81,22 @@ bool IDuplicatesItemModel::event(QEvent *e) emit progressFinished(); } - if(ev->progress == IDuplicatesItemEvent::ProgressError) + if (ev->progress == IDuplicatesItemEvent::ProgressError) { - //Emit error after finishing + // Emit error after finishing emit error(errText); } - //Delete task before handling event because otherwise it is detected as still running + // Delete task before handling event because otherwise it is detected as still + // running delete mTask; mTask = nullptr; } else { - if(mState != ev->state) + if (mState != ev->state) { - mState = State(ev->state); + mState = State(ev->state); cachedCount = ev->ducplicatesCount; emit stateChanged(mState); } @@ -107,7 +107,9 @@ bool IDuplicatesItemModel::event(QEvent *e) return QAbstractItemModel::event(e); } -IDuplicatesItemModel *IDuplicatesItemModel::createModel(ModelModes::Mode mode, sqlite3pp::database &db, ICheckName *iface, QObject *parent) +IDuplicatesItemModel *IDuplicatesItemModel::createModel(ModelModes::Mode mode, + sqlite3pp::database &db, ICheckName *iface, + QObject *parent) { switch (mode) { @@ -123,15 +125,15 @@ IDuplicatesItemModel *IDuplicatesItemModel::createModel(ModelModes::Mode mode, s bool IDuplicatesItemModel::startLoading(int mode) { - if(mState != Loaded) - return true; //Already started + if (mState != Loaded) + return true; // Already started mTask = createTask(mode); - if(!mTask) + if (!mTask) return false; cachedCount = -1; - mState = Starting; + mState = Starting; emit stateChanged(mState); QThreadPool::globalInstance()->start(mTask); @@ -140,10 +142,10 @@ bool IDuplicatesItemModel::startLoading(int mode) void IDuplicatesItemModel::cancelLoading() { - if(mState == Loaded) - return; //No active process + if (mState == Loaded) + return; // No active process - //TODO: wait finished? + // TODO: wait finished? mTask->stop(); mTask->cleanup(); mTask = nullptr; diff --git a/src/rollingstock/importer/intefaces/iduplicatesitemmodel.h b/src/rollingstock/importer/intefaces/iduplicatesitemmodel.h index 843de4c..64e7fb4 100644 --- a/src/rollingstock/importer/intefaces/iduplicatesitemmodel.h +++ b/src/rollingstock/importer/intefaces/iduplicatesitemmodel.h @@ -49,12 +49,16 @@ public: bool event(QEvent *e) override; - static IDuplicatesItemModel *createModel(ModelModes::Mode mode, sqlite3pp::database &db, ICheckName *iface, QObject *parent = nullptr); + static IDuplicatesItemModel *createModel(ModelModes::Mode mode, sqlite3pp::database &db, + ICheckName *iface, QObject *parent = nullptr); - inline State getState() const { return mState; } + inline State getState() const + { + return mState; + } inline int getItemCount() const { - if(mState == Loaded || mState == LoadingData) + if (mState == Loaded || mState == LoadingData) return cachedCount; return -1; } @@ -63,14 +67,14 @@ public: void cancelLoading(); signals: - void error(const QString& text); + void error(const QString &text); void stateChanged(int state); void progressChanged(int progress, int max); void progressFinished(); void processAborted(); protected: - virtual IQuittableTask* createTask(int mode) = 0; + virtual IQuittableTask *createTask(int mode) = 0; virtual void handleResult(IQuittableTask *task) = 0; protected: diff --git a/src/rollingstock/importer/intefaces/irsimportmodel.cpp b/src/rollingstock/importer/intefaces/irsimportmodel.cpp index 4d33792..28988fc 100644 --- a/src/rollingstock/importer/intefaces/irsimportmodel.cpp +++ b/src/rollingstock/importer/intefaces/irsimportmodel.cpp @@ -22,5 +22,4 @@ IRsImportModel::IRsImportModel(sqlite3pp::database &db, QObject *parent) : IPagedItemModel(500, db, parent) { - } diff --git a/src/rollingstock/importer/model/duplicatesimporteditemsmodel.cpp b/src/rollingstock/importer/model/duplicatesimporteditemsmodel.cpp index 481b6f2..94b9539 100644 --- a/src/rollingstock/importer/model/duplicatesimporteditemsmodel.cpp +++ b/src/rollingstock/importer/model/duplicatesimporteditemsmodel.cpp @@ -36,12 +36,12 @@ public: QVector items; ModelModes::Mode m_mode; - inline DuplicatesImportedItemsModelTask(sqlite3pp::database &db, ModelModes::Mode mode, QObject *receiver) : + inline DuplicatesImportedItemsModelTask(sqlite3pp::database &db, ModelModes::Mode mode, + QObject *receiver) : IQuittableTask(receiver), m_mode(mode), mDb(db) { - } void run() override @@ -49,36 +49,38 @@ public: QElapsedTimer timer; timer.start(); - int count = -1; + int count = -1; IDuplicatesItemModel::State state = IDuplicatesItemModel::CountingItems; - if(wasStopped()) + if (wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, + state), true); return; } - //Inform model that task is started - int max = 100; + // Inform model that task is started + int max = 100; int progress = 0; sendEvent(new IDuplicatesItemEvent(this, progress, max, count, state), false); - //Count how many items - QByteArray sql = "SELECT COUNT(imp.id)," - " (CASE WHEN imp.new_name NOT NULL THEN imp.new_name ELSE imp.name END) AS name1," - " (CASE WHEN dup.new_name NOT NULL THEN dup.new_name ELSE dup.name END) AS name2" - " FROM %1 imp" - " JOIN %1 dup ON dup.id<>imp.id AND %2 name1=name2" - " WHERE imp.match_existing_id IS NULL AND imp.import=1 AND dup.import=1"; - if(m_mode == ModelModes::Models) + // Count how many items + QByteArray sql = + "SELECT COUNT(imp.id)," + " (CASE WHEN imp.new_name NOT NULL THEN imp.new_name ELSE imp.name END) AS name1," + " (CASE WHEN dup.new_name NOT NULL THEN dup.new_name ELSE dup.name END) AS name2" + " FROM %1 imp" + " JOIN %1 dup ON dup.id<>imp.id AND %2 name1=name2" + " WHERE imp.match_existing_id IS NULL AND imp.import=1 AND dup.import=1"; + if (m_mode == ModelModes::Models) { sql = sql.replace("%1", "imported_rs_models"); sql = sql.replace("%2", "imp.suffix=dup.suffix AND"); - }else{ + } + else + { sql = sql.replace("%1", "imported_rs_owners"); sql = sql.replace("%2", " "); } @@ -87,33 +89,32 @@ public: q.step(); count = q.getRows().get(0); - if(wasStopped()) + if (wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, + state), true); return; } - if(count == 0) + if (count == 0) { - //No data to load, finish + // No data to load, finish state = IDuplicatesItemModel::Loaded; - sendEvent(new IDuplicatesItemEvent(this, progress, IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent( + this, progress, IDuplicatesItemEvent::ProgressMaxFinished, count, state), true); return; } - //Now load data - state = IDuplicatesItemModel::LoadingData; - max = count + 10; + // Now load data + state = IDuplicatesItemModel::LoadingData; + max = count + 10; progress = 10; - //Do not send event if the process is fast - if(timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) + // Do not send event if the process is fast + if (timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) sendEvent(new IDuplicatesItemEvent(this, progress, max, count, state), false); items.reserve(count); @@ -125,12 +126,14 @@ public: " JOIN %1 dup ON dup.id<>imp.id AND %3 name1=name2" " WHERE imp.match_existing_id IS NULL AND imp.import=1 AND dup.import=1" " ORDER BY imp.name"; - if(m_mode == ModelModes::Models) + if (m_mode == ModelModes::Models) { sql = sql.replace("%1", "imported_rs_models"); sql = sql.replace("%2", " "); sql = sql.replace("%3", "imp.suffix=dup.suffix AND"); - }else{ + } + else + { sql = sql.replace("%1", "imported_rs_owners"); sql = sql.replace("%2", "imp.sheet_idx,"); sql = sql.replace("%3", " "); @@ -138,40 +141,41 @@ public: q.prepare(sql); - //Send about 5 progress events during loading (but process at least 5 items between 2 events) + // Send about 5 progress events during loading (but process at least 5 items between 2 + // events) const int sentTreshold = qMax(5, max / 5); - for(auto r : q) + for (auto r : q) { - if(progress % 8 == 0 && wasStopped()) + if (progress % 8 == 0 && wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), - true); + sendEvent( + new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, state), + true); return; } - if(progress % sentTreshold && timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) + if (progress % sentTreshold + && timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) { - //It's time to report our progress + // It's time to report our progress sendEvent(new IDuplicatesItemEvent(this, progress, max, count, state), false); } DuplicatesImportedItemsModel::DuplicatedItem item; - item.importedId = r.get(0); + item.importedId = r.get(0); item.originalName = r.get(1); - item.customName = r.get(2); - item.sheetIdx = m_mode == ModelModes::Owners ? r.get(3) : 0; - item.import = true; + item.customName = r.get(2); + item.sheetIdx = m_mode == ModelModes::Owners ? r.get(3) : 0; + item.import = true; items.append(item); } state = IDuplicatesItemModel::Loaded; - sendEvent(new IDuplicatesItemEvent(this, progress, IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, progress, + IDuplicatesItemEvent::ProgressMaxFinished, count, state), true); } @@ -179,19 +183,21 @@ private: sqlite3pp::database &mDb; }; -DuplicatesImportedItemsModel::DuplicatesImportedItemsModel(ModelModes::Mode mode, database &db, ICheckName *i, QObject *parent): +DuplicatesImportedItemsModel::DuplicatesImportedItemsModel(ModelModes::Mode mode, database &db, + ICheckName *i, QObject *parent) : IDuplicatesItemModel(db, parent), iface(i), m_mode(mode) { } -QVariant DuplicatesImportedItemsModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant DuplicatesImportedItemsModel::headerData(int section, Qt::Orientation orientation, + int role) const { - if(orientation == Qt::Horizontal && role == Qt::DisplayRole) + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - if(m_mode == ModelModes::Models && section >= SheetIdx) - section++; //Skip SheetIdx for Models + if (m_mode == ModelModes::Models && section >= SheetIdx) + section++; // Skip SheetIdx for Models switch (section) { @@ -221,13 +227,13 @@ int DuplicatesImportedItemsModel::columnCount(const QModelIndex &parent) const QVariant DuplicatesImportedItemsModel::data(const QModelIndex &idx, int role) const { int col = idx.column(); - if(m_mode == ModelModes::Models && col >= SheetIdx) - col++; //Skip SheetIdx for Models + if (m_mode == ModelModes::Models && col >= SheetIdx) + col++; // Skip SheetIdx for Models if (!idx.isValid() || idx.row() >= items.size() || col >= NCols) return QVariant(); - const DuplicatedItem& item = items.at(idx.row()); + const DuplicatedItem &item = items.at(idx.row()); switch (role) { @@ -246,19 +252,19 @@ QVariant DuplicatesImportedItemsModel::data(const QModelIndex &idx, int role) co } case Qt::EditRole: { - if(col == CustomName) + if (col == CustomName) return item.customName; break; } case Qt::BackgroundRole: { - if(!item.import || (idx.column() == CustomName && item.customName.isEmpty())) + if (!item.import || (idx.column() == CustomName && item.customName.isEmpty())) return QBrush(Qt::lightGray); break; } case Qt::CheckStateRole: { - if(col == Import) + if (col == Import) return item.import ? Qt::Checked : Qt::Unchecked; break; } @@ -269,44 +275,42 @@ QVariant DuplicatesImportedItemsModel::data(const QModelIndex &idx, int role) co bool DuplicatesImportedItemsModel::setData(const QModelIndex &idx, const QVariant &value, int role) { int col = idx.column(); - if(m_mode == ModelModes::Models && col >= SheetIdx) - col++; //Skip SheetIdx for Models + if (m_mode == ModelModes::Models && col >= SheetIdx) + col++; // Skip SheetIdx for Models if (!idx.isValid() || idx.row() >= items.size()) return false; - QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex first = idx; + QModelIndex last = idx; - DuplicatedItem& item =items[idx.row()]; + DuplicatedItem &item = items[idx.row()]; switch (role) { case Qt::EditRole: { - if(col == CustomName) + if (col == CustomName) { QString newName = value.toString().simplified(); - if(item.customName == newName) + if (item.customName == newName) return false; QString errText; - if(!iface->checkCustomNameValid(item.importedId, item.originalName, newName, &errText)) + if (!iface->checkCustomNameValid(item.importedId, item.originalName, newName, &errText)) { emit error(errText); return false; } - const char *sql[NModes] = { - "UPDATE imported_rs_owners SET new_name=? WHERE id=?", + const char *sql[NModes] = {"UPDATE imported_rs_owners SET new_name=? WHERE id=?", - "UPDATE imported_rs_models SET new_name=? WHERE id=?" - }; + "UPDATE imported_rs_models SET new_name=? WHERE id=?"}; command set_name(mDb, sql[m_mode]); set_name.bind(1, newName); set_name.bind(2, item.importedId); - if(set_name.execute() != SQLITE_OK) + if (set_name.execute() != SQLITE_OK) return false; item.customName = newName; @@ -315,41 +319,40 @@ bool DuplicatesImportedItemsModel::setData(const QModelIndex &idx, const QVarian } case Qt::CheckStateRole: { - if(col == Import) + if (col == Import) { Qt::CheckState cs = value.value(); const bool import = cs == Qt::Checked; - if(item.import == import) - return false; //No change + if (item.import == import) + return false; // No change - if(import) + if (import) { - //Newly imported, check if there are duplicates + // Newly imported, check if there are duplicates QString errText; - if(!iface->checkCustomNameValid(item.importedId, item.originalName, item.customName, &errText)) + if (!iface->checkCustomNameValid(item.importedId, item.originalName, + item.customName, &errText)) { emit error(errText); return false; } } - const char *sql[NModes] = { - "UPDATE imported_rs_owners SET import=? WHERE id=?", + const char *sql[NModes] = {"UPDATE imported_rs_owners SET import=? WHERE id=?", - "UPDATE imported_rs_models SET import=? WHERE id=?" - }; + "UPDATE imported_rs_models SET import=? WHERE id=?"}; command set_imported(mDb, sql[m_mode]); set_imported.bind(1, import ? 1 : 0); set_imported.bind(2, item.importedId); - if(set_imported.execute() != SQLITE_OK) + if (set_imported.execute() != SQLITE_OK) return false; item.import = import; - //Update all columns to update background + // Update all columns to update background first = index(idx.row(), 0); - //Do not use NCols because in Models mode SheetIdx is hidden + // Do not use NCols because in Models mode SheetIdx is hidden last = index(idx.row(), columnCount()); } break; @@ -366,12 +369,12 @@ Qt::ItemFlags DuplicatesImportedItemsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; - int col = idx.column(); - if(m_mode == ModelModes::Models && col >= SheetIdx) - col++; //Skip SheetIdx for Models - if(col == Import) + int col = idx.column(); + if (m_mode == ModelModes::Models && col >= SheetIdx) + col++; // Skip SheetIdx for Models + if (col == Import) f.setFlag(Qt::ItemIsUserCheckable); - if(col == CustomName) + if (col == CustomName) f.setFlag(Qt::ItemIsEditable); return f; @@ -379,7 +382,7 @@ Qt::ItemFlags DuplicatesImportedItemsModel::flags(const QModelIndex &idx) const IQuittableTask *DuplicatesImportedItemsModel::createTask(int mode) { - Q_UNUSED(mode) //Only 1 mode possible + Q_UNUSED(mode) // Only 1 mode possible return new DuplicatesImportedItemsModelTask(mDb, m_mode, this); } diff --git a/src/rollingstock/importer/model/duplicatesimporteditemsmodel.h b/src/rollingstock/importer/model/duplicatesimporteditemsmodel.h index a69c3a1..6926542 100644 --- a/src/rollingstock/importer/model/duplicatesimporteditemsmodel.h +++ b/src/rollingstock/importer/model/duplicatesimporteditemsmodel.h @@ -38,7 +38,8 @@ class DuplicatesImportedItemsModel : public IDuplicatesItemModel Q_OBJECT public: - enum{ + enum + { NModes = 2 }; @@ -60,12 +61,14 @@ public: bool import; }; - DuplicatesImportedItemsModel(ModelModes::Mode mode, database &db, ICheckName *i, QObject *parent = nullptr); + DuplicatesImportedItemsModel(ModelModes::Mode mode, database &db, ICheckName *i, + QObject *parent = nullptr); // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -74,14 +77,13 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; protected: // IDuplicatesItemModel - IQuittableTask* createTask(int mode) override; + IQuittableTask *createTask(int mode) override; void handleResult(IQuittableTask *task) override; private: diff --git a/src/rollingstock/importer/model/duplicatesimportedrsmodel.cpp b/src/rollingstock/importer/model/duplicatesimportedrsmodel.cpp index 74a465b..781c8d8 100644 --- a/src/rollingstock/importer/model/duplicatesimportedrsmodel.cpp +++ b/src/rollingstock/importer/model/duplicatesimportedrsmodel.cpp @@ -31,7 +31,6 @@ #include - class DuplicatesImportedRSModelTask : public IQuittableTask { public: @@ -48,209 +47,214 @@ public: { timer.start(); - int count = -1; + int count = -1; IDuplicatesItemModel::State state = IDuplicatesItemModel::CountingItems; - if(wasStopped()) + if (wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, + state), true); return; } - //Inform model that task is started - int max = 100; + // Inform model that task is started + int max = 100; int progress = 0; sendEvent(new IDuplicatesItemEvent(this, progress++, max, count, state), false); - if(fixItemsWithSameValues) + if (fixItemsWithSameValues) execFixItemsWithSameValues(); - //Count how many items - query q(mDb, "SELECT COUNT(1) FROM (" - "SELECT (CASE WHEN imp.new_number NOT NULL THEN imp.new_number ELSE imp.number END) AS num," - " (CASE WHEN dup.new_number NOT NULL THEN dup.new_number ELSE dup.number END) AS dup_num" - " FROM imported_rs_list imp" - " JOIN imported_rs_models mod1 ON mod1.id=imp.model_id" - " JOIN imported_rs_owners own1 ON own1.id=imp.owner_id" + // Count how many items + query q( + mDb, + "SELECT COUNT(1) FROM (" + "SELECT (CASE WHEN imp.new_number NOT NULL THEN imp.new_number ELSE imp.number END) AS " + "num," + " (CASE WHEN dup.new_number NOT NULL THEN dup.new_number ELSE dup.number END) AS dup_num" + " FROM imported_rs_list imp" + " JOIN imported_rs_models mod1 ON mod1.id=imp.model_id" + " JOIN imported_rs_owners own1 ON own1.id=imp.owner_id" - " LEFT JOIN imported_rs_list dup ON dup.id<>imp.id" - " LEFT JOIN imported_rs_models mod2 ON mod2.id=dup.model_id" - " LEFT JOIN imported_rs_owners own2 ON own2.id=dup.owner_id" - " LEFT JOIN rs_list ON rs_list.model_id=mod1.match_existing_id" - " WHERE own1.import AND mod1.import AND imp.import=1 AND" - " (" - " rs_list.number=num OR" - " (" - " (" - " imp.model_id=dup.model_id OR" - " (" - " mod1.match_existing_id NOT NULL AND mod1.match_existing_id=mod2.match_existing_id" - " )" - " )" - " AND num=dup_num AND own2.import=1 AND mod2.import=1 AND dup.import=1" - " )" - " )" - " GROUP BY imp.id)"); + " LEFT JOIN imported_rs_list dup ON dup.id<>imp.id" + " LEFT JOIN imported_rs_models mod2 ON mod2.id=dup.model_id" + " LEFT JOIN imported_rs_owners own2 ON own2.id=dup.owner_id" + " LEFT JOIN rs_list ON rs_list.model_id=mod1.match_existing_id" + " WHERE own1.import AND mod1.import AND imp.import=1 AND" + " (" + " rs_list.number=num OR" + " (" + " (" + " imp.model_id=dup.model_id OR" + " (" + " mod1.match_existing_id NOT NULL AND mod1.match_existing_id=mod2.match_existing_id" + " )" + " )" + " AND num=dup_num AND own2.import=1 AND mod2.import=1 AND dup.import=1" + " )" + " )" + " GROUP BY imp.id)"); q.step(); count = q.getRows().get(0); - if(wasStopped()) + if (wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, + state), true); return; } - if(count == 0) + if (count == 0) { - //No data to load, finish + // No data to load, finish state = IDuplicatesItemModel::Loaded; - sendEvent(new IDuplicatesItemEvent(this, progress, IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent( + this, progress, IDuplicatesItemEvent::ProgressMaxFinished, count, state), true); return; } - //Now load data - state = IDuplicatesItemModel::LoadingData; - max = count + 10; + // Now load data + state = IDuplicatesItemModel::LoadingData; + max = count + 10; progress = 10; - //Do not send event if the process is fast - if(timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) + // Do not send event if the process is fast + if (timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) sendEvent(new IDuplicatesItemEvent(this, progress, max, count, state), false); items.reserve(count); - q.prepare("SELECT imp.id, mod1.id, mod1.match_existing_id, mod1.type," - " mod1.name, mod1.new_name, rs_models.name, rs_models.type," - " imp.number, imp.new_number," - " own1.name, own1.new_name, rs_owners.name," - " (CASE WHEN imp.new_number NOT NULL THEN imp.new_number ELSE imp.number END) AS num," - " (CASE WHEN dup.new_number NOT NULL THEN dup.new_number ELSE dup.number END) AS dup_num" - " FROM imported_rs_list imp" - " JOIN imported_rs_models mod1 ON mod1.id=imp.model_id" - " JOIN imported_rs_owners own1 ON own1.id=imp.owner_id" + q.prepare( + "SELECT imp.id, mod1.id, mod1.match_existing_id, mod1.type," + " mod1.name, mod1.new_name, rs_models.name, rs_models.type," + " imp.number, imp.new_number," + " own1.name, own1.new_name, rs_owners.name," + " (CASE WHEN imp.new_number NOT NULL THEN imp.new_number ELSE imp.number END) AS num," + " (CASE WHEN dup.new_number NOT NULL THEN dup.new_number ELSE dup.number END) AS dup_num" + " FROM imported_rs_list imp" + " JOIN imported_rs_models mod1 ON mod1.id=imp.model_id" + " JOIN imported_rs_owners own1 ON own1.id=imp.owner_id" - " LEFT JOIN imported_rs_list dup ON dup.id<>imp.id" - " LEFT JOIN imported_rs_models mod2 ON mod2.id=dup.model_id" - " LEFT JOIN imported_rs_owners own2 ON own2.id=dup.owner_id" - " LEFT JOIN rs_list ON rs_list.model_id=mod1.match_existing_id" + " LEFT JOIN imported_rs_list dup ON dup.id<>imp.id" + " LEFT JOIN imported_rs_models mod2 ON mod2.id=dup.model_id" + " LEFT JOIN imported_rs_owners own2 ON own2.id=dup.owner_id" + " LEFT JOIN rs_list ON rs_list.model_id=mod1.match_existing_id" - " LEFT JOIN rs_owners ON rs_owners.id=own1.match_existing_id" - " LEFT JOIN rs_models ON rs_models.id=mod1.match_existing_id" + " LEFT JOIN rs_owners ON rs_owners.id=own1.match_existing_id" + " LEFT JOIN rs_models ON rs_models.id=mod1.match_existing_id" - " WHERE own1.import AND mod1.import AND imp.import=1 AND" - " (" - " rs_list.number=num OR" - " (" - " (" - " imp.model_id=dup.model_id OR" - " (" - " mod1.match_existing_id NOT NULL AND mod1.match_existing_id=mod2.match_existing_id" - " )" - " )" - " AND num=dup_num AND own2.import=1 AND mod2.import=1 AND dup.import=1" - " )" - " )" - " GROUP BY imp.id" - " ORDER BY mod1.name, imp.number, own1.name"); + " WHERE own1.import AND mod1.import AND imp.import=1 AND" + " (" + " rs_list.number=num OR" + " (" + " (" + " imp.model_id=dup.model_id OR" + " (" + " mod1.match_existing_id NOT NULL AND mod1.match_existing_id=mod2.match_existing_id" + " )" + " )" + " AND num=dup_num AND own2.import=1 AND mod2.import=1 AND dup.import=1" + " )" + " )" + " GROUP BY imp.id" + " ORDER BY mod1.name, imp.number, own1.name"); sqlite3_stmt *st = q.stmt(); - //Send about 5 progress events during loading (but process at least 5 items between 2 events) + // Send about 5 progress events during loading (but process at least 5 items between 2 + // events) const int sentTreshold = qMax(5, max / 5); - for(auto r : q) + for (auto r : q) { - if(progress % 8 == 0 && wasStopped()) + if (progress % 8 == 0 && wasStopped()) { - sendEvent(new IDuplicatesItemEvent(this, - IDuplicatesItemEvent::ProgressAbortedByUser, - IDuplicatesItemEvent::ProgressMaxFinished, - count, state), - true); + sendEvent( + new IDuplicatesItemEvent(this, IDuplicatesItemEvent::ProgressAbortedByUser, + IDuplicatesItemEvent::ProgressMaxFinished, count, state), + true); return; } - if(progress % sentTreshold && timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) + if (progress % sentTreshold + && timer.elapsed() > IDuplicatesItemEvent::MinimumMSecsBeforeFirstEvent) { - //It's time to report our progress + // It's time to report our progress sendEvent(new IDuplicatesItemEvent(this, progress, max, count, state), false); } DuplicatesImportedRSModel::DuplicatedItem item; - item.importedId = r.get(0); + item.importedId = r.get(0); item.importedModelId = r.get(1); - //Model + // Model item.matchExistingModelId = r.get(2); - item.type = RsType(r.get(3)); - item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 4)), + item.type = RsType(r.get(3)); + item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 4)), sqlite3_column_bytes(st, 4)); - if(r.column_type(5) != SQLITE_NULL) + if (r.column_type(5) != SQLITE_NULL) { // 'name (new_name)' item.modelName.append(" (", 2); - item.modelName.append(reinterpret_cast(sqlite3_column_text(st, 5)), + item.modelName.append(reinterpret_cast(sqlite3_column_text(st, 5)), sqlite3_column_bytes(st, 5)); item.modelName.append(')'); } - if(r.column_type(6) != SQLITE_NULL) + if (r.column_type(6) != SQLITE_NULL) { // 'name (match_existing name)' - QByteArray tmp = QByteArray::fromRawData(reinterpret_cast(sqlite3_column_text(st, 6)), - sqlite3_column_bytes(st, 6)); + QByteArray tmp = QByteArray::fromRawData( + reinterpret_cast(sqlite3_column_text(st, 6)), + sqlite3_column_bytes(st, 6)); - if(tmp != item.modelName) + if (tmp != item.modelName) { item.modelName.append(" (", 2); item.modelName.append(tmp); item.modelName.append(')'); } - //Prefer matched model type when available + // Prefer matched model type when available item.type = RsType(r.get(7)); } - //Number + // Number item.number = r.get(8); - if(r.column_type(9) == SQLITE_NULL) + if (r.column_type(9) == SQLITE_NULL) item.new_number = -1; else item.new_number = r.get(9); - item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 10)), + item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 10)), sqlite3_column_bytes(st, 10)); - if(r.column_type(11) != SQLITE_NULL) + if (r.column_type(11) != SQLITE_NULL) { // 'name (new_name)' item.ownerName.append(" (", 2); - item.ownerName.append(reinterpret_cast(sqlite3_column_text(st, 11)), + item.ownerName.append(reinterpret_cast(sqlite3_column_text(st, 11)), sqlite3_column_bytes(st, 11)); item.ownerName.append(')'); } - if(r.column_type(12) != SQLITE_NULL) + if (r.column_type(12) != SQLITE_NULL) { // 'name (match_existing name)' - QByteArray tmp = QByteArray::fromRawData(reinterpret_cast(sqlite3_column_text(st, 12)), - sqlite3_column_bytes(st, 12)); + QByteArray tmp = QByteArray::fromRawData( + reinterpret_cast(sqlite3_column_text(st, 12)), + sqlite3_column_bytes(st, 12)); - if(tmp != item.ownerName) + if (tmp != item.ownerName) { item.ownerName.append(" (", 2); item.ownerName.append(tmp); item.ownerName.append(')'); } } - item.import = true; //Only imported items get selected so import is true + item.import = true; // Only imported items get selected so import is true items.append(item); @@ -258,18 +262,18 @@ public: } state = IDuplicatesItemModel::Loaded; - sendEvent(new IDuplicatesItemEvent(this, progress, IDuplicatesItemEvent::ProgressMaxFinished, - count, state), + sendEvent(new IDuplicatesItemEvent(this, progress, + IDuplicatesItemEvent::ProgressMaxFinished, count, state), true); } void execFixItemsWithSameValues() { - //If 2 (or mode) rollingstock items have - //same model and same number and same owner - //pick one of them and discart the other(s) - //TODO: implement and add button to FixDuplicatesDlg to trigger this mode - //And re-evalue progress values + // If 2 (or mode) rollingstock items have + // same model and same number and same owner + // pick one of them and discart the other(s) + // TODO: implement and add button to FixDuplicatesDlg to trigger this mode + // And re-evalue progress values } private: @@ -278,16 +282,16 @@ private: bool fixItemsWithSameValues; }; -DuplicatesImportedRSModel::DuplicatesImportedRSModel(database &db, ICheckName *i, QObject *parent): +DuplicatesImportedRSModel::DuplicatesImportedRSModel(database &db, ICheckName *i, QObject *parent) : IDuplicatesItemModel(db, parent), iface(i) { - } -QVariant DuplicatesImportedRSModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant DuplicatesImportedRSModel::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) { @@ -321,7 +325,7 @@ QVariant DuplicatesImportedRSModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= items.size() || idx.column() >= NCols) return QVariant(); - const DuplicatedItem& item = items.at(idx.row()); + const DuplicatedItem &item = items.at(idx.row()); switch (role) { @@ -334,7 +338,8 @@ QVariant DuplicatesImportedRSModel::data(const QModelIndex &idx, int role) const case Number: return rs_utils::formatNum(item.type, item.number); case NewNumber: - return item.new_number == -1 ? QVariant() : rs_utils::formatNum(item.type, item.new_number); + return item.new_number == -1 ? QVariant() + : rs_utils::formatNum(item.type, item.new_number); case OwnerName: return item.ownerName; } @@ -342,19 +347,19 @@ QVariant DuplicatesImportedRSModel::data(const QModelIndex &idx, int role) const } case Qt::EditRole: { - if(idx.column() == NewNumber) + if (idx.column() == NewNumber) return item.new_number; break; } case Qt::TextAlignmentRole: { - if(idx.column() == Number || idx.column() == NewNumber) + if (idx.column() == Number || idx.column() == NewNumber) return Qt::AlignRight + Qt::AlignVCenter; break; } case Qt::BackgroundRole: { - if(!item.import || (idx.column() == NewNumber && item.new_number == -1)) + if (!item.import || (idx.column() == NewNumber && item.new_number == -1)) return QBrush(Qt::lightGray); break; } @@ -376,34 +381,35 @@ bool DuplicatesImportedRSModel::setData(const QModelIndex &idx, const QVariant & if (!idx.isValid() || idx.row() >= items.size()) return false; - DuplicatedItem& item =items[idx.row()]; + DuplicatedItem &item = items[idx.row()]; switch (role) { case Qt::EditRole: { - if(idx.column() == NewNumber) + if (idx.column() == NewNumber) { int newNumber = value.toInt(); - if(item.new_number == newNumber) + if (item.new_number == newNumber) return false; QString errText; - if(!iface->checkNewNumberIsValid(item.importedId, item.importedModelId, item.matchExistingModelId, - item.type, item.number, newNumber, &errText)) + if (!iface->checkNewNumberIsValid(item.importedId, item.importedModelId, + item.matchExistingModelId, item.type, item.number, + newNumber, &errText)) { emit error(errText); return false; } command set_newNumber(mDb, "UPDATE imported_rs_list SET new_number=? WHERE id=?"); - if(newNumber == -1) - set_newNumber.bind(1); //Bind NULL + if (newNumber == -1) + set_newNumber.bind(1); // Bind NULL else set_newNumber.bind(1, newNumber); set_newNumber.bind(2, item.importedId); - if(set_newNumber.execute() != SQLITE_OK) + if (set_newNumber.execute() != SQLITE_OK) return false; item.new_number = newNumber; @@ -413,19 +419,20 @@ bool DuplicatesImportedRSModel::setData(const QModelIndex &idx, const QVariant & } case Qt::CheckStateRole: { - if(idx.column() == Import) + if (idx.column() == Import) { Qt::CheckState cs = value.value(); const bool import = cs == Qt::Checked; - if(item.import == import) - return false; //No change + if (item.import == import) + return false; // No change - if(import) + if (import) { - //Newly imported, check if there are duplicates + // Newly imported, check if there are duplicates QString errText; - if(!iface->checkNewNumberIsValid(item.importedId, item.importedModelId, item.matchExistingModelId, - item.type, item.number, item.new_number, &errText)) + if (!iface->checkNewNumberIsValid(item.importedId, item.importedModelId, + item.matchExistingModelId, item.type, item.number, + item.new_number, &errText)) { emit error(errText); return false; @@ -435,14 +442,14 @@ bool DuplicatesImportedRSModel::setData(const QModelIndex &idx, const QVariant & command set_imported(mDb, "UPDATE imported_rs_list SET import=? WHERE id=?"); set_imported.bind(1, import ? 1 : 0); set_imported.bind(2, item.importedId); - if(set_imported.execute() != SQLITE_OK) + if (set_imported.execute() != SQLITE_OK) return false; item.import = import; - //Update all columns to update background + // Update all columns to update background QModelIndex first = index(idx.row(), 0); - QModelIndex last = index(idx.row(), NCols - 1); + QModelIndex last = index(idx.row(), NCols - 1); emit dataChanged(first, last); } break; @@ -458,9 +465,9 @@ Qt::ItemFlags DuplicatesImportedRSModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; - if(idx.column() == NewNumber) + if (idx.column() == NewNumber) f.setFlag(Qt::ItemIsEditable); - else if(idx.column() == Import) + else if (idx.column() == Import) f.setFlag(Qt::ItemIsUserCheckable); return f; diff --git a/src/rollingstock/importer/model/duplicatesimportedrsmodel.h b/src/rollingstock/importer/model/duplicatesimportedrsmodel.h index 3abad39..09b3bdb 100644 --- a/src/rollingstock/importer/model/duplicatesimportedrsmodel.h +++ b/src/rollingstock/importer/model/duplicatesimportedrsmodel.h @@ -63,7 +63,8 @@ public: DuplicatesImportedRSModel(database &db, ICheckName *i, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -72,14 +73,13 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; protected: // IDuplicatesItemModel - IQuittableTask* createTask(int mode) override; + IQuittableTask *createTask(int mode) override; void handleResult(IQuittableTask *task) override; private: diff --git a/src/rollingstock/importer/model/rsimportedmodelsmodel.cpp b/src/rollingstock/importer/model/rsimportedmodelsmodel.cpp index 7b7f061..a3da0dd 100644 --- a/src/rollingstock/importer/model/rsimportedmodelsmodel.cpp +++ b/src/rollingstock/importer/model/rsimportedmodelsmodel.cpp @@ -36,7 +36,10 @@ class ModelsResultEvent : public QEvent { public: static constexpr Type _Type = Type(CustomEvents::RsImportedModelsResult); - inline ModelsResultEvent() : QEvent(_Type) {} + inline ModelsResultEvent() : + QEvent(_Type) + { + } QVector items; int firstRow; @@ -52,7 +55,7 @@ RSImportedModelsModel::RSImportedModelsModel(database &db, QObject *parent) : bool RSImportedModelsModel::event(QEvent *e) { - if(e->type() == ModelsResultEvent::_Type) + if (e->type() == ModelsResultEvent::_Type) { ModelsResultEvent *ev = static_cast(e); ev->setAccepted(true); @@ -67,33 +70,33 @@ bool RSImportedModelsModel::event(QEvent *e) void RSImportedModelsModel::fetchRow(int row) { - if(row >= firstPendingRow && row < firstPendingRow + BatchSize) - return; //Already fetching + if (row >= firstPendingRow && row < firstPendingRow + BatchSize) + return; // Already fetching - if(row >= cacheFirstRow && row < cacheFirstRow + cache.size()) - return; //Already cached + if (row >= cacheFirstRow && row < cacheFirstRow + cache.size()) + return; // Already cached - //TODO: abort fetching here + // TODO: abort fetching here const int remainder = row % BatchSize; - firstPendingRow = row - remainder; + firstPendingRow = row - remainder; qDebug() << "Requested:" << row << "From:" << firstPendingRow; QVariant val; - int valRow = 0; + int valRow = 0; ModelItem *item = nullptr; - if(cache.size()) + if (cache.size()) { - if(firstPendingRow >= cacheFirstRow + cache.size()) + if (firstPendingRow >= cacheFirstRow + cache.size()) { valRow = cacheFirstRow + cache.size(); - item = &cache.last(); + item = &cache.last(); } - else if(firstPendingRow > (cacheFirstRow - firstPendingRow)) + else if (firstPendingRow > (cacheFirstRow - firstPendingRow)) { valRow = cacheFirstRow; - item = &cache.first(); + item = &cache.first(); } } @@ -101,41 +104,45 @@ void RSImportedModelsModel::fetchRow(int row) { case Name: { - if(item) + if (item) { val = item->name; } break; } - //No data hint for other columns + // No data hint for other columns } - //TODO: use a custom QRunnable + // TODO: use a custom QRunnable QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection, Q_ARG(int, firstPendingRow), Q_ARG(int, sortColumn), Q_ARG(int, valRow), Q_ARG(QVariant, val)); } -void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, const QVariant& val) +void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, const QVariant &val) { query q(mDb); - int offset = first - valRow; + int offset = first - valRow; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - //FIXME: maybe show cyan background if there aren't RS of this model (like if owner or RS is not imported), and do the same for owners + // FIXME: maybe show cyan background if there aren't RS of this model (like if owner or RS is + // not imported), and do the same for owners - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; - QByteArray sql = "SELECT imp.id,imp.name,imp.suffix,imp.import,imp.new_name,imp.match_existing_id,rs_models.name," - " imp.max_speed,imp.axes,imp.type,imp.sub_type" - " FROM imported_rs_models imp LEFT JOIN rs_models ON rs_models.id=imp.match_existing_id"; + QByteArray sql = + "SELECT " + "imp.id,imp.name,imp.suffix,imp.import,imp.new_name,imp.match_existing_id,rs_models.name," + " imp.max_speed,imp.axes,imp.type,imp.sub_type" + " FROM imported_rs_models imp LEFT JOIN rs_models ON rs_models.id=imp.match_existing_id"; const char *sortColExpr = nullptr; switch (sortCol) @@ -147,7 +154,7 @@ void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, co } case Import: { - sortColExpr = "imp.import DESC, imp.name"; //Order by 2 columns, no where clause + sortColExpr = "imp.import DESC, imp.name"; // Order by 2 columns, no where clause break; } case MaxSpeedCol: @@ -162,16 +169,16 @@ void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, co } case TypeCol: { - sortColExpr = "imp.type,imp.sub_type"; //Order by 2 columns, no where clause + sortColExpr = "imp.type,imp.sub_type"; // Order by 2 columns, no where clause break; } } - if(val.isValid()) + if (val.isValid()) { sql += " WHERE "; sql += sortColExpr; - if(reverse) + if (reverse) sql += "?3"; @@ -180,19 +187,19 @@ void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, co sql += " ORDER BY "; sql += sortColExpr; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); - if(val.isValid()) + if (val.isValid()) { switch (sortCol) { @@ -206,81 +213,80 @@ void RSImportedModelsModel::internalFetch(int first, int sortCol, int valRow, co QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - if(reverse) + if (reverse) { int i = BatchSize - 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - ModelItem &item = vec[i]; + auto r = *it; + ModelItem &item = vec[i]; item.importdModelId = r.get(0); - item.name = r.get(1); - item.suffix = r.get(2); - item.import = r.get(3) != 0; - if(r.column_type(4) != SQLITE_NULL) + item.name = r.get(1); + item.suffix = r.get(2); + item.import = r.get(3) != 0; + if (r.column_type(4) != SQLITE_NULL) item.customName = r.get(4); item.matchExistingId = r.get(5); - if(item.matchExistingId) + if (item.matchExistingId) item.matchExistingName = r.get(6); item.maxSpeedKmH = qint16(r.get(7)); - item.axes = qint8(r.get(8)); - item.type = RsType(r.get(9)); - item.subType = RsEngineSubType(r.get(10)); + item.axes = qint8(r.get(8)); + item.type = RsType(r.get(9)); + item.subType = RsEngineSubType(r.get(10)); i--; } - if(i > -1) + if (i > -1) vec.remove(0, i + 1); } else { int i = 0; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - ModelItem &item = vec[i]; + auto r = *it; + ModelItem &item = vec[i]; item.importdModelId = r.get(0); - item.name = r.get(1); - item.suffix = r.get(2); - item.import = r.get(3) != 0; - if(r.column_type(4) != SQLITE_NULL) + item.name = r.get(1); + item.suffix = r.get(2); + item.import = r.get(3) != 0; + if (r.column_type(4) != SQLITE_NULL) item.customName = r.get(4); item.matchExistingId = r.get(5); - if(item.matchExistingId) + if (item.matchExistingId) item.matchExistingName = r.get(6); item.maxSpeedKmH = qint16(r.get(7)); - item.axes = qint8(r.get(8)); - item.type = RsType(r.get(9)); - item.subType = RsEngineSubType(r.get(10)); + item.axes = qint8(r.get(8)); + item.type = RsType(r.get(9)); + item.subType = RsEngineSubType(r.get(10)); i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); } - ModelsResultEvent *ev = new ModelsResultEvent; - ev->items = vec; - ev->firstRow = first; + ev->items = vec; + ev->firstRow = first; qApp->postEvent(this, ev); } -void RSImportedModelsModel::handleResult(const QVector& items, int firstRow) +void RSImportedModelsModel::handleResult(const QVector &items, int firstRow) { - if(firstRow == cacheFirstRow + cache.size()) + if (firstRow == cacheFirstRow + cache.size()) { qDebug() << "RES: appending First:" << cacheFirstRow; cache.append(items); - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { - const int extra = cache.size() - ItemsPerPage; //Round up to BatchSize + const int extra = cache.size() - ItemsPerPage; // Round up to BatchSize const int remainder = extra % BatchSize; - const int n = remainder ? extra + BatchSize - remainder : extra; + const int n = remainder ? extra + BatchSize - remainder : extra; qDebug() << "RES: removing last" << n; cache.remove(0, n); cacheFirstRow += n; @@ -288,13 +294,13 @@ void RSImportedModelsModel::handleResult(const QVector& items, int fi } else { - if(firstRow + items.size() == cacheFirstRow) + if (firstRow + items.size() == cacheFirstRow) { qDebug() << "RES: prepending First:" << cacheFirstRow; QVector tmp = items; tmp.append(cache); cache = tmp; - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { const int n = cache.size() - ItemsPerPage; cache.remove(ItemsPerPage, n); @@ -310,10 +316,10 @@ void RSImportedModelsModel::handleResult(const QVector& items, int fi qDebug() << "NEW First:" << cacheFirstRow; } - firstPendingRow = -BatchSize; + firstPendingRow = -BatchSize; QModelIndex firstIdx = index(firstRow, 0); - QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); + QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); emit dataChanged(firstIdx, lastIdx); qDebug() << "TOTAL: From:" << cacheFirstRow << "To:" << cacheFirstRow + cache.size() - 1; @@ -321,7 +327,7 @@ void RSImportedModelsModel::handleResult(const QVector& items, int fi QVariant RSImportedModelsModel::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) { @@ -364,18 +370,18 @@ QVariant RSImportedModelsModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return QVariant("..."); } - const ModelItem& item = cache.at(row - cacheFirstRow); + const ModelItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -398,7 +404,7 @@ QVariant RSImportedModelsModel::data(const QModelIndex &idx, int role) const case TypeCol: return RsTypeNames::name(item.type); case SubTypeCol: - if(item.type != RsType::Engine) + if (item.type != RsType::Engine) break; return RsTypeNames::name(item.subType); } @@ -415,10 +421,10 @@ QVariant RSImportedModelsModel::data(const QModelIndex &idx, int role) const } case Qt::BackgroundRole: { - if(!item.import || - (idx.column() == CustomName && item.customName.isEmpty()) || - (idx.column() == MatchExisting && item.matchExistingId == 0)) - return QBrush(Qt::lightGray); //If not imported mark background or no custom/matching name set + if (!item.import || (idx.column() == CustomName && item.customName.isEmpty()) + || (idx.column() == MatchExisting && item.matchExistingId == 0)) + return QBrush( + Qt::lightGray); // If not imported mark background or no custom/matching name set break; } case Qt::CheckStateRole: @@ -438,12 +444,13 @@ QVariant RSImportedModelsModel::data(const QModelIndex &idx, int role) const bool RSImportedModelsModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - ModelItem &item = cache[row - cacheFirstRow]; + ModelItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -454,27 +461,28 @@ bool RSImportedModelsModel::setData(const QModelIndex &idx, const QVariant &valu case CustomName: { const QString newName = value.toString().simplified(); - if(item.customName == newName) - return false; //No change + if (item.customName == newName) + return false; // No change QString errText; - if(!checkCustomNameValid(item.importdModelId, item.name, newName, &errText)) + if (!checkCustomNameValid(item.importdModelId, item.name, newName, &errText)) { emit modelError(errText); return false; } - command set_name(mDb, "UPDATE imported_rs_models SET new_name=?,match_existing_id=NULL WHERE id=?"); + command set_name( + mDb, "UPDATE imported_rs_models SET new_name=?,match_existing_id=NULL WHERE id=?"); - if(newName.isEmpty()) - set_name.bind(1); //Bind NULL + if (newName.isEmpty()) + set_name.bind(1); // Bind NULL else set_name.bind(1, newName); set_name.bind(2, item.importdModelId); - if(set_name.execute() != SQLITE_OK) + if (set_name.execute() != SQLITE_OK) return false; - item.customName = newName; + item.customName = newName; item.matchExistingId = 0; item.matchExistingName.clear(); item.matchExistingName.squeeze(); @@ -496,14 +504,15 @@ bool RSImportedModelsModel::setData(const QModelIndex &idx, const QVariant &valu { Qt::CheckState cs = value.value(); const bool import = cs == Qt::Checked; - if(item.import == import) - return false; //No change + if (item.import == import) + return false; // No change - if(import) + if (import) { - //Newly imported, check for duplicates + // Newly imported, check for duplicates QString errText; - if(!checkCustomNameValid(item.importdModelId, item.name, item.customName, &errText)) + if (!checkCustomNameValid(item.importdModelId, item.name, item.customName, + &errText)) { emit modelError(errText); return false; @@ -513,25 +522,25 @@ bool RSImportedModelsModel::setData(const QModelIndex &idx, const QVariant &valu command set_imported(mDb, "UPDATE imported_rs_models SET import=? WHERE id=?"); set_imported.bind(1, import ? 1 : 0); set_imported.bind(2, item.importdModelId); - if(set_imported.execute() != SQLITE_OK) + if (set_imported.execute() != SQLITE_OK) return false; item.import = import; - if(sortColumn == Import) + if (sortColumn == Import) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } emit importCountChanged(); - //Update all columns to update background + // Update all columns to update background first = index(row, 0); - last = index(row, NCols - 1); + last = index(row, NCols - 1); break; } default: @@ -553,12 +562,12 @@ Qt::ItemFlags RSImportedModelsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == Import) + if (idx.column() == Import) f.setFlag(Qt::ItemIsUserCheckable); - if(idx.column() == CustomName || idx.column() == MatchExisting) + if (idx.column() == CustomName || idx.column() == MatchExisting) f.setFlag(Qt::ItemIsEditable); return f; @@ -583,14 +592,15 @@ void RSImportedModelsModel::clearCache() void RSImportedModelsModel::setSortingColumn(int col) { - if(sortColumn == col || col == CustomName || col == MatchExisting || col == SuffixCol || col == SubTypeCol) - return; //Do not sort by CustomName or MatchExisting (not useful and complicated) + if (sortColumn == col || col == CustomName || col == MatchExisting || col == SuffixCol + || col == SubTypeCol) + return; // Do not sort by CustomName or MatchExisting (not useful and complicated) clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -606,98 +616,109 @@ int RSImportedModelsModel::countImported() /* ICheckName */ -bool RSImportedModelsModel::checkCustomNameValid(db_id importedModelId, const QString& originalName, const QString& newCustomName, QString *errTextOut) +bool RSImportedModelsModel::checkCustomNameValid(db_id importedModelId, const QString &originalName, + const QString &newCustomName, QString *errTextOut) { - if(originalName == newCustomName) + if (originalName == newCustomName) { - if(errTextOut) + if (errTextOut) { - if(originalName.isEmpty()) + if (originalName.isEmpty()) + { + *errTextOut = tr("Models with empty name must have a Custom Name or must be " + "matched to an existing model"); + } + else { - *errTextOut = tr("Models with empty name must have a Custom Name or must be matched to an existing model"); - }else{ *errTextOut = tr("You cannot set the same name in the 'Custom Name' field.\n" - "If you meant to revert to original name then clear the custom name and leave the cell empty"); + "If you meant to revert to original name then clear the custom " + "name and leave the cell empty"); } } return false; } - //FIXME: maybe use EXISTS instead of WHERE for performance + // FIXME: maybe use EXISTS instead of WHERE for performance - //First check for duplicates + // First check for duplicates query q_nameDuplicates(mDb, "SELECT id FROM rs_models WHERE name=? LIMIT 1"); - //If removing custom name check against original sheet name + // If removing custom name check against original sheet name QString nameToCheck = newCustomName; - if(newCustomName.isEmpty()) + if (newCustomName.isEmpty()) nameToCheck = originalName; q_nameDuplicates.bind(1, nameToCheck); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { db_id modelId = q_nameDuplicates.getRows().get(0); - Q_UNUSED(modelId) //TODO: maybe use it? + Q_UNUSED(modelId) // TODO: maybe use it? - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("There is already an existing Model with same name: %1
" - "If you meant to merge theese rollingstock pieces with this existing model " - "please use 'Match Existing' field") - .arg(nameToCheck); + *errTextOut = + tr("There is already an existing Model with same name: %1
" + "If you meant to merge theese rollingstock pieces with this existing model " + "please use 'Match Existing' field") + .arg(nameToCheck); } return false; } - //Check also against other imported models original names (that don't have a custom name) - q_nameDuplicates.prepare("SELECT id FROM imported_rs_models WHERE name=? AND new_name IS NULL AND id<>? LIMIT 1"); + // Check also against other imported models original names (that don't have a custom name) + q_nameDuplicates.prepare( + "SELECT id FROM imported_rs_models WHERE name=? AND new_name IS NULL AND id<>? LIMIT 1"); q_nameDuplicates.bind(1, nameToCheck); q_nameDuplicates.bind(2, importedModelId); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { db_id modelId = q_nameDuplicates.getRows().get(0); - Q_UNUSED(modelId) //TODO: maybe use it? + Q_UNUSED(modelId) // TODO: maybe use it? - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("There is already an imported Model with name: %1
" - "If you meant to merge theese rollingstock pieces with this existing model " - "after importing rollingstock use the merge tool to merge them") - .arg(nameToCheck); + *errTextOut = + tr("There is already an imported Model with name: %1
" + "If you meant to merge theese rollingstock pieces with this existing model " + "after importing rollingstock use the merge tool to merge them") + .arg(nameToCheck); } return false; } - //Check also against other imported models custom names - q_nameDuplicates.prepare("SELECT id, name FROM imported_rs_models WHERE new_name=? AND id<>? LIMIT 1"); + // Check also against other imported models custom names + q_nameDuplicates.prepare( + "SELECT id, name FROM imported_rs_models WHERE new_name=? AND id<>? LIMIT 1"); q_nameDuplicates.bind(1, nameToCheck); q_nameDuplicates.bind(2, importedModelId); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { db_id modelId = q_nameDuplicates.getRows().get(0); - Q_UNUSED(modelId) //TODO: maybe use it? + Q_UNUSED(modelId) // TODO: maybe use it? QString otherOriginalName = q_nameDuplicates.getRows().get(1); - if(newCustomName.isEmpty()) + if (newCustomName.isEmpty()) { - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("You already gave the same custom name: %1
" - "to the imported model: %2
" - "In order to proceed you need to assign a different custom name to %2") - .arg(nameToCheck, otherOriginalName); + *errTextOut = + tr("You already gave the same custom name: %1
" + "to the imported model: %2
" + "In order to proceed you need to assign a different custom name to %2") + .arg(nameToCheck, otherOriginalName); } } else { - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("You already gave the same custom name: %1
" - "to the imported model: %2
" - "Please choose a different name or leave empty for the original name") - .arg(nameToCheck, otherOriginalName); + *errTextOut = + tr("You already gave the same custom name: %1
" + "to the imported model: %2
" + "Please choose a different name or leave empty for the original name") + .arg(nameToCheck, otherOriginalName); } } @@ -709,60 +730,64 @@ bool RSImportedModelsModel::checkCustomNameValid(db_id importedModelId, const QS /* IFKField */ -bool RSImportedModelsModel::getFieldData(int row, int /*col*/, db_id &modelIdOut, QString &modelNameOut) const +bool RSImportedModelsModel::getFieldData(int row, int /*col*/, db_id &modelIdOut, + QString &modelNameOut) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - const ModelItem& item = cache.at(row - cacheFirstRow); - modelIdOut = item.matchExistingId; - modelNameOut = item.matchExistingName; + const ModelItem &item = cache.at(row - cacheFirstRow); + modelIdOut = item.matchExistingId; + modelNameOut = item.matchExistingName; return true; } -bool RSImportedModelsModel::validateData(int /*row*/, int /*col*/, db_id /*modelId*/, const QString &/*modelName*/) +bool RSImportedModelsModel::validateData(int /*row*/, int /*col*/, db_id /*modelId*/, + const QString & /*modelName*/) { - return true; //TODO: implement + return true; // TODO: implement } -bool RSImportedModelsModel::setFieldData(int row, int /*col*/, db_id modelId, const QString &modelName) +bool RSImportedModelsModel::setFieldData(int row, int /*col*/, db_id modelId, + const QString &modelName) { - //NOTE: CustomName and MatchExisting exclude each other - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + // NOTE: CustomName and MatchExisting exclude each other + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - ModelItem& item = cache[row - cacheFirstRow]; - if(item.matchExistingId == modelId) - return true; //No change + ModelItem &item = cache[row - cacheFirstRow]; + if (item.matchExistingId == modelId) + return true; // No change - if(modelId == 0) + if (modelId == 0) { - //Check if we can leave it with no match and no custom name - //FIXME: if owner is matched and instead user wants to set a custom name - //but you can't remove the match because the name is a duplicate - //The user should set a custom name, it will automatically remove the match - //BUT we need to show a proper error test if just removing the match - //so add it to checkCustomNameValid() with like 'bool isMatchingOwner=true' argument + // Check if we can leave it with no match and no custom name + // FIXME: if owner is matched and instead user wants to set a custom name + // but you can't remove the match because the name is a duplicate + // The user should set a custom name, it will automatically remove the match + // BUT we need to show a proper error test if just removing the match + // so add it to checkCustomNameValid() with like 'bool isMatchingOwner=true' argument QString errText; - if(!checkCustomNameValid(item.importdModelId, item.name, QString(), &errText)) + if (!checkCustomNameValid(item.importdModelId, item.name, QString(), &errText)) { emit modelError(errText); return false; } } - command set_match(mDb, "UPDATE imported_rs_models SET new_name=NULL,match_existing_id=? WHERE id=?"); - if(modelId) + command set_match(mDb, + "UPDATE imported_rs_models SET new_name=NULL,match_existing_id=? WHERE id=?"); + if (modelId) set_match.bind(1, modelId); else - set_match.bind(1); //Bind NULL + set_match.bind(1); // Bind NULL set_match.bind(2, item.importdModelId); - if(set_match.execute() != SQLITE_OK) + if (set_match.execute() != SQLITE_OK) return false; - item.matchExistingId = modelId; + item.matchExistingId = modelId; item.matchExistingName = modelName; item.customName.clear(); item.customName.squeeze(); diff --git a/src/rollingstock/importer/model/rsimportedmodelsmodel.h b/src/rollingstock/importer/model/rsimportedmodelsmodel.h index bf33fbc..dfabdaa 100644 --- a/src/rollingstock/importer/model/rsimportedmodelsmodel.h +++ b/src/rollingstock/importer/model/rsimportedmodelsmodel.h @@ -34,7 +34,10 @@ class RSImportedModelsModel : public IRsImportModel, public IFKField Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; enum Columns { @@ -59,7 +62,7 @@ public: QString matchExistingName; QString suffix; qint16 maxSpeedKmH; - qint8 axes; + qint8 axes; RsType type; RsEngineSubType subType; bool import; @@ -72,7 +75,8 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -81,11 +85,9 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel @@ -95,14 +97,12 @@ public: // Sorting TODO: enable multiple columns sort/filter with custom QHeaderView virtual void setSortingColumn(int col) override; - // IRsImportModel: int countImported() override; - // ICheckName: - bool checkCustomNameValid(db_id importedModelId, const QString& originalName, const QString& newCustomName, - QString *errTextOut) override; + bool checkCustomNameValid(db_id importedModelId, const QString &originalName, + const QString &newCustomName, QString *errTextOut) override; // IFKField: bool getFieldData(int row, int col, db_id &modelIdOut, QString &modelNameOut) const override; @@ -114,8 +114,8 @@ protected: private: void fetchRow(int row); - Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant& val); - void handleResult(const QVector& items, int firstRow); + Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant &val); + void handleResult(const QVector &items, int firstRow); private: QVector cache; diff --git a/src/rollingstock/importer/model/rsimportedownersmodel.cpp b/src/rollingstock/importer/model/rsimportedownersmodel.cpp index eb5dea8..2280a20 100644 --- a/src/rollingstock/importer/model/rsimportedownersmodel.cpp +++ b/src/rollingstock/importer/model/rsimportedownersmodel.cpp @@ -34,7 +34,10 @@ class OwnerResultEvent : public QEvent { public: static constexpr Type _Type = Type(CustomEvents::RsImportedOwnersResult); - inline OwnerResultEvent() : QEvent(_Type) {} + inline OwnerResultEvent() : + QEvent(_Type) + { + } QVector items; int firstRow; @@ -50,7 +53,7 @@ RSImportedOwnersModel::RSImportedOwnersModel(database &db, QObject *parent) : bool RSImportedOwnersModel::event(QEvent *e) { - if(e->type() == OwnerResultEvent::_Type) + if (e->type() == OwnerResultEvent::_Type) { OwnerResultEvent *ev = static_cast(e); ev->setAccepted(true); @@ -65,37 +68,37 @@ bool RSImportedOwnersModel::event(QEvent *e) void RSImportedOwnersModel::fetchRow(int row) { - if(row >= firstPendingRow && row < firstPendingRow + BatchSize) - return; //Already fetching + if (row >= firstPendingRow && row < firstPendingRow + BatchSize) + return; // Already fetching - if(row >= cacheFirstRow && row < cacheFirstRow + cache.size()) - return; //Already cached + if (row >= cacheFirstRow && row < cacheFirstRow + cache.size()) + return; // Already cached - //TODO: abort fetching here + // TODO: abort fetching here const int remainder = row % BatchSize; - firstPendingRow = row - remainder; + firstPendingRow = row - remainder; qDebug() << "Requested:" << row << "From:" << firstPendingRow; - //NOTE: Sorting hint: - //because LIMIT ? OFFSET ? can be slow when offset is big - //we give an hint to reduce offset + // NOTE: Sorting hint: + // because LIMIT ? OFFSET ? can be slow when offset is big + // we give an hint to reduce offset QVariant val; - int valRow = 0; + int valRow = 0; OwnerItem *item = nullptr; - //We can give an hint only if we already have cached some data - if(cache.size()) + // We can give an hint only if we already have cached some data + if (cache.size()) { - if(firstPendingRow >= cacheFirstRow + cache.size()) + if (firstPendingRow >= cacheFirstRow + cache.size()) { valRow = cacheFirstRow + cache.size(); - item = &cache.last(); + item = &cache.last(); } - else if(firstPendingRow > (cacheFirstRow - firstPendingRow)) + else if (firstPendingRow > (cacheFirstRow - firstPendingRow)) { valRow = cacheFirstRow; - item = &cache.first(); + item = &cache.first(); } } @@ -103,7 +106,7 @@ void RSImportedOwnersModel::fetchRow(int row) { case SheetIdx: { - if(item) + if (item) { val = item->sheetIdx; } @@ -111,40 +114,43 @@ void RSImportedOwnersModel::fetchRow(int row) } case Name: { - if(item) + if (item) { val = item->name; } break; } - //No data hint for Import column + // No data hint for Import column } - //TODO: use a custom QRunnable + // TODO: use a custom QRunnable QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection, Q_ARG(int, firstPendingRow), Q_ARG(int, sortColumn), Q_ARG(int, valRow), Q_ARG(QVariant, val)); } -void RSImportedOwnersModel::internalFetch(int first, int sortCol, int valRow, const QVariant& val) +void RSImportedOwnersModel::internalFetch(int first, int sortCol, int valRow, const QVariant &val) { query q(mDb); - int offset = first - valRow; + int offset = first - valRow; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT imp.id,imp.name,imp.import,imp.new_name,imp.match_existing_id,imp.sheet_idx,rs_owners.name" - " FROM imported_rs_owners imp LEFT JOIN rs_owners ON rs_owners.id=imp.match_existing_id"; + QByteArray sql = + "SELECT " + "imp.id,imp.name,imp.import,imp.new_name,imp.match_existing_id,imp.sheet_idx,rs_owners.name" + " FROM imported_rs_owners imp LEFT JOIN rs_owners ON rs_owners.id=imp.match_existing_id"; switch (sortCol) { case SheetIdx: @@ -159,16 +165,16 @@ void RSImportedOwnersModel::internalFetch(int first, int sortCol, int valRow, co } case Import: { - whereCol = "imp.import DESC, imp.name"; //Order by 2 columns, no where clause + whereCol = "imp.import DESC, imp.name"; // Order by 2 columns, no where clause break; } } - if(val.isValid()) + if (val.isValid()) { sql += " WHERE "; sql += whereCol; - if(reverse) + if (reverse) sql += "?3"; @@ -177,19 +183,19 @@ void RSImportedOwnersModel::internalFetch(int first, int sortCol, int valRow, co sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); - if(val.isValid()) + if (val.isValid()) { switch (sortCol) { @@ -208,72 +214,72 @@ void RSImportedOwnersModel::internalFetch(int first, int sortCol, int valRow, co QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - if(reverse) + if (reverse) { int i = BatchSize - 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - OwnerItem &item = vec[i]; + auto r = *it; + OwnerItem &item = vec[i]; item.importedOwnerId = r.get(0); - item.name = r.get(1); - item.import = r.get(2) != 0; - if(r.column_type(3) != SQLITE_NULL) + item.name = r.get(1); + item.import = r.get(2) != 0; + if (r.column_type(3) != SQLITE_NULL) item.customName = r.get(3); item.matchExistingId = r.get(4); - item.sheetIdx = r.get(5); - if(item.matchExistingId) + item.sheetIdx = r.get(5); + if (item.matchExistingId) item.matchExistingName = r.get(6); i--; } - if(i > -1) + if (i > -1) vec.remove(0, i + 1); } else { int i = 0; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - OwnerItem &item = vec[i]; + auto r = *it; + OwnerItem &item = vec[i]; item.importedOwnerId = r.get(0); - item.name = r.get(1); - item.import = r.get(2) != 0; - if(r.column_type(3) != SQLITE_NULL) + item.name = r.get(1); + item.import = r.get(2) != 0; + if (r.column_type(3) != SQLITE_NULL) item.customName = r.get(3); item.matchExistingId = r.get(4); - item.sheetIdx = r.get(5); - if(item.matchExistingId) + item.sheetIdx = r.get(5); + if (item.matchExistingId) item.matchExistingName = r.get(6); i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); } OwnerResultEvent *ev = new OwnerResultEvent; - ev->items = vec; - ev->firstRow = first; + ev->items = vec; + ev->firstRow = first; qApp->postEvent(this, ev); } -void RSImportedOwnersModel::handleResult(const QVector& items, int firstRow) +void RSImportedOwnersModel::handleResult(const QVector &items, int firstRow) { - if(firstRow == cacheFirstRow + cache.size()) + if (firstRow == cacheFirstRow + cache.size()) { qDebug() << "RES: appending First:" << cacheFirstRow; cache.append(items); - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { - const int extra = cache.size() - ItemsPerPage; //Round up to BatchSize + const int extra = cache.size() - ItemsPerPage; // Round up to BatchSize const int remainder = extra % BatchSize; - const int n = remainder ? extra + BatchSize - remainder : extra; + const int n = remainder ? extra + BatchSize - remainder : extra; qDebug() << "RES: removing last" << n; cache.remove(0, n); cacheFirstRow += n; @@ -281,13 +287,13 @@ void RSImportedOwnersModel::handleResult(const QVector& items, int fi } else { - if(firstRow + items.size() == cacheFirstRow) + if (firstRow + items.size() == cacheFirstRow) { qDebug() << "RES: prepending First:" << cacheFirstRow; QVector tmp = items; tmp.append(cache); cache = tmp; - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { const int n = cache.size() - ItemsPerPage; cache.remove(ItemsPerPage, n); @@ -303,10 +309,10 @@ void RSImportedOwnersModel::handleResult(const QVector& items, int fi qDebug() << "NEW First:" << cacheFirstRow; } - firstPendingRow = -BatchSize; + firstPendingRow = -BatchSize; QModelIndex firstIdx = index(firstRow, 0); - QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); + QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); emit dataChanged(firstIdx, lastIdx); qDebug() << "TOTAL: From:" << cacheFirstRow << "To:" << cacheFirstRow + cache.size() - 1; @@ -316,7 +322,7 @@ void RSImportedOwnersModel::handleResult(const QVector& items, int fi QVariant RSImportedOwnersModel::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) { @@ -351,14 +357,14 @@ QVariant RSImportedOwnersModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return QVariant(); } @@ -371,7 +377,7 @@ QVariant RSImportedOwnersModel::data(const QModelIndex &idx, int role) const switch (idx.column()) { case SheetIdx: - return item.sheetIdx + 1; //1-based index (Start from 1) + return item.sheetIdx + 1; // 1-based index (Start from 1) case Name: return item.name; case CustomName: @@ -392,10 +398,10 @@ QVariant RSImportedOwnersModel::data(const QModelIndex &idx, int role) const } case Qt::BackgroundRole: { - if(!item.import || - (idx.column() == CustomName && item.customName.isEmpty()) || - (idx.column() == MatchExisting && item.matchExistingId == 0)) - return QBrush(Qt::lightGray); //If not imported mark background or no custom/matching name set + if (!item.import || (idx.column() == CustomName && item.customName.isEmpty()) + || (idx.column() == MatchExisting && item.matchExistingId == 0)) + return QBrush( + Qt::lightGray); // If not imported mark background or no custom/matching name set break; } case Qt::CheckStateRole: @@ -415,12 +421,13 @@ QVariant RSImportedOwnersModel::data(const QModelIndex &idx, int role) const bool RSImportedOwnersModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - OwnerItem &item = cache[row - cacheFirstRow]; + OwnerItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -431,27 +438,28 @@ bool RSImportedOwnersModel::setData(const QModelIndex &idx, const QVariant &valu case CustomName: { const QString newName = value.toString().simplified(); - if(item.customName == newName) - return false; //No change + if (item.customName == newName) + return false; // No change QString errText; - if(!checkCustomNameValid(item.importedOwnerId, item.name, newName, &errText)) + if (!checkCustomNameValid(item.importedOwnerId, item.name, newName, &errText)) { emit modelError(errText); return false; } - command set_name(mDb, "UPDATE imported_rs_owners SET new_name=?,match_existing_id=NULL WHERE id=?"); + command set_name( + mDb, "UPDATE imported_rs_owners SET new_name=?,match_existing_id=NULL WHERE id=?"); - if(newName.isEmpty()) - set_name.bind(1); //Bind NULL + if (newName.isEmpty()) + set_name.bind(1); // Bind NULL else set_name.bind(1, newName); set_name.bind(2, item.importedOwnerId); - if(set_name.execute() != SQLITE_OK) + if (set_name.execute() != SQLITE_OK) return false; - item.customName = newName; + item.customName = newName; item.matchExistingId = 0; item.matchExistingName.clear(); item.matchExistingName.squeeze(); @@ -473,14 +481,15 @@ bool RSImportedOwnersModel::setData(const QModelIndex &idx, const QVariant &valu { Qt::CheckState cs = value.value(); const bool import = cs == Qt::Checked; - if(item.import == import) - return false; //No change + if (item.import == import) + return false; // No change - if(import) + if (import) { - //Newly imported, check if there are duplicates + // Newly imported, check if there are duplicates QString errText; - if(!checkCustomNameValid(item.importedOwnerId, item.name, item.customName, &errText)) + if (!checkCustomNameValid(item.importedOwnerId, item.name, item.customName, + &errText)) { emit modelError(errText); return false; @@ -490,25 +499,25 @@ bool RSImportedOwnersModel::setData(const QModelIndex &idx, const QVariant &valu command set_imported(mDb, "UPDATE imported_rs_owners SET import=? WHERE id=?"); set_imported.bind(1, import ? 1 : 0); set_imported.bind(2, item.importedOwnerId); - if(set_imported.execute() != SQLITE_OK) + if (set_imported.execute() != SQLITE_OK) return false; item.import = import; - if(sortColumn == Import) + if (sortColumn == Import) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } emit importCountChanged(); - //Update all columns to update background + // Update all columns to update background first = index(row, 0); - last = index(row, NCols - 1); + last = index(row, NCols - 1); break; } default: @@ -530,12 +539,12 @@ Qt::ItemFlags RSImportedOwnersModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == Import) + if (idx.column() == Import) f.setFlag(Qt::ItemIsUserCheckable); - if(idx.column() == CustomName || idx.column() == MatchExisting) + if (idx.column() == CustomName || idx.column() == MatchExisting) f.setFlag(Qt::ItemIsEditable); return f; @@ -560,14 +569,14 @@ void RSImportedOwnersModel::clearCache() void RSImportedOwnersModel::setSortingColumn(int col) { - if(sortColumn == col || col == CustomName || col == MatchExisting) - return; //Do not sort by CustomName or MatchExisting (not useful and complicated) + if (sortColumn == col || col == CustomName || col == MatchExisting) + return; // Do not sort by CustomName or MatchExisting (not useful and complicated) clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -583,99 +592,110 @@ int RSImportedOwnersModel::countImported() /* ICheckName */ -bool RSImportedOwnersModel::checkCustomNameValid(db_id importedOwnerId, const QString& originalName, const QString& newCustomName, QString *errTextOut) +bool RSImportedOwnersModel::checkCustomNameValid(db_id importedOwnerId, const QString &originalName, + const QString &newCustomName, QString *errTextOut) { - if(originalName == newCustomName) + if (originalName == newCustomName) { - if(errTextOut) + if (errTextOut) { - if(originalName.isEmpty()) + if (originalName.isEmpty()) + { + *errTextOut = tr("Owners with empty name must have a Custom Name or must be " + "matched to an existing owner"); + } + else { - *errTextOut = tr("Owners with empty name must have a Custom Name or must be matched to an existing owner"); - }else{ *errTextOut = tr("You cannot set the same name in the 'Custom Name' field.\n" - "If you meant to revert to original name then clear the custom name and leave the cell empty"); + "If you meant to revert to original name then clear the custom " + "name and leave the cell empty"); } } return false; } - //FIXME: maybe use EXISTS instead of WHERE for performance + // FIXME: maybe use EXISTS instead of WHERE for performance - //First check for duplicates + // First check for duplicates query q_nameDuplicates(mDb, "SELECT id FROM rs_owners WHERE name=? LIMIT 1"); - //If removing custom name check against original sheet name + // If removing custom name check against original sheet name QString nameToCheck = newCustomName; - if(newCustomName.isEmpty()) + if (newCustomName.isEmpty()) nameToCheck = originalName; q_nameDuplicates.bind(1, nameToCheck); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { db_id ownerId = q_nameDuplicates.getRows().get(0); - Q_UNUSED(ownerId) //TODO: maybe use it? + Q_UNUSED(ownerId) // TODO: maybe use it? - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("There is already an existing Owner with same name: %1
" - "If you meant to merge theese rollingstock pieces with this existing owner " - "please use 'Match Existing' field") - .arg(nameToCheck); + *errTextOut = + tr("There is already an existing Owner with same name: %1
" + "If you meant to merge theese rollingstock pieces with this existing owner " + "please use 'Match Existing' field") + .arg(nameToCheck); } return false; } - //Check also against other imported owners original names (that don't have a custom name) - q_nameDuplicates.prepare("SELECT id FROM imported_rs_owners WHERE name=? AND new_name IS NULL AND id<>? LIMIT 1"); + // Check also against other imported owners original names (that don't have a custom name) + q_nameDuplicates.prepare( + "SELECT id FROM imported_rs_owners WHERE name=? AND new_name IS NULL AND id<>? LIMIT 1"); q_nameDuplicates.bind(1, nameToCheck); q_nameDuplicates.bind(2, importedOwnerId); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { db_id ownerId = q_nameDuplicates.getRows().get(0); - Q_UNUSED(ownerId) //TODO: maybe use it? + Q_UNUSED(ownerId) // TODO: maybe use it? - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("There is already an imported Owner with name: %1
" - "If you meant to merge theese rollingstock pieces with this existing owner " - "after importing rollingstock use the merge tool to merge them") - .arg(nameToCheck); + *errTextOut = + tr("There is already an imported Owner with name: %1
" + "If you meant to merge theese rollingstock pieces with this existing owner " + "after importing rollingstock use the merge tool to merge them") + .arg(nameToCheck); } return false; } - //Check also against other imported owners custom names - q_nameDuplicates.prepare("SELECT id, name FROM imported_rs_owners WHERE new_name=? AND id<>? LIMIT 1"); + // Check also against other imported owners custom names + q_nameDuplicates.prepare( + "SELECT id, name FROM imported_rs_owners WHERE new_name=? AND id<>? LIMIT 1"); q_nameDuplicates.bind(1, nameToCheck); q_nameDuplicates.bind(2, importedOwnerId); - if(q_nameDuplicates.step() == SQLITE_ROW) + if (q_nameDuplicates.step() == SQLITE_ROW) { - auto r = q_nameDuplicates.getRows(); + auto r = q_nameDuplicates.getRows(); db_id ownerId = r.get(0); - Q_UNUSED(ownerId) //TODO: maybe use it? + Q_UNUSED(ownerId) // TODO: maybe use it? QString otherOriginalName = r.get(1); - if(newCustomName.isEmpty()) + if (newCustomName.isEmpty()) { - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("You already gave the same custom name: %1
" - "to the imported owner: %2
" - "In order to proceed you need to assign a different custom name to %2") - .arg(nameToCheck, otherOriginalName); + *errTextOut = + tr("You already gave the same custom name: %1
" + "to the imported owner: %2
" + "In order to proceed you need to assign a different custom name to %2") + .arg(nameToCheck, otherOriginalName); } } else { - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("You already gave the same custom name: %1
" - "to the imported owner: %2
" - "Please choose a different name or leave empty for the original name") - .arg(nameToCheck, otherOriginalName); + *errTextOut = + tr("You already gave the same custom name: %1
" + "to the imported owner: %2
" + "Please choose a different name or leave empty for the original name") + .arg(nameToCheck, otherOriginalName); } } @@ -687,60 +707,64 @@ bool RSImportedOwnersModel::checkCustomNameValid(db_id importedOwnerId, const QS /* IFKField */ -bool RSImportedOwnersModel::getFieldData(int row, int /*col*/, db_id &ownerIdOut, QString &ownerNameOut) const +bool RSImportedOwnersModel::getFieldData(int row, int /*col*/, db_id &ownerIdOut, + QString &ownerNameOut) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - const OwnerItem& item = cache.at(row - cacheFirstRow); - ownerIdOut = item.matchExistingId; - ownerNameOut = item.matchExistingName; + const OwnerItem &item = cache.at(row - cacheFirstRow); + ownerIdOut = item.matchExistingId; + ownerNameOut = item.matchExistingName; return true; } -bool RSImportedOwnersModel::validateData(int /*row*/, int /*col*/, db_id /*ownerId*/, const QString &/*ownerName*/) +bool RSImportedOwnersModel::validateData(int /*row*/, int /*col*/, db_id /*ownerId*/, + const QString & /*ownerName*/) { - return true; //TODO: implement + return true; // TODO: implement } -bool RSImportedOwnersModel::setFieldData(int row, int /*col*/, db_id ownerId, const QString &ownerName) +bool RSImportedOwnersModel::setFieldData(int row, int /*col*/, db_id ownerId, + const QString &ownerName) { - //NOTE: CustomName and MatchExisting exclude each other - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + // NOTE: CustomName and MatchExisting exclude each other + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - OwnerItem& item = cache[row - cacheFirstRow]; - if(item.matchExistingId == ownerId) - return true; //No change + OwnerItem &item = cache[row - cacheFirstRow]; + if (item.matchExistingId == ownerId) + return true; // No change - if(ownerId == 0) + if (ownerId == 0) { - //Check if we can leave it with no match and no custom name - //FIXME: if owner is matched and instead user wants to set a custom name - //but you can't remove the match because the name is a duplicate - //The user should set a custom name, it will automatically remove the match - //BUT we need to show a proper error test if just removing the match - //so add it to checkCustomNameValid() with like 'bool isMatchingOwner=true' argument + // Check if we can leave it with no match and no custom name + // FIXME: if owner is matched and instead user wants to set a custom name + // but you can't remove the match because the name is a duplicate + // The user should set a custom name, it will automatically remove the match + // BUT we need to show a proper error test if just removing the match + // so add it to checkCustomNameValid() with like 'bool isMatchingOwner=true' argument QString errText; - if(!checkCustomNameValid(item.importedOwnerId, item.name, QString(), &errText)) + if (!checkCustomNameValid(item.importedOwnerId, item.name, QString(), &errText)) { emit modelError(errText); return false; } } - command set_match(mDb, "UPDATE imported_rs_owners SET new_name=NULL,match_existing_id=? WHERE id=?"); - if(ownerId) + command set_match(mDb, + "UPDATE imported_rs_owners SET new_name=NULL,match_existing_id=? WHERE id=?"); + if (ownerId) set_match.bind(1, ownerId); else - set_match.bind(1); //Bind NULL + set_match.bind(1); // Bind NULL set_match.bind(2, item.importedOwnerId); - if(set_match.execute() != SQLITE_OK) + if (set_match.execute() != SQLITE_OK) return false; - item.matchExistingId = ownerId; + item.matchExistingId = ownerId; item.matchExistingName = ownerName; item.customName.clear(); item.customName.squeeze(); @@ -749,4 +773,3 @@ bool RSImportedOwnersModel::setFieldData(int row, int /*col*/, db_id ownerId, co return true; } - diff --git a/src/rollingstock/importer/model/rsimportedownersmodel.h b/src/rollingstock/importer/model/rsimportedownersmodel.h index 2a1ed1c..292013b 100644 --- a/src/rollingstock/importer/model/rsimportedownersmodel.h +++ b/src/rollingstock/importer/model/rsimportedownersmodel.h @@ -34,7 +34,10 @@ class RSImportedOwnersModel : public IRsImportModel, public IFKField Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; enum Columns { @@ -63,7 +66,8 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -72,11 +76,9 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel @@ -86,14 +88,12 @@ public: // Sorting TODO: enable multiple columns sort/filter with custom QHeaderView virtual void setSortingColumn(int col) override; - // IRsImportModel: int countImported() override; - // ICheckName: - bool checkCustomNameValid(db_id importedOwnerId, const QString& originalName, const QString& newCustomName, - QString *errTextOut) override; + bool checkCustomNameValid(db_id importedOwnerId, const QString &originalName, + const QString &newCustomName, QString *errTextOut) override; // IFKField: bool getFieldData(int row, int col, db_id &ownerIdOut, QString &ownerNameOut) const override; @@ -105,8 +105,8 @@ protected: private: void fetchRow(int row); - Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant& val); - void handleResult(const QVector& items, int firstRow); + Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant &val); + void handleResult(const QVector &items, int firstRow); private: QVector cache; diff --git a/src/rollingstock/importer/model/rsimportedrollingstockmodel.cpp b/src/rollingstock/importer/model/rsimportedrollingstockmodel.cpp index 08e4dbb..7b8b9f0 100644 --- a/src/rollingstock/importer/model/rsimportedrollingstockmodel.cpp +++ b/src/rollingstock/importer/model/rsimportedrollingstockmodel.cpp @@ -36,7 +36,10 @@ class RSResultEvent : public QEvent { public: static constexpr Type _Type = Type(CustomEvents::RsImportedRSModelResult); - inline RSResultEvent() : QEvent(_Type) {} + inline RSResultEvent() : + QEvent(_Type) + { + } QVector items; int firstRow; @@ -52,7 +55,7 @@ RSImportedRollingstockModel::RSImportedRollingstockModel(database &db, QObject * bool RSImportedRollingstockModel::event(QEvent *e) { - if(e->type() == RSResultEvent::_Type) + if (e->type() == RSResultEvent::_Type) { RSResultEvent *ev = static_cast(e); ev->setAccepted(true); @@ -67,33 +70,33 @@ bool RSImportedRollingstockModel::event(QEvent *e) void RSImportedRollingstockModel::fetchRow(int row) { - if(row >= firstPendingRow && row < firstPendingRow + BatchSize) - return; //Already fetching + if (row >= firstPendingRow && row < firstPendingRow + BatchSize) + return; // Already fetching - if(row >= cacheFirstRow && row < cacheFirstRow + cache.size()) - return; //Already cached + if (row >= cacheFirstRow && row < cacheFirstRow + cache.size()) + return; // Already cached - //TODO: abort fetching here + // TODO: abort fetching here const int remainder = row % BatchSize; - firstPendingRow = row - remainder; + firstPendingRow = row - remainder; qDebug() << "Requested:" << row << "From:" << firstPendingRow; QVariant val; - int valRow = 0; + int valRow = 0; RSItem *item = nullptr; - if(cache.size()) + if (cache.size()) { - if(firstPendingRow >= cacheFirstRow + cache.size()) + if (firstPendingRow >= cacheFirstRow + cache.size()) { valRow = cacheFirstRow + cache.size(); - item = &cache.last(); + item = &cache.last(); } - else if(firstPendingRow > (cacheFirstRow - firstPendingRow)) + else if (firstPendingRow > (cacheFirstRow - firstPendingRow)) { - valRow = cacheFirstRow; //It's shortet to get here by reverse from cache first - item = &cache.first(); + valRow = cacheFirstRow; // It's shortet to get here by reverse from cache first + item = &cache.first(); } } @@ -101,7 +104,7 @@ void RSImportedRollingstockModel::fetchRow(int row) { case Model: { - if(item) + if (item) { val = item->modelName; } @@ -109,7 +112,7 @@ void RSImportedRollingstockModel::fetchRow(int row) } case Number: { - if(item) + if (item) { val = item->number; } @@ -117,7 +120,7 @@ void RSImportedRollingstockModel::fetchRow(int row) } case Owner: { - if(item) + if (item) { val = item->ownerName; } @@ -125,31 +128,34 @@ void RSImportedRollingstockModel::fetchRow(int row) } } - //TODO: use a custom QRunnable + // TODO: use a custom QRunnable QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection, Q_ARG(int, firstPendingRow), Q_ARG(int, sortColumn), Q_ARG(int, valRow), Q_ARG(QVariant, val)); } -void RSImportedRollingstockModel::internalFetch(int first, int sortCol, int valRow, const QVariant& val) +void RSImportedRollingstockModel::internalFetch(int first, int sortCol, int valRow, + const QVariant &val) { query q(mDb); - int offset = first - valRow; + int offset = first - valRow; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; - QByteArray sql = "SELECT imp.id, imp.import, imp.model_id, imp.owner_id, imp.number, imp.new_number, models.name, models.type, owners.name, owners.new_name" - " FROM imported_rs_list imp" - " JOIN imported_rs_models models ON models.id=imp.model_id" - " JOIN imported_rs_owners owners ON owners.id=imp.owner_id"; + QByteArray sql = "SELECT imp.id, imp.import, imp.model_id, imp.owner_id, imp.number, " + "imp.new_number, models.name, models.type, owners.name, owners.new_name" + " FROM imported_rs_list imp" + " JOIN imported_rs_models models ON models.id=imp.model_id" + " JOIN imported_rs_owners owners ON owners.id=imp.owner_id"; const char *sortColExpr = nullptr; switch (sortCol) @@ -177,11 +183,11 @@ void RSImportedRollingstockModel::internalFetch(int first, int sortCol, int valR } sql += " WHERE owners.import=1 AND models.import=1"; - if(val.isValid()) + if (val.isValid()) { sql += " AND "; sql += sortColExpr; - if(reverse) + if (reverse) sql += "?3"; @@ -190,20 +196,20 @@ void RSImportedRollingstockModel::internalFetch(int first, int sortCol, int valR sql += " ORDER BY "; sql += sortColExpr; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); sqlite3_stmt *st = q.stmt(); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); - if(val.isValid()) + if (val.isValid()) { switch (sortCol) { @@ -225,103 +231,104 @@ void RSImportedRollingstockModel::internalFetch(int first, int sortCol, int valR QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - if(reverse) + if (reverse) { int i = BatchSize - 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - RSItem &item = vec[i]; - item.importdRsId = r.get(0); - item.import = r.get(1) == 1; + auto r = *it; + RSItem &item = vec[i]; + item.importdRsId = r.get(0); + item.import = r.get(1) == 1; item.importedModelId = r.get(2); item.importedOwnerId = r.get(3); - item.number = r.get(4); + item.number = r.get(4); - if(r.column_type(5) == SQLITE_NULL) + if (r.column_type(5) == SQLITE_NULL) item.new_number = -1; else item.new_number = r.get(5); - item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 6)), + item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 6)), sqlite3_column_bytes(st, 6)); - item.type = RsType(r.get(7)); + item.type = RsType(r.get(7)); - item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 8)), + item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 8)), sqlite3_column_bytes(st, 8)); - if(r.column_type(8) != SQLITE_NULL) + if (r.column_type(8) != SQLITE_NULL) { - item.ownerCustomName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 9)), - sqlite3_column_bytes(st, 9)); + item.ownerCustomName = + QByteArray(reinterpret_cast(sqlite3_column_text(st, 9)), + sqlite3_column_bytes(st, 9)); } i--; } - if(i > -1) + if (i > -1) vec.remove(0, i + 1); } else { int i = 0; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - RSItem &item = vec[i]; - item.importdRsId = r.get(0); - item.import = r.get(1) == 1; + auto r = *it; + RSItem &item = vec[i]; + item.importdRsId = r.get(0); + item.import = r.get(1) == 1; item.importedModelId = r.get(2); item.importedOwnerId = r.get(3); - item.number = r.get(4); + item.number = r.get(4); - if(r.column_type(5) == SQLITE_NULL) + if (r.column_type(5) == SQLITE_NULL) item.new_number = -1; else item.new_number = r.get(5); - item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 6)), + item.modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 6)), sqlite3_column_bytes(st, 6)); - item.type = RsType(r.get(7)); + item.type = RsType(r.get(7)); - item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 8)), + item.ownerName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 8)), sqlite3_column_bytes(st, 8)); - if(r.column_type(8) != SQLITE_NULL) + if (r.column_type(8) != SQLITE_NULL) { - item.ownerCustomName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 9)), - sqlite3_column_bytes(st, 9)); + item.ownerCustomName = + QByteArray(reinterpret_cast(sqlite3_column_text(st, 9)), + sqlite3_column_bytes(st, 9)); } i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); } - RSResultEvent *ev = new RSResultEvent; - ev->items = vec; - ev->firstRow = first; + ev->items = vec; + ev->firstRow = first; qApp->postEvent(this, ev); } -void RSImportedRollingstockModel::handleResult(const QVector& items, int firstRow) +void RSImportedRollingstockModel::handleResult(const QVector &items, int firstRow) { - if(firstRow == cacheFirstRow + cache.size()) + if (firstRow == cacheFirstRow + cache.size()) { qDebug() << "RES: appending First:" << cacheFirstRow; cache.append(items); - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { - const int extra = cache.size() - ItemsPerPage; //Round up to BatchSize + const int extra = cache.size() - ItemsPerPage; // Round up to BatchSize const int remainder = extra % BatchSize; - const int n = remainder ? extra + BatchSize - remainder : extra; + const int n = remainder ? extra + BatchSize - remainder : extra; qDebug() << "RES: removing last" << n; cache.remove(0, n); cacheFirstRow += n; @@ -329,13 +336,13 @@ void RSImportedRollingstockModel::handleResult(const QVector& items, int } else { - if(firstRow + items.size() == cacheFirstRow) + if (firstRow + items.size() == cacheFirstRow) { qDebug() << "RES: prepending First:" << cacheFirstRow; QVector tmp = items; tmp.append(cache); cache = tmp; - if(cache.size() > ItemsPerPage) + if (cache.size() > ItemsPerPage) { const int n = cache.size() - ItemsPerPage; cache.remove(ItemsPerPage, n); @@ -351,10 +358,10 @@ void RSImportedRollingstockModel::handleResult(const QVector& items, int qDebug() << "NEW First:" << cacheFirstRow; } - firstPendingRow = -BatchSize; + firstPendingRow = -BatchSize; QModelIndex firstIdx = index(firstRow, 0); - QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); + QModelIndex lastIdx = index(firstRow + items.count() - 1, NCols - 1); emit dataChanged(firstIdx, lastIdx); qDebug() << "TOTAL: From:" << cacheFirstRow << "To:" << cacheFirstRow + cache.size() - 1; @@ -362,9 +369,10 @@ void RSImportedRollingstockModel::handleResult(const QVector& items, int /* QAbstractTableModel */ -QVariant RSImportedRollingstockModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant RSImportedRollingstockModel::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) { @@ -399,14 +407,14 @@ QVariant RSImportedRollingstockModel::data(const QModelIndex &idx, int role) con if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return QVariant("..."); } @@ -423,11 +431,12 @@ QVariant RSImportedRollingstockModel::data(const QModelIndex &idx, int role) con case Number: return rs_utils::formatNum(item.type, item.number); case Owner: - if(item.ownerCustomName.isEmpty()) + if (item.ownerCustomName.isEmpty()) return item.ownerName; return item.ownerName + " (" + item.ownerCustomName + ')'; case NewNumber: - return item.new_number == -1 ? QVariant() : rs_utils::formatNum(item.type, item.new_number); + return item.new_number == -1 ? QVariant() + : rs_utils::formatNum(item.type, item.new_number); } break; } @@ -442,14 +451,14 @@ QVariant RSImportedRollingstockModel::data(const QModelIndex &idx, int role) con } case Qt::TextAlignmentRole: { - if(idx.column() == Number || idx.column() == NewNumber) + if (idx.column() == Number || idx.column() == NewNumber) return Qt::AlignRight + Qt::AlignVCenter; break; } case Qt::BackgroundRole: { - if(!item.import || (idx.column() == NewNumber && item.new_number == -1)) - return QBrush(Qt::lightGray); //If not imported mark background or no custom number set + if (!item.import || (idx.column() == NewNumber && item.new_number == -1)) + return QBrush(Qt::lightGray); // If not imported mark background or no custom number set break; } case Qt::CheckStateRole: @@ -459,7 +468,7 @@ QVariant RSImportedRollingstockModel::data(const QModelIndex &idx, int role) con case Import: return item.import ? Qt::Checked : Qt::Unchecked; case NewNumber: - if(item.new_number == -1) + if (item.new_number == -1) return QVariant(); return Qt::Checked; } @@ -473,13 +482,14 @@ QVariant RSImportedRollingstockModel::data(const QModelIndex &idx, int role) con bool RSImportedRollingstockModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - RSItem &item = cache[row - cacheFirstRow]; + RSItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -491,24 +501,25 @@ bool RSImportedRollingstockModel::setData(const QModelIndex &idx, const QVariant { int newNumber = value.toInt() % 10000; - if(item.new_number == newNumber) + if (item.new_number == newNumber) return false; QString errText; - if(!checkNewNumberIsValid(item.importdRsId, item.importedModelId, item.importedModelMatchId, - item.type, item.number, newNumber, &errText)) + if (!checkNewNumberIsValid(item.importdRsId, item.importedModelId, + item.importedModelMatchId, item.type, item.number, newNumber, + &errText)) { emit modelError(errText); return false; } command set_newNumber(mDb, "UPDATE imported_rs_list SET new_number=? WHERE id=?"); - if(newNumber == -1) - set_newNumber.bind(1); //Bind NULL + if (newNumber == -1) + set_newNumber.bind(1); // Bind NULL else set_newNumber.bind(1, newNumber); set_newNumber.bind(2, item.importdRsId); - if(set_newNumber.execute() != SQLITE_OK) + if (set_newNumber.execute() != SQLITE_OK) return false; item.new_number = newNumber; @@ -528,15 +539,16 @@ bool RSImportedRollingstockModel::setData(const QModelIndex &idx, const QVariant { Qt::CheckState cs = value.value(); const bool import = cs == Qt::Checked; - if(item.import == import) - return false; //No change + if (item.import == import) + return false; // No change - if(import) + if (import) { - //Newly imported, check if there are duplicates + // Newly imported, check if there are duplicates QString errText; - if(!checkNewNumberIsValid(item.importdRsId, item.importedModelId, item.importedModelMatchId, - item.type, item.number, item.new_number, &errText)) + if (!checkNewNumberIsValid(item.importdRsId, item.importedModelId, + item.importedModelMatchId, item.type, item.number, + item.new_number, &errText)) { emit modelError(errText); return false; @@ -546,32 +558,32 @@ bool RSImportedRollingstockModel::setData(const QModelIndex &idx, const QVariant command set_imported(mDb, "UPDATE imported_rs_list SET import=? WHERE id=?"); set_imported.bind(1, import ? 1 : 0); set_imported.bind(2, item.importdRsId); - if(set_imported.execute() != SQLITE_OK) + if (set_imported.execute() != SQLITE_OK) return false; item.import = import; - if(sortColumn == Import) + if (sortColumn == Import) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } emit importCountChanged(); - //Update all columns to update background + // Update all columns to update background first = index(row, 0); - last = index(row, NCols - 1); + last = index(row, NCols - 1); break; } case NewNumber: { Qt::CheckState cs = value.value(); - if(cs == Qt::Unchecked) - return setData(idx, -1, Qt::EditRole); //Set -1 as new_number -> NULL + if (cs == Qt::Unchecked) + return setData(idx, -1, Qt::EditRole); // Set -1 as new_number -> NULL return false; } default: @@ -593,12 +605,12 @@ Qt::ItemFlags RSImportedRollingstockModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == Import) + if (idx.column() == Import) f.setFlag(Qt::ItemIsUserCheckable); - if(idx.column() == NewNumber) + if (idx.column() == NewNumber) { f.setFlag(Qt::ItemIsEditable); f.setFlag(Qt::ItemIsUserCheckable, cache.at(idx.row() - cacheFirstRow).new_number != -1); @@ -629,14 +641,14 @@ void RSImportedRollingstockModel::clearCache() void RSImportedRollingstockModel::setSortingColumn(int col) { - if(sortColumn == col || col == NewNumber) - return; //Don't sort by NewNumber because some are NULL + if (sortColumn == col || col == NewNumber) + return; // Don't sort by NewNumber because some are NULL clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -655,26 +667,29 @@ int RSImportedRollingstockModel::countImported() /* ICheckName */ -bool RSImportedRollingstockModel::checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, db_id matchExistingModelId, - RsType rsType, int number, int newNumber, QString *errTextOut) +bool RSImportedRollingstockModel::checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, + db_id matchExistingModelId, RsType rsType, + int number, int newNumber, + QString *errTextOut) { RsType type = RsType(rsType); - if(number == newNumber) + if (number == newNumber) { - if(errTextOut) + if (errTextOut) { *errTextOut = tr("You cannot set the same name in the 'Custom Name' field.\n" - "If you meant to revert to original name then clear the custom name and leave the cell empty"); + "If you meant to revert to original name then clear the custom name " + "and leave the cell empty"); } return false; } int numberToCheck = newNumber; - if(newNumber == -1) + if (newNumber == -1) numberToCheck = number; - //First check if there is an imported RS with same number or new number + // First check if there is an imported RS with same number or new number query q(mDb, "SELECT imp.id, imp.new_number, m.name, m.new_name, rs_models.name" " FROM imported_rs_models m" " LEFT JOIN rs_models ON rs_models.id=m.match_existing_id" @@ -688,60 +703,65 @@ bool RSImportedRollingstockModel::checkNewNumberIsValid(db_id importedRsId, db_i q.bind(3, importedRsId); q.bind(4, numberToCheck); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { - auto r = q.getRows(); + auto r = q.getRows(); db_id dupId = r.get(0); - Q_UNUSED(dupId) //TODO: maybe use it? + Q_UNUSED(dupId) // TODO: maybe use it? - sqlite3_stmt *st = q.stmt(); + sqlite3_stmt *st = q.stmt(); bool matchedNewNumber = true; - if(r.column_type(1) == SQLITE_NULL) + if (r.column_type(1) == SQLITE_NULL) { - matchedNewNumber = false; //We matched original number + matchedNewNumber = false; // We matched original number } - QByteArray modelName = QByteArray(reinterpret_cast(sqlite3_column_text(st, 2)), - sqlite3_column_bytes(st, 2)); + QByteArray modelName = QByteArray( + reinterpret_cast(sqlite3_column_text(st, 2)), sqlite3_column_bytes(st, 2)); - if(errTextOut) + if (errTextOut) { - if(r.column_type(3) != SQLITE_NULL) + if (r.column_type(3) != SQLITE_NULL) { // 'name (new_name)' modelName.append(" (", 2); - modelName.append(reinterpret_cast(sqlite3_column_text(st, 3)), + modelName.append(reinterpret_cast(sqlite3_column_text(st, 3)), sqlite3_column_bytes(st, 3)); modelName.append(')'); } - if(r.column_type(4) != SQLITE_NULL) + if (r.column_type(4) != SQLITE_NULL) { // 'name (match_existing name)' modelName.append(" (", 2); - modelName.append(reinterpret_cast(sqlite3_column_text(st, 4)), + modelName.append(reinterpret_cast(sqlite3_column_text(st, 4)), sqlite3_column_bytes(st, 4)); modelName.append(')'); } QString model = QString::fromUtf8(modelName); - if(matchedNewNumber) + if (matchedNewNumber) { - *errTextOut = tr("There is already another imported rollingstock with same 'New Number': %1 %2") - .arg(model, rs_utils::formatNum(type, numberToCheck)); - }else{ - *errTextOut = tr("There is already another imported rollingstock with same number: %1 %2") - .arg(model, rs_utils::formatNum(type, numberToCheck)); + *errTextOut = tr("There is already another imported rollingstock with same 'New " + "Number': %1 %2") + .arg(model, rs_utils::formatNum(type, numberToCheck)); + } + else + { + *errTextOut = + tr( + "There is already another imported rollingstock with same number: %1 %2") + .arg(model, rs_utils::formatNum(type, numberToCheck)); } } return false; } - //Then check for an existing RS with same number if model is matched - if(matchExistingModelId) + // Then check for an existing RS with same number if model is matched + if (matchExistingModelId) { q.prepare("SELECT rs_list.id, rs_models.name" " FROM rs_list" @@ -750,18 +770,19 @@ bool RSImportedRollingstockModel::checkNewNumberIsValid(db_id importedRsId, db_i q.bind(1, matchExistingModelId); q.bind(2, numberToCheck); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { - auto r = q.getRows(); + auto r = q.getRows(); db_id dupExistingId = r.get(0); - Q_UNUSED(dupExistingId) //TODO: maybe use it? + Q_UNUSED(dupExistingId) // TODO: maybe use it? QString modelName = r.get(1); - if(errTextOut) + if (errTextOut) { - *errTextOut = tr("There is already an existing rollingstock with same number: %1 %2") - .arg(modelName, rs_utils::formatNum(type, numberToCheck)); + *errTextOut = + tr("There is already an existing rollingstock with same number: %1 %2") + .arg(modelName, rs_utils::formatNum(type, numberToCheck)); } return false; } diff --git a/src/rollingstock/importer/model/rsimportedrollingstockmodel.h b/src/rollingstock/importer/model/rsimportedrollingstockmodel.h index ae319ae..fce5b1d 100644 --- a/src/rollingstock/importer/model/rsimportedrollingstockmodel.h +++ b/src/rollingstock/importer/model/rsimportedrollingstockmodel.h @@ -33,7 +33,10 @@ class RSImportedRollingstockModel : public IRsImportModel Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; enum Columns { @@ -66,7 +69,8 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -75,11 +79,9 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel @@ -89,14 +91,12 @@ public: // Sorting TODO: enable multiple columns sort/filter with custom QHeaderView virtual void setSortingColumn(int col) override; - // IRsImportModel: int countImported() override; - // ICheckName: - bool checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, db_id matchExistingModelId, RsType rsType, - int number, int newNumber, + bool checkNewNumberIsValid(db_id importedRsId, db_id importedModelId, + db_id matchExistingModelId, RsType rsType, int number, int newNumber, QString *errTextOut) override; protected: @@ -104,8 +104,8 @@ protected: private: void fetchRow(int row); - Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant& val); - void handleResult(const QVector& items, int firstRow); + Q_INVOKABLE void internalFetch(int first, int sortCol, int valRow, const QVariant &val); + void handleResult(const QVector &items, int firstRow); private: QVector cache; diff --git a/src/rollingstock/importer/pages/fixduplicatesdlg.cpp b/src/rollingstock/importer/pages/fixduplicatesdlg.cpp index ea7b2b0..e9bc3d1 100644 --- a/src/rollingstock/importer/pages/fixduplicatesdlg.cpp +++ b/src/rollingstock/importer/pages/fixduplicatesdlg.cpp @@ -44,18 +44,18 @@ public: dlg(parent) { setAutoReset(false); - //Manually handle cancel + // Manually handle cancel disconnect(this, SIGNAL(canceled()), this, SLOT(cancel())); connect(this, SIGNAL(canceled()), this, SLOT(reject())); } void done(int res) override { - if(res != QDialog::Accepted) + if (res != QDialog::Accepted) { res = dlg->warnCancel(this); - if(res == QDialog::Accepted) - return; //Give user a second chance + if (res == QDialog::Accepted) + return; // Give user a second chance } QDialog::done(res); } @@ -71,19 +71,20 @@ FixDuplicatesDlg::FixDuplicatesDlg(IDuplicatesItemModel *m, bool enableGoBack, Q { QVBoxLayout *lay = new QVBoxLayout(this); - QLabel *label = new QLabel(RsImportStrings::tr("The file constains some duplicates in item names wich need to be fixed in order to procced.\n" - "There also may be some items with empty name.\n" - "Please assign a custom name to them so that there are no duplicates")); + QLabel *label = new QLabel( + RsImportStrings::tr("The file constains some duplicates in item names wich need to be fixed " + "in order to procced.\n" + "There also may be some items with empty name.\n" + "Please assign a custom name to them so that there are no duplicates")); lay->addWidget(label); view = new QTableView; - //Prevent changing names by accidentally pressing a key + // Prevent changing names by accidentally pressing a key view->setEditTriggers(QTableView::DoubleClicked); view->setModel(model); view->resizeColumnsToContents(); lay->addWidget(view); - box = new QDialogButtonBox(QDialogButtonBox::Ok); connect(box, &QDialogButtonBox::accepted, this, &QDialog::accept); lay->addWidget(box); @@ -105,55 +106,58 @@ void FixDuplicatesDlg::setItemDelegateForColumn(int column, QAbstractItemDelegat view->setItemDelegateForColumn(column, delegate); } -void FixDuplicatesDlg::showModelError(const QString& text) +void FixDuplicatesDlg::showModelError(const QString &text) { QMessageBox::warning(this, RsImportStrings::tr("Invalid Operation"), text); } void FixDuplicatesDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { - //Check if all are fixed + // Check if all are fixed res = blockingReloadCount(IDuplicatesItemModel::LoadingData); - if(res != QDialog::Accepted) + if (res != QDialog::Accepted) { QDialog::done(res); return; } int count = model->getItemCount(); - if(count) + if (count) { OwningQPointer msgBox = new QMessageBox(this); msgBox->setIcon(QMessageBox::Warning); msgBox->setWindowTitle(RsImportStrings::tr("Not yet!")); msgBox->setText(RsImportStrings::tr("There are still %1 items to be fixed").arg(count)); - QPushButton *okBut = msgBox->addButton(QMessageBox::Ok); + QPushButton *okBut = msgBox->addButton(QMessageBox::Ok); QPushButton *backToPrevPage = nullptr; - if(canGoBack) - backToPrevPage = msgBox->addButton(RsImportStrings::tr("Previuos page"), QMessageBox::NoRole); + if (canGoBack) + backToPrevPage = + msgBox->addButton(RsImportStrings::tr("Previuos page"), QMessageBox::NoRole); msgBox->setDefaultButton(okBut); - msgBox->setEscapeButton(okBut); //If dialog gets closed of Esc is pressed act ad if Ok was pressed + msgBox->setEscapeButton( + okBut); // If dialog gets closed of Esc is pressed act ad if Ok was pressed msgBox->exec(); - const bool goBack = msgBox && msgBox->clickedButton() == backToPrevPage && backToPrevPage; + const bool goBack = + msgBox && msgBox->clickedButton() == backToPrevPage && backToPrevPage; - if(goBack) + if (goBack) { res = GoBackToPrevPage; } else { - return; //Give user a second chance + return; // Give user a second chance } } } else { res = warnCancel(this); - if(res == QDialog::Accepted) - return; //Give user a second chance + if (res == QDialog::Accepted) + return; // Give user a second chance } return QDialog::done(res); @@ -190,7 +194,7 @@ void FixDuplicatesDlg::handleModelState(int state) int FixDuplicatesDlg::blockingReloadCount(int mode) { - if(!model->startLoading(mode)) + if (!model->startLoading(mode)) return canGoBack ? int(GoBackToPrevPage) : int(QDialog::Rejected); progressDlg->reset(); @@ -207,17 +211,18 @@ int FixDuplicatesDlg::blockingReloadCount(int mode) int FixDuplicatesDlg::warnCancel(QWidget *w) { - //Warn user + // Warn user OwningQPointer msgBox = new QMessageBox(w); msgBox->setIcon(QMessageBox::Warning); msgBox->setWindowTitle(RsImportStrings::tr("Aborting RS Import")); msgBox->setText(RsImportStrings::tr("If you don't fix duplicated items you cannot proceed.\n" "Do you wish to Abort the process?")); - QPushButton *abortBut = msgBox->addButton(QMessageBox::Abort); - QPushButton *noBut = msgBox->addButton(QMessageBox::No); + QPushButton *abortBut = msgBox->addButton(QMessageBox::Abort); + QPushButton *noBut = msgBox->addButton(QMessageBox::No); QPushButton *backToPrevPage = nullptr; - if(canGoBack) - backToPrevPage = msgBox->addButton(RsImportStrings::tr("Previuos page"), QMessageBox::NoRole); + if (canGoBack) + backToPrevPage = + msgBox->addButton(RsImportStrings::tr("Previuos page"), QMessageBox::NoRole); msgBox->setDefaultButton(noBut); msgBox->setEscapeButton(noBut); @@ -225,16 +230,16 @@ int FixDuplicatesDlg::warnCancel(QWidget *w) connect(model, &IDuplicatesItemModel::processAborted, msgBox, &QMessageBox::accept); msgBox->exec(); - if(!msgBox) + if (!msgBox) return QDialog::Rejected; QAbstractButton *but = msgBox->clickedButton(); - int ret = QDialog::Accepted; //Default give second chance - if(but == abortBut) + int ret = QDialog::Accepted; // Default give second chance + if (but == abortBut) { ret = QDialog::Rejected; } - else if(but == backToPrevPage && backToPrevPage) + else if (but == backToPrevPage && backToPrevPage) { ret = FixDuplicatesDlg::GoBackToPrevPage; } diff --git a/src/rollingstock/importer/pages/fixduplicatesdlg.h b/src/rollingstock/importer/pages/fixduplicatesdlg.h index 6441935..e4ccf57 100644 --- a/src/rollingstock/importer/pages/fixduplicatesdlg.h +++ b/src/rollingstock/importer/pages/fixduplicatesdlg.h @@ -32,8 +32,10 @@ class FixDuplicatesDlg : public QDialog { Q_OBJECT public: - - enum { GoBackToPrevPage = QDialog::Accepted + 1 }; + enum + { + GoBackToPrevPage = QDialog::Accepted + 1 + }; FixDuplicatesDlg(IDuplicatesItemModel *m, bool enableGoBack, QWidget *parent = nullptr); diff --git a/src/rollingstock/importer/pages/itemselectionpage.cpp b/src/rollingstock/importer/pages/itemselectionpage.cpp index 749a466..8b726d6 100644 --- a/src/rollingstock/importer/pages/itemselectionpage.cpp +++ b/src/rollingstock/importer/pages/itemselectionpage.cpp @@ -41,31 +41,28 @@ #include "../rsimportstrings.h" #include "utils/rs_types_names.h" -static const char *title_strings[] = { - QT_TRANSLATE_NOOP("RsTypeNames", "Owners"), - QT_TRANSLATE_NOOP("RsTypeNames", "Models"), - QT_TRANSLATE_NOOP("RsTypeNames", "Rollingstock") -}; +static const char *title_strings[] = {QT_TRANSLATE_NOOP("RsTypeNames", "Owners"), + QT_TRANSLATE_NOOP("RsTypeNames", "Models"), + QT_TRANSLATE_NOOP("RsTypeNames", "Rollingstock")}; static const char *descr_strings[] = { - QT_TRANSLATE_NOOP("RsImportStrings", "Select owners of rollingstock you want to import"), - QT_TRANSLATE_NOOP("RsImportStrings", "Select models of rollingstock you want to import"), - QT_TRANSLATE_NOOP("RsImportStrings", "Select rollingstock pieces you want to import") -}; + QT_TRANSLATE_NOOP("RsImportStrings", "Select owners of rollingstock you want to import"), + QT_TRANSLATE_NOOP("RsImportStrings", "Select models of rollingstock you want to import"), + QT_TRANSLATE_NOOP("RsImportStrings", "Select rollingstock pieces you want to import")}; static const char *error_strings[] = { - QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 owner"), - QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 model"), - QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 rollingsock piece") -}; + QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 owner"), + QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 model"), + QT_TRANSLATE_NOOP("RsImportStrings", "You must select at least 1 rollingsock piece")}; -static const char *display_strings[] = { //FIXME plurals - QT_TRANSLATE_NOOP("RsImportStrings", "%1 owners selected"), - QT_TRANSLATE_NOOP("RsImportStrings", "%1 models selected"), - QT_TRANSLATE_NOOP("RsImportStrings", "%1 rollingstock pieces selected") -}; +static const char *display_strings[] = { // FIXME plurals + QT_TRANSLATE_NOOP("RsImportStrings", "%1 owners selected"), + QT_TRANSLATE_NOOP("RsImportStrings", "%1 models selected"), + QT_TRANSLATE_NOOP("RsImportStrings", "%1 rollingstock pieces selected")}; -ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItemEditorFactory *edFactory, IFKField *ifaceDelegate, int delegateCol, ModelModes::Mode mode, QWidget *parent) : +ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, + QItemEditorFactory *edFactory, IFKField *ifaceDelegate, + int delegateCol, ModelModes::Mode mode, QWidget *parent) : QWizardPage(parent), mWizard(w), model(m), @@ -74,10 +71,11 @@ ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItem { QVBoxLayout *lay = new QVBoxLayout(this); - //TODO: add SelectAll, SelectNone + // TODO: add SelectAll, SelectNone view = new QTableView(this); - view->setEditTriggers(QTableView::DoubleClicked); //Prevent changing names by accidentally pressing a key + view->setEditTriggers( + QTableView::DoubleClicked); // Prevent changing names by accidentally pressing a key lay->addWidget(view); auto ps = new ModelPageSwitcher(false, this); @@ -90,21 +88,21 @@ ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItem ps->setModel(model); connect(model, &IRsImportModel::modelError, this, &ItemSelectionPage::showModelError); - if(ifaceDelegate) + if (ifaceDelegate) { - SqlFKFieldDelegate *delegate = new SqlFKFieldDelegate(new RSMatchModelFactory(m_mode, model->getDb(), this), ifaceDelegate, this); + SqlFKFieldDelegate *delegate = new SqlFKFieldDelegate( + new RSMatchModelFactory(m_mode, model->getDb(), this), ifaceDelegate, this); view->setItemDelegateForColumn(delegateCol, delegate); - } - else if(editorFactory) + else if (editorFactory) { QStyledItemDelegate *delegate = new QStyledItemDelegate(this); delegate->setItemEditorFactory(editorFactory); view->setItemDelegateForColumn(delegateCol, delegate); } - //Custom colun sorting - //NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work + // Custom colun sorting + // NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work QHeaderView *header = view->horizontalHeader(); disconnect(header, SIGNAL(sectionPressed(int)), view, SLOT(selectColumn(int))); disconnect(header, SIGNAL(sectionEntered(int)), view, SLOT(_q_selectColumn(int))); @@ -119,7 +117,7 @@ ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItem setTitle(RsTypeNames::tr(title_strings[m_mode])); setSubTitle(RsImportStrings::tr(descr_strings[m_mode])); - if(m_mode == ModelModes::Rollingstock) + if (m_mode == ModelModes::Rollingstock) { setCommitPage(true); setButtonText(QWizard::CommitButton, RsImportStrings::tr("Import")); @@ -128,22 +126,22 @@ ItemSelectionPage::ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItem void ItemSelectionPage::initializePage() { - //Check for duplicates + // Check for duplicates std::unique_ptr dupModel; dupModel.reset(IDuplicatesItemModel::createModel(m_mode, model->getDb(), model, this)); - bool canGoBack = mWizard->currentId() != RSImportWizard::SelectOwnersIdx; + bool canGoBack = mWizard->currentId() != RSImportWizard::SelectOwnersIdx; OwningQPointer dlg = new FixDuplicatesDlg(dupModel.get(), canGoBack, this); - if(m_mode == ModelModes::Rollingstock && editorFactory) + if (m_mode == ModelModes::Rollingstock && editorFactory) { QStyledItemDelegate *delegate = new QStyledItemDelegate(this); delegate->setItemEditorFactory(editorFactory); dlg->setItemDelegateForColumn(DuplicatesImportedRSModel::NewNumber, delegate); } - //First load + // First load int res = dlg->blockingReloadCount(IDuplicatesItemModel::LoadingData); - if(res == FixDuplicatesDlg::GoBackToPrevPage && canGoBack) + if (res == FixDuplicatesDlg::GoBackToPrevPage && canGoBack) { /* HACK: * we are inside 'initializePage()' which is called before QWizard @@ -155,32 +153,32 @@ void ItemSelectionPage::initializePage() mWizard->goToPrevPageQueued(); return; } - else if(res != QDialog::Accepted) + else if (res != QDialog::Accepted) { - //Prevent showing another message box asking user if he is sure about quitting + // Prevent showing another message box asking user if he is sure about quitting mWizard->done(RSImportWizard::RejectWithoutAsking); return; } - if(dupModel->getItemCount() > 0) + if (dupModel->getItemCount() > 0) { - //We have duplicates, run dialog + // We have duplicates, run dialog res = dlg->exec(); - if(res == FixDuplicatesDlg::GoBackToPrevPage && canGoBack) + if (res == FixDuplicatesDlg::GoBackToPrevPage && canGoBack) { /* HACK: see above */ mWizard->goToPrevPageQueued(); return; } - else if(res != QDialog::Accepted) + else if (res != QDialog::Accepted) { - //Prevent showing another message box asking user if he is sure about quitting + // Prevent showing another message box asking user if he is sure about quitting mWizard->done(RSImportWizard::RejectWithoutAsking); return; } } - //Duplicates are now fixed, refresh main model + // Duplicates are now fixed, refresh main model model->refreshData(); } @@ -192,15 +190,16 @@ void ItemSelectionPage::cleanupPage() bool ItemSelectionPage::validatePage() { int count = model->countImported(); - if(count == 0) + if (count == 0) { - QMessageBox::warning(this, RsImportStrings::tr("Invalid Operation"), RsImportStrings::tr(error_strings[m_mode])); + QMessageBox::warning(this, RsImportStrings::tr("Invalid Operation"), + RsImportStrings::tr(error_strings[m_mode])); return false; } model->clearCache(); - if(m_mode == ModelModes::Rollingstock) + if (m_mode == ModelModes::Rollingstock) { mWizard->startImportTask(); } @@ -220,7 +219,7 @@ void ItemSelectionPage::sectionClicked(int col) view->horizontalHeader()->setSortIndicator(model->getSortingColumn(), Qt::AscendingOrder); } -void ItemSelectionPage::showModelError(const QString& text) +void ItemSelectionPage::showModelError(const QString &text) { QMessageBox::warning(this, RsImportStrings::tr("Invalid Operation"), text); } diff --git a/src/rollingstock/importer/pages/itemselectionpage.h b/src/rollingstock/importer/pages/itemselectionpage.h index bd063c6..84597c5 100644 --- a/src/rollingstock/importer/pages/itemselectionpage.h +++ b/src/rollingstock/importer/pages/itemselectionpage.h @@ -36,7 +36,9 @@ class ItemSelectionPage : public QWizardPage { Q_OBJECT public: - ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItemEditorFactory *edFactory, IFKField *ifaceDelegate, int delegateCol, ModelModes::Mode mode, QWidget *parent = nullptr); + ItemSelectionPage(RSImportWizard *w, IRsImportModel *m, QItemEditorFactory *edFactory, + IFKField *ifaceDelegate, int delegateCol, ModelModes::Mode mode, + QWidget *parent = nullptr); virtual void initializePage() override; virtual void cleanupPage() override; diff --git a/src/rollingstock/importer/pages/loadingpage.cpp b/src/rollingstock/importer/pages/loadingpage.cpp index ddf7061..7cd5f2a 100644 --- a/src/rollingstock/importer/pages/loadingpage.cpp +++ b/src/rollingstock/importer/pages/loadingpage.cpp @@ -29,7 +29,7 @@ LoadingPage::LoadingPage(QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - progressBar = new QProgressBar; + progressBar = new QProgressBar; lay->addWidget(progressBar); } @@ -40,7 +40,7 @@ bool LoadingPage::isComplete() const void LoadingPage::handleProgress(int pr, int max) { - if(max == LoadProgressEvent::ProgressMaxFinished) + if (max == LoadProgressEvent::ProgressMaxFinished) { progressBar->setValue(progressBar->maximum()); emit completeChanged(); diff --git a/src/rollingstock/importer/pages/optionspage.cpp b/src/rollingstock/importer/pages/optionspage.cpp index 9db622b..4c24e23 100644 --- a/src/rollingstock/importer/pages/optionspage.cpp +++ b/src/rollingstock/importer/pages/optionspage.cpp @@ -45,11 +45,11 @@ OptionsPage::OptionsPage(QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - //General options - generalBox = new QGroupBox(RsImportStrings::tr("General options")); + // General options + generalBox = new QGroupBox(RsImportStrings::tr("General options")); QFormLayout *generalLay = new QFormLayout(generalBox); - importOwners = new QCheckBox(RsImportStrings::tr("Import rollingstick owners")); + importOwners = new QCheckBox(RsImportStrings::tr("Import rollingstick owners")); connect(importOwners, &QCheckBox::toggled, this, &OptionsPage::updateGeneralCheckBox); generalLay->addRow(importOwners); @@ -61,34 +61,37 @@ OptionsPage::OptionsPage(QWidget *parent) : connect(importRS, &QCheckBox::toggled, this, &OptionsPage::updateGeneralCheckBox); generalLay->addRow(importRS); - //NOTE: see 'RollingStockManager::setupPages()' in 'Setup delegates' section + // NOTE: see 'RollingStockManager::setupPages()' in 'Setup delegates' section defaultSpeedSpin = new QSpinBox; defaultSpeedSpin->setRange(1, 999); defaultSpeedSpin->setSuffix(" km/h"); defaultSpeedSpin->setValue(120); - defaultSpeedSpin->setToolTip(tr("Default speed is applied when a rollingstock model is not matched to an existing one" - " and has to be created from scratch")); + defaultSpeedSpin->setToolTip( + tr("Default speed is applied when a rollingstock model is not matched to an existing one" + " and has to be created from scratch")); generalLay->addRow(tr("Default speed"), defaultSpeedSpin); defaultTypeCombo = new QComboBox; QStringList list; list.reserve(int(RsType::NTypes)); - for(int i = 0; i < int(RsType::NTypes); i++) + for (int i = 0; i < int(RsType::NTypes); i++) list.append(RsTypeNames::name(RsType(i))); QStringListModel *rsTypeModel = new QStringListModel(list, this); defaultTypeCombo->setModel(rsTypeModel); defaultTypeCombo->setCurrentIndex(int(RsType::FreightWagon)); - defaultTypeCombo->setToolTip(tr("Default type is applied when a rollingstock model is not matched to an existing one" - " and has to be created from scratch")); + defaultTypeCombo->setToolTip( + tr("Default type is applied when a rollingstock model is not matched to an existing one" + " and has to be created from scratch")); generalLay->addRow(tr("Default type"), defaultTypeCombo); lay->addWidget(generalBox); - //Specific options - specificBox = new QGroupBox(RsImportStrings::tr("Import options")); + // Specific options + specificBox = new QGroupBox(RsImportStrings::tr("Import options")); QFormLayout *specificlLay = new QFormLayout(specificBox); - backendCombo = new QComboBox; - connect(backendCombo, static_cast(&QComboBox::activated), this, &OptionsPage::setSource); + backendCombo = new QComboBox; + connect(backendCombo, static_cast(&QComboBox::activated), this, + &OptionsPage::setSource); specificlLay->addRow(RsImportStrings::tr("Import source:"), backendCombo); scrollArea = new QScrollArea; scrollArea->setWidgetResizable(true); @@ -109,8 +112,8 @@ void OptionsPage::initializePage() bool OptionsPage::validatePage() { RSImportWizard *w = static_cast(wizard()); - int backendIdx = backendCombo->currentIndex(); - if(backendCombo->currentIndex() < 0 || !optionsWidget) + int backendIdx = backendCombo->currentIndex(); + if (backendCombo->currentIndex() < 0 || !optionsWidget) return false; w->setDefaultTypeAndSpeed(RsType(defaultTypeCombo->currentIndex()), defaultSpeedSpin->value()); @@ -121,9 +124,9 @@ bool OptionsPage::validatePage() void OptionsPage::setMode(int m) { - if(m == 0) + if (m == 0) m = RSImportMode::ImportRSPieces; - if(m & RSImportMode::ImportRSPieces) + if (m & RSImportMode::ImportRSPieces) { m = RSImportMode::ImportRSOwners | RSImportMode::ImportRSModels; @@ -131,13 +134,13 @@ void OptionsPage::setMode(int m) importRS->setChecked(true); importRS->blockSignals(false); } - if(m & RSImportMode::ImportRSOwners) + if (m & RSImportMode::ImportRSOwners) { importOwners->blockSignals(true); importOwners->setChecked(true); importOwners->blockSignals(false); } - if(m & RSImportMode::ImportRSModels) + if (m & RSImportMode::ImportRSModels) { importModels->blockSignals(true); importModels->setChecked(true); @@ -149,11 +152,11 @@ void OptionsPage::setMode(int m) int OptionsPage::getMode() { int mode = 0; - if(importOwners->isChecked()) + if (importOwners->isChecked()) mode |= RSImportMode::ImportRSOwners; - if(importModels->isChecked()) + if (importModels->isChecked()) mode |= RSImportMode::ImportRSModels; - if(importRS->isChecked()) + if (importRS->isChecked()) mode |= RSImportMode::ImportRSPieces; return mode; } @@ -161,7 +164,7 @@ int OptionsPage::getMode() void OptionsPage::setSource(int backendIdx) { backendCombo->setCurrentIndex(backendIdx); - if(optionsWidget) + if (optionsWidget) { scrollArea->takeWidget(); delete optionsWidget; @@ -169,43 +172,46 @@ void OptionsPage::setSource(int backendIdx) } RSImportWizard *w = static_cast(wizard()); - optionsWidget = w->createOptionsWidget(backendIdx, this); + optionsWidget = w->createOptionsWidget(backendIdx, this); scrollArea->setWidget(optionsWidget); } void OptionsPage::updateGeneralCheckBox() { - if(!importOwners->isChecked() && !importModels->isChecked()) + if (!importOwners->isChecked() && !importModels->isChecked()) { QMessageBox::warning(this, RsImportStrings::tr("Invalid option"), RsImportStrings::tr("You must at least import owners or models")); - importModels->setChecked(true); //Tiggers an updateGeneralCheckBox() so return + importModels->setChecked(true); // Tiggers an updateGeneralCheckBox() so return return; } importRS->blockSignals(true); - if(importOwners->isChecked() && importModels->isChecked()) + if (importOwners->isChecked() && importModels->isChecked()) { importRS->setEnabled(true); importRS->setToolTip(QString()); } else { - if(importRS->isChecked()) + if (importRS->isChecked()) { - QMessageBox::warning(this, RsImportStrings::tr("No rolloingstock imported"), - RsImportStrings::tr("No rollingstock piece will be imported.\n" - "In order to import rollingstock pieces you must also import models and owners.")); + QMessageBox::warning( + this, RsImportStrings::tr("No rolloingstock imported"), + RsImportStrings::tr( + "No rollingstock piece will be imported.\n" + "In order to import rollingstock pieces you must also import models and owners.")); } importRS->setEnabled(false); importRS->setChecked(false); - importRS->setToolTip(RsImportStrings::tr("In order to import rollingstock pieces you must also import models and owners.")); + importRS->setToolTip(RsImportStrings::tr( + "In order to import rollingstock pieces you must also import models and owners.")); } importRS->blockSignals(false); - //Default type and speed have meaning only if importing models + // Default type and speed have meaning only if importing models defaultSpeedSpin->setEnabled(importModels->isChecked()); defaultTypeCombo->setEnabled(importModels->isChecked()); } diff --git a/src/rollingstock/importer/pages/optionspage.h b/src/rollingstock/importer/pages/optionspage.h index 5798fb0..ad1249c 100644 --- a/src/rollingstock/importer/pages/optionspage.h +++ b/src/rollingstock/importer/pages/optionspage.h @@ -51,7 +51,7 @@ private: QCheckBox *importOwners; QCheckBox *importModels; QCheckBox *importRS; - QSpinBox *defaultSpeedSpin; + QSpinBox *defaultSpeedSpin; QComboBox *defaultTypeCombo; QGroupBox *specificBox; diff --git a/src/rollingstock/importer/rsimportwizard.cpp b/src/rollingstock/importer/rsimportwizard.cpp index 24da23a..e1bda61 100644 --- a/src/rollingstock/importer/rsimportwizard.cpp +++ b/src/rollingstock/importer/rsimportwizard.cpp @@ -41,7 +41,7 @@ #include "backends/importtask.h" #include -//Backends +// Backends #include "backends/ods/rsimportodsbackend.h" #include "backends/sqlite/rsimportsqlitebackend.h" @@ -51,7 +51,7 @@ #include "utils/owningqpointer.h" RSImportWizard::RSImportWizard(bool resume, QWidget *parent) : - QWizard (parent), + QWizard(parent), loadTask(nullptr), importTask(nullptr), isStoppingTask(false), @@ -60,21 +60,21 @@ RSImportWizard::RSImportWizard(bool resume, QWidget *parent) : importMode(RSImportMode::ImportRSPieces), backendIdx(0) { - //Load backends + // Load backends backends = new RSImportBackendsModel(this); backends->addBackend(new RSImportODSBackend); backends->addBackend(new RSImportSQLiteBackend); - modelsModel = new RSImportedModelsModel(Session->m_Db, this); - ownersModel = new RSImportedOwnersModel(Session->m_Db, this); - listModel = new RSImportedRollingstockModel(Session->m_Db, this); + modelsModel = new RSImportedModelsModel(Session->m_Db, this); + ownersModel = new RSImportedOwnersModel(Session->m_Db, this); + listModel = new RSImportedRollingstockModel(Session->m_Db, this); loadFilePage = new LoadingPage(this); loadFilePage->setCommitPage(true); loadFilePage->setTitle(RsImportStrings::tr("File loading")); loadFilePage->setSubTitle(RsImportStrings::tr("Parsing file data...")); - //HACK: I don't like the 'Commit' button. This hack makes it similar to 'Next' button + // HACK: I don't like the 'Commit' button. This hack makes it similar to 'Next' button loadFilePage->setButtonText(QWizard::CommitButton, buttonText(QWizard::NextButton)); importPage = new LoadingPage(this); @@ -89,19 +89,26 @@ RSImportWizard::RSImportWizard(bool resume, QWidget *parent) : ChooseFilePage *chooseFilePage = new ChooseFilePage; connect(chooseFilePage, &ChooseFilePage::fileChosen, this, &RSImportWizard::onFileChosen); - setPage(OptionsPageIdx, new OptionsPage); - setPage(ChooseFileIdx, chooseFilePage); - setPage(LoadFileIdx, loadFilePage); - setPage(SelectOwnersIdx, new ItemSelectionPage(this, ownersModel, nullptr, ownersModel, RSImportedOwnersModel::MatchExisting, ModelModes::Owners)); - setPage(SelectModelsIdx, new ItemSelectionPage(this, modelsModel, nullptr, modelsModel, RSImportedModelsModel::MatchExisting, ModelModes::Models)); - setPage(SelectRsIdx, new ItemSelectionPage(this, listModel, spinFactory, nullptr, RSImportedRollingstockModel::NewNumber, ModelModes::Rollingstock)); - setPage(ImportRsIdx, importPage); + setPage(OptionsPageIdx, new OptionsPage); + setPage(ChooseFileIdx, chooseFilePage); + setPage(LoadFileIdx, loadFilePage); + setPage(SelectOwnersIdx, + new ItemSelectionPage(this, ownersModel, nullptr, ownersModel, + RSImportedOwnersModel::MatchExisting, ModelModes::Owners)); + setPage(SelectModelsIdx, + new ItemSelectionPage(this, modelsModel, nullptr, modelsModel, + RSImportedModelsModel::MatchExisting, ModelModes::Models)); + setPage(SelectRsIdx, new ItemSelectionPage(this, listModel, spinFactory, nullptr, + RSImportedRollingstockModel::NewNumber, + ModelModes::Rollingstock)); + setPage(ImportRsIdx, importPage); - if(resume) + if (resume) { setStartId(SelectOwnersIdx); setWindowTitle(tr("Continue Rollingstock Importation")); - }else + } + else { setWindowTitle(tr("Import Rollingstock")); } @@ -118,34 +125,36 @@ RSImportWizard::~RSImportWizard() void RSImportWizard::done(int result) { - if(result == QDialog::Rejected || result == RejectWithoutAsking) + if (result == QDialog::Rejected || result == RejectWithoutAsking) { - if(!isStoppingTask) + if (!isStoppingTask) { - if(result == QDialog::Rejected) //RejectWithoutAsking skips this + if (result == QDialog::Rejected) // RejectWithoutAsking skips this { OwningQPointer msgBox = new QMessageBox(this); msgBox->setIcon(QMessageBox::Question); msgBox->setWindowTitle(RsImportStrings::tr("Abort import?")); - msgBox->setText(RsImportStrings::tr("Do you want to import process? No data will be imported")); + msgBox->setText( + RsImportStrings::tr("Do you want to import process? No data will be imported")); QPushButton *abortBut = msgBox->addButton(QMessageBox::Abort); - QPushButton *noBut = msgBox->addButton(QMessageBox::No); + QPushButton *noBut = msgBox->addButton(QMessageBox::No); msgBox->setDefaultButton(noBut); - msgBox->setEscapeButton(noBut); //Do not Abort if dialog is closed by Esc or X window button + msgBox->setEscapeButton( + noBut); // Do not Abort if dialog is closed by Esc or X window button msgBox->exec(); bool abortClicked = msgBox && msgBox->clickedButton() == abortBut; - if(!abortClicked) + if (!abortClicked) return; } - if(loadTask) + if (loadTask) { loadTask->stop(); isStoppingTask = true; loadFilePage->setSubTitle(RsImportStrings::tr("Aborting...")); } - if(importTask) + if (importTask) { importTask->stop(); isStoppingTask = true; @@ -154,15 +163,15 @@ void RSImportWizard::done(int result) } else { - if(loadTask || importTask) - return; //Already sent 'stop', just wait + if (loadTask || importTask) + return; // Already sent 'stop', just wait } - //Reset to standard value because QWizard doesn't know about RejectWithoutAsking + // Reset to standard value because QWizard doesn't know about RejectWithoutAsking result = QDialog::Rejected; } - //Clear tables after import process completed or was aborted + // Clear tables after import process completed or was aborted Session->clearImportRSTables(); QWizard::done(result); @@ -170,9 +179,9 @@ void RSImportWizard::done(int result) bool RSImportWizard::validateCurrentPage() { - if(QWizard::validateCurrentPage()) + if (QWizard::validateCurrentPage()) { - if(nextId() == ImportRsIdx) + if (nextId() == ImportRsIdx) { startImportTask(); } @@ -188,27 +197,27 @@ int RSImportWizard::nextId() const { case LoadFileIdx: { - if((importMode & RSImportMode::ImportRSOwners) == 0) + if ((importMode & RSImportMode::ImportRSOwners) == 0) { - //Skip owners page + // Skip owners page id = SelectModelsIdx; } break; } case SelectOwnersIdx: { - if((importMode & RSImportMode::ImportRSModels) == 0) + if ((importMode & RSImportMode::ImportRSModels) == 0) { - //Skip models and rollingstock pages + // Skip models and rollingstock pages id = ImportRsIdx; } break; } case SelectModelsIdx: { - if((importMode & RSImportMode::ImportRSPieces) == 0) + if ((importMode & RSImportMode::ImportRSPieces) == 0) { - //Skip rollingstock page + // Skip rollingstock page id = ImportRsIdx; } break; @@ -219,24 +228,25 @@ int RSImportWizard::nextId() const bool RSImportWizard::event(QEvent *e) { - if(e->type() == LoadProgressEvent::_Type) + if (e->type() == LoadProgressEvent::_Type) { LoadProgressEvent *ev = static_cast(e); ev->setAccepted(true); - if(ev->task == loadTask) + if (ev->task == loadTask) { QString errText; - if(ev->max == LoadProgressEvent::ProgressMaxFinished) + if (ev->max == LoadProgressEvent::ProgressMaxFinished) { - if(ev->progress == LoadProgressEvent::ProgressError) + if (ev->progress == LoadProgressEvent::ProgressError) { errText = loadTask->getErrorText(); } loadFilePage->setSubTitle(tr("Completed.")); - //Delete task before handling event because otherwise it is detected as still running + // Delete task before handling event because otherwise it is detected as still + // running delete loadTask; loadTask = nullptr; loadFilePage->setProgressCompleted(true); @@ -244,21 +254,22 @@ bool RSImportWizard::event(QEvent *e) loadFilePage->handleProgress(ev->progress, ev->max); - if(ev->progress == LoadProgressEvent::ProgressError) + if (ev->progress == LoadProgressEvent::ProgressError) { QMessageBox::warning(this, RsImportStrings::tr("Loading Error"), errText); reject(); } - else if(ev->progress == LoadProgressEvent::ProgressAbortedByUser) + else if (ev->progress == LoadProgressEvent::ProgressAbortedByUser) { - reject(); //Reject the second time + reject(); // Reject the second time } } - else if(ev->task == importTask) + else if (ev->task == importTask) { - if(ev->max == LoadProgressEvent::ProgressMaxFinished) + if (ev->max == LoadProgressEvent::ProgressMaxFinished) { - //Delete task before handling event because otherwise it is detected as still running + // Delete task before handling event because otherwise it is detected as still + // running delete importTask; importTask = nullptr; importPage->setProgressCompleted(true); @@ -266,20 +277,20 @@ bool RSImportWizard::event(QEvent *e) importPage->handleProgress(ev->progress, ev->max); - if(ev->progress == LoadProgressEvent::ProgressError) + if (ev->progress == LoadProgressEvent::ProgressError) { - //QMessageBox::warning(this, RsImportStrings::tr("Loading Error"), errText); TODO + // QMessageBox::warning(this, RsImportStrings::tr("Loading Error"), errText); TODO reject(); } - else if(ev->progress == LoadProgressEvent::ProgressAbortedByUser) + else if (ev->progress == LoadProgressEvent::ProgressAbortedByUser) { - reject(); //Reject the second time + reject(); // Reject the second time } } return true; } - else if(e->type() == QEvent::Type(CustomEvents::RsImportGoBackPrevPage)) + else if (e->type() == QEvent::Type(CustomEvents::RsImportGoBackPrevPage)) { e->setAccepted(true); back(); @@ -292,16 +303,16 @@ void RSImportWizard::onFileChosen(const QString &filename) startLoadTask(filename); } -bool RSImportWizard::startLoadTask(const QString& fileName) +bool RSImportWizard::startLoadTask(const QString &fileName) { abortLoadTask(); - - //Clear tables before starting new import process + + // Clear tables before starting new import process Session->clearImportRSTables(); loadTask = createLoadTask(optionsMap, fileName); - if(!loadTask) + if (!loadTask) { QMessageBox::warning(this, RsImportStrings::tr("Error"), RsImportStrings::tr("Invalid option selected. Please try again.")); @@ -315,7 +326,7 @@ bool RSImportWizard::startLoadTask(const QString& fileName) void RSImportWizard::abortLoadTask() { - if(loadTask) + if (loadTask) { loadTask->stop(); loadTask->cleanup(); @@ -334,7 +345,7 @@ void RSImportWizard::startImportTask() void RSImportWizard::abortImportTask() { - if(importTask) + if (importTask) { importTask->stop(); importTask->cleanup(); @@ -350,14 +361,14 @@ void RSImportWizard::goToPrevPageQueued() void RSImportWizard::setDefaultTypeAndSpeed(RsType t, int speed) { defaultRsType = t; - defaultSpeed = speed; + defaultSpeed = speed; } void RSImportWizard::setImportMode(int m) { - if(m == 0) + if (m == 0) m = RSImportMode::ImportRSPieces; - if(m & RSImportMode::ImportRSPieces) + if (m & RSImportMode::ImportRSPieces) m |= RSImportMode::ImportRSOwners | RSImportMode::ImportRSModels; importMode = m; } @@ -370,11 +381,11 @@ QAbstractItemModel *RSImportWizard::getBackendsModel() const IOptionsWidget *RSImportWizard::createOptionsWidget(int idx, QWidget *parent) { RSImportBackend *back = backends->getBackend(idx); - if(!back) + if (!back) return nullptr; IOptionsWidget *w = back->createOptionsWidget(); - if(!w) + if (!w) return nullptr; w->setParent(parent); @@ -388,7 +399,7 @@ void RSImportWizard::setSource(int idx, IOptionsWidget *options) optionsMap.clear(); options->saveSettings(optionsMap); - //Update ChooseFilePage + // Update ChooseFilePage ChooseFilePage *chooseFilePage = static_cast(page(ChooseFileIdx)); QString dlgTitle; QStringList fileFormats; @@ -397,14 +408,14 @@ void RSImportWizard::setSource(int idx, IOptionsWidget *options) chooseFilePage->setFileDlgOptions(dlgTitle, fileFormats); } -ILoadRSTask *RSImportWizard::createLoadTask(const QMap &arguments, const QString& fileName) +ILoadRSTask *RSImportWizard::createLoadTask(const QMap &arguments, + const QString &fileName) { RSImportBackend *back = backends->getBackend(backendIdx); - if(!back) + if (!back) return nullptr; - ILoadRSTask *task = back->createLoadTask(arguments, Session->m_Db, importMode, - defaultSpeed, defaultRsType, fileName, - this); + ILoadRSTask *task = back->createLoadTask(arguments, Session->m_Db, importMode, defaultSpeed, + defaultRsType, fileName, this); return task; } diff --git a/src/rollingstock/importer/rsimportwizard.h b/src/rollingstock/importer/rsimportwizard.h index 50a0273..341d72f 100644 --- a/src/rollingstock/importer/rsimportwizard.h +++ b/src/rollingstock/importer/rsimportwizard.h @@ -70,33 +70,42 @@ public: bool startLoadTask(const QString &fileName); void abortLoadTask(); - inline bool taskRunning() const { return loadTask || importTask; } + inline bool taskRunning() const + { + return loadTask || importTask; + } void startImportTask(); void abortImportTask(); void goToPrevPageQueued(); -public: //Settings +public: // Settings void setDefaultTypeAndSpeed(RsType t, int speed); - inline int getImportMode() const { return importMode; } + inline int getImportMode() const + { + return importMode; + } void setImportMode(int m); - inline int getBackendIdx() const { return backendIdx; } + inline int getBackendIdx() const + { + return backendIdx; + } QAbstractItemModel *getBackendsModel() const; IOptionsWidget *createOptionsWidget(int idx, QWidget *parent); void setSource(int idx, IOptionsWidget *options); - ILoadRSTask *createLoadTask(const QMap& arguments, const QString &fileName); + ILoadRSTask *createLoadTask(const QMap &arguments, const QString &fileName); protected: bool event(QEvent *e) override; private slots: - void onFileChosen(const QString& filename); + void onFileChosen(const QString &filename); private: RSImportedOwnersModel *ownersModel; @@ -110,7 +119,7 @@ private: LoadingPage *importPage; bool isStoppingTask; - //Import options + // Import options int defaultSpeed; RsType defaultRsType; int importMode; diff --git a/src/rollingstock/manager/delegates/rsnumberdelegate.cpp b/src/rollingstock/manager/delegates/rsnumberdelegate.cpp index 806e09d..8ad552b 100644 --- a/src/rollingstock/manager/delegates/rsnumberdelegate.cpp +++ b/src/rollingstock/manager/delegates/rsnumberdelegate.cpp @@ -23,25 +23,25 @@ #include "rsnumspinbox.h" -//TODO: remove +// TODO: remove RsNumberDelegate::RsNumberDelegate(QObject *parent) : QStyledItemDelegate(parent) { - } -QWidget *RsNumberDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &index) const +QWidget *RsNumberDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex &index) const { QSpinBox *ed = nullptr; - QVariant v = index.data(RS_IS_ENGINE); - if(!v.toBool()) + QVariant v = index.data(RS_IS_ENGINE); + if (!v.toBool()) { - //Custom spinbox for Wagons 'XXX-X' + // Custom spinbox for Wagons 'XXX-X' ed = new RsNumSpinBox(parent); } else { - //Normal spinbox for Engines + // Normal spinbox for Engines ed = new QSpinBox(parent); ed->setRange(0, 9999); } @@ -52,9 +52,9 @@ QWidget *RsNumberDelegate::createEditor(QWidget *parent, const QStyleOptionViewI void RsNumberDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QSpinBox *ed = static_cast(editor); - QVariant v = index.data(RS_NUMBER); - int val = 0; - if(v.isValid()) + QVariant v = index.data(RS_NUMBER); + int val = 0; + if (v.isValid()) { val = v.toInt(); } @@ -62,13 +62,15 @@ void RsNumberDelegate::setEditorData(QWidget *editor, const QModelIndex &index) ed->setValue(val); } -void RsNumberDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void RsNumberDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const { QSpinBox *ed = static_cast(editor); model->setData(index, ed->value(), RS_NUMBER); } -void RsNumberDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const +void RsNumberDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex & /*index*/) const { editor->setGeometry(option.rect); } diff --git a/src/rollingstock/manager/delegates/rsnumberdelegate.h b/src/rollingstock/manager/delegates/rsnumberdelegate.h index e64dc51..e4623ff 100644 --- a/src/rollingstock/manager/delegates/rsnumberdelegate.h +++ b/src/rollingstock/manager/delegates/rsnumberdelegate.h @@ -35,8 +35,8 @@ public: void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; signals: diff --git a/src/rollingstock/manager/delegates/rsnumspinbox.cpp b/src/rollingstock/manager/delegates/rsnumspinbox.cpp index f184e1b..e969b5e 100644 --- a/src/rollingstock/manager/delegates/rsnumspinbox.cpp +++ b/src/rollingstock/manager/delegates/rsnumspinbox.cpp @@ -19,20 +19,20 @@ #include "rsnumspinbox.h" -//TODO: remove +// TODO: remove RsNumSpinBox::RsNumSpinBox(QWidget *parent) : QSpinBox(parent) { - setRange(0, 9999); //from 000-0 to 999-9 + setRange(0, 9999); // from 000-0 to 999-9 } -QValidator::State RsNumSpinBox::validate(QString &input, int &/*pos*/) const +QValidator::State RsNumSpinBox::validate(QString &input, int & /*pos*/) const { QString s = input; s.remove(QChar('-')); bool ok = false; int val = s.toInt(&ok); - if(ok && val >= minimum() && val <= maximum()) + if (ok && val >= minimum() && val <= maximum()) return QValidator::Acceptable; return QValidator::Invalid; } @@ -43,7 +43,7 @@ int RsNumSpinBox::valueFromText(const QString &str) const s.remove(QChar('-')); bool ok = false; int val = s.toInt(&ok); - if(ok) + if (ok) return val; return 0; } @@ -51,7 +51,7 @@ int RsNumSpinBox::valueFromText(const QString &str) const QString RsNumSpinBox::textFromValue(int val) const { QString str = QString::number(val); - str = str.rightJustified(4, QChar('0')); + str = str.rightJustified(4, QChar('0')); str.insert(3, QChar('-')); - return str; //XXX-X + return str; // XXX-X } diff --git a/src/rollingstock/manager/delegates/rsnumspinbox.h b/src/rollingstock/manager/delegates/rsnumspinbox.h index 421a5c1..2438a90 100644 --- a/src/rollingstock/manager/delegates/rsnumspinbox.h +++ b/src/rollingstock/manager/delegates/rsnumspinbox.h @@ -31,7 +31,7 @@ public: virtual QValidator::State validate(QString &input, int &pos) const override; protected: - int valueFromText(const QString& text) const override; + int valueFromText(const QString &text) const override; QString textFromValue(int val) const override; }; diff --git a/src/rollingstock/manager/delegates/rstypedelegate.cpp b/src/rollingstock/manager/delegates/rstypedelegate.cpp index 3f7e5c5..792dd15 100644 --- a/src/rollingstock/manager/delegates/rstypedelegate.cpp +++ b/src/rollingstock/manager/delegates/rstypedelegate.cpp @@ -27,53 +27,56 @@ #include RSTypeDelegate::RSTypeDelegate(bool subType, QObject *parent) : - QStyledItemDelegate (parent), + QStyledItemDelegate(parent), m_subType(subType) { QStringList list; - if(subType) + if (subType) { list.reserve(int(RsEngineSubType::NTypes)); - for(int i = 0; i < int(RsEngineSubType::NTypes); i++) + for (int i = 0; i < int(RsEngineSubType::NTypes); i++) list.append(RsTypeNames::name(RsEngineSubType(i))); } else { list.reserve(int(RsType::NTypes)); - for(int i = 0; i < int(RsType::NTypes); i++) + for (int i = 0; i < int(RsType::NTypes); i++) list.append(RsTypeNames::name(RsType(i))); } comboModel.setStringList(list); } -QWidget *RSTypeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*options*/, const QModelIndex &/*idx*/) const +QWidget *RSTypeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*options*/, + const QModelIndex & /*idx*/) const { QComboBox *combo = new QComboBox(parent); - combo->setModel(const_cast(&comboModel)); + combo->setModel(const_cast(&comboModel)); return combo; } void RSTypeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QComboBox *combo = static_cast(editor); - int type = index.data(m_subType ? RS_SUB_TYPE_ROLE : RS_TYPE_ROLE).toInt(); - connect(combo, static_cast(&QComboBox::activated), this, &RSTypeDelegate::onItemClicked); + int type = index.data(m_subType ? RS_SUB_TYPE_ROLE : RS_TYPE_ROLE).toInt(); + connect(combo, static_cast(&QComboBox::activated), this, + &RSTypeDelegate::onItemClicked); combo->setCurrentIndex(type); combo->showPopup(); } -void RSTypeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void RSTypeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const { QComboBox *combo = static_cast(editor); - int type = combo->currentIndex(); + int type = combo->currentIndex(); model->setData(index, type, m_subType ? RS_SUB_TYPE_ROLE : RS_TYPE_ROLE); } void RSTypeDelegate::onItemClicked() { QComboBox *combo = qobject_cast(sender()); - if(combo) + if (combo) { emit commitData(combo); emit closeEditor(combo); diff --git a/src/rollingstock/manager/delegates/rstypedelegate.h b/src/rollingstock/manager/delegates/rstypedelegate.h index 23d6c88..89cce33 100644 --- a/src/rollingstock/manager/delegates/rstypedelegate.h +++ b/src/rollingstock/manager/delegates/rstypedelegate.h @@ -29,7 +29,8 @@ class RSTypeDelegate : public QStyledItemDelegate public: explicit RSTypeDelegate(bool subType, QObject *parent = nullptr); - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &options, const QModelIndex &idx) const override; + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &options, + const QModelIndex &idx) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; diff --git a/src/rollingstock/manager/dialogs/mergemodelsdialog.cpp b/src/rollingstock/manager/dialogs/mergemodelsdialog.cpp index 2656a9a..b7b83aa 100644 --- a/src/rollingstock/manager/dialogs/mergemodelsdialog.cpp +++ b/src/rollingstock/manager/dialogs/mergemodelsdialog.cpp @@ -39,9 +39,9 @@ MergeModelsDialog::MergeModelsDialog(sqlite3pp::database &db, QWidget *parent) : { ui->setupUi(this); - model = new RSModelsMatchModel(mDb, this); + model = new RSModelsMatchModel(mDb, this); sourceModelEdit = new CustomCompletionLineEdit(model); - destModelEdit = new CustomCompletionLineEdit(model); + destModelEdit = new CustomCompletionLineEdit(model); sourceModelEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); destModelEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); @@ -49,8 +49,10 @@ MergeModelsDialog::MergeModelsDialog(sqlite3pp::database &db, QWidget *parent) : ui->gridLayout->addWidget(sourceModelEdit, 1, 0); ui->gridLayout->addWidget(destModelEdit, 2, 0); - connect(sourceModelEdit, &CustomCompletionLineEdit::dataIdChanged, this, &MergeModelsDialog::sourceModelChanged); - connect(destModelEdit, &CustomCompletionLineEdit::dataIdChanged, this, &MergeModelsDialog::destModelChanged); + connect(sourceModelEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &MergeModelsDialog::sourceModelChanged); + connect(destModelEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &MergeModelsDialog::destModelChanged); ui->removeSourceCheckBox->setChecked(AppSettings.getRemoveMergedSourceModel()); } @@ -62,32 +64,33 @@ MergeModelsDialog::~MergeModelsDialog() void MergeModelsDialog::done(int r) { - if(r == QDialog::Accepted) + if (r == QDialog::Accepted) { db_id sourceModelId = 0; - db_id destModelId = 0; + db_id destModelId = 0; QString tmp; sourceModelEdit->getData(sourceModelId, tmp); destModelEdit->getData(destModelId, tmp); - //Check input is valid - if(!sourceModelId || !destModelId || sourceModelId == destModelId) + // Check input is valid + if (!sourceModelId || !destModelId || sourceModelId == destModelId) { - QMessageBox::warning(this, tr("Invalid Models"), tr("Models must not be null and must be different")); - return; //We don't want the dialog to be closed + QMessageBox::warning(this, tr("Invalid Models"), + tr("Models must not be null and must be different")); + return; // We don't want the dialog to be closed } - if(mergeModels(sourceModelId, destModelId, ui->removeSourceCheckBox->isChecked())) + if (mergeModels(sourceModelId, destModelId, ui->removeSourceCheckBox->isChecked())) { - //Operation succeded, inform user - QMessageBox::information(this, - tr("Merging completed"), + // Operation succeded, inform user + QMessageBox::information(this, tr("Merging completed"), tr("Models merged succesfully.")); } else { - QMessageBox::warning(this, tr("Error while merging"), tr("Some error occurred while merging models.")); - //Accept dialog to close it, so don't return here + QMessageBox::warning(this, tr("Error while merging"), + tr("Some error occurred while merging models.")); + // Accept dialog to close it, so don't return here } } @@ -106,60 +109,61 @@ void MergeModelsDialog::destModelChanged(db_id modelId) void MergeModelsDialog::fillModelInfo(QLabel *label, db_id modelId) { - if(!modelId) + if (!modelId) { label->setText(tr("No model set")); return; } q_getModelInfo.bind(1, modelId); - if(q_getModelInfo.step() != SQLITE_ROW) + if (q_getModelInfo.step() != SQLITE_ROW) { label->setText(tr("Error")); q_getModelInfo.reset(); return; } - auto r = q_getModelInfo.getRows(); - QString suffix = r.get(0); - int maxSpeedKmH = r.get(1); - int axes = r.get(2); - RsType type = RsType(r.get(3)); + auto r = q_getModelInfo.getRows(); + QString suffix = r.get(0); + int maxSpeedKmH = r.get(1); + int axes = r.get(2); + RsType type = RsType(r.get(3)); RsEngineSubType subType = RsEngineSubType(r.get(4)); - QString typeStr = RsTypeNames::name(type); - if(type == RsType::Engine) + QString typeStr = RsTypeNames::name(type); + if (type == RsType::Engine) { typeStr.append(", "); typeStr.append(RsTypeNames::name(subType)); } - if(!suffix.isEmpty()) + if (!suffix.isEmpty()) { QString tmp; tmp.reserve(suffix.size() + 8); - tmp.append(""); //3 char + tmp.append(""); // 3 char tmp.append(suffix); - tmp.append(" "); //5 char + tmp.append(" "); // 5 char suffix = tmp; } label->setText(tr("%1Axes: %2 Max.Speed: %3 km/h
Type: %4") - .arg(suffix) - .arg(axes) - .arg(maxSpeedKmH) - .arg(typeStr)); + .arg(suffix) + .arg(axes) + .arg(maxSpeedKmH) + .arg(typeStr)); adjustSize(); - model->autoSuggest(QString()); //Reset query + model->autoSuggest(QString()); // Reset query q_getModelInfo.reset(); } /* Merge sourceModel in destModel: * - all rollingstock of model 'sourceModel' will be changed to model 'destModel' - * - if removeSource is true then at the end of the operation 'sourceModel' is deleted from the database + * - if removeSource is true then at the end of the operation 'sourceModel' is deleted from the + * database * * If fails returns -1 * If succeds returns the number of rollingstock pieces that have been changed @@ -176,8 +180,8 @@ void MergeModelsDialog::fillModelInfo(QLabel *label, db_id modelId) */ int MergeModelsDialog::mergeModels(db_id sourceModelId, db_id destModelId, bool removeSource) { - if(sourceModelId == destModelId) - return false; //Error: must be different models + if (sourceModelId == destModelId) + return false; // Error: must be different models command q_mergeModels(mDb, "UPDATE rs_list SET model_id=? WHERE model_id=?"); q_mergeModels.bind(1, destModelId); @@ -185,19 +189,19 @@ int MergeModelsDialog::mergeModels(db_id sourceModelId, db_id destModelId, bool int ret = q_mergeModels.execute(); q_mergeModels.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qDebug() << "Merging Models" << sourceModelId << destModelId; qDebug() << "DB Error:" << ret << mDb.error_msg() << mDb.extended_error_code(); return false; } - if(removeSource) + if (removeSource) { command q_removeSource(mDb, "DELETE FROM rs_models WHERE id=?"); q_removeSource.bind(1, sourceModelId); ret = q_removeSource.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qDebug() << "Removing model" << sourceModelId; qDebug() << "DB Error:" << ret << mDb.error_msg() << mDb.extended_error_code(); diff --git a/src/rollingstock/manager/dialogs/mergeownersdialog.cpp b/src/rollingstock/manager/dialogs/mergeownersdialog.cpp index 46794dc..f3e8883 100644 --- a/src/rollingstock/manager/dialogs/mergeownersdialog.cpp +++ b/src/rollingstock/manager/dialogs/mergeownersdialog.cpp @@ -36,9 +36,9 @@ MergeOwnersDialog::MergeOwnersDialog(database &db, QWidget *parent) : { ui->setupUi(this); - model = new RSOwnersMatchModel(mDb, this); + model = new RSOwnersMatchModel(mDb, this); sourceOwnerEdit = new CustomCompletionLineEdit(model); - destOwnerEdit = new CustomCompletionLineEdit(model); + destOwnerEdit = new CustomCompletionLineEdit(model); sourceOwnerEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); destOwnerEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); @@ -47,8 +47,10 @@ MergeOwnersDialog::MergeOwnersDialog(database &db, QWidget *parent) : ui->verticalLayout->insertWidget(idx + 1, destOwnerEdit); ui->verticalLayout->insertWidget(idx + 1, sourceOwnerEdit); - connect(sourceOwnerEdit, &CustomCompletionLineEdit::editingFinished, this, &MergeOwnersDialog::resetModel); - connect(destOwnerEdit, &CustomCompletionLineEdit::editingFinished, this, &MergeOwnersDialog::resetModel); + connect(sourceOwnerEdit, &CustomCompletionLineEdit::editingFinished, this, + &MergeOwnersDialog::resetModel); + connect(destOwnerEdit, &CustomCompletionLineEdit::editingFinished, this, + &MergeOwnersDialog::resetModel); ui->removeSourceCheckBox->setChecked(AppSettings.getRemoveMergedSourceOwner()); } @@ -60,31 +62,33 @@ MergeOwnersDialog::~MergeOwnersDialog() void MergeOwnersDialog::done(int r) { - if(r == QDialog::Accepted) + if (r == QDialog::Accepted) { db_id sourceOwnerId = 0; - db_id destOwnerId = 0; + db_id destOwnerId = 0; QString tmp; sourceOwnerEdit->getData(sourceOwnerId, tmp); destOwnerEdit->getData(destOwnerId, tmp); - //Check input is valid - if(!sourceOwnerId || !destOwnerId || sourceOwnerId == destOwnerId) + // Check input is valid + if (!sourceOwnerId || !destOwnerId || sourceOwnerId == destOwnerId) { - QMessageBox::warning(this, tr("Invalid Owners"), tr("Owners must not be null and must be different")); - return; //We don't want the dialog to be closed + QMessageBox::warning(this, tr("Invalid Owners"), + tr("Owners must not be null and must be different")); + return; // We don't want the dialog to be closed } - if(mergeOwners(sourceOwnerId, destOwnerId, ui->removeSourceCheckBox->isChecked())) + if (mergeOwners(sourceOwnerId, destOwnerId, ui->removeSourceCheckBox->isChecked())) { - //Operation succeded, inform user + // Operation succeded, inform user QMessageBox::information(this, tr("Merging completed"), tr("Owners merged succesfully.")); } else { - QMessageBox::warning(this, tr("Error while merging"), tr("Some error occurred while merging owners.")); - //Accept dialog to close it, so don't return here + QMessageBox::warning(this, tr("Error while merging"), + tr("Some error occurred while merging owners.")); + // Accept dialog to close it, so don't return here } } @@ -104,19 +108,19 @@ bool MergeOwnersDialog::mergeOwners(db_id sourceOwnerId, db_id destOwnerId, bool int ret = q_mergeOwners.execute(); q_mergeOwners.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qDebug() << "Merging Owners" << sourceOwnerId << destOwnerId; qDebug() << "DB Error:" << ret << mDb.error_msg() << mDb.extended_error_code(); return false; } - if(removeSource) + if (removeSource) { command q_removeSource(mDb, "DELETE FROM rs_owners WHERE id=?"); q_removeSource.bind(1, sourceOwnerId); ret = q_removeSource.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qDebug() << "Removing owner" << sourceOwnerId; qDebug() << "DB Error:" << ret << mDb.error_msg() << mDb.extended_error_code(); diff --git a/src/rollingstock/manager/rollingstockmanager.cpp b/src/rollingstock/manager/rollingstockmanager.cpp index ffc0e28..d26d6c5 100644 --- a/src/rollingstock/manager/rollingstockmanager.cpp +++ b/src/rollingstock/manager/rollingstockmanager.cpp @@ -85,7 +85,7 @@ RollingStockManager::RollingStockManager(QWidget *parent) : void RollingStockManager::setupPages() { - //RollingStock Page + // RollingStock Page QWidget *rollingstockTab = new QWidget; tabWidget->addTab(rollingstockTab, RsTypeNames::tr("Rollingstock")); QVBoxLayout *rsLay = new QVBoxLayout(rollingstockTab); @@ -94,22 +94,19 @@ void RollingStockManager::setupPages() rsToolBar = new QToolBar; rsLay->addWidget(rsToolBar); - actNewRs = rsToolBar->addAction(tr("New Rollingstock"), - this, &RollingStockManager::onNewRs); - actDeleteRs = rsToolBar->addAction(tr("Remove"), - this, &RollingStockManager::onRemoveRs); + actNewRs = rsToolBar->addAction(tr("New Rollingstock"), this, &RollingStockManager::onNewRs); + actDeleteRs = rsToolBar->addAction(tr("Remove"), this, &RollingStockManager::onRemoveRs); rsToolBar->addSeparator(); - actViewRSPlan = rsToolBar->addAction(tr("View Plan"), - this, &RollingStockManager::onViewRSPlan); + actViewRSPlan = rsToolBar->addAction(tr("View Plan"), this, &RollingStockManager::onViewRSPlan); QMenu *actionRsPlanMenu = new QMenu; - actViewRSPlanSearch = actionRsPlanMenu->addAction(tr("Search rollingstock item"), - this, &RollingStockManager::onViewRSPlanSearch); + actViewRSPlanSearch = actionRsPlanMenu->addAction(tr("Search rollingstock item"), this, + &RollingStockManager::onViewRSPlanSearch); actViewRSPlan->setMenu(actionRsPlanMenu); rsToolBar->addSeparator(); - actDeleteAllRs = rsToolBar->addAction(tr("Delete All Rollingstock"), - this, &RollingStockManager::onRemoveAllRs); + actDeleteAllRs = rsToolBar->addAction(tr("Delete All Rollingstock"), this, + &RollingStockManager::onRemoveAllRs); rsToolBar->addSeparator(); rsToolBar->addAction(tr("Import"), this, &RollingStockManager::onImportRS); @@ -129,14 +126,14 @@ void RollingStockManager::setupPages() rsLay->addWidget(ps); ps->setModel(rsSQLModel); - connect(rsView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &RollingStockManager::onRollingstockSelectionChanged); - connect(rsSQLModel, &QAbstractItemModel::modelReset, - this, &RollingStockManager::onRollingstockSelectionChanged); - connect(rsSQLModel, &RollingstockSQLModel::modelError, - this, &RollingStockManager::onModelError); + connect(rsView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &RollingStockManager::onRollingstockSelectionChanged); + connect(rsSQLModel, &QAbstractItemModel::modelReset, this, + &RollingStockManager::onRollingstockSelectionChanged); + connect(rsSQLModel, &RollingstockSQLModel::modelError, this, + &RollingStockManager::onModelError); - //Models Page + // Models Page QWidget *modelsTab = new QWidget; tabWidget->addTab(modelsTab, RsTypeNames::tr("Models")); QVBoxLayout *modelsLay = new QVBoxLayout(modelsTab); @@ -145,24 +142,26 @@ void RollingStockManager::setupPages() modelToolBar = new QToolBar; modelsLay->addWidget(modelToolBar); - actNewModel = modelToolBar->addAction(tr("New Model"), - this, &RollingStockManager::onNewRsModel); - actDeleteModel = modelToolBar->addAction(tr("Remove"), - this, &RollingStockManager::onRemoveRsModel); - actMergeModels = modelToolBar->addAction(tr("Merge Models"), - this, &RollingStockManager::onMergeModels); - actNewModelWithSuffix = modelToolBar->addAction(tr("New with suffix"), - this, &RollingStockManager::onNewRsModelWithDifferentSuffixFromCurrent); + actNewModel = + modelToolBar->addAction(tr("New Model"), this, &RollingStockManager::onNewRsModel); + actDeleteModel = + modelToolBar->addAction(tr("Remove"), this, &RollingStockManager::onRemoveRsModel); + actMergeModels = + modelToolBar->addAction(tr("Merge Models"), this, &RollingStockManager::onMergeModels); + actNewModelWithSuffix = + modelToolBar->addAction(tr("New with suffix"), this, + &RollingStockManager::onNewRsModelWithDifferentSuffixFromCurrent); QMenu *actionModelSuffixMenu = new QMenu; - actNewModelWithSuffixSearch = actionModelSuffixMenu->addAction(tr("Search rollingstock model"), - this, &RollingStockManager::onNewRsModelWithDifferentSuffixFromSearch); + actNewModelWithSuffixSearch = actionModelSuffixMenu->addAction( + tr("Search rollingstock model"), this, + &RollingStockManager::onNewRsModelWithDifferentSuffixFromSearch); actNewModelWithSuffix->setMenu(actionModelSuffixMenu); modelToolBar->addSeparator(); - actDeleteAllRsModels = modelToolBar->addAction(tr("Delete All Models"), - this, &RollingStockManager::onRemoveAllRsModels); + actDeleteAllRsModels = modelToolBar->addAction(tr("Delete All Models"), this, + &RollingStockManager::onRemoveAllRsModels); - rsModelsView = new QTableView; + rsModelsView = new QTableView; rsModelsView->setSelectionMode(QTableView::SingleSelection); modelsLay->addWidget(rsModelsView); @@ -176,14 +175,14 @@ void RollingStockManager::setupPages() modelsLay->addWidget(ps); ps->setModel(modelsSQLModel); - connect(rsModelsView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &RollingStockManager::onRsModelSelectionChanged); - connect(modelsSQLModel, &QAbstractItemModel::modelReset, - this, &RollingStockManager::onRsModelSelectionChanged); - connect(modelsSQLModel, &RSModelsSQLModel::modelError, - this, &RollingStockManager::onModelError); + connect(rsModelsView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &RollingStockManager::onRsModelSelectionChanged); + connect(modelsSQLModel, &QAbstractItemModel::modelReset, this, + &RollingStockManager::onRsModelSelectionChanged); + connect(modelsSQLModel, &RSModelsSQLModel::modelError, this, + &RollingStockManager::onModelError); - //Owners Page + // Owners Page QWidget *ownersTab = new QWidget; tabWidget->addTab(ownersTab, RsTypeNames::tr("Owners")); QVBoxLayout *ownersLay = new QVBoxLayout(ownersTab); @@ -192,17 +191,16 @@ void RollingStockManager::setupPages() ownersToolBar = new QToolBar; ownersLay->addWidget(ownersToolBar); - actNewOwner = ownersToolBar->addAction(tr("New Owner"), this, - &RollingStockManager::onNewOwner); - actDeleteOwner = ownersToolBar->addAction(tr("Remove"), this, - &RollingStockManager::onRemoveOwner); - actMergeOwners = ownersToolBar->addAction(tr("Merge Owners"), this, - &RollingStockManager::onMergeOwners); + actNewOwner = ownersToolBar->addAction(tr("New Owner"), this, &RollingStockManager::onNewOwner); + actDeleteOwner = + ownersToolBar->addAction(tr("Remove"), this, &RollingStockManager::onRemoveOwner); + actMergeOwners = + ownersToolBar->addAction(tr("Merge Owners"), this, &RollingStockManager::onMergeOwners); ownersToolBar->addSeparator(); - actDeleteAllRsOwners = ownersToolBar->addAction(tr("Delete All Owners"), - this, &RollingStockManager::onRemoveAllRsOwners); + actDeleteAllRsOwners = ownersToolBar->addAction(tr("Delete All Owners"), this, + &RollingStockManager::onRemoveAllRsOwners); - ownersView = new QTableView; + ownersView = new QTableView; ownersView->setSelectionMode(QTableView::SingleSelection); ownersLay->addWidget(ownersView); @@ -216,27 +214,29 @@ void RollingStockManager::setupPages() ownersLay->addWidget(ps); ps->setModel(ownersSQLModel); - connect(ownersView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &RollingStockManager::onRsOwnerSelectionChanged); - connect(ownersSQLModel, &QAbstractItemModel::modelReset, - this, &RollingStockManager::onRsOwnerSelectionChanged); - connect(ownersSQLModel, &RSOwnersSQLModel::modelError, - this, &RollingStockManager::onModelError); + connect(ownersView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &RollingStockManager::onRsOwnerSelectionChanged); + connect(ownersSQLModel, &QAbstractItemModel::modelReset, this, + &RollingStockManager::onRsOwnerSelectionChanged); + connect(ownersSQLModel, &RSOwnersSQLModel::modelError, this, + &RollingStockManager::onModelError); - //Setup Delegates - //auto modelDelegate = new RSModelDelegate(modelsModel, this); - auto modelDelegate = new SqlFKFieldDelegate(new RSMatchModelFactory(ModelModes::Models, Session->m_Db, this), rsSQLModel, this); + // Setup Delegates + // auto modelDelegate = new RSModelDelegate(modelsModel, this); + auto modelDelegate = new SqlFKFieldDelegate( + new RSMatchModelFactory(ModelModes::Models, Session->m_Db, this), rsSQLModel, this); rsView->setItemDelegateForColumn(RollingstockSQLModel::Model, modelDelegate); - //auto ownerDelegate = new RSOwnerDelegate(ownersModel, this); - auto ownerDelegate = new SqlFKFieldDelegate(new RSMatchModelFactory(ModelModes::Owners, Session->m_Db, this), rsSQLModel, this); + // auto ownerDelegate = new RSOwnerDelegate(ownersModel, this); + auto ownerDelegate = new SqlFKFieldDelegate( + new RSMatchModelFactory(ModelModes::Owners, Session->m_Db, this), rsSQLModel, this); rsView->setItemDelegateForColumn(RollingstockSQLModel::Owner, ownerDelegate); auto numberDelegate = new RsNumberDelegate(this); rsView->setItemDelegateForColumn(RollingstockSQLModel::Number, numberDelegate); auto rsSpeedDelegate = new QStyledItemDelegate(this); - speedSpinFactory = new SpinBoxEditorFactory; + speedSpinFactory = new SpinBoxEditorFactory; speedSpinFactory->setRange(1, 999); speedSpinFactory->setSuffix(" km/h"); speedSpinFactory->setAlignment(Qt::AlignRight | Qt::AlignVCenter); @@ -244,7 +244,7 @@ void RollingStockManager::setupPages() rsModelsView->setItemDelegateForColumn(RSModelsSQLModel::MaxSpeed, rsSpeedDelegate); auto rsAxesDelegate = new QStyledItemDelegate(this); - axesSpinFactory = new SpinBoxEditorFactory; + axesSpinFactory = new SpinBoxEditorFactory; axesSpinFactory->setRange(2, 999); axesSpinFactory->setAlignment(Qt::AlignRight | Qt::AlignVCenter); rsAxesDelegate->setItemEditorFactory(axesSpinFactory); @@ -256,7 +256,7 @@ void RollingStockManager::setupPages() auto rsSubTypeDelegate = new RSTypeDelegate(true, this); rsModelsView->setItemDelegateForColumn(RSModelsSQLModel::SubTypeCol, rsSubTypeDelegate); - //Setup actions + // Setup actions editActGroup = new QActionGroup(this); editActGroup->addAction(actNewRs); editActGroup->addAction(actDeleteRs); @@ -278,9 +278,9 @@ RollingStockManager::~RollingStockManager() delete speedSpinFactory; delete axesSpinFactory; - for(int i = 0; i < NTabs; i++) + for (int i = 0; i < NTabs; i++) { - if(clearModelTimers[i] > 0) + if (clearModelTimers[i] > 0) { killTimer(clearModelTimers[i]); clearModelTimers[i] = 0; @@ -290,14 +290,14 @@ RollingStockManager::~RollingStockManager() void RollingStockManager::setReadOnly(bool readOnly) { - if(m_readOnly == readOnly) + if (m_readOnly == readOnly) return; m_readOnly = readOnly; editActGroup->setDisabled(m_readOnly); - if(m_readOnly) + if (m_readOnly) { rsView->setEditTriggers(QAbstractItemView::NoEditTriggers); rsModelsView->setEditTriggers(QAbstractItemView::NoEditTriggers); @@ -315,14 +315,14 @@ void RollingStockManager::updateModels() { int curTab = tabWidget->currentIndex(); - if(clearModelTimers[curTab] > 0) + if (clearModelTimers[curTab] > 0) { - //This page was already cached, stop it from clearing + // This page was already cached, stop it from clearing killTimer(clearModelTimers[curTab]); } - else if(clearModelTimers[curTab] == ModelCleared) + else if (clearModelTimers[curTab] == ModelCleared) { - //This page wasn't already cached + // This page wasn't already cached switch (curTab) { case RollingstockTab: @@ -344,8 +344,9 @@ void RollingStockManager::updateModels() } clearModelTimers[curTab] = ModelLoaded; - //Now start timer to clear old current page if not already done - if(oldCurrentTab != curTab && clearModelTimers[oldCurrentTab] == ModelLoaded) //Wait 10 seconds and then clear cache + // Now start timer to clear old current page if not already done + if (oldCurrentTab != curTab + && clearModelTimers[oldCurrentTab] == ModelLoaded) // Wait 10 seconds and then clear cache { clearModelTimers[oldCurrentTab] = startTimer(ClearModelTimeout, Qt::VeryCoarseTimer); } @@ -355,15 +356,17 @@ void RollingStockManager::updateModels() void RollingStockManager::visibilityChanged(int v) { - if(v == QWindow::Minimized || v == QWindow::Hidden) + if (v == QWindow::Minimized || v == QWindow::Hidden) { - //If the window is minimized start timer to clear model cache of current tab - //The other tabs already have been cleared or are waiting with their timers - if(clearModelTimers[oldCurrentTab] == ModelLoaded) + // If the window is minimized start timer to clear model cache of current tab + // The other tabs already have been cleared or are waiting with their timers + if (clearModelTimers[oldCurrentTab] == ModelLoaded) { clearModelTimers[oldCurrentTab] = startTimer(ClearModelTimeout, Qt::VeryCoarseTimer); } - }else{ + } + else + { updateModels(); } } @@ -382,11 +385,11 @@ void RollingStockManager::importRS(bool resume, QWidget *parent) void RollingStockManager::onViewRSPlan() { QModelIndex idx = rsView->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; db_id rsId = rsSQLModel->getIdAtRow(idx.row()); - if(!rsId) + if (!rsId) return; Session->getViewManager()->requestRSInfo(rsId); } @@ -403,7 +406,7 @@ void RollingStockManager::onViewRSPlanSearch() int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; Session->getViewManager()->requestRSInfo(dlg->getItemId()); @@ -411,13 +414,13 @@ void RollingStockManager::onViewRSPlanSearch() void RollingStockManager::onNewRs() { - if(m_readOnly) + if (m_readOnly) return; QString errText; - int row = 0; + int row = 0; db_id rsId = rsSQLModel->addRSItem(&row, &errText); - if(!rsId) + if (!rsId) { QMessageBox::warning(this, tr("Error adding rollingstock piece"), errText); return; @@ -426,47 +429,49 @@ void RollingStockManager::onNewRs() void RollingStockManager::onRemoveRs() { - if(m_readOnly) + if (m_readOnly) return; QModelIndex idx = rsView->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; - if(!rsSQLModel->removeRSItemAt(idx.row())) + if (!rsSQLModel->removeRSItemAt(idx.row())) { - //ERRORMSG: display error + // ERRORMSG: display error return; } } void RollingStockManager::onRemoveAllRs() { - int ret = QMessageBox::question(this, tr("Delete All Rollingstock?"), - tr("Are you really sure you want to delete all rollingstock from this session?\n" - "NOTE: this will not erease model and owners, just rollingstock pieces.")); - if(ret == QMessageBox::Yes) + int ret = QMessageBox::question( + this, tr("Delete All Rollingstock?"), + tr("Are you really sure you want to delete all rollingstock from this session?\n" + "NOTE: this will not erease model and owners, just rollingstock pieces.")); + if (ret == QMessageBox::Yes) { - if(!rsSQLModel->removeAllRS()) + if (!rsSQLModel->removeAllRS()) { - QMessageBox::warning(this, tr("Error"), - tr("Failed to remove rollingstock.\n" - "Make sure there are no more couplings in this session.\n" - "NOTE: you can remove all jobs at once from the Jobs Manager.")); + QMessageBox::warning( + this, tr("Error"), + tr("Failed to remove rollingstock.\n" + "Make sure there are no more couplings in this session.\n" + "NOTE: you can remove all jobs at once from the Jobs Manager.")); } } } void RollingStockManager::onNewRsModel() { - if(m_readOnly) + if (m_readOnly) return; int row = 0; QString errText; db_id modelId = modelsSQLModel->addRSModel(&row, 0, QString(), &errText); - if(!modelId) + if (!modelId) { QMessageBox::warning(this, tr("Error adding model"), errText); return; @@ -476,23 +481,24 @@ void RollingStockManager::onNewRsModel() rsModelsView->setCurrentIndex(idx); rsModelsView->scrollTo(idx); - rsModelsView->edit(idx); //TODO: delay call until row is fetched!!! Like save it and wait for a signal from model + rsModelsView->edit(idx); // TODO: delay call until row is fetched!!! Like save it and wait for a + // signal from model } void RollingStockManager::onNewRsModelWithDifferentSuffixFromCurrent() { - if(m_readOnly) + if (m_readOnly) return; QModelIndex idx = rsModelsView->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; db_id modelId = modelsSQLModel->getModelIdAtRow(idx.row()); - if(modelId) + if (modelId) { QString errMsg; - if(!createRsModelWithDifferentSuffix(modelId, errMsg, this)) + if (!createRsModelWithDifferentSuffix(modelId, errMsg, this)) { QMessageBox::warning(this, tr("Error"), errMsg); } @@ -501,7 +507,7 @@ void RollingStockManager::onNewRsModelWithDifferentSuffixFromCurrent() void RollingStockManager::onNewRsModelWithDifferentSuffixFromSearch() { - if(m_readOnly) + if (m_readOnly) return; RSMatchModelFactory factory(ModelModes::Models, Session->m_Db, this); @@ -511,77 +517,81 @@ void RollingStockManager::onNewRsModelWithDifferentSuffixFromSearch() OwningQPointer dlg = new ChooseItemDlg(matchModel.get(), this); dlg->setDescription(tr("Please choose a rollingstock model")); dlg->setPlaceholder(tr("Model")); - dlg->setCallback([this, &dlg](db_id modelId, QString &errMsg) -> bool - { - if(!modelId) - { - errMsg = tr("You must select a valid rollingstock model."); - return false; - } + dlg->setCallback( + [this, &dlg](db_id modelId, QString &errMsg) -> bool + { + if (!modelId) + { + errMsg = tr("You must select a valid rollingstock model."); + return false; + } - return createRsModelWithDifferentSuffix(modelId, errMsg, dlg); - }); + return createRsModelWithDifferentSuffix(modelId, errMsg, dlg); + }); - if(dlg->exec() != QDialog::Accepted) + if (dlg->exec() != QDialog::Accepted) return; - //TODO: select and edit the new item + // TODO: select and edit the new item } -bool RollingStockManager::createRsModelWithDifferentSuffix(db_id sourceModelId, QString &errMsg, QWidget *w) +bool RollingStockManager::createRsModelWithDifferentSuffix(db_id sourceModelId, QString &errMsg, + QWidget *w) { OwningQPointer dlg = new QInputDialog(w); dlg->setLabelText(tr("Please choose an unique suffix for this model, or leave empty")); dlg->setWindowTitle(tr("Choose Suffix")); dlg->setInputMode(QInputDialog::TextInput); - if(dlg->exec() != QDialog::Accepted || !dlg) - return true; //Default: Abort without errors + if (dlg->exec() != QDialog::Accepted || !dlg) + return true; // Default: Abort without errors return modelsSQLModel->addRSModel(nullptr, sourceModelId, dlg->textValue(), &errMsg); } void RollingStockManager::onRemoveRsModel() { - if(m_readOnly) + if (m_readOnly) return; QModelIndex idx = rsModelsView->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; - if(!modelsSQLModel->removeRSModelAt(idx.row())) + if (!modelsSQLModel->removeRSModelAt(idx.row())) { - //ERRORMSG: + // ERRORMSG: } } void RollingStockManager::onRemoveAllRsModels() { - int ret = QMessageBox::question(this, tr("Delete All Rollingstock Models?"), - tr("Are you really sure you want to delete all rollingstock models from this session?\n" - "NOTE: this can be done only if there are no rollingstock pieces in this session.")); - if(ret == QMessageBox::Yes) + int ret = QMessageBox::question( + this, tr("Delete All Rollingstock Models?"), + tr("Are you really sure you want to delete all rollingstock models from this session?\n" + "NOTE: this can be done only if there are no rollingstock pieces in this session.")); + if (ret == QMessageBox::Yes) { - if(!modelsSQLModel->removeAllRSModels()) + if (!modelsSQLModel->removeAllRSModels()) { - QMessageBox::warning(this, tr("Error"), - tr("Failed to remove rollingstock models.\n" - "Make sure there are no more rollingstock pieces in this session.\n" - "NOTE: you can remove all rollinstock pieces at once from the Rollingstock tab.")); + QMessageBox::warning( + this, tr("Error"), + tr("Failed to remove rollingstock models.\n" + "Make sure there are no more rollingstock pieces in this session.\n" + "NOTE: you can remove all rollinstock pieces at once from the Rollingstock tab.")); } } } void RollingStockManager::onNewOwner() { - if(m_readOnly) + if (m_readOnly) return; int row = 0; - if(!ownersSQLModel->addRSOwner(&row)) + if (!ownersSQLModel->addRSOwner(&row)) { - //ERRORMSG: display + // ERRORMSG: display return; } @@ -594,49 +604,52 @@ void RollingStockManager::onNewOwner() void RollingStockManager::onRemoveOwner() { - if(m_readOnly) + if (m_readOnly) return; QModelIndex idx = ownersView->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; - if(!ownersSQLModel->removeRSOwnerAt(idx.row())) + if (!ownersSQLModel->removeRSOwnerAt(idx.row())) { - //ERRORMSG: display error + // ERRORMSG: display error } } void RollingStockManager::onRemoveAllRsOwners() { - int ret = QMessageBox::question(this, tr("Delete All Rollingstock Owners?"), - tr("Are you really sure you want to delete all rollingstock owners from this session?\n" - "NOTE: this can be done only if there are no rollingstock pieces in this session.")); - if(ret == QMessageBox::Yes) + int ret = QMessageBox::question( + this, tr("Delete All Rollingstock Owners?"), + tr("Are you really sure you want to delete all rollingstock owners from this session?\n" + "NOTE: this can be done only if there are no rollingstock pieces in this session.")); + if (ret == QMessageBox::Yes) { - if(!ownersSQLModel->removeAllRSOwners()) + if (!ownersSQLModel->removeAllRSOwners()) { - QMessageBox::warning(this, tr("Error"), - tr("Failed to remove rollingstock owners.\n" - "Make sure there are no more rollingstock pieces in this session.\n" - "NOTE: you can remove all rollingstock pieces at once from the Rollingstock tab.")); + QMessageBox::warning( + this, tr("Error"), + tr( + "Failed to remove rollingstock owners.\n" + "Make sure there are no more rollingstock pieces in this session.\n" + "NOTE: you can remove all rollingstock pieces at once from the Rollingstock tab.")); } } } void RollingStockManager::onMergeModels() { - if(m_readOnly) + if (m_readOnly) return; OwningQPointer dlg = new MergeModelsDialog(Session->m_Db, this); dlg->exec(); - if(clearModelTimers[ModelsTab] == ModelLoaded) + if (clearModelTimers[ModelsTab] == ModelLoaded) { modelsSQLModel->refreshData(); } - if(clearModelTimers[RollingstockTab] == ModelLoaded) + if (clearModelTimers[RollingstockTab] == ModelLoaded) { rsSQLModel->refreshData(true); } @@ -644,17 +657,17 @@ void RollingStockManager::onMergeModels() void RollingStockManager::onMergeOwners() { - if(m_readOnly) + if (m_readOnly) return; OwningQPointer dlg = new MergeOwnersDialog(Session->m_Db, this); dlg->exec(); - if(clearModelTimers[OwnersTab] == ModelLoaded) + if (clearModelTimers[OwnersTab] == ModelLoaded) { ownersSQLModel->refreshData(); } - if(clearModelTimers[RollingstockTab] == ModelLoaded) + if (clearModelTimers[RollingstockTab] == ModelLoaded) { rsSQLModel->refreshData(true); } @@ -698,21 +711,21 @@ void RollingStockManager::onRsOwnerSelectionChanged() void RollingStockManager::timerEvent(QTimerEvent *e) { - if(e->timerId() == clearModelTimers[RollingstockTab]) + if (e->timerId() == clearModelTimers[RollingstockTab]) { rsSQLModel->clearCache(); killTimer(e->timerId()); clearModelTimers[RollingstockTab] = ModelCleared; return; } - else if(e->timerId() == clearModelTimers[ModelsTab]) + else if (e->timerId() == clearModelTimers[ModelsTab]) { modelsSQLModel->clearCache(); killTimer(e->timerId()); clearModelTimers[ModelsTab] = ModelCleared; return; } - else if(e->timerId() == clearModelTimers[OwnersTab]) + else if (e->timerId() == clearModelTimers[OwnersTab]) { ownersSQLModel->clearCache(); killTimer(e->timerId()); @@ -725,10 +738,10 @@ void RollingStockManager::timerEvent(QTimerEvent *e) void RollingStockManager::showEvent(QShowEvent *e) { - if(!windowConnected) + if (!windowConnected) { QWindow *w = windowHandle(); - if(w) + if (w) { windowConnected = true; connect(w, &QWindow::visibilityChanged, this, &RollingStockManager::visibilityChanged); diff --git a/src/rollingstock/manager/rollingstockmanager.h b/src/rollingstock/manager/rollingstockmanager.h index b40ec53..dc8c35d 100644 --- a/src/rollingstock/manager/rollingstockmanager.h +++ b/src/rollingstock/manager/rollingstockmanager.h @@ -52,10 +52,13 @@ public: enum ModelState { ModelCleared = 0, - ModelLoaded = -1 + ModelLoaded = -1 }; - enum { ClearModelTimeout = 5000 }; // 5 seconds + enum + { + ClearModelTimeout = 5000 + }; // 5 seconds explicit RollingStockManager(QWidget *parent = nullptr); ~RollingStockManager(); @@ -68,7 +71,7 @@ private slots: void updateModels(); void visibilityChanged(int v); - void onModelError(const QString& msg); + void onModelError(const QString &msg); void onViewRSPlan(); void onViewRSPlanSearch(); @@ -107,45 +110,44 @@ private: bool createRsModelWithDifferentSuffix(db_id sourceModelId, QString &errMsg, QWidget *w); private: - QTabWidget *tabWidget; + QTabWidget *tabWidget; - QToolBar *rsToolBar; - QToolBar *modelToolBar; - QToolBar *ownersToolBar; + QToolBar *rsToolBar; + QToolBar *modelToolBar; + QToolBar *ownersToolBar; - QActionGroup *editActGroup; + QActionGroup *editActGroup; - QAction *actNewRs; - QAction *actDeleteRs; - QAction *actDeleteAllRs; + QAction *actNewRs; + QAction *actDeleteRs; + QAction *actDeleteAllRs; - QAction *actNewModel; - QAction *actNewModelWithSuffix; - QAction *actNewModelWithSuffixSearch; - QAction *actDeleteModel; - QAction *actDeleteAllRsModels; + QAction *actNewModel; + QAction *actNewModelWithSuffix; + QAction *actNewModelWithSuffixSearch; + QAction *actDeleteModel; + QAction *actDeleteAllRsModels; - QAction *actNewOwner; - QAction *actDeleteOwner; - QAction *actDeleteAllRsOwners; + QAction *actNewOwner; + QAction *actDeleteOwner; + QAction *actDeleteAllRsOwners; - QAction *actMergeModels; - QAction *actMergeOwners; + QAction *actMergeModels; + QAction *actMergeOwners; - QAction *actViewRSPlan; - QAction *actViewRSPlanSearch; + QAction *actViewRSPlan; + QAction *actViewRSPlanSearch; - QTableView *rsView; - QTableView *rsModelsView; - QTableView *ownersView; + QTableView *rsView; + QTableView *rsModelsView; + QTableView *ownersView; SpinBoxEditorFactory *speedSpinFactory; SpinBoxEditorFactory *axesSpinFactory; RollingstockSQLModel *rsSQLModel; - RSModelsSQLModel *modelsSQLModel; - RSOwnersSQLModel *ownersSQLModel; - + RSModelsSQLModel *modelsSQLModel; + RSOwnersSQLModel *ownersSQLModel; int oldCurrentTab; int clearModelTimers[NTabs]; diff --git a/src/rollingstock/rollingstockmatchmodel.cpp b/src/rollingstock/rollingstockmatchmodel.cpp index 33af9c6..da70236 100644 --- a/src/rollingstock/rollingstockmatchmodel.cpp +++ b/src/rollingstock/rollingstockmatchmodel.cpp @@ -26,18 +26,21 @@ RollingstockMatchModel::RollingstockMatchModel(database &db, QObject *parent) : mDb(db), q_getMatches(mDb) { - regExp.setPattern("(?[\\w\\s-]*)\\s*\\.?\\s*(?\\d*)\\s*(:(?[\\w\\s-]+)?)?\\w*"); + regExp.setPattern( + "(?[\\w\\s-]*)\\s*\\.?\\s*(?\\d*)\\s*(:(?[\\w\\s-]+)?)?\\w*"); regExp.optimize(); - q_getMatches.prepare("SELECT rs_list.id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type,rs_owners.name," - "(CASE WHEN rs_list.number LIKE ?1 THEN 2 ELSE 0 END +" - " CASE WHEN rs_models.name LIKE ?2 THEN 1 ELSE 0 END +" - " CASE WHEN rs_models.suffix LIKE ?2 THEN 1 ELSE 0 END +" - " CASE WHEN rs_owners.name LIKE ?3 THEN 3 ELSE 0 END) AS s" - " FROM rs_list" - " JOIN rs_models ON rs_models.id=rs_list.model_id" - " JOIN rs_owners ON rs_owners.id=rs_list.owner_id" - " ORDER BY s DESC LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); - //FIXME: non funziona bene, i risultati sembrano casuali + q_getMatches.prepare( + "SELECT " + "rs_list.id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type,rs_owners.name," + "(CASE WHEN rs_list.number LIKE ?1 THEN 2 ELSE 0 END +" + " CASE WHEN rs_models.name LIKE ?2 THEN 1 ELSE 0 END +" + " CASE WHEN rs_models.suffix LIKE ?2 THEN 1 ELSE 0 END +" + " CASE WHEN rs_owners.name LIKE ?3 THEN 3 ELSE 0 END) AS s" + " FROM rs_list" + " JOIN rs_models ON rs_models.id=rs_list.model_id" + " JOIN rs_owners ON rs_owners.id=rs_list.owner_id" + " ORDER BY s DESC LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); + // FIXME: non funziona bene, i risultati sembrano casuali } int RollingstockMatchModel::columnCount(const QModelIndex &parent) const @@ -54,16 +57,16 @@ QVariant RollingstockMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return idx.column() == NumberCol ? ISqlFKMatchModel::tr("Empty") : QVariant(); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } - const RSItem& item = items[idx.row()]; + const RSItem &item = items[idx.row()]; switch (idx.column()) { @@ -80,7 +83,7 @@ QVariant RollingstockMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(isEmptyRow(idx.row()) || idx.column() == OwnerCol) + if (isEmptyRow(idx.row()) || idx.column() == OwnerCol) { return boldFont(); } @@ -95,9 +98,9 @@ void RollingstockMatchModel::autoSuggest(const QString &text) { QRegularExpressionMatch match = regExp.match(text); - QString tmp = match.captured("model").toUtf8(); + QString tmp = match.captured("model").toUtf8(); model.clear(); - if(!tmp.isEmpty()) + if (!tmp.isEmpty()) { model.reserve(tmp.size() + 2); model.append('%'); @@ -107,7 +110,7 @@ void RollingstockMatchModel::autoSuggest(const QString &text) tmp = match.captured("num").toUtf8(); number.clear(); - if(!tmp.isEmpty()) + if (!tmp.isEmpty()) { number.reserve(tmp.size() + 2); number.append('%'); @@ -117,7 +120,7 @@ void RollingstockMatchModel::autoSuggest(const QString &text) tmp = match.captured("owner").toUtf8(); owner.clear(); - if(!tmp.isEmpty()) + if (!tmp.isEmpty()) { owner.reserve(tmp.size() + 2); owner.append('%'); @@ -130,48 +133,47 @@ void RollingstockMatchModel::autoSuggest(const QString &text) void RollingstockMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); - if(number.isEmpty()) + if (number.isEmpty()) sqlite3_bind_null(q_getMatches.stmt(), 1); else sqlite3_bind_text(q_getMatches.stmt(), 1, number, number.size(), SQLITE_STATIC); - if(model.isEmpty()) + if (model.isEmpty()) sqlite3_bind_null(q_getMatches.stmt(), 2); else sqlite3_bind_text(q_getMatches.stmt(), 2, model, model.size(), SQLITE_STATIC); - if(owner.isEmpty()) + if (owner.isEmpty()) sqlite3_bind_null(q_getMatches.stmt(), 3); else sqlite3_bind_text(q_getMatches.stmt(), 3, owner, owner.size(), SQLITE_STATIC); - - int i = 0; + int i = 0; int ret = SQLITE_OK; while ((ret = q_getMatches.step() == SQLITE_ROW) && i < MaxMatchItems) { - auto r = q_getMatches.getRows(); - RSItem &item = items[i]; - item.rsId = r.get(0); - item.number = r.get(1); - item.modelName = r.get(2); + auto r = q_getMatches.getRows(); + RSItem &item = items[i]; + item.rsId = r.get(0); + item.number = r.get(1); + item.modelName = r.get(2); item.modelSuffix = r.get(3); - item.type = RsType(r.get(4)); - item.ownerName = r.get(5); + item.type = RsType(r.get(4)); + item.ownerName = r.get(5); i++; } - size = i + 1; //Items + Empty + size = i + 1; // Items + Empty - if(ret == SQLITE_ROW) + if (ret == SQLITE_ROW) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -182,23 +184,23 @@ void RollingstockMatchModel::refreshData() QString RollingstockMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT rs_list.number,rs_models.name,rs_models.suffix,rs_models.type" " FROM rs_list JOIN rs_models ON rs_models.id=rs_list.model_id" " WHERE rs_list.id=?"); q.bind(1, id); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return QString(); - int num = sqlite3_column_int(q.stmt(), 0); - int modelNameLen = sqlite3_column_bytes(q.stmt(), 1); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 1)); + int num = sqlite3_column_int(q.stmt(), 0); + int modelNameLen = sqlite3_column_bytes(q.stmt(), 1); + const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 1)); - int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 2); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); - RsType type = RsType(sqlite3_column_int(q.stmt(), 3)); + int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 2); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); + RsType type = RsType(sqlite3_column_int(q.stmt(), 3)); return rs_utils::formatNameRef(modelName, modelNameLen, num, modelSuffix, modelSuffixLen, type); } @@ -210,5 +212,6 @@ db_id RollingstockMatchModel::getIdAtRow(int row) const QString RollingstockMatchModel::getNameAtRow(int row) const { - return rs_utils::formatName(items[row].modelName, items[row].number, items[row].modelSuffix, items[row].type); + return rs_utils::formatName(items[row].modelName, items[row].number, items[row].modelSuffix, + items[row].type); } diff --git a/src/rollingstock/rollingstockmatchmodel.h b/src/rollingstock/rollingstockmatchmodel.h index 1d14168..5bb1d6e 100644 --- a/src/rollingstock/rollingstockmatchmodel.h +++ b/src/rollingstock/rollingstockmatchmodel.h @@ -49,7 +49,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; @@ -72,7 +72,7 @@ private: query q_getMatches; QRegularExpression regExp; - QByteArray model,owner,number; + QByteArray model, owner, number; }; #endif // ROLLINGSTOCKMATCHMODEL_H diff --git a/src/rollingstock/rollingstocksqlmodel.cpp b/src/rollingstock/rollingstocksqlmodel.cpp index 5f293b9..c99a1b4 100644 --- a/src/rollingstock/rollingstocksqlmodel.cpp +++ b/src/rollingstock/rollingstocksqlmodel.cpp @@ -32,11 +32,11 @@ using namespace sqlite3pp; #include -//ERRORMSG: show other errors -static constexpr char - errorRSInUseCannotDelete[] = QT_TRANSLATE_NOOP("RollingstockSQLModel", - "Rollingstock item %1 is used in some jobs so it cannot be removed.
" - "If you wish to remove it, please first remove it from its jobs."); +// ERRORMSG: show other errors +static constexpr char errorRSInUseCannotDelete[] = + QT_TRANSLATE_NOOP("RollingstockSQLModel", + "Rollingstock item %1 is used in some jobs so it cannot be removed.
" + "If you wish to remove it, please first remove it from its jobs."); RollingstockSQLModel::RollingstockSQLModel(sqlite3pp::database &db, QObject *parent) : BaseClass(500, db, parent) @@ -46,9 +46,9 @@ RollingstockSQLModel::RollingstockSQLModel(sqlite3pp::database &db, QObject *par QVariant RollingstockSQLModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (section) { @@ -80,18 +80,18 @@ QVariant RollingstockSQLModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const RSItem& item = cache.at(row - cacheFirstRow); + const RSItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -116,7 +116,7 @@ QVariant RollingstockSQLModel::data(const QModelIndex &idx, int role) const } case Qt::TextAlignmentRole: { - if(idx.column() == Number) + if (idx.column() == Number) { return Qt::AlignVCenter + Qt::AlignRight; } @@ -134,18 +134,19 @@ QVariant RollingstockSQLModel::data(const QModelIndex &idx, int role) const bool RollingstockSQLModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - RSItem &item = cache[row - cacheFirstRow]; + RSItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; - if(role == RS_NUMBER) + if (role == RS_NUMBER) { - bool ok = false; + bool ok = false; int number = value.toInt(&ok); - if(!ok || !setNumber(item, number)) + if (!ok || !setNumber(item, number)) return false; } @@ -159,25 +160,25 @@ Qt::ItemFlags RollingstockSQLModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() != Suffix && idx.column() != TypeCol) - f.setFlag(Qt::ItemIsEditable); //Suffix and TypeCol are deduced from Model + if (idx.column() != Suffix && idx.column() != TypeCol) + f.setFlag(Qt::ItemIsEditable); // Suffix and TypeCol are deduced from Model return f; } void RollingstockSQLModel::setSortingColumn(int col) { - if(sortColumn == col || col == Number || col == Suffix || col >= NCols) + if (sortColumn == col || col == Number || col == Suffix || col >= NCols) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -209,8 +210,8 @@ bool RollingstockSQLModel::setFilterAtCol(int col, const QString &str) } case Number: { - if(isNull) - return false; //Cannot have NULL Number + if (isNull) + return false; // Cannot have NULL Number m_numberFilter = str; break; } @@ -229,22 +230,22 @@ bool RollingstockSQLModel::setFilterAtCol(int col, const QString &str) bool RollingstockSQLModel::getFieldData(int row, int col, db_id &idOut, QString &nameOut) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - const RSItem& item = cache[row - cacheFirstRow]; + const RSItem &item = cache[row - cacheFirstRow]; switch (col) { case Model: { - idOut = item.modelId; + idOut = item.modelId; nameOut = item.modelName; break; } case Owner: { - idOut = item.ownerId; + idOut = item.ownerId; nameOut = item.ownerName; break; } @@ -255,18 +256,19 @@ bool RollingstockSQLModel::getFieldData(int row, int col, db_id &idOut, QString return true; } -bool RollingstockSQLModel::validateData(int /*row*/, int /*col*/, db_id /*id*/, const QString &/*name*/) +bool RollingstockSQLModel::validateData(int /*row*/, int /*col*/, db_id /*id*/, + const QString & /*name*/) { return true; } bool RollingstockSQLModel::setFieldData(int row, int col, db_id id, const QString &name) { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - RSItem& item = cache[row - cacheFirstRow]; - bool ret = false; + RSItem &item = cache[row - cacheFirstRow]; + bool ret = false; switch (col) { case Model: @@ -283,7 +285,7 @@ bool RollingstockSQLModel::setFieldData(int row, int col, db_id id, const QStrin break; } - if(ret) + if (ret) { QModelIndex idx = index(row, col); emit dataChanged(idx, idx); @@ -294,21 +296,22 @@ bool RollingstockSQLModel::setFieldData(int row, int col, db_id id, const QStrin bool RollingstockSQLModel::removeRSItem(db_id rsId, const RSItem *item) { - if(!rsId) + if (!rsId) return false; command cmd(mDb, "DELETE FROM rs_list WHERE id=?"); cmd.bind(1, rsId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { ret = mDb.extended_error_code(); - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { QString name; - if(item) + if (item) { - name = rs_utils::formatName(item->modelName, item->number, item->modelSuffix, item->type); + name = rs_utils::formatName(item->modelName, item->number, item->modelSuffix, + item->type); } else { @@ -321,19 +324,19 @@ bool RollingstockSQLModel::removeRSItem(db_id rsId, const RSItem *item) sqlite3_stmt *stmt = q.stmt(); - int number = sqlite3_column_int(stmt, 0); - int modelNameLen = sqlite3_column_bytes(stmt, 1); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 1)); + int number = sqlite3_column_int(stmt, 0); + int modelNameLen = sqlite3_column_bytes(stmt, 1); + const char *modelName = + reinterpret_cast(sqlite3_column_text(stmt, 1)); int modelSuffixLen = sqlite3_column_bytes(stmt, 2); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 2)); + const char *modelSuffix = + reinterpret_cast(sqlite3_column_text(stmt, 2)); RsType type = RsType(sqlite3_column_int(stmt, 3)); - name = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); } emit modelError(tr(errorRSInUseCannotDelete).arg(name)); @@ -345,14 +348,14 @@ bool RollingstockSQLModel::removeRSItem(db_id rsId, const RSItem *item) emit Session->rollingstockRemoved(rsId); - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } bool RollingstockSQLModel::removeRSItemAt(int row) { - if(row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid const RSItem &item = cache.at(row - cacheFirstRow); return removeRSItem(item.rsId, &item); @@ -366,29 +369,30 @@ db_id RollingstockSQLModel::addRSItem(int *outRow, QString *errOut) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); int ret = cmd.execute(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) { rsId = mDb.last_insert_rowid(); } sqlite3_mutex_leave(mutex); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { - //There is already an RS with no model set, use that instead + // There is already an RS with no model set, use that instead query findEmpty(mDb, "SELECT id FROM rs_list WHERE model_id=0 OR model_id IS NULL LIMIT 1"); - if(findEmpty.step() == SQLITE_ROW) + if (findEmpty.step() == SQLITE_ROW) { rsId = findEmpty.getRows().get(0); } } - else if(ret != SQLITE_OK) + else if (ret != SQLITE_OK) { - if(errOut) + if (errOut) *errOut = mDb.error_msg(); - qDebug() << "RollingstockSQLModel Error adding:" << ret << mDb.error_msg() << mDb.error_code() << mDb.extended_error_code(); + qDebug() << "RollingstockSQLModel Error adding:" << ret << mDb.error_msg() + << mDb.error_code() << mDb.extended_error_code(); } - //Clear filters + // Clear filters m_modelFilter.clear(); m_modelFilter.squeeze(); m_numberFilter.clear(); @@ -397,11 +401,11 @@ db_id RollingstockSQLModel::addRSItem(int *outRow, QString *errOut) m_ownerFilter.squeeze(); emit filterChanged(); - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row - if(outRow) - *outRow = rsId ? 0 : -1; //Empty model is always the first + if (outRow) + *outRow = rsId ? 0 : -1; // Empty model is always the first return rsId; } @@ -410,13 +414,14 @@ bool RollingstockSQLModel::removeAllRS() { command cmd(mDb, "DELETE FROM rs_list"); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Removing ALL RS:" << ret << mDb.extended_error_code() << "Err:" << mDb.error_msg(); + qWarning() << "Removing ALL RS:" << ret << mDb.extended_error_code() + << "Err:" << mDb.error_msg(); return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } @@ -433,7 +438,7 @@ qint64 RollingstockSQLModel::recalcTotalItemCount() void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool fullData) { QByteArray sql; - if(fullData) + if (fullData) { sql = "SELECT rs_list.id,rs_list.number,rs_list.model_id,rs_list.owner_id," "rs_models.name,rs_models.suffix,rs_models.type,rs_owners.name" @@ -444,23 +449,23 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs sql = "SELECT COUNT(1) FROM rs_list"; } - //If counting but filtering by model name (not null) we need to JOIN rs_models + // If counting but filtering by model name (not null) we need to JOIN rs_models bool modelIsNull = m_modelFilter.startsWith(nullFilterStr, Qt::CaseInsensitive); - if(fullData || (!modelIsNull && !m_modelFilter.isEmpty())) + if (fullData || (!modelIsNull && !m_modelFilter.isEmpty())) sql += " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id"; - //If counting but filtering by owner name (not null) we need to JOIN rs_owners + // If counting but filtering by owner name (not null) we need to JOIN rs_owners bool ownerIsNull = m_ownerFilter.startsWith(nullFilterStr, Qt::CaseInsensitive); - if(fullData || (!ownerIsNull && !m_ownerFilter.isEmpty())) + if (fullData || (!ownerIsNull && !m_ownerFilter.isEmpty())) sql += " LEFT JOIN rs_owners ON rs_owners.id=rs_list.owner_id"; bool whereClauseAdded = false; - if(!m_modelFilter.isEmpty()) + if (!m_modelFilter.isEmpty()) { sql.append(" WHERE "); - if(modelIsNull) + if (modelIsNull) { sql.append("rs_list.model_id IS NULL"); } @@ -472,9 +477,9 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs whereClauseAdded = true; } - if(!m_numberFilter.isEmpty()) + if (!m_numberFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); @@ -484,14 +489,14 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs whereClauseAdded = true; } - if(!m_ownerFilter.isEmpty()) + if (!m_ownerFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); - if(ownerIsNull) + if (ownerIsNull) { sql.append("rs_list.owner_id IS NULL"); } @@ -501,25 +506,27 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs } } - if(fullData) + if (fullData) { - //Apply sorting + // Apply sorting const char *sortColExpr = nullptr; switch (sortCol) { case Model: { - sortColExpr = "rs_models.name,rs_list.number"; //Order by 2 columns, no where clause + sortColExpr = "rs_models.name,rs_list.number"; // Order by 2 columns, no where clause break; } case Owner: { - sortColExpr = "rs_owners.name,rs_models.name,rs_list.number"; //Order by 3 columns, no where clause + sortColExpr = + "rs_owners.name,rs_models.name,rs_list.number"; // Order by 3 columns, no where clause break; } case TypeCol: { - sortColExpr = "rs_models.type,rs_models.name,rs_list.number"; //Order by 3 columns, no where clause + sortColExpr = + "rs_models.type,rs_models.name,rs_list.number"; // Order by 3 columns, no where clause break; } } @@ -528,23 +535,23 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs sql += sortColExpr; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; } q.prepare(sql); - if(fullData) + if (fullData) { - //Apply offset and batch size + // Apply offset and batch size q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); } - //Apply filters + // Apply filters QByteArray modelFilter; - if(!m_modelFilter.isEmpty() && !modelIsNull) + if (!m_modelFilter.isEmpty() && !modelIsNull) { modelFilter.reserve(m_modelFilter.size() + 2); modelFilter.append('%'); @@ -555,19 +562,19 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs } QByteArray numberFilter; - if(!m_numberFilter.isEmpty()) + if (!m_numberFilter.isEmpty()) { numberFilter.reserve(m_numberFilter.size() + 2); numberFilter.append('%'); numberFilter.append(m_numberFilter.toUtf8()); numberFilter.append('%'); - numberFilter.replace('-', nullptr); //Remove dashes + numberFilter.replace('-', nullptr); // Remove dashes sqlite3_bind_text(q.stmt(), 4, numberFilter, numberFilter.size(), SQLITE_STATIC); } QByteArray ownerFilter; - if(!m_ownerFilter.isEmpty() && !ownerIsNull) + if (!m_ownerFilter.isEmpty() && !ownerIsNull) { ownerFilter.reserve(m_ownerFilter.size() + 2); ownerFilter.append('%'); @@ -578,7 +585,8 @@ void RollingstockSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offs } } -void RollingstockSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant& /*val*/) +void RollingstockSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); @@ -590,27 +598,27 @@ void RollingstockSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; - RSItem &item = vec[i]; - item.rsId = r.get(0); - item.number = r.get(1); - item.modelId = r.get(2); - item.ownerId = r.get(3); - item.modelName = r.get(4); + auto r = *it; + RSItem &item = vec[i]; + item.rsId = r.get(0); + item.number = r.get(1); + item.modelId = r.get(2); + item.ownerId = r.get(3); + item.modelName = r.get(4); item.modelSuffix = r.get(5); - item.type = RsType(r.get(6)); - item.ownerName = r.get(7); + item.type = RsType(r.get(6)); + item.ownerName = r.get(7); i += 1; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); @@ -618,30 +626,31 @@ void RollingstockSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, bool RollingstockSQLModel::setModel(RSItem &item, db_id modelId, const QString &name) { - if(item.modelId == modelId) + if (item.modelId == modelId) return false; - //FIXME: should be already handled by UNIQUE constraints - //Check if there is already that combination of - //Model.Number, if so set an higher number - query q_hasModelNumCombination(mDb, "SELECT id, model_id, number FROM rs_list WHERE model_id=? AND number=?"); + // FIXME: should be already handled by UNIQUE constraints + // Check if there is already that combination of + // Model.Number, if so set an higher number + query q_hasModelNumCombination( + mDb, "SELECT id, model_id, number FROM rs_list WHERE model_id=? AND number=?"); q_hasModelNumCombination.bind(1, modelId); q_hasModelNumCombination.bind(2, item.number); int ret = q_hasModelNumCombination.step(); q_hasModelNumCombination.reset(); - if(ret == SQLITE_ROW) + if (ret == SQLITE_ROW) { - //There's already that Model.Number, change our number + // There's already that Model.Number, change our number query q_getMaxNumberOfThatModel(mDb, "SELECT MAX(number) FROM rs_list WHERE model_id=?"); q_getMaxNumberOfThatModel.bind(1, modelId); q_getMaxNumberOfThatModel.step(); - auto r = q_getMaxNumberOfThatModel.getRows(); - int number = r.get(0) + 1; //Max + 1 + auto r = q_getMaxNumberOfThatModel.getRows(); + int number = r.get(0) + 1; // Max + 1 q_getMaxNumberOfThatModel.reset(); - //BIG TODO: numeri carri/carrozze hanno cifra di controllo, non posono essere aumentati di +1 a caso - //ERRORMSG: ask user + // BIG TODO: numeri carri/carrozze hanno cifra di controllo, non posono essere aumentati di + // +1 a caso ERRORMSG: ask user command q_setNumber(mDb, "UPDATE rs_list SET number=? WHERE id=?"); q_setNumber.bind(1, number); @@ -649,7 +658,7 @@ bool RollingstockSQLModel::setModel(RSItem &item, db_id modelId, const QString & ret = q_setNumber.execute(); q_setNumber.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; item.number = number; @@ -661,15 +670,15 @@ bool RollingstockSQLModel::setModel(RSItem &item, db_id modelId, const QString & ret = q_setModel.execute(); q_setModel.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; item.modelId = modelId; - Q_UNUSED(name) //We clear the cache so the name will be re-queried + Q_UNUSED(name) // We clear the cache so the name will be re-queried - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -678,9 +687,9 @@ bool RollingstockSQLModel::setModel(RSItem &item, db_id modelId, const QString & return true; } -bool RollingstockSQLModel::setOwner(RSItem &item, db_id ownerId, const QString& name) +bool RollingstockSQLModel::setOwner(RSItem &item, db_id ownerId, const QString &name) { - if(item.ownerId == ownerId) + if (item.ownerId == ownerId) return false; command q_setOwner(mDb, "UPDATE rs_list SET owner_id=? WHERE id=?"); @@ -689,19 +698,19 @@ bool RollingstockSQLModel::setOwner(RSItem &item, db_id ownerId, const QString& int ret = q_setOwner.execute(); q_setOwner.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; - item.ownerId = ownerId; + item.ownerId = ownerId; item.ownerName = name; emit Session->rollingStockModified(item.rsId); - if(sortColumn == Owner) + if (sortColumn == Owner) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } @@ -711,20 +720,21 @@ bool RollingstockSQLModel::setOwner(RSItem &item, db_id ownerId, const QString& bool RollingstockSQLModel::setNumber(RSItem &item, int number) { - if(item.number == number) + if (item.number == number) return false; - //Check if there is already that combination of - //Model.Number, if so don't set new number - //ERRORMSG: show error to user (emit error(int code, QString msg)) - //TODO: use UNIQUE constraint??? - command q_hasModelNumCombination(mDb, "SELECT id,model_id,number FROM rs_list WHERE model_id=? AND number=?"); + // Check if there is already that combination of + // Model.Number, if so don't set new number + // ERRORMSG: show error to user (emit error(int code, QString msg)) + // TODO: use UNIQUE constraint??? + command q_hasModelNumCombination( + mDb, "SELECT id,model_id,number FROM rs_list WHERE model_id=? AND number=?"); q_hasModelNumCombination.bind(1, item.modelId); q_hasModelNumCombination.bind(2, number); int ret = q_hasModelNumCombination.step(); q_hasModelNumCombination.reset(); - if(ret == SQLITE_ROW) //We already have one + if (ret == SQLITE_ROW) // We already have one return false; command q_setNumber(mDb, "UPDATE rs_list SET number=? WHERE id=?"); @@ -733,13 +743,13 @@ bool RollingstockSQLModel::setNumber(RSItem &item, int number) ret = q_setNumber.execute(); q_setNumber.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; item.number = number; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; diff --git a/src/rollingstock/rollingstocksqlmodel.h b/src/rollingstock/rollingstocksqlmodel.h index e3cb8ba..0ea1958 100644 --- a/src/rollingstock/rollingstocksqlmodel.h +++ b/src/rollingstock/rollingstocksqlmodel.h @@ -41,16 +41,20 @@ struct RollingstockSQLModelItem RsType type; }; -class RollingstockSQLModel : public IPagedItemModelImpl, - public IFKField +class RollingstockSQLModel + : public IPagedItemModelImpl, + public IFKField { Q_OBJECT public: + enum + { + BatchSize = 100 + }; - enum { BatchSize = 100 }; - - enum Columns { + enum Columns + { Model = 0, Number, Suffix, @@ -67,25 +71,24 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel virtual void setSortingColumn(int col) override; - //Filter + // Filter std::pair getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // IFKField bool getFieldData(int row, int col, db_id &idOut, QString &nameOut) const override; @@ -103,13 +106,12 @@ public: inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const RSItem& item = cache.at(row - cacheFirstRow); + const RSItem &item = cache.at(row - cacheFirstRow); return item.rsId; } - protected: virtual qint64 recalcTotalItemCount() override; @@ -122,7 +124,6 @@ private: bool setOwner(RSItem &item, db_id ownerId, const QString &name); bool setNumber(RSItem &item, int number); - private: QString m_modelFilter; QString m_numberFilter; diff --git a/src/rollingstock/rs_checker/rs_error_data.h b/src/rollingstock/rs_checker/rs_error_data.h index 9ab1f62..23aa7d5 100644 --- a/src/rollingstock/rs_checker/rs_error_data.h +++ b/src/rollingstock/rs_checker/rs_error_data.h @@ -22,24 +22,23 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "utils/types.h" +# include "utils/types.h" -#include -#include -#include +# include +# include +# include -namespace RsErrors -{ +namespace RsErrors { enum ErrType : quint32 { NoError = 0, StopIsTransit, - CoupledWhileBusy, //otherId: previous coupling id - UncoupledWhenNotCoupled, //otherId: previous uncoupling id - NotUncoupledAtJobEnd, //otherId: next operation id or zero - CoupledInDifferentStation, //otherId: previous coupling id - UncoupledInSameStop //otherId: previous coupling id + CoupledWhileBusy, // otherId: previous coupling id + UncoupledWhenNotCoupled, // otherId: previous uncoupling id + NotUncoupledAtJobEnd, // otherId: next operation id or zero + CoupledInDifferentStation, // otherId: previous coupling id + UncoupledInSameStop // otherId: previous coupling id }; struct RSErrorData @@ -61,19 +60,28 @@ struct RSErrorList QString rsName; QVector errors; - inline int childCount() const { return errors.size(); } - inline const RSErrorData *ptrForRow(int row) const { return &errors.at(row); } + inline int childCount() const + { + return errors.size(); + } + inline const RSErrorData *ptrForRow(int row) const + { + return &errors.at(row); + } }; struct RSErrorMap { QMap map; - inline int topLevelCount() const { return map.size(); } + inline int topLevelCount() const + { + return map.size(); + } inline const RSErrorList *getTopLevelAtRow(int row) const { - if(row >= topLevelCount()) + if (row >= topLevelCount()) return nullptr; return &(map.constBegin() + row).value(); } @@ -81,7 +89,7 @@ struct RSErrorMap inline const RSErrorList *getParent(RSErrorData *child) const { auto it = map.constFind(child->rsId); - if(it == map.constEnd()) + if (it == map.constEnd()) return nullptr; return &it.value(); } @@ -89,13 +97,13 @@ struct RSErrorMap inline int getParentRow(RSErrorData *child) const { auto it = map.constFind(child->rsId); - if(it == map.constEnd()) + if (it == map.constEnd()) return -1; return std::distance(map.constBegin(), it); } }; -} //namespace RsErrors +} // namespace RsErrors #endif // ENABLE_BACKGROUND_MANAGER diff --git a/src/rollingstock/rs_checker/rscheckermanager.cpp b/src/rollingstock/rs_checker/rscheckermanager.cpp index 1147582..6996e20 100644 --- a/src/rollingstock/rs_checker/rscheckermanager.cpp +++ b/src/rollingstock/rs_checker/rscheckermanager.cpp @@ -21,33 +21,34 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "app/session.h" -#include "viewmanager/viewmanager.h" +# include "app/session.h" +# include "viewmanager/viewmanager.h" -#include "rsworker.h" -#include "rserrortreemodel.h" +# include "rsworker.h" +# include "rserrortreemodel.h" -#include +# include -#include "utils/owningqpointer.h" -#include +# include "utils/owningqpointer.h" +# include RsCheckerManager::RsCheckerManager(sqlite3pp::database &db, QObject *parent) : IBackgroundChecker(db, parent) { - eventType = RsWorkerResultEvent::_Type; + eventType = RsWorkerResultEvent::_Type; errorsModel = new RsErrorTreeModel(this); - connect(Session, &MeetingSession::rollingStockPlanChanged, this, &RsCheckerManager::onRSPlanChanged); + connect(Session, &MeetingSession::rollingStockPlanChanged, this, + &RsCheckerManager::onRSPlanChanged); } void RsCheckerManager::checkRs(const QSet &rsIds) { - if(rsIds.isEmpty() || !Session->m_Db.db()) + if (rsIds.isEmpty() || !Session->m_Db.db()) return; QVector vec(rsIds.size()); - for(db_id rsId : rsIds) + for (db_id rsId : rsIds) vec.append(rsId); RsErrWorker *task = new RsErrWorker(Session->m_Db, this, vec); @@ -64,27 +65,28 @@ void RsCheckerManager::clearModel() static_cast(errorsModel)->clear(); } -void RsCheckerManager::showContextMenu(QWidget *panel, const QPoint &pos, const QModelIndex &idx) const +void RsCheckerManager::showContextMenu(QWidget *panel, const QPoint &pos, + const QModelIndex &idx) const { const RsErrorTreeModel *model = static_cast(errorsModel); - auto item = model->getItem(idx); - if(!item) + auto item = model->getItem(idx); + if (!item) return; OwningQPointer menu = new QMenu(panel); - QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); - QAction *showRsPlan = new QAction(tr("Show rollingstock plan"), menu); + QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); + QAction *showRsPlan = new QAction(tr("Show rollingstock plan"), menu); menu->addAction(showInJobEditor); menu->addAction(showRsPlan); QAction *act = menu->exec(pos); - if(act == showInJobEditor) + if (act == showInJobEditor) { Session->getViewManager()->requestJobEditor(item->job.jobId, item->stopId); } - else if(act == showRsPlan) + else if (act == showRsPlan) { Session->getViewManager()->requestRSInfo(item->rsId); } @@ -92,13 +94,13 @@ void RsCheckerManager::showContextMenu(QWidget *panel, const QPoint &pos, const void RsCheckerManager::sessionLoadedHandler() { - if(AppSettings.getCheckRSWhenOpeningDB()) + if (AppSettings.getCheckRSWhenOpeningDB()) startWorker(); } void RsCheckerManager::onRSPlanChanged(const QSet &rsIds) { - if(!AppSettings.getCheckRSOnJobEdit()) + if (!AppSettings.getCheckRSOnJobEdit()) return; checkRs(rsIds); @@ -112,8 +114,8 @@ IQuittableTask *RsCheckerManager::createMainWorker() void RsCheckerManager::setErrors(QEvent *e, bool merge) { auto model = static_cast(errorsModel); - auto ev = static_cast(e); - if(merge) + auto ev = static_cast(e); + if (merge) model->mergeErrors(ev->results); else model->setErrors(ev->results); diff --git a/src/rollingstock/rs_checker/rscheckermanager.h b/src/rollingstock/rs_checker/rscheckermanager.h index 9e4d4c7..07be9b2 100644 --- a/src/rollingstock/rs_checker/rscheckermanager.h +++ b/src/rollingstock/rs_checker/rscheckermanager.h @@ -22,9 +22,9 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "backgroundmanager/ibackgroundchecker.h" +# include "backgroundmanager/ibackgroundchecker.h" -#include "utils/types.h" +# include "utils/types.h" class RsCheckerManager : public IBackgroundChecker { @@ -36,7 +36,7 @@ public: QString getName() const override; void clearModel() override; - void showContextMenu(QWidget *panel, const QPoint& pos, const QModelIndex& idx) const override; + void showContextMenu(QWidget *panel, const QPoint &pos, const QModelIndex &idx) const override; void sessionLoadedHandler() override; diff --git a/src/rollingstock/rs_checker/rserrortreemodel.cpp b/src/rollingstock/rs_checker/rserrortreemodel.cpp index 11da9ed..581b6c4 100644 --- a/src/rollingstock/rs_checker/rserrortreemodel.cpp +++ b/src/rollingstock/rs_checker/rserrortreemodel.cpp @@ -19,21 +19,22 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "rserrortreemodel.h" +# include "rserrortreemodel.h" -#include //For translations +# include //For translations -#include "utils/jobcategorystrings.h" +# include "utils/jobcategorystrings.h" -static const char* error_texts[] = { - nullptr, - QT_TRANSLATE_NOOP("RsErrors", "Stop is transit. Cannot couple/uncouple rollingstock."), - QT_TRANSLATE_NOOP("RsErrors", "Coupled while busy: it was already coupled to another job."), - QT_TRANSLATE_NOOP("RsErrors", "Uncoupled when not coupled."), - QT_TRANSLATE_NOOP("RsErrors", "Not uncoupled at the end of the job or coupled by another job before this jobs uncouples it."), - QT_TRANSLATE_NOOP("RsErrors", "Coupled in a different station than that where it was uncoupled."), - QT_TRANSLATE_NOOP("RsErrors", "Uncoupled in the same stop it was coupled.") -}; +static const char *error_texts[] = { + nullptr, + QT_TRANSLATE_NOOP("RsErrors", "Stop is transit. Cannot couple/uncouple rollingstock."), + QT_TRANSLATE_NOOP("RsErrors", "Coupled while busy: it was already coupled to another job."), + QT_TRANSLATE_NOOP("RsErrors", "Uncoupled when not coupled."), + QT_TRANSLATE_NOOP( + "RsErrors", + "Not uncoupled at the end of the job or coupled by another job before this jobs uncouples it."), + QT_TRANSLATE_NOOP("RsErrors", "Coupled in a different station than that where it was uncoupled."), + QT_TRANSLATE_NOOP("RsErrors", "Uncoupled in the same stop it was coupled.")}; class RsError { @@ -43,12 +44,12 @@ class RsError RsErrorTreeModel::RsErrorTreeModel(QObject *parent) : RsErrorTreeModelBase(parent) { - //FIXME: listen for changes in rs/job/station names and update them + // FIXME: listen for changes in rs/job/station names and update them } QVariant RsErrorTreeModel::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) { @@ -69,11 +70,11 @@ QVariant RsErrorTreeModel::headerData(int section, Qt::Orientation orientation, QVariant RsErrorTreeModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid() || role != Qt::DisplayRole) + if (!idx.isValid() || role != Qt::DisplayRole) return QVariant(); const RsErrors::RSErrorData *item = getItem(idx); - if(item) + if (item) { switch (idx.column()) { @@ -89,8 +90,8 @@ QVariant RsErrorTreeModel::data(const QModelIndex &idx, int role) const } else { - //Caption - if(idx.row() >= m_data.topLevelCount() || idx.column() != 0) + // Caption + if (idx.row() >= m_data.topLevelCount() || idx.column() != 0) return QVariant(); auto topLevel = m_data.getTopLevelAtRow(idx.row()); @@ -102,7 +103,7 @@ QVariant RsErrorTreeModel::data(const QModelIndex &idx, int role) const /* Description: * Clear current errors and set new ones -*/ + */ void RsErrorTreeModel::setErrors(const QMap &data) { beginResetModel(); @@ -114,19 +115,20 @@ void RsErrorTreeModel::setErrors(const QMap &data) * Merge new errors with pre-existing. * - If an RS is passed with no errors (i.e. empty QVector) it gets removed from the model * - If an new RS is passed it gets inserted in the model - * - If an RS already in the model is passed then its current errors are cleared and the new errors are inserted -*/ + * - If an RS already in the model is passed then its current errors are cleared and the new errors + * are inserted + */ void RsErrorTreeModel::mergeErrors(const QMap &data) { auto oldIter = m_data.map.begin(); - int row = 0; - for(auto it = data.constBegin(); it != data.constEnd(); it++) + int row = 0; + for (auto it = data.constBegin(); it != data.constEnd(); it++) { auto iter = m_data.map.find(it.key()); - if(iter == m_data.map.end()) //Insert a new RS + if (iter == m_data.map.end()) // Insert a new RS { - if(it->errors.isEmpty()) - continue; //Error: tried to remove an RS not in this model (maybe already removed) + if (it->errors.isEmpty()) + continue; // Error: tried to remove an RS not in this model (maybe already removed) auto pos = m_data.map.lowerBound(it.key()); row += std::distance(oldIter, pos); @@ -139,22 +141,23 @@ void RsErrorTreeModel::mergeErrors(const QMap &dat { row += std::distance(oldIter, iter); - if(it->errors.isEmpty()) //Remove RS + if (it->errors.isEmpty()) // Remove RS { beginRemoveRows(QModelIndex(), row, row); iter = m_data.map.erase(iter); endRemoveRows(); } - else //Repopulate + else // Repopulate { - //First remove old rows to invalidate QModelIndex because they store a pointer to vector elements that will become dangling + // First remove old rows to invalidate QModelIndex because they store a pointer to + // vector elements that will become dangling QModelIndex parent = createIndex(row, 0, nullptr); beginRemoveRows(parent, 0, iter->errors.size() - 1); iter->errors.clear(); endRemoveRows(); beginInsertRows(parent, 0, it->errors.size() - 1); - iter.value() = it.value(); //Copy errors QVector + iter.value() = it.value(); // Copy errors QVector endInsertRows(); } } @@ -173,11 +176,11 @@ void RsErrorTreeModel::clear() void RsErrorTreeModel::onRSInfoChanged(db_id rsId) { Q_UNUSED(rsId) - //Update top-level items that show RS names - if(m_data.topLevelCount()) + // Update top-level items that show RS names + if (m_data.topLevelCount()) { QModelIndex first = index(0, 0); - QModelIndex last = index(m_data.topLevelCount(), 0); + QModelIndex last = index(m_data.topLevelCount(), 0); emit dataChanged(first, last); } diff --git a/src/rollingstock/rs_checker/rserrortreemodel.h b/src/rollingstock/rs_checker/rserrortreemodel.h index e7a822c..84cc63c 100644 --- a/src/rollingstock/rs_checker/rserrortreemodel.h +++ b/src/rollingstock/rs_checker/rserrortreemodel.h @@ -22,13 +22,14 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "rs_error_data.h" -#include "utils/singledepthtreemodelhelper.h" +# include "rs_error_data.h" +# include "utils/singledepthtreemodelhelper.h" class RsErrorTreeModel; -typedef SingleDepthTreeModelHelper RsErrorTreeModelBase; +typedef SingleDepthTreeModelHelper + RsErrorTreeModelBase; -//TODO: make on-demand +// TODO: make on-demand class RsErrorTreeModel : public RsErrorTreeModelBase { Q_OBJECT @@ -45,7 +46,8 @@ public: RsErrorTreeModel(QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; diff --git a/src/rollingstock/rs_checker/rsworker.cpp b/src/rollingstock/rs_checker/rsworker.cpp index f7e6cfb..92c970f 100644 --- a/src/rollingstock/rs_checker/rsworker.cpp +++ b/src/rollingstock/rs_checker/rsworker.cpp @@ -19,16 +19,16 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "rsworker.h" +# include "rsworker.h" -#include "utils/types.h" -#include "utils/rs_utils.h" +# include "utils/types.h" +# include "utils/rs_utils.h" -#include +# include -#include +# include -#include +# include using namespace sqlite3pp; RsErrWorker::RsErrWorker(database &db, QObject *receiver, const QVector &vec) : @@ -44,7 +44,8 @@ void RsErrWorker::run() QMap data; - try{ + try + { query q_selectCoupling(mDb, "SELECT coupling.id, coupling.operation, coupling.stop_id," " stops.job_id, jobs.category," @@ -58,7 +59,7 @@ void RsErrWorker::run() qDebug() << "Starting WORKER: rs check"; - if(rsToCheck.isEmpty()) + if (rsToCheck.isEmpty()) { query q_countRs(mDb, "SELECT COUNT() FROM rs_list"); query q_selectRs(mDb, "SELECT rs_list.id,rs_list.number," @@ -73,35 +74,35 @@ void RsErrWorker::run() int i = 0; sendEvent(new TaskProgressEvent(this, 0, rsCount), false); - for(auto r : q_selectRs) + for (auto r : q_selectRs) { - if(++i % 4 == 0) //Check every 4 RS to keep overhead low. + if (++i % 4 == 0) // Check every 4 RS to keep overhead low. { - if(wasStopped()) + if (wasStopped()) break; sendEvent(new TaskProgressEvent(this, i, rsCount), false); } RSErrorList rs; - rs.rsId = r.get(0); + rs.rsId = r.get(0); - int number = r.get(1); + int number = r.get(1); int modelNameLen = sqlite3_column_bytes(q_selectRs.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q_selectRs.stmt(), 2)); + const char *modelName = + reinterpret_cast(sqlite3_column_text(q_selectRs.stmt(), 2)); int modelSuffixLen = sqlite3_column_bytes(q_selectRs.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q_selectRs.stmt(), 3)); + const char *modelSuffix = + reinterpret_cast(sqlite3_column_text(q_selectRs.stmt(), 3)); RsType type = RsType(r.get(4)); - rs.rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + rs.rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); checkRs(rs, q_selectCoupling); - if(rs.errors.size()) //Insert only if there are errors + if (rs.errors.size()) // Insert only if there are errors data.insert(rs.rsId, rs); } } @@ -113,38 +114,38 @@ void RsErrWorker::run() " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" " WHERE rs_list.id=?"); int i = 0; - for(db_id rsId : qAsConst(rsToCheck)) + for (db_id rsId : qAsConst(rsToCheck)) { - if(++i % 4 == 0 && wasStopped()) //Check every 4 RS to keep overhead low. + if (++i % 4 == 0 && wasStopped()) // Check every 4 RS to keep overhead low. break; RSErrorList rs; rs.rsId = rsId; q_getRsInfo.bind(1, rs.rsId); - if(q_getRsInfo.step() != SQLITE_ROW) + if (q_getRsInfo.step() != SQLITE_ROW) { q_getRsInfo.reset(); - continue; //RS does not exist! + continue; // RS does not exist! } - int number = sqlite3_column_int(q_getRsInfo.stmt(), 0); + int number = sqlite3_column_int(q_getRsInfo.stmt(), 0); int modelNameLen = sqlite3_column_bytes(q_getRsInfo.stmt(), 1); - const char *modelName = reinterpret_cast(sqlite3_column_text(q_getRsInfo.stmt(), 1)); + const char *modelName = + reinterpret_cast(sqlite3_column_text(q_getRsInfo.stmt(), 1)); int modelSuffixLen = sqlite3_column_bytes(q_getRsInfo.stmt(), 2); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q_getRsInfo.stmt(), 2)); + const char *modelSuffix = + reinterpret_cast(sqlite3_column_text(q_getRsInfo.stmt(), 2)); RsType type = RsType(sqlite3_column_int(q_getRsInfo.stmt(), 3)); - rs.rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + rs.rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); q_getRsInfo.reset(); checkRs(rs, q_selectCoupling); - //Insert also if there aren't errors to tell RsErrorTreeModel to remove this RS + // Insert also if there aren't errors to tell RsErrorTreeModel to remove this RS data.insert(rs.rsId, rs); } } @@ -152,86 +153,85 @@ void RsErrWorker::run() sendEvent(new RsWorkerResultEvent(this, data, !rsToCheck.isEmpty()), true); return; } - catch(std::exception& e) + catch (std::exception &e) { qWarning() << "RsErrWorker: exception " << e.what(); } - catch(...) + catch (...) { qWarning() << "RsErrWorker: generic exception"; } - //FIXME: Send error + // FIXME: Send error sendEvent(new RsWorkerResultEvent(this, data, !rsToCheck.isEmpty()), true); } -void RsErrWorker::checkRs(RsErrors::RSErrorList &rs, query& q_selectCoupling) +void RsErrWorker::checkRs(RsErrors::RSErrorList &rs, query &q_selectCoupling) { using namespace RsErrors; RSErrorData err; - err.rsId = rs.rsId; + err.rsId = rs.rsId; - RsOp prevOp = RsOp::Uncoupled; + RsOp prevOp = RsOp::Uncoupled; db_id prevCouplingId = 0; - db_id prevStopId = 0; - db_id prevStation = 0; + db_id prevStopId = 0; + db_id prevStation = 0; JobEntry prevJob; QTime prevTime; q_selectCoupling.bind(1, err.rsId); - for(auto coup : q_selectCoupling) + for (auto coup : q_selectCoupling) { - err.couplingId = coup.get(0); - RsOp op = RsOp(coup.get(1)); - err.stopId = coup.get(2); - err.job.jobId = coup.get(3); + err.couplingId = coup.get(0); + RsOp op = RsOp(coup.get(1)); + err.stopId = coup.get(2); + err.job.jobId = coup.get(3); err.job.category = JobCategory(coup.get(4)); - err.stationId = coup.get(5); - err.stationName = coup.get(6); - int transit = coup.get(7); - QTime arrival = coup.get(8); - //QTime departure = coup.get(9); TODO: check departure less than next arrival + err.stationId = coup.get(5); + err.stationName = coup.get(6); + int transit = coup.get(7); + QTime arrival = coup.get(8); + // QTime departure = coup.get(9); TODO: check departure less than next arrival - err.time = arrival; //TODO: maybe arrival or departure depending + err.time = arrival; // TODO: maybe arrival or departure depending err.otherId = prevCouplingId; - if(op == prevOp) + if (op == prevOp) { - if(op == RsOp::Coupled) + if (op == RsOp::Coupled) { - if(err.job.jobId != prevJob.jobId && prevJob.jobId != 0) + if (err.job.jobId != prevJob.jobId && prevJob.jobId != 0) { - //Rs was not uncoupled at the end of the job - //Or it was coupled by another job before prevJob uncouples it - //NOTE: this might be a false positive. Example below: - // 00:00 - Job 1 couples Rs - // 00:30 - Job 2 couples Rs - // --> here we detect 'Coupled twice' and 'Not uncoupled at end of job' - // 00:45 - Job 2 uncouples Rs - // 00:50 - Job 1 uncouples Rs - // --> here we detect 'Uncoupled when not coupled' - // because Job 2 already has uncoupled. - // But this also means that it's not true that Rs isn't uncoupled at end of the jobs + // Rs was not uncoupled at the end of the job + // Or it was coupled by another job before prevJob uncouples it + // NOTE: this might be a false positive. Example below: + // 00:00 - Job 1 couples Rs + // 00:30 - Job 2 couples Rs + // --> here we detect 'Coupled twice' and 'Not uncoupled at end of job' + // 00:45 - Job 2 uncouples Rs + // 00:50 - Job 1 uncouples Rs + // --> here we detect 'Uncoupled when not coupled' + // because Job 2 already has uncoupled. + // But this also means that it's not true that Rs isn't uncoupled at end of the + // jobs - - //Here we create another structure to fill it with previous data + // Here we create another structure to fill it with previous data RSErrorData e; e.couplingId = prevCouplingId; - e.rsId = rs.rsId; - e.stopId = prevStopId; - e.stationId = prevStation; - e.job = prevJob; - e.otherId = e.couplingId; - e.time = prevTime; - e.errorType = NotUncoupledAtJobEnd; + e.rsId = rs.rsId; + e.stopId = prevStopId; + e.stationId = prevStation; + e.job = prevJob; + e.otherId = e.couplingId; + e.time = prevTime; + e.errorType = NotUncoupledAtJobEnd; rs.errors.append(e); } - //Inform Rs was also coupled twice + // Inform Rs was also coupled twice err.errorType = CoupledWhileBusy; - } else { @@ -240,57 +240,59 @@ void RsErrWorker::checkRs(RsErrors::RSErrorList &rs, query& q_selectCoupling) rs.errors.append(err); } - if(transit) + if (transit) { err.errorType = StopIsTransit; rs.errors.append(err); } - if(op == RsOp::Coupled && prevOp == RsOp::Uncoupled && err.stationId != prevStation && prevStation != 0) + if (op == RsOp::Coupled && prevOp == RsOp::Uncoupled && err.stationId != prevStation + && prevStation != 0) { err.errorType = CoupledInDifferentStation; rs.errors.append(err); } - if(op == RsOp::Uncoupled && prevOp == RsOp::Coupled && err.job.jobId != prevJob.jobId && prevJob.jobId != 0) + if (op == RsOp::Uncoupled && prevOp == RsOp::Coupled && err.job.jobId != prevJob.jobId + && prevJob.jobId != 0) { err.errorType = UncoupledWhenNotCoupled; rs.errors.append(err); } - if(err.stopId == prevStopId) + if (err.stopId == prevStopId) { err.errorType = UncoupledInSameStop; rs.errors.append(err); } - prevOp = op; + prevOp = op; prevCouplingId = err.couplingId; - prevStopId = err.stopId; - prevStation = err.stationId; - prevJob = err.job; - prevTime = err.time; + prevStopId = err.stopId; + prevStation = err.stationId; + prevJob = err.job; + prevTime = err.time; } q_selectCoupling.reset(); - if(prevOp == RsOp::Coupled) + if (prevOp == RsOp::Coupled) { err.errorType = NotUncoupledAtJobEnd; rs.errors.append(err); } } -RsWorkerResultEvent::RsWorkerResultEvent(RsErrWorker *worker, const QMap &data, bool merge) : +RsWorkerResultEvent::RsWorkerResultEvent(RsErrWorker *worker, + const QMap &data, + bool merge) : GenericTaskEvent(_Type, worker), results(data), mergeErrors(merge) { - } RsWorkerResultEvent::~RsWorkerResultEvent() { - } #endif // ENABLE_BACKGROUND_MANAGER diff --git a/src/rollingstock/rs_checker/rsworker.h b/src/rollingstock/rs_checker/rsworker.h index 32c3df7..948e9e7 100644 --- a/src/rollingstock/rs_checker/rsworker.h +++ b/src/rollingstock/rs_checker/rsworker.h @@ -22,25 +22,23 @@ #ifdef ENABLE_BACKGROUND_MANAGER -#include "utils/thread/iquittabletask.h" -#include "utils/thread/taskprogressevent.h" +# include "utils/thread/iquittabletask.h" +# include "utils/thread/taskprogressevent.h" -#include -#include +# include +# include -#include "rs_error_data.h" +# include "rs_error_data.h" - -namespace sqlite3pp -{ +namespace sqlite3pp { class database; class query; -} +} // namespace sqlite3pp class RsErrWorker : public IQuittableTask { public: - RsErrWorker(sqlite3pp::database& db, QObject *receiver, const QVector& vec); + RsErrWorker(sqlite3pp::database &db, QObject *receiver, const QVector &vec); void run() override; @@ -59,7 +57,8 @@ class RsWorkerResultEvent : public GenericTaskEvent public: static const Type _Type = Type(CustomEvents::RsErrWorkerResult); - RsWorkerResultEvent(RsErrWorker *worker, const QMap &data, bool merge); + RsWorkerResultEvent(RsErrWorker *worker, const QMap &data, + bool merge); ~RsWorkerResultEvent(); QMap results; diff --git a/src/rollingstock/rsmatchmodelfactory.cpp b/src/rollingstock/rsmatchmodelfactory.cpp index 33790f1..e7f16b7 100644 --- a/src/rollingstock/rsmatchmodelfactory.cpp +++ b/src/rollingstock/rsmatchmodelfactory.cpp @@ -23,12 +23,12 @@ #include "rsownersmatchmodel.h" #include "rollingstockmatchmodel.h" -RSMatchModelFactory::RSMatchModelFactory(ModelModes::Mode mode, sqlite3pp::database &db, QObject *parent) : +RSMatchModelFactory::RSMatchModelFactory(ModelModes::Mode mode, sqlite3pp::database &db, + QObject *parent) : IMatchModelFactory(parent), mDb(db), m_mode(mode) { - } ISqlFKMatchModel *RSMatchModelFactory::createModel() diff --git a/src/rollingstock/rsmatchmodelfactory.h b/src/rollingstock/rsmatchmodelfactory.h index efee758..6608b5b 100644 --- a/src/rollingstock/rsmatchmodelfactory.h +++ b/src/rollingstock/rsmatchmodelfactory.h @@ -24,8 +24,7 @@ #include "utils/model_mode.h" -namespace sqlite3pp -{ +namespace sqlite3pp { class database; } diff --git a/src/rollingstock/rsmodelsmatchmodel.cpp b/src/rollingstock/rsmodelsmatchmodel.cpp index bcb390c..0bf37de 100644 --- a/src/rollingstock/rsmodelsmatchmodel.cpp +++ b/src/rollingstock/rsmodelsmatchmodel.cpp @@ -24,7 +24,8 @@ RSModelsMatchModel::RSModelsMatchModel(database &db, QObject *parent) : mDb(db), q_getMatches(mDb) { - q_getMatches.prepare("SELECT id,name,suffix FROM rs_models WHERE name LIKE ?1 OR suffix LIKE ?1 LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); + q_getMatches.prepare("SELECT id,name,suffix FROM rs_models WHERE name LIKE ?1 OR suffix LIKE " + "?1 LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); } QVariant RSModelsMatchModel::data(const QModelIndex &idx, int role) const @@ -36,11 +37,11 @@ QVariant RSModelsMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -49,7 +50,7 @@ QVariant RSModelsMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -63,7 +64,7 @@ QVariant RSModelsMatchModel::data(const QModelIndex &idx, int role) const void RSModelsMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -77,33 +78,34 @@ void RSModelsMatchModel::autoSuggest(const QString &text) void RSModelsMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); - auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { - items[i].modelId = (*it).get(0); + items[i].modelId = (*it).get(0); items[i].nameLength = sqlite3_column_bytes(q_getMatches.stmt(), 1); - const char *name = reinterpret_cast(sqlite3_column_text(q_getMatches.stmt(), 1)); + const char *name = + reinterpret_cast(sqlite3_column_text(q_getMatches.stmt(), 1)); int suffixLength = sqlite3_column_bytes(q_getMatches.stmt(), 2); - const char *suffix = reinterpret_cast(sqlite3_column_text(q_getMatches.stmt(), 2)); + const char *suffix = + reinterpret_cast(sqlite3_column_text(q_getMatches.stmt(), 2)); - if(suffix && suffixLength) + if (suffix && suffixLength) { QByteArray buf; buf.reserve(items[i].nameLength + suffixLength + 3); @@ -112,18 +114,20 @@ void RSModelsMatchModel::refreshData() buf.append(suffix, suffixLength); buf.append(')'); items[i].nameWithSuffix = QString::fromUtf8(buf); - }else{ + } + else + { items[i].nameWithSuffix = QString::fromUtf8(name, items[i].nameLength); } ++it; } - size = i + 1; //Items + Empty + size = i + 1; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -134,12 +138,12 @@ void RSModelsMatchModel::refreshData() QString RSModelsMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM rs_models WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } @@ -151,5 +155,6 @@ db_id RSModelsMatchModel::getIdAtRow(int row) const QString RSModelsMatchModel::getNameAtRow(int row) const { - return items[row].nameWithSuffix.left(items[row].nameLength); //Remove the suffix, keep only the name + return items[row].nameWithSuffix.left( + items[row].nameLength); // Remove the suffix, keep only the name } diff --git a/src/rollingstock/rsmodelsmatchmodel.h b/src/rollingstock/rsmodelsmatchmodel.h index 13de6e8..abf0713 100644 --- a/src/rollingstock/rsmodelsmatchmodel.h +++ b/src/rollingstock/rsmodelsmatchmodel.h @@ -38,7 +38,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; diff --git a/src/rollingstock/rsmodelssqlmodel.cpp b/src/rollingstock/rsmodelssqlmodel.cpp index 6992c77..fa42ab5 100644 --- a/src/rollingstock/rsmodelssqlmodel.cpp +++ b/src/rollingstock/rsmodelssqlmodel.cpp @@ -29,30 +29,25 @@ using namespace sqlite3pp; #include -static constexpr char -errorModelNameAlreadyUsedWithSameSuffix[] = QT_TRANSLATE_NOOP("RSModelsSQLModel", - "This model name (%1) is already used with the same" - " suffix (%2).
" - "If you intend to create a new model of same name but different" - " suffix, please first set the suffix."); +static constexpr char errorModelNameAlreadyUsedWithSameSuffix[] = QT_TRANSLATE_NOOP( + "RSModelsSQLModel", "This model name (%1) is already used with the same" + " suffix (%2).
" + "If you intend to create a new model of same name but different" + " suffix, please first set the suffix."); -static constexpr char -errorModelSuffixAlreadyUsedWithSameName[] = QT_TRANSLATE_NOOP("RSModelsSQLModel", - "This model suffix (%1) is already used with the same" - " name (%2)."); +static constexpr char errorModelSuffixAlreadyUsedWithSameName[] = QT_TRANSLATE_NOOP( + "RSModelsSQLModel", "This model suffix (%1) is already used with the same" + " name (%2)."); -static constexpr char -errorSpeedMustBeGreaterThanZero[] = QT_TRANSLATE_NOOP("RSModelsSQLModel", - "Rollingstock maximum speed must be > 0 km/h."); +static constexpr char errorSpeedMustBeGreaterThanZero[] = + QT_TRANSLATE_NOOP("RSModelsSQLModel", "Rollingstock maximum speed must be > 0 km/h."); -static constexpr char -errorAtLeastTwoAxes[] = QT_TRANSLATE_NOOP("RSModelsSQLModel", - "Rollingstock must have at least 2 axes."); +static constexpr char errorAtLeastTwoAxes[] = + QT_TRANSLATE_NOOP("RSModelsSQLModel", "Rollingstock must have at least 2 axes."); -static constexpr char -errorModelInUseCannotDelete[] = QT_TRANSLATE_NOOP("RSModelsSQLModel", - "There are rollingstock pieces of model %1 so it cannot be removed.\n" - "If you wish to remove it, please first delete all %1 pieces."); +static constexpr char errorModelInUseCannotDelete[] = QT_TRANSLATE_NOOP( + "RSModelsSQLModel", "There are rollingstock pieces of model %1 so it cannot be removed.\n" + "If you wish to remove it, please first delete all %1 pieces."); RSModelsSQLModel::RSModelsSQLModel(sqlite3pp::database &db, QObject *parent) : BaseClass(500, db, parent) @@ -62,9 +57,9 @@ RSModelsSQLModel::RSModelsSQLModel(sqlite3pp::database &db, QObject *parent) : QVariant RSModelsSQLModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (section) { @@ -98,18 +93,18 @@ QVariant RSModelsSQLModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const RSModel& item = cache.at(row - cacheFirstRow); + const RSModel &item = cache.at(row - cacheFirstRow); switch (role) { @@ -122,7 +117,9 @@ QVariant RSModelsSQLModel::data(const QModelIndex &idx, int role) const case Suffix: return item.suffix; case MaxSpeed: - return QStringLiteral("%1 km/h").arg(item.maxSpeedKmH); //TODO: maybe QString('%1 km/h').arg(maxSpeed) AND custom spinBox with suffix + return QStringLiteral("%1 km/h").arg( + item.maxSpeedKmH); // TODO: maybe QString('%1 km/h').arg(maxSpeed) AND custom spinBox + // with suffix case Axes: return int(item.axes); case TypeCol: @@ -131,7 +128,7 @@ QVariant RSModelsSQLModel::data(const QModelIndex &idx, int role) const } case SubTypeCol: { - if(item.type != RsType::Engine) + if (item.type != RsType::Engine) break; return RsTypeNames::name(item.sub_type); @@ -158,7 +155,7 @@ QVariant RSModelsSQLModel::data(const QModelIndex &idx, int role) const } case Qt::TextAlignmentRole: { - if(idx.column() == MaxSpeed || idx.column() == Axes) + if (idx.column() == MaxSpeed || idx.column() == Axes) return Qt::AlignRight + Qt::AlignVCenter; break; } @@ -174,12 +171,13 @@ QVariant RSModelsSQLModel::data(const QModelIndex &idx, int role) const bool RSModelsSQLModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - RSModel &item = cache[row - cacheFirstRow]; + RSModel &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -190,33 +188,33 @@ bool RSModelsSQLModel::setData(const QModelIndex &idx, const QVariant &value, in case Name: { const QString newName = value.toString().simplified(); - if(!setNameOrSuffix(item, newName, false)) + if (!setNameOrSuffix(item, newName, false)) return false; break; } case Suffix: { const QString newName = value.toString().simplified(); - if(!setNameOrSuffix(item, newName, true)) + if (!setNameOrSuffix(item, newName, true)) return false; break; } case MaxSpeed: { int speedKmH = value.toInt(); - if(speedKmH < 1) + if (speedKmH < 1) { emit modelError(tr(errorSpeedMustBeGreaterThanZero)); return false; } - if(item.maxSpeedKmH == speedKmH) - return false; //No change + if (item.maxSpeedKmH == speedKmH) + return false; // No change command set_speed(mDb, "UPDATE rs_models SET max_speed=? WHERE id=?"); set_speed.bind(1, speedKmH); set_speed.bind(2, item.modelId); - if(set_speed.execute() != SQLITE_OK) + if (set_speed.execute() != SQLITE_OK) return false; item.maxSpeedKmH = qint16(speedKmH); @@ -225,19 +223,19 @@ bool RSModelsSQLModel::setData(const QModelIndex &idx, const QVariant &value, in case Axes: { int axes = value.toInt(); - if(axes < 2) + if (axes < 2) { emit modelError(tr(errorAtLeastTwoAxes)); return false; } - if(item.axes == axes) - return false; //No change + if (item.axes == axes) + return false; // No change command set_axes(mDb, "UPDATE rs_models SET axes=? WHERE id=?"); set_axes.bind(1, axes); set_axes.bind(2, item.modelId); - if(set_axes.execute() != SQLITE_OK) + if (set_axes.execute() != SQLITE_OK) return false; item.axes = qint8(axes); @@ -248,20 +246,20 @@ bool RSModelsSQLModel::setData(const QModelIndex &idx, const QVariant &value, in } break; } - case RS_TYPE_ROLE: //Set through RS_TYPE_ROLE only + case RS_TYPE_ROLE: // Set through RS_TYPE_ROLE only { - if(!setType(item, RsType(value.toInt()), RsEngineSubType::NTypes)) + if (!setType(item, RsType(value.toInt()), RsEngineSubType::NTypes)) return false; first = index(row, TypeCol); - last = index(row, SubTypeCol); + last = index(row, SubTypeCol); break; } case RS_SUB_TYPE_ROLE: { - if(!setType(item, RsType::NTypes, RsEngineSubType(value.toInt()))) + if (!setType(item, RsType::NTypes, RsEngineSubType(value.toInt()))) return false; first = index(row, TypeCol); - last = index(row, SubTypeCol); + last = index(row, SubTypeCol); break; } default: @@ -278,25 +276,25 @@ Qt::ItemFlags RSModelsSQLModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() != SubTypeCol || cache[idx.row() - cacheFirstRow].type == RsType::Engine) - f.setFlag(Qt::ItemIsEditable); //NOTE: SubTypeCol is editable only fot Engines + if (idx.column() != SubTypeCol || cache[idx.row() - cacheFirstRow].type == RsType::Engine) + f.setFlag(Qt::ItemIsEditable); // NOTE: SubTypeCol is editable only fot Engines return f; } void RSModelsSQLModel::setSortingColumn(int col) { - if(sortColumn == col || (col != Name && col != TypeCol)) + if (sortColumn == col || (col != Name && col != TypeCol)) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -323,8 +321,8 @@ bool RSModelsSQLModel::setFilterAtCol(int col, const QString &str) { case Name: { - if(isNull) - return false; //Cannot have NULL Name + if (isNull) + return false; // Cannot have NULL Name m_nameFilter = str; break; } @@ -335,8 +333,8 @@ bool RSModelsSQLModel::setFilterAtCol(int col, const QString &str) } case MaxSpeed: { - if(isNull) - return false; //Cannot have NULL Speed + if (isNull) + return false; // Cannot have NULL Speed m_speedFilter = str; break; } @@ -348,21 +346,21 @@ bool RSModelsSQLModel::setFilterAtCol(int col, const QString &str) return true; } -bool RSModelsSQLModel::removeRSModel(db_id modelId, const QString& name) +bool RSModelsSQLModel::removeRSModel(db_id modelId, const QString &name) { - if(!modelId) + if (!modelId) return false; command cmd(mDb, "DELETE FROM rs_models WHERE id=?"); cmd.bind(1, modelId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { ret = mDb.extended_error_code(); - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { QString tmp = name; - if(name.isNull()) + if (name.isNull()) { query q(mDb, "SELECT name FROM rs_models WHERE id=?"); q.bind(1, modelId); @@ -377,75 +375,81 @@ bool RSModelsSQLModel::removeRSModel(db_id modelId, const QString& name) return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } bool RSModelsSQLModel::removeRSModelAt(int row) { - if(row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid const RSModel &item = cache.at(row - cacheFirstRow); return removeRSModel(item.modelId, item.name); } -db_id RSModelsSQLModel::addRSModel(int *outRow, db_id sourceModelId, const QString& suffix, QString *errOut) +db_id RSModelsSQLModel::addRSModel(int *outRow, db_id sourceModelId, const QString &suffix, + QString *errOut) { db_id modelId = 0; command cmd(mDb); - if(sourceModelId) + if (sourceModelId) { cmd.prepare("INSERT INTO rs_models(id,name,suffix,max_speed,axes,type,sub_type)" "SELECT NULL,name,?,max_speed,axes,type,sub_type FROM rs_models WHERE id=?"); cmd.bind(1, suffix); cmd.bind(2, sourceModelId); - }else{ - cmd.prepare("INSERT INTO rs_models(id,name,suffix,max_speed,axes,type,sub_type) VALUES (NULL,'','',120,4,0,0)"); + } + else + { + cmd.prepare("INSERT INTO rs_models(id,name,suffix,max_speed,axes,type,sub_type) VALUES " + "(NULL,'','',120,4,0,0)"); } sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); int ret = cmd.execute(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) { modelId = mDb.last_insert_rowid(); } sqlite3_mutex_leave(mutex); - if(outRow) - *outRow = modelId ? 0 : -1; //Empty name is always the first + if (outRow) + *outRow = modelId ? 0 : -1; // Empty name is always the first - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { - if(sourceModelId) + if (sourceModelId) { - //Error: suffix is already used - if(errOut) - *errOut = tr("Suffix is already used. Suffix must be different among models of same name."); + // Error: suffix is already used + if (errOut) + *errOut = + tr("Suffix is already used. Suffix must be different among models of same name."); return 0; } - //There is already an empty model, use that instead + // There is already an empty model, use that instead query findEmpty(mDb, "SELECT id FROM rs_models WHERE name='' OR name IS NULL LIMIT 1"); - if(findEmpty.step() == SQLITE_ROW) + if (findEmpty.step() == SQLITE_ROW) { modelId = findEmpty.getRows().get(0); - if(outRow) - *outRow = modelId ? 0 : -1; //Empty name is always the first + if (outRow) + *outRow = modelId ? 0 : -1; // Empty name is always the first } } - else if(ret != SQLITE_OK) + else if (ret != SQLITE_OK) { QString msg = mDb.error_msg(); - if(errOut) + if (errOut) *errOut = msg; - qDebug() << "RS Model Error adding:" << ret << msg << mDb.error_code() << mDb.extended_error_code(); + qDebug() << "RS Model Error adding:" << ret << msg << mDb.error_code() + << mDb.extended_error_code(); } - //Clear filters + // Clear filters m_nameFilter.clear(); m_nameFilter.squeeze(); m_suffixFilter.clear(); @@ -454,16 +458,16 @@ db_id RSModelsSQLModel::addRSModel(int *outRow, db_id sourceModelId, const QStri m_speedFilter.squeeze(); emit filterChanged(); - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row return modelId; } db_id RSModelsSQLModel::getModelIdAtRow(int row) const { - if(row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Not fetched yet or invalid + if (row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return 0; // Not fetched yet or invalid const RSModel &item = cache.at(row - cacheFirstRow); return item.modelId; } @@ -472,13 +476,14 @@ bool RSModelsSQLModel::removeAllRSModels() { command cmd(mDb, "DELETE FROM rs_models"); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Removing ALL RS MODELS:" << ret << mDb.extended_error_code() << "Err:" << mDb.error_msg(); + qWarning() << "Removing ALL RS MODELS:" << ret << mDb.extended_error_code() + << "Err:" << mDb.error_msg(); return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } @@ -495,38 +500,38 @@ qint64 RSModelsSQLModel::recalcTotalItemCount() void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool fullData) { QByteArray sql; - if(fullData) + if (fullData) sql = "SELECT id,name,suffix,max_speed,axes,type,sub_type FROM rs_models"; else sql = "SELECT COUNT(1) FROM rs_models"; bool whereClauseAdded = false; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { sql.append(" WHERE name LIKE ?3"); whereClauseAdded = true; } bool suffixFilterIsNull = m_suffixFilter.startsWith(nullFilterStr, Qt::CaseInsensitive); - if(!m_suffixFilter.isEmpty()) + if (!m_suffixFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); - //NOTE: suffix cannot be NULL because we need to enforce UNIQUE constraint - //To emulate NULL suffix we store an empty string - if(suffixFilterIsNull) + // NOTE: suffix cannot be NULL because we need to enforce UNIQUE constraint + // To emulate NULL suffix we store an empty string + if (suffixFilterIsNull) sql.append("suffix = ''"); else sql.append("suffix LIKE ?4"); } - if(!m_speedFilter.isEmpty()) + if (!m_speedFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); @@ -534,20 +539,20 @@ void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, sql.append("max_speed LIKE ?5"); } - if(fullData) + if (fullData) { - //Apply sorting + // Apply sorting const char *sortColExpr = nullptr; switch (sortCol) { case Name: { - sortColExpr = "name,suffix"; //Order by 2 columns, no where clause + sortColExpr = "name,suffix"; // Order by 2 columns, no where clause break; } case TypeCol: { - sortColExpr = "type,sub_type,name,suffix"; //Order by 4 columns, no where clause + sortColExpr = "type,sub_type,name,suffix"; // Order by 4 columns, no where clause break; } } @@ -556,23 +561,23 @@ void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, sql += sortColExpr; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; } q.prepare(sql); - if(fullData) + if (fullData) { - //Apply offset and batch size + // Apply offset and batch size q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); } - //Apply filters + // Apply filters QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -582,7 +587,7 @@ void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, } QByteArray suffixFilter; - if(!m_suffixFilter.isEmpty() && !suffixFilterIsNull) + if (!m_suffixFilter.isEmpty() && !suffixFilterIsNull) { suffixFilter.reserve(m_suffixFilter.size() + 2); suffixFilter.append('%'); @@ -592,7 +597,7 @@ void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, } QByteArray speedFilter; - if(!m_speedFilter.isEmpty()) + if (!m_speedFilter.isEmpty()) { speedFilter.reserve(m_speedFilter.size() + 2); speedFilter.append('%'); @@ -602,7 +607,8 @@ void RSModelsSQLModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, } } -void RSModelsSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant& /*val*/) +void RSModelsSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); @@ -614,63 +620,63 @@ void RSModelsSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, con QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; - RSModel &item = vec[i]; - item.modelId = r.get(0); - item.name = r.get(1); - item.suffix = r.get(2); + auto r = *it; + RSModel &item = vec[i]; + item.modelId = r.get(0); + item.name = r.get(1); + item.suffix = r.get(2); item.maxSpeedKmH = r.get(3); - item.axes = r.get(4); - item.type = RsType(r.get(5)); - item.sub_type = RsEngineSubType(r.get(6)); + item.axes = r.get(4); + item.type = RsType(r.get(5)); + item.sub_type = RsEngineSubType(r.get(6)); i += 1; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); } -bool RSModelsSQLModel::setNameOrSuffix(RSModel& item, const QString& newName, bool suffix) +bool RSModelsSQLModel::setNameOrSuffix(RSModel &item, const QString &newName, bool suffix) { - if(suffix ? item.suffix == newName : item.name == newName) - return false; //No change + if (suffix ? item.suffix == newName : item.name == newName) + return false; // No change command set_name(mDb, suffix ? "UPDATE rs_models SET suffix=? WHERE id=?" : "UPDATE rs_models SET name=? WHERE id=?"); set_name.bind(1, newName); set_name.bind(2, item.modelId); int ret = set_name.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qDebug() << "setNameOrSuffix()" << ret << mDb.error_code() << mDb.extended_error_code() << mDb.error_msg(); + qDebug() << "setNameOrSuffix()" << ret << mDb.error_code() << mDb.extended_error_code() + << mDb.error_msg(); ret = mDb.extended_error_code(); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(suffix ? errorModelSuffixAlreadyUsedWithSameName : errorModelNameAlreadyUsedWithSameSuffix) - .arg(newName, - suffix ? item.name : item.suffix)); + .arg(newName, suffix ? item.name : item.suffix)); } return false; } - if(suffix) + if (suffix) item.suffix = newName; else item.name = newName; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -679,29 +685,29 @@ bool RSModelsSQLModel::setNameOrSuffix(RSModel& item, const QString& newName, bo bool RSModelsSQLModel::setType(RSModel &item, RsType type, RsEngineSubType subType) { - if(type == RsType::NTypes) + if (type == RsType::NTypes) type = item.type; else subType = item.sub_type; - if(type != RsType::Engine) - subType = RsEngineSubType::Invalid; //Only engines can have a subType for now + if (type != RsType::Engine) + subType = RsEngineSubType::Invalid; // Only engines can have a subType for now command set_type(mDb, "UPDATE rs_models SET type=?,sub_type=? WHERE id=?"); set_type.bind(1, int(type)); set_type.bind(2, int(subType)); set_type.bind(3, item.modelId); - if(set_type.execute() != SQLITE_OK) + if (set_type.execute() != SQLITE_OK) return false; - item.type = type; + item.type = type; item.sub_type = subType; - if(sortColumn == TypeCol) + if (sortColumn == TypeCol) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } diff --git a/src/rollingstock/rsmodelssqlmodel.h b/src/rollingstock/rsmodelssqlmodel.h index cf6d0f1..df5382e 100644 --- a/src/rollingstock/rsmodelssqlmodel.h +++ b/src/rollingstock/rsmodelssqlmodel.h @@ -39,16 +39,18 @@ struct RSModelsSQLModelItem RsEngineSubType sub_type; }; - class RSModelsSQLModel : public IPagedItemModelImpl { Q_OBJECT public: + enum + { + BatchSize = 100 + }; - enum { BatchSize = 100 }; - - enum Columns { + enum Columns + { Name = 0, Suffix, MaxSpeed, @@ -66,24 +68,23 @@ public: // QAbstractTableModel: // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel: virtual void setSortingColumn(int col) override; - //Filter + // Filter std::pair getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // RSModelsSQLModel: bool removeRSModel(db_id modelId, const QString &name); diff --git a/src/rollingstock/rsownersmatchmodel.cpp b/src/rollingstock/rsownersmatchmodel.cpp index 0d092c7..e433a58 100644 --- a/src/rollingstock/rsownersmatchmodel.cpp +++ b/src/rollingstock/rsownersmatchmodel.cpp @@ -24,7 +24,8 @@ RSOwnersMatchModel::RSOwnersMatchModel(database &db, QObject *parent) : mDb(db), q_getMatches(mDb) { - q_getMatches.prepare("SELECT id,name FROM rs_owners WHERE name LIKE ? LIMIT " QT_STRINGIFY(MaxMatchItems)); + q_getMatches.prepare( + "SELECT id,name FROM rs_owners WHERE name LIKE ? LIMIT " QT_STRINGIFY(MaxMatchItems)); } QVariant RSOwnersMatchModel::data(const QModelIndex &idx, int role) const @@ -36,11 +37,11 @@ QVariant RSOwnersMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -49,7 +50,7 @@ QVariant RSOwnersMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -63,7 +64,7 @@ QVariant RSOwnersMatchModel::data(const QModelIndex &idx, int role) const void RSOwnersMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -77,35 +78,34 @@ void RSOwnersMatchModel::autoSuggest(const QString &text) void RSOwnersMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); - auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { items[i].ownerId = (*it).get(0); - items[i].name = (*it).get(1); + items[i].name = (*it).get(1); ++it; } - size = i + 1; //Items + Empty + size = i + 1; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -116,12 +116,12 @@ void RSOwnersMatchModel::refreshData() QString RSOwnersMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM rs_owners WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } diff --git a/src/rollingstock/rsownersmatchmodel.h b/src/rollingstock/rsownersmatchmodel.h index 03effed..839cd8b 100644 --- a/src/rollingstock/rsownersmatchmodel.h +++ b/src/rollingstock/rsownersmatchmodel.h @@ -38,7 +38,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; diff --git a/src/rollingstock/rsownerssqlmodel.cpp b/src/rollingstock/rsownerssqlmodel.cpp index 52f9257..c573cfa 100644 --- a/src/rollingstock/rsownerssqlmodel.cpp +++ b/src/rollingstock/rsownerssqlmodel.cpp @@ -28,16 +28,14 @@ using namespace sqlite3pp; #include -static constexpr char -errorOwnerNameAlreadyUsed[] = QT_TRANSLATE_NOOP("RSOwnersSQLModel", - "This owner name (%1) is already used."); +static constexpr char errorOwnerNameAlreadyUsed[] = + QT_TRANSLATE_NOOP("RSOwnersSQLModel", "This owner name (%1) is already used."); -static constexpr char -errorOwnerInUseCannotDelete[] - = QT_TRANSLATE_NOOP("RSOwnersSQLModel", - "There are rollingstock pieces of owner %1 so it cannot be removed.
" - "If you wish to remove it, please first delete all pieces belonging to %1 " - "or change their owner."); +static constexpr char errorOwnerInUseCannotDelete[] = QT_TRANSLATE_NOOP( + "RSOwnersSQLModel", + "There are rollingstock pieces of owner %1 so it cannot be removed.
" + "If you wish to remove it, please first delete all pieces belonging to %1 " + "or change their owner."); RSOwnersSQLModel::RSOwnersSQLModel(sqlite3pp::database &db, QObject *parent) : BaseClass(500, db, parent) @@ -47,9 +45,9 @@ RSOwnersSQLModel::RSOwnersSQLModel(sqlite3pp::database &db, QObject *parent) : QVariant RSOwnersSQLModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (section) { @@ -73,18 +71,18 @@ QVariant RSOwnersSQLModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - //qDebug() << "Data:" << idx.row(); + // qDebug() << "Data:" << idx.row(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const RSOwner& item = cache.at(row - cacheFirstRow); + const RSOwner &item = cache.at(row - cacheFirstRow); switch (role) { @@ -107,12 +105,13 @@ QVariant RSOwnersSQLModel::data(const QModelIndex &idx, int role) const bool RSOwnersSQLModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - RSOwner &item = cache[row - cacheFirstRow]; + RSOwner &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -123,33 +122,33 @@ bool RSOwnersSQLModel::setData(const QModelIndex &idx, const QVariant &value, in case Name: { QString newName = value.toString().simplified(); - if(item.name == newName) - return false; //No change + if (item.name == newName) + return false; // No change command set_name(mDb, "UPDATE rs_owners SET name=? WHERE id=?"); - if(newName.isEmpty()) - set_name.bind(1); //Bind NULL + if (newName.isEmpty()) + set_name.bind(1); // Bind NULL else set_name.bind(1, newName); set_name.bind(2, item.ownerId); int ret = set_name.execute(); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorOwnerNameAlreadyUsed).arg(newName)); return false; } - else if(ret != SQLITE_OK) + else if (ret != SQLITE_OK) { return false; } item.name = newName; - //FIXME: maybe emit some signals? + // FIXME: maybe emit some signals? - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -174,8 +173,8 @@ Qt::ItemFlags RSOwnersSQLModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet f.setFlag(Qt::ItemIsEditable); return f; } @@ -199,8 +198,8 @@ bool RSOwnersSQLModel::setFilterAtCol(int col, const QString &str) { case Name: { - if(isNull) - return false; //Cannot have NULL OwnerName + if (isNull) + return false; // Cannot have NULL OwnerName m_ownerFilter = str; break; } @@ -212,21 +211,21 @@ bool RSOwnersSQLModel::setFilterAtCol(int col, const QString &str) return true; } -bool RSOwnersSQLModel::removeRSOwner(db_id ownerId, const QString& name) +bool RSOwnersSQLModel::removeRSOwner(db_id ownerId, const QString &name) { - if(!ownerId) + if (!ownerId) return false; command cmd(mDb, "DELETE FROM rs_owners WHERE id=?"); cmd.bind(1, ownerId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { ret = mDb.extended_error_code(); - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { QString tmp = name; - if(name.isNull()) + if (name.isNull()) { query q(mDb, "SELECT name FROM rs_owners WHERE id=?"); q.bind(1, ownerId); @@ -241,14 +240,14 @@ bool RSOwnersSQLModel::removeRSOwner(db_id ownerId, const QString& name) return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } bool RSOwnersSQLModel::removeRSOwnerAt(int row) { - if(row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid const RSOwner &item = cache.at(row - cacheFirstRow); @@ -263,36 +262,37 @@ db_id RSOwnersSQLModel::addRSOwner(int *outRow) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); int ret = cmd.execute(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) { ownerId = mDb.last_insert_rowid(); } sqlite3_mutex_leave(mutex); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { - //There is already an empty owner, use that instead + // There is already an empty owner, use that instead query findEmpty(mDb, "SELECT id FROM rs_owners WHERE name='' OR name IS NULL LIMIT 1"); - if(findEmpty.step() == SQLITE_ROW) + if (findEmpty.step() == SQLITE_ROW) { ownerId = findEmpty.getRows().get(0); } } - else if(ret != SQLITE_OK) + else if (ret != SQLITE_OK) { - qDebug() << "RS Owner Error adding:" << ret << mDb.error_msg() << mDb.error_code() << mDb.extended_error_code(); + qDebug() << "RS Owner Error adding:" << ret << mDb.error_msg() << mDb.error_code() + << mDb.extended_error_code(); } - //Clear filters + // Clear filters m_ownerFilter.clear(); m_ownerFilter.squeeze(); emit filterChanged(); - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row - if(outRow) - *outRow = ownerId ? 0 : -1; //Empty name is always the first + if (outRow) + *outRow = ownerId ? 0 : -1; // Empty name is always the first return ownerId; } @@ -301,27 +301,28 @@ bool RSOwnersSQLModel::removeAllRSOwners() { command cmd(mDb, "DELETE FROM rs_owners"); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Removing ALL RS OWNERS:" << ret << mDb.extended_error_code() << "Err:" << mDb.error_msg(); + qWarning() << "Removing ALL RS OWNERS:" << ret << mDb.extended_error_code() + << "Err:" << mDb.error_msg(); return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } qint64 RSOwnersSQLModel::recalcTotalItemCount() { QByteArray sql = "SELECT COUNT(1) FROM rs_owners"; - if(!m_ownerFilter.isEmpty()) + if (!m_ownerFilter.isEmpty()) { sql.append(" WHERE rs_owners.name LIKE ?1"); } query q(mDb, sql); - if(!m_ownerFilter.isEmpty()) + if (!m_ownerFilter.isEmpty()) { QByteArray ownerFilter; ownerFilter.reserve(m_ownerFilter.size() + 2); @@ -336,7 +337,8 @@ qint64 RSOwnersSQLModel::recalcTotalItemCount() return count; } -void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant& /*val*/) +void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); @@ -344,9 +346,8 @@ void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, con qDebug() << "Fetching:" << first << "Offset:" << offset; - QByteArray sql = "SELECT id,name FROM rs_owners"; - if(!m_ownerFilter.isEmpty()) + if (!m_ownerFilter.isEmpty()) { sql.append(" WHERE rs_owners.name LIKE ?3"); } @@ -356,7 +357,7 @@ void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, con { case Name: { - sertColExpr = "name"; //Order by 2 columns, no where clause + sertColExpr = "name"; // Order by 2 columns, no where clause break; } } @@ -365,15 +366,15 @@ void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, con sql += sertColExpr; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); - if(!m_ownerFilter.isEmpty()) + if (!m_ownerFilter.isEmpty()) { QByteArray ownerFilter; ownerFilter.reserve(m_ownerFilter.size() + 2); @@ -385,21 +386,21 @@ void RSOwnersSQLModel::internalFetch(int first, int sortCol, int /*valRow*/, con QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; + auto r = *it; RSOwner &item = vec[i]; - item.ownerId = r.get(0); - item.name = r.get(1); + item.ownerId = r.get(0); + item.name = r.get(1); i += 1; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/rollingstock/rsownerssqlmodel.h b/src/rollingstock/rsownerssqlmodel.h index a04224a..48373bf 100644 --- a/src/rollingstock/rsownerssqlmodel.h +++ b/src/rollingstock/rsownerssqlmodel.h @@ -30,16 +30,18 @@ struct RSOwnersSQLModelItem QString name; }; - class RSOwnersSQLModel : public IPagedItemModelImpl { Q_OBJECT public: + enum + { + BatchSize = 100 + }; - enum { BatchSize = 100 }; - - enum Columns { + enum Columns + { Name = 0, NCols }; @@ -52,22 +54,21 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - - Qt::ItemFlags flags(const QModelIndex& idx) const override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel - //Filter + // Filter std::pair getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // RSOwnersSQLModel diff --git a/src/searchbox/searchresultevent.cpp b/src/searchbox/searchresultevent.cpp index 812b0f1..bd1f12f 100644 --- a/src/searchbox/searchresultevent.cpp +++ b/src/searchbox/searchresultevent.cpp @@ -19,21 +19,19 @@ #ifdef SEARCHBOX_MODE_ASYNC -#include "searchresultevent.h" +# include "searchresultevent.h" -#include "searchresultitem.h" +# include "searchresultitem.h" SearchResultEvent::SearchResultEvent(SearchTask *ta, const QVector &vec) : QEvent(_Type), task(ta), results(vec) { - } SearchResultEvent::~SearchResultEvent() { - } -#endif //SEARCHBOX_MODE_ASYNC +#endif // SEARCHBOX_MODE_ASYNC diff --git a/src/searchbox/searchresultevent.h b/src/searchbox/searchresultevent.h index e1f1d9e..bab3833 100644 --- a/src/searchbox/searchresultevent.h +++ b/src/searchbox/searchresultevent.h @@ -22,11 +22,11 @@ #ifdef SEARCHBOX_MODE_ASYNC -#include +# include -#include +# include -#include "utils/worker_event_types.h" +# include "utils/worker_event_types.h" class SearchTask; struct SearchResultItem; @@ -44,6 +44,6 @@ public: QVector results; }; -#endif //SEARCHBOX_MODE_ASYNC +#endif // SEARCHBOX_MODE_ASYNC #endif // SEARCHRESULTEVENT_H diff --git a/src/searchbox/searchresultmodel.cpp b/src/searchbox/searchresultmodel.cpp index 9a35085..bc66f9b 100644 --- a/src/searchbox/searchresultmodel.cpp +++ b/src/searchbox/searchresultmodel.cpp @@ -26,16 +26,16 @@ #ifdef SEARCHBOX_MODE_ASYNC -#ifndef ENABLE_BACKGROUND_MANAGER -#error "Cannot use SEARCHBOX_MODE_ASYNC without ENABLE_BACKGROUND_MANAGER" -#endif +# ifndef ENABLE_BACKGROUND_MANAGER +# error "Cannot use SEARCHBOX_MODE_ASYNC without ENABLE_BACKGROUND_MANAGER" +# endif -#include "searchtask.h" -#include "searchresultevent.h" -#include +# include "searchtask.h" +# include "searchresultevent.h" +# include -#include "app/session.h" -#include "backgroundmanager/backgroundmanager.h" +# include "app/session.h" +# include "backgroundmanager/backgroundmanager.h" #endif SearchResultModel::SearchResultModel(sqlite3pp::database &db, QObject *parent) : @@ -46,7 +46,8 @@ SearchResultModel::SearchResultModel(sqlite3pp::database &db, QObject *parent) : { m_font.setPointSize(13); setHasEmptyRow(false); - connect(Session->getBackgroundManager(), &BackgroundManager::abortTrivialTasks, this, &SearchResultModel::stopAllTasks); + connect(Session->getBackgroundManager(), &BackgroundManager::abortTrivialTasks, this, + &SearchResultModel::stopAllTasks); } SearchResultModel::~SearchResultModel() @@ -63,10 +64,10 @@ int SearchResultModel::columnCount(const QModelIndex &parent) const QVariant SearchResultModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid() || idx.row() >= size) + if (!idx.isValid() || idx.row() >= size) return QVariant(); - const SearchResultItem& item = m_data.at(idx.row()); + const SearchResultItem &item = m_data.at(idx.row()); switch (role) { @@ -76,7 +77,7 @@ QVariant SearchResultModel::data(const QModelIndex &idx, int role) const { case JobCategoryCol: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { break; } @@ -84,7 +85,7 @@ QVariant SearchResultModel::data(const QModelIndex &idx, int role) const } case JobNumber: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -95,7 +96,7 @@ QVariant SearchResultModel::data(const QModelIndex &idx, int role) const } case Qt::ForegroundRole: { - if(isEllipsesRow(idx.row())) + if (isEllipsesRow(idx.row())) { break; } @@ -132,7 +133,7 @@ QVariant SearchResultModel::data(const QModelIndex &idx, int role) const void SearchResultModel::autoSuggest(const QString &text) { #ifdef SEARCHBOX_MODE_ASYNC - abortSearch(); //Stop previous search + abortSearch(); // Stop previous search SearchTask *task = createTask(text); tasks.append(task); @@ -140,7 +141,7 @@ void SearchResultModel::autoSuggest(const QString &text) QThreadPool::globalInstance()->start(task); #else - searchFor(editor->text()); //TODO + searchFor(editor->text()); // TODO #endif } @@ -155,29 +156,29 @@ void SearchResultModel::clearCache() db_id SearchResultModel::getIdAtRow(int row) const { - if(row >= m_data.size()) + if (row >= m_data.size()) return 0; return m_data.at(row).jobId; } QString SearchResultModel::getNameAtRow(int row) const { - if(row >= m_data.size()) + if (row >= m_data.size()) return QString(); - const SearchResultItem& item = m_data.at(row); + const SearchResultItem &item = m_data.at(row); return JobCategoryName::jobName(item.jobId, item.category); } #ifdef SEARCHBOX_MODE_ASYNC void SearchResultModel::abortSearch() { - if(!tasks.isEmpty()) + if (!tasks.isEmpty()) tasks.last()->stop(); } void SearchResultModel::stopAllTasks() { - for(SearchTask *task : qAsConst(tasks)) + for (SearchTask *task : qAsConst(tasks)) { task->stop(); task->cleanup(); @@ -188,42 +189,45 @@ void SearchResultModel::stopAllTasks() void SearchResultModel::disposeTask(SearchTask *task) { - if(reusableTask) + if (reusableTask) { - delete task; //We already have a reusable task - }else{ - reusableTask = task; - deleteReusableTaskTimerId = startTimer(3000, Qt::VeryCoarseTimer); //3 sec, then delete + delete task; // We already have a reusable task + } + else + { + reusableTask = task; + deleteReusableTaskTimerId = startTimer(3000, Qt::VeryCoarseTimer); // 3 sec, then delete } } -SearchTask *SearchResultModel::createTask(const QString& text) +SearchTask *SearchResultModel::createTask(const QString &text) { - if(catNames.isEmpty()) + if (catNames.isEmpty()) { - //Load categories names + // Load categories names 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::tr(JobCategoryFullNameTable[cat])); } catNamesAbbr.reserve(int(JobCategory::NCategories)); - for(int cat = 0; cat < int(JobCategory::NCategories); cat++) + for (int cat = 0; cat < int(JobCategory::NCategories); cat++) { catNamesAbbr.append(JobCategoryName::tr(JobCategoryAbbrNameTable[cat])); } } SearchTask *task; - if(reusableTask) + if (reusableTask) { killTimer(deleteReusableTaskTimerId); deleteReusableTaskTimerId = 0; - task = reusableTask; - reusableTask = nullptr; + task = reusableTask; + reusableTask = nullptr; - //NOTE: SearchTask gets disposed after finishing running so IQuittableTask has set mReceiver to nullptr + // NOTE: SearchTask gets disposed after finishing running so IQuittableTask has set + // mReceiver to nullptr task->setReceiver(this); } else @@ -236,17 +240,17 @@ SearchTask *SearchResultModel::createTask(const QString& text) void SearchResultModel::clearReusableTask() { - if(deleteReusableTaskTimerId) + if (deleteReusableTaskTimerId) { killTimer(deleteReusableTaskTimerId); deleteReusableTaskTimerId = 0; } - if(reusableTask) + if (reusableTask) { delete reusableTask; reusableTask = nullptr; } - if(tasks.isEmpty()) + if (tasks.isEmpty()) { catNames.clear(); catNamesAbbr.clear(); @@ -255,29 +259,30 @@ void SearchResultModel::clearReusableTask() bool SearchResultModel::event(QEvent *ev) { - if(ev->type() == QEvent::Timer && static_cast(ev)->timerId() == deleteReusableTaskTimerId) + if (ev->type() == QEvent::Timer + && static_cast(ev)->timerId() == deleteReusableTaskTimerId) { clearReusableTask(); return true; } - if(ev->type() == SearchResultEvent::_Type) + if (ev->type() == SearchResultEvent::_Type) { SearchResultEvent *e = static_cast(ev); e->setAccepted(true); int idx = tasks.indexOf(e->task); - if(idx != -1) + if (idx != -1) { bool wasLast = idx == tasks.size() - 1; tasks.removeAt(idx); disposeTask(e->task); - if(wasLast) + if (wasLast) { beginResetModel(); m_data = e->results; - if(m_data.size() > MaxMatchItems) - size = MaxMatchItems + 1; //There would be still rows, show Ellipses + if (m_data.size() > MaxMatchItems) + size = MaxMatchItems + 1; // There would be still rows, show Ellipses else size = m_data.size(); diff --git a/src/searchbox/searchresultmodel.h b/src/searchbox/searchresultmodel.h index 70851d5..90c43b6 100644 --- a/src/searchbox/searchresultmodel.h +++ b/src/searchbox/searchresultmodel.h @@ -62,7 +62,7 @@ public: QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel - virtual void autoSuggest(const QString& text) override; + virtual void autoSuggest(const QString &text) override; virtual void clearCache() override; virtual db_id getIdAtRow(int row) const override; diff --git a/src/searchbox/searchtask.cpp b/src/searchbox/searchtask.cpp index 42dae17..275e060 100644 --- a/src/searchbox/searchtask.cpp +++ b/src/searchbox/searchtask.cpp @@ -19,15 +19,15 @@ #ifdef SEARCHBOX_MODE_ASYNC -#include "searchtask.h" -#include "searchresultitem.h" -#include "searchresultevent.h" +# include "searchtask.h" +# include "searchresultitem.h" +# include "searchresultevent.h" -#include +# include -#include "app/session.h" +# include "app/session.h" -#include +# include SearchTask::SearchTask(QObject *receiver, int limitRows, sqlite3pp::database &db, const QStringList &catNames_, const QStringList &catNamesAbbr_) : @@ -44,7 +44,7 @@ SearchTask::SearchTask(QObject *receiver, int limitRows, sqlite3pp::database &db SearchTask::~SearchTask() { - if(regExp) + if (regExp) { delete regExp; regExp = nullptr; @@ -55,86 +55,86 @@ void SearchTask::run() { QVector results; - if(!regExp) + if (!regExp) regExp = new QRegularExpression("(?[^0-9\\s]*)\\s*(?\\d*)"); QRegularExpressionMatch match = regExp->match(mQuery); - if(!match.hasMatch()) + if (!match.hasMatch()) { sendEvent(new SearchResultEvent(this, results), true); return; } QString name = match.captured("name"); - QString num = match.captured("num"); + QString num = match.captured("num"); - if(wasStopped()) + if (wasStopped()) { sendEvent(new SearchResultEvent(this, results), true); return; } - if(!name.isEmpty()) + if (!name.isEmpty()) { - //Find the matching category + // Find the matching category name = name.toUpper(); QList categories; int cat = catNamesAbbr.indexOf(name); - if(cat == -1) //Retry with full names + if (cat == -1) // Retry with full names cat = catNames.indexOf(name); - if(cat != -1) + if (cat != -1) { categories.append(cat); } else { - //Retry with full names that start with ... (partial names) - for(int i = 0; i < catNames.size(); i++) + // Retry with full names that start with ... (partial names) + for (int i = 0; i < catNames.size(); i++) { - if(catNames.at(i).startsWith(name, Qt::CaseInsensitive)) + if (catNames.at(i).startsWith(name, Qt::CaseInsensitive)) { - categories.append(i); //Don't break, allow multiple categories + categories.append(i); // Don't break, allow multiple categories } } } - if(categories.isEmpty()) - return; //Failed to find a category + if (categories.isEmpty()) + return; // Failed to find a category - if(num.isEmpty()) + if (num.isEmpty()) { - //It's a category like 'IC' - //Match all jobs with that category + // It's a category like 'IC' + // Match all jobs with that category searchByCat(categories, results); } else { - //Category + number - //Match all jobs beggining with this number and with this category + // Category + number + // Match all jobs beggining with this number and with this category searchByCatAndNum(categories, num, results); } } - else if(!num.isEmpty()) + else if (!num.isEmpty()) { - //Search all jobs beginning with this number + // Search all jobs beginning with this number searchByNum(num, results); } sendEvent(new SearchResultEvent(this, results), true); } -void SearchTask::searchByCat(const QList& categories, QVector& jobs) +void SearchTask::searchByCat(const QList &categories, QVector &jobs) { - if(queryType != ByCat) + if (queryType != ByCat) { q_selectJobs.prepare("SELECT id FROM jobs WHERE category=?1 ORDER BY id LIMIT ?2"); queryType = ByCat; } - for(const int cat : categories) + for (const int cat : categories) { SearchResultItem item; item.category = JobCategory(cat); @@ -142,10 +142,10 @@ void SearchTask::searchByCat(const QList& categories, QVector(0); @@ -155,9 +155,10 @@ void SearchTask::searchByCat(const QList& categories, QVector& categories, const QString& num, QVector& jobs) +void SearchTask::searchByCatAndNum(const QList &categories, const QString &num, + QVector &jobs) { - if(queryType != ByCatAndNum) + if (queryType != ByCatAndNum) { q_selectJobs.prepare("SELECT id, id LIKE ?2 as job_rank FROM jobs" " WHERE category=?1 AND id LIKE ?3" @@ -165,7 +166,7 @@ void SearchTask::searchByCatAndNum(const QList& categories, const QString& queryType = ByCatAndNum; } - for(const int cat : categories) + for (const int cat : categories) { SearchResultItem item; item.category = JobCategory(cat); @@ -175,10 +176,10 @@ void SearchTask::searchByCatAndNum(const QList& categories, const QString& q_selectJobs.bind(3, '%' + num + '%'); q_selectJobs.bind(4, limitResultRows); - for(auto job : q_selectJobs) + for (auto job : q_selectJobs) { - //Check every 4 items - if(jobs.size() % 4 == 0 && wasStopped()) + // Check every 4 items + if (jobs.size() % 4 == 0 && wasStopped()) return; item.jobId = job.get(0); @@ -188,9 +189,9 @@ void SearchTask::searchByCatAndNum(const QList& categories, const QString& } } -void SearchTask::searchByNum(const QString& num, QVector& jobs) +void SearchTask::searchByNum(const QString &num, QVector &jobs) { - if(queryType != ByNum) + if (queryType != ByNum) { q_selectJobs.prepare("SELECT id, category, id LIKE ?1 as job_rank FROM jobs" " WHERE id LIKE ?2" @@ -202,14 +203,14 @@ void SearchTask::searchByNum(const QString& num, QVector& jobs q_selectJobs.bind(2, '%' + num + '%'); q_selectJobs.bind(3, limitResultRows); - for(auto job : q_selectJobs) + for (auto job : q_selectJobs) { - //Check every 4 items - if(jobs.size() % 4 == 0 && wasStopped()) + // Check every 4 items + if (jobs.size() % 4 == 0 && wasStopped()) return; SearchResultItem item; - item.jobId = job.get(0); + item.jobId = job.get(0); item.category = JobCategory(job.get(1)); jobs.append(item); } @@ -221,4 +222,4 @@ void SearchTask::setQuery(const QString &query) mQuery = query; } -#endif //SEARCHBOX_MODE_ASYNC +#endif // SEARCHBOX_MODE_ASYNC diff --git a/src/searchbox/searchtask.h b/src/searchbox/searchtask.h index 6605943..abf9fa5 100644 --- a/src/searchbox/searchtask.h +++ b/src/searchbox/searchtask.h @@ -22,12 +22,12 @@ #ifdef SEARCHBOX_MODE_ASYNC -#include "utils/thread/iquittabletask.h" +# include "utils/thread/iquittabletask.h" -#include -#include "utils/types.h" +# include +# include "utils/types.h" -#include +# include struct SearchResultItem; class QRegularExpression; @@ -36,7 +36,7 @@ class SearchTask : public IQuittableTask { public: SearchTask(QObject *receiver, int limitRows, sqlite3pp::database &db, - const QStringList& catNames_, const QStringList& catNamesAbbr_); + const QStringList &catNames_, const QStringList &catNamesAbbr_); ~SearchTask(); void run() override; @@ -45,7 +45,8 @@ public: private: void searchByCat(const QList &categories, QVector &jobs); - void searchByCatAndNum(const QList &categories, const QString &num, QVector &jobs); + void searchByCatAndNum(const QList &categories, const QString &num, + QVector &jobs); void searchByNum(const QString &num, QVector &jobs); private: @@ -64,9 +65,9 @@ private: QString mQuery; int limitResultRows; QueryType queryType; - QStringList catNames, catNamesAbbr; //FIXME: store in search engine cache + QStringList catNames, catNamesAbbr; // FIXME: store in search engine cache }; -#endif //SEARCHBOX_MODE_ASYNC +#endif // SEARCHBOX_MODE_ASYNC #endif // SEARCHTASK_H diff --git a/src/settings/appsettings.cpp b/src/settings/appsettings.cpp index a94f768..b65bd1b 100644 --- a/src/settings/appsettings.cpp +++ b/src/settings/appsettings.cpp @@ -30,10 +30,9 @@ MRTPSettings::MRTPSettings(QObject *parent) : QObject(parent) { - } -void MRTPSettings::loadSettings(const QString& fileName) +void MRTPSettings::loadSettings(const QString &fileName) { m_settings.reset(new QSettings(fileName, QSettings::IniFormat)); qDebug() << "SETTINGS:" << m_settings->fileName() << m_settings->isWritable(); @@ -41,13 +40,13 @@ void MRTPSettings::loadSettings(const QString& fileName) void MRTPSettings::saveSettings() { - if(m_settings) + if (m_settings) m_settings->sync(); } void MRTPSettings::restoreDefaultSettings() { - if(!m_settings) + if (!m_settings) return; m_settings->clear(); @@ -55,24 +54,25 @@ void MRTPSettings::restoreDefaultSettings() QColor MRTPSettings::getCategoryColor(int category) { - if(!m_settings || category >= int(JobCategory::NCategories) || category < 0) - return QColor(); //Invalid Category + if (!m_settings || category >= int(JobCategory::NCategories) || category < 0) + return QColor(); // Invalid Category - QRgb defaultColors[int(JobCategory::NCategories)] = { //NOTE: keep in sync wiht JobCategory - 0x00FFFF, //FREIGHT (MERCI) - 0x0000FF, //LIS (LIS) - 0x808000, //POSTAL (POSTALE) + QRgb defaultColors[int(JobCategory::NCategories)] = { + // NOTE: keep in sync wiht JobCategory + 0x00FFFF, // FREIGHT (MERCI) + 0x0000FF, // LIS (LIS) + 0x808000, // POSTAL (POSTALE) - 0x008000, //REGIONAL (REGIONALE) - 0x005500, //FAST_REGIONAL (REGIONALE VELOCE) - 0x00FF00, //LOCAL (LOCALE) - 0xFFAA00, //INTERCITY (INTERCITY) - 0x800080, //EXPRESS (ESPRESSO) - 0x800000, //DIRECT (DIRETTO) - 0xFF0000, //HIGH_SPEED (ALTA VELOCITA') + 0x008000, // REGIONAL (REGIONALE) + 0x005500, // FAST_REGIONAL (REGIONALE VELOCE) + 0x00FF00, // LOCAL (LOCALE) + 0xFFAA00, // INTERCITY (INTERCITY) + 0x800080, // EXPRESS (ESPRESSO) + 0x800000, // DIRECT (DIRETTO) + 0xFF0000, // HIGH_SPEED (ALTA VELOCITA') }; - //TODO: maybe use english category names in key instead of enum index + // TODO: maybe use english category names in key instead of enum index const QString key = QStringLiteral("job_colors/category_") + QString::number(category); return utils::fromVariant(m_settings->value(key, QColor(defaultColors[category]))); @@ -80,10 +80,11 @@ QColor MRTPSettings::getCategoryColor(int category) void MRTPSettings::setCategoryColor(int category, const QColor &color) { - if(!m_settings || category >= int(JobCategory::NCategories) || category < 0 || !color.isValid()) - return; //Invalid Category + if (!m_settings || category >= int(JobCategory::NCategories) || category < 0 + || !color.isValid()) + return; // Invalid Category - //TODO: maybe use english category names in key instead of enum index + // TODO: maybe use english category names in key instead of enum index const QString key = QStringLiteral("job_colors/category_") + QString::number(category); m_settings->setValue(key, utils::toVariant(color)); @@ -91,59 +92,60 @@ void MRTPSettings::setCategoryColor(int category, const QColor &color) int MRTPSettings::getDefaultStopMins(int category) { - if(!m_settings || category >= int(JobCategory::NCategories) || category < 0) - return -1; //Invalid Category + if (!m_settings || category >= int(JobCategory::NCategories) || category < 0) + return -1; // Invalid Category - //0 minutes means transit + // 0 minutes means transit - quint8 defaultTimesArr[int(JobCategory::NCategories)] = { //NOTE: keep in sync wiht JobCategory - 10, //FREIGHT (MERCI) - 10, //LIS (LIS) - 10, //POSTAL (POSTALE) + quint8 defaultTimesArr[int(JobCategory::NCategories)] = { + // NOTE: keep in sync wiht JobCategory + 10, // FREIGHT (MERCI) + 10, // LIS (LIS) + 10, // POSTAL (POSTALE) - 2, //REGIONAL (REGIONALE) - 2, //FAST_REGIONAL (REGIONALE VELOCE) - 2, //LOCAL (LOCALE) - 0, //INTERCITY (INTERCITY) - 0, //EXPRESS (ESPRESSO) - 0, //DIRECT (DIRETTO) - 0, //HIGH_SPEED (ALTA VELOCITA') + 2, // REGIONAL (REGIONALE) + 2, // FAST_REGIONAL (REGIONALE VELOCE) + 2, // LOCAL (LOCALE) + 0, // INTERCITY (INTERCITY) + 0, // EXPRESS (ESPRESSO) + 0, // DIRECT (DIRETTO) + 0, // HIGH_SPEED (ALTA VELOCITA') }; - //TODO: maybe use english category names in key instead of enum index + // TODO: maybe use english category names in key instead of enum index const QString key = QStringLiteral("stops/default_stop_mins_") + QString::number(category); return m_settings->value(key, defaultTimesArr[category]).toInt(); } void MRTPSettings::setDefaultStopMins(int category, int mins) { - if(!m_settings || category >= int(JobCategory::NCategories) || category < 0 || mins < 0) - return; //Invalid Category + if (!m_settings || category >= int(JobCategory::NCategories) || category < 0 || mins < 0) + return; // Invalid Category - //TODO: maybe use english category names in key instead of enum index + // TODO: maybe use english category names in key instead of enum index const QString key = QStringLiteral("stops/default_stop_mins_") + QString::number(category); m_settings->setValue(key, mins); } QFont MRTPSettings::getFontHelper(const QString &baseKey, QFont defFont) { - //NOTE: split into 2 keys: family, pt - if(!m_settings) + // NOTE: split into 2 keys: family, pt + if (!m_settings) return defFont; - const int pt_size = m_settings->value(baseKey + QLatin1String("_pt")).toInt(); + const int pt_size = m_settings->value(baseKey + QLatin1String("_pt")).toInt(); const QString family = m_settings->value(baseKey + QLatin1String("_family")).toString(); - if(pt_size != 0) + if (pt_size != 0) defFont.setPointSize(pt_size); - if(!family.isEmpty()) + if (!family.isEmpty()) defFont.setFamily(family); return defFont; } void MRTPSettings::setFontHelper(const QString &baseKey, const QFont &f) { - if(!m_settings) + if (!m_settings) return; m_settings->setValue(baseKey + QLatin1String("_pt"), f.pointSize()); diff --git a/src/settings/appsettings.h b/src/settings/appsettings.h index bd92e71..a0aced7 100644 --- a/src/settings/appsettings.h +++ b/src/settings/appsettings.h @@ -30,36 +30,36 @@ #include "info.h" -//FIXME: check if all settings are wired to SettingsDialog +// FIXME: check if all settings are wired to SettingsDialog -#define FIELD_GET(name, str, type, val)\ - type get ## name ()\ - {\ - if(m_settings)\ - return utils::fromVariant(m_settings->value(QStringLiteral(str), val));\ - return val;\ +#define FIELD_GET(name, str, type, val) \ + type get##name() \ + { \ + if (m_settings) \ + return utils::fromVariant(m_settings->value(QStringLiteral(str), val)); \ + return val; \ } -#define FIELD_SET(name, str, type)\ - void set ## name (utils::const_ref_t::Type v)\ - {\ - if(!m_settings)\ - return;\ - return m_settings->setValue(QStringLiteral(str), utils::toVariant(v));\ +#define FIELD_SET(name, str, type) \ + void set##name(utils::const_ref_t::Type v) \ + { \ + if (!m_settings) \ + return; \ + return m_settings->setValue(QStringLiteral(str), utils::toVariant(v)); \ } -#define FIELD(name, str, type, val)\ - FIELD_GET(name, str, type, val)\ +#define FIELD(name, str, type, val) \ + FIELD_GET(name, str, type, val) \ FIELD_SET(name, str, type) -#define FONT_FIELD(name, str, val)\ - QFont get ## name ()\ - {\ - return getFontHelper(str, val);\ - }\ - void set ## name (const QFont& f)\ - {\ - return setFontHelper(str, f);\ +#define FONT_FIELD(name, str, val) \ + QFont get##name() \ + { \ + return getFontHelper(str, val); \ + } \ + void set##name(const QFont &f) \ + { \ + return setFontHelper(str, f); \ } class MRTPSettings : public QObject @@ -73,77 +73,72 @@ public: void saveSettings(); void restoreDefaultSettings(); - //General - FIELD(Language, "language", QLocale, QLocale(QLocale::English)) + // General + FIELD(Language, "language", QLocale, QLocale(QLocale::English)) FIELD(RecentFiles, "recent_files", QStringList, QStringList()) - //Job Graph - FIELD(HorizontalOffset, "job_graph/horizontal_offset", int, 50) - FIELD(VerticalOffset, "job_graph/vertical_offset", int, 50) - FIELD(HourOffset, "job_graph/hour_offset", int, 100) - FIELD(StationOffset, "job_graph/station_offset", int, 150) - FIELD(PlatformOffset, "job_graph/platform_offset", int, 20) + // Job Graph + FIELD(HorizontalOffset, "job_graph/horizontal_offset", int, 50) + FIELD(VerticalOffset, "job_graph/vertical_offset", int, 50) + FIELD(HourOffset, "job_graph/hour_offset", int, 100) + FIELD(StationOffset, "job_graph/station_offset", int, 150) + FIELD(PlatformOffset, "job_graph/platform_offset", int, 20) - FIELD(PlatformLineWidth, "job_graph/platf_line_width", int, 2) - FIELD(HourLineWidth, "job_graph/hour_line_width", int, 2) - FIELD(JobLineWidth, "job_graph/job_line_width", int, 6) + FIELD(PlatformLineWidth, "job_graph/platf_line_width", int, 2) + FIELD(HourLineWidth, "job_graph/hour_line_width", int, 2) + FIELD(JobLineWidth, "job_graph/job_line_width", int, 6) - FIELD(HourLineColor, "job_graph/hour_line_color", QColor, QColor(Qt::black)) - FIELD(HourTextColor, "job_graph/hour_text_color", QColor, QColor(Qt::green)) - FIELD(StationTextColor, "job_graph/station_text_color", QColor, QColor(Qt::red)) - FIELD(MainPlatfColor, "job_graph/main_platf_color", QColor, QColor(Qt::magenta)) - FIELD(DepotPlatfColor, "job_graph/depot_platf_color", QColor, QColor(Qt::darkGray)) + FIELD(HourLineColor, "job_graph/hour_line_color", QColor, QColor(Qt::black)) + FIELD(HourTextColor, "job_graph/hour_text_color", QColor, QColor(Qt::green)) + FIELD(StationTextColor, "job_graph/station_text_color", QColor, QColor(Qt::red)) + FIELD(MainPlatfColor, "job_graph/main_platf_color", QColor, QColor(Qt::magenta)) + FIELD(DepotPlatfColor, "job_graph/depot_platf_color", QColor, QColor(Qt::darkGray)) - FIELD(JobLabelFontSize, "job_graph/job_label_font_size", qreal , 12.0) + FIELD(JobLabelFontSize, "job_graph/job_label_font_size", qreal, 12.0) FIELD(FollowSelectionOnGraphChange, "job_graph/follow_selection_on_graph_change", bool, true) FIELD(SyncSelectionOnAllGraphs, "job_graph/sync_job_selection", bool, true) - //Job Colors + // Job Colors QColor getCategoryColor(int category); - void setCategoryColor(int category, const QColor& color); + void setCategoryColor(int category, const QColor &color); - //Stops - FIELD(AutoInsertTransits, "job_editor/auto_insert_transits", bool, true) + // Stops + FIELD(AutoInsertTransits, "job_editor/auto_insert_transits", bool, true) FIELD(AutoShiftLastStopCouplings, "job_editor/auto_shift_couplings", bool, true) FIELD(AutoUncoupleAtLastStop, "job_editor/auto_uncouple_at_last_stop", bool, true) int getDefaultStopMins(int category); void setDefaultStopMins(int category, int mins); - //Shift Graph - FIELD(ShiftHourOffset, "shift_graph/hour_offset", double, 150.0) - FIELD(ShiftHorizOffset, "shift_graph/horiz_offset", double, 50.0) - FIELD(ShiftVertOffset, "shift_graph/vert_offset", double, 35.0) - FIELD(ShiftJobRowHeight, "shift_graph/job_row_height", double, 70.0) - FIELD(ShiftJobRowSpace, "shift_graph/job_row_space", double, 4.0) + // Shift Graph + FIELD(ShiftHourOffset, "shift_graph/hour_offset", double, 150.0) + FIELD(ShiftHorizOffset, "shift_graph/horiz_offset", double, 50.0) + FIELD(ShiftVertOffset, "shift_graph/vert_offset", double, 35.0) + FIELD(ShiftJobRowHeight, "shift_graph/job_row_height", double, 70.0) + FIELD(ShiftJobRowSpace, "shift_graph/job_row_space", double, 4.0) FIELD(ShiftHideSameStations, "shift_graph/hide_same_stations", bool, true) - //RollingStock - FIELD(RemoveMergedSourceModel, - "rollingstock/remove_merged_source_model", - bool, false) - FIELD(RemoveMergedSourceOwner, - "rollingstock/remove_merged_source_owner", - bool, false) - FIELD(ShowCouplingLegend, - "rollingstock/show_coupling_legend", - bool, false) + // RollingStock + FIELD(RemoveMergedSourceModel, "rollingstock/remove_merged_source_model", bool, false) + FIELD(RemoveMergedSourceOwner, "rollingstock/remove_merged_source_owner", bool, false) + FIELD(ShowCouplingLegend, "rollingstock/show_coupling_legend", bool, false) - //RS Import - FIELD(ODSFirstRow, "rs_import/first_row", int, 3) - FIELD(ODSNumCol, "rs_import/num_column", int, 1) - FIELD(ODSNameCol, "rs_import/model_column", int, 3) + // RS Import + FIELD(ODSFirstRow, "rs_import/first_row", int, 3) + FIELD(ODSNumCol, "rs_import/num_column", int, 1) + FIELD(ODSNameCol, "rs_import/model_column", int, 3) - //Sheet export ODT, NOTE: header/footer can be overriden by session specific values + // Sheet export ODT, NOTE: header/footer can be overriden by session specific values FIELD(SheetHeader, "sheet_export/header", QString, QString()) - FIELD(SheetFooter, "sheet_export/footer", QString, QStringLiteral("Generated by %1").arg(AppDisplayName)) + FIELD(SheetFooter, "sheet_export/footer", QString, + QStringLiteral("Generated by %1").arg(AppDisplayName)) FIELD(SheetStoreLocationDateInMeta, "sheet_export/location_date_in_meta", bool, true) - //Background Tasks + // Background Tasks FIELD(CheckRSWhenOpeningDB, "background_tasks/check_rs_at_startup", bool, true) - FIELD(CheckRSOnJobEdit, "background_tasks/check_rs_on_job_edited", bool, true) + FIELD(CheckRSOnJobEdit, "background_tasks/check_rs_on_job_edited", bool, true) FIELD(CheckCrossingWhenOpeningDB, "background_tasks/check_crossing_at_startup", bool, true) - FIELD(CheckCrossingOnJobEdit, "background_tasks/check_crossing_on_job_edited", bool, true) + FIELD(CheckCrossingOnJobEdit, "background_tasks/check_crossing_on_job_edited", bool, true) signals: void jobColorsChanged(); @@ -152,8 +147,8 @@ signals: void stopOptionsChanged(); private: - QFont getFontHelper(const QString& baseKey, QFont defFont); - void setFontHelper(const QString& baseKey, const QFont& f); + QFont getFontHelper(const QString &baseKey, QFont defFont); + void setFontHelper(const QString &baseKey, const QFont &f); QScopedPointer m_settings; }; diff --git a/src/settings/languagemodel.cpp b/src/settings/languagemodel.cpp index 359ec1d..045e90c 100644 --- a/src/settings/languagemodel.cpp +++ b/src/settings/languagemodel.cpp @@ -21,16 +21,16 @@ #include "utils/localization/languageutils.h" -LanguageModel::LanguageModel(QObject *parent) - : QAbstractListModel(parent) +LanguageModel::LanguageModel(QObject *parent) : + QAbstractListModel(parent) { } QVariant LanguageModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal && role == Qt::DisplayRole) + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { - if(section == 0) + if (section == 0) return tr("Language"); } @@ -47,19 +47,19 @@ QVariant LanguageModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= m_data.size()) return QVariant(); - const QLocale& loc = m_data.at(idx.row()); + const QLocale &loc = m_data.at(idx.row()); switch (role) { case Qt::DisplayRole: { - //NOTE: Do not show "American English" for default locale (row 0) - if(idx.row() > 0) + // NOTE: Do not show "American English" for default locale (row 0) + if (idx.row() > 0) return loc.nativeLanguageName(); Q_FALLTHROUGH(); } case Qt::ToolTipRole: - return QLocale::languageToString(loc.language()); //Return english name in tooltip + return QLocale::languageToString(loc.language()); // Return english name in tooltip } return QVariant(); @@ -79,16 +79,16 @@ QLocale LanguageModel::getLocaleAt(int idx) int LanguageModel::findMatchingRow(const QLocale &loc) { - int exactMatchIdx = -1; + int exactMatchIdx = -1; int partialMatchIdx = -1; - for(int i = 0; i < m_data.size(); i++) + for (int i = 0; i < m_data.size(); i++) { - const QLocale& item = m_data.at(i); - if(item.language() == loc.language()) + const QLocale &item = m_data.at(i); + if (item.language() == loc.language()) { partialMatchIdx = i; - if(item.country() == loc.country()) + if (item.country() == loc.country()) { exactMatchIdx = i; break; @@ -96,10 +96,10 @@ int LanguageModel::findMatchingRow(const QLocale &loc) } } - if(exactMatchIdx != -1) + if (exactMatchIdx != -1) return exactMatchIdx; - if(partialMatchIdx != -1) + if (partialMatchIdx != -1) return partialMatchIdx; return 0; diff --git a/src/settings/languagemodel.h b/src/settings/languagemodel.h index ec0ad85..95ab414 100644 --- a/src/settings/languagemodel.h +++ b/src/settings/languagemodel.h @@ -32,7 +32,8 @@ public: explicit LanguageModel(QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &p = QModelIndex()) const override; @@ -43,7 +44,7 @@ public: QLocale getLocaleAt(int idx); - int findMatchingRow(const QLocale& loc); + int findMatchingRow(const QLocale &loc); private: QVector m_data; diff --git a/src/settings/settingsdialog.cpp b/src/settings/settingsdialog.cpp index 535c598..eb39d5b 100644 --- a/src/settings/settingsdialog.cpp +++ b/src/settings/settingsdialog.cpp @@ -44,16 +44,17 @@ SettingsDialog::SettingsDialog(QWidget *parent) : connect(this, &QDialog::accepted, this, &SettingsDialog::saveSettings); connect(ui->restoreBut, &QPushButton::clicked, this, &SettingsDialog::onRestore); - connect(ui->resetSheetLangBut, &QPushButton::clicked, this, &SettingsDialog::resetSheetLanguage); + connect(ui->resetSheetLangBut, &QPushButton::clicked, this, + &SettingsDialog::resetSheetLanguage); - //Setup default stop time section - QFormLayout *lay = new QFormLayout(ui->stopDurationBox); + // Setup default stop time section + QFormLayout *lay = new QFormLayout(ui->stopDurationBox); const QString suffix = tr("minutes"); - for(int i = 0; i < int(JobCategory::NCategories); i++) + for (int i = 0; i < int(JobCategory::NCategories); i++) { QSpinBox *spin = new QSpinBox; spin->setMinimum(0); - spin->setMaximum(5 * 60); //Maximum 5 hours + spin->setMaximum(5 * 60); // Maximum 5 hours spin->setSuffix(suffix); lay->addRow(JobCategoryName::fullName(JobCategory(i)), spin); @@ -62,48 +63,68 @@ SettingsDialog::SettingsDialog(QWidget *parent) : setupJobColorsPage(); - connect(ui->vertOffsetSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->horizOffsetSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->hourOffsetSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->stationsOffsetSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->platformsOffsetSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->vertOffsetSpin, static_cast(&QSpinBox::valueChanged), this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->horizOffsetSpin, static_cast(&QSpinBox::valueChanged), + this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->hourOffsetSpin, static_cast(&QSpinBox::valueChanged), this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->stationsOffsetSpin, static_cast(&QSpinBox::valueChanged), + this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->platformsOffsetSpin, static_cast(&QSpinBox::valueChanged), + this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->hourLineWidthSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->jobLineWidthSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->platformsLineWidthSpin, static_cast(&QSpinBox::valueChanged), this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->hourLineWidthSpin, static_cast(&QSpinBox::valueChanged), + this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->jobLineWidthSpin, static_cast(&QSpinBox::valueChanged), + this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->platformsLineWidthSpin, + static_cast(&QSpinBox::valueChanged), this, + &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->hourTextColor, &ColorView::colorChanged, this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->hourLineColor, &ColorView::colorChanged, this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->stationTextColor, &ColorView::colorChanged, this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->mainPlatformColor, &ColorView::colorChanged, this, &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->depotPlatformColor, &ColorView::colorChanged, this, &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->hourTextColor, &ColorView::colorChanged, this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->hourLineColor, &ColorView::colorChanged, this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->stationTextColor, &ColorView::colorChanged, this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->mainPlatformColor, &ColorView::colorChanged, this, + &SettingsDialog::onJobGraphOptionsChanged); + connect(ui->depotPlatformColor, &ColorView::colorChanged, this, + &SettingsDialog::onJobGraphOptionsChanged); - connect(ui->shiftHourOffsetSpin, static_cast(&QDoubleSpinBox::valueChanged), - this, &SettingsDialog::onShiftGraphOptionsChanged); - connect(ui->shiftHorizOffsetSpin, static_cast(&QDoubleSpinBox::valueChanged), - this, &SettingsDialog::onShiftGraphOptionsChanged); - connect(ui->shiftVertOffsetSpin, static_cast(&QDoubleSpinBox::valueChanged), - this, &SettingsDialog::onShiftGraphOptionsChanged); - connect(ui->shiftJobRowHeightSpin, static_cast(&QDoubleSpinBox::valueChanged), - this, &SettingsDialog::onShiftGraphOptionsChanged); - connect(ui->shiftJobRowSpaceSpin, static_cast(&QDoubleSpinBox::valueChanged), - this, &SettingsDialog::onShiftGraphOptionsChanged); - connect(ui->shiftHideSameStCheck, &QCheckBox::toggled, this, &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftHourOffsetSpin, + static_cast(&QDoubleSpinBox::valueChanged), this, + &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftHorizOffsetSpin, + static_cast(&QDoubleSpinBox::valueChanged), this, + &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftVertOffsetSpin, + static_cast(&QDoubleSpinBox::valueChanged), this, + &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftJobRowHeightSpin, + static_cast(&QDoubleSpinBox::valueChanged), this, + &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftJobRowSpaceSpin, + static_cast(&QDoubleSpinBox::valueChanged), this, + &SettingsDialog::onShiftGraphOptionsChanged); + connect(ui->shiftHideSameStCheck, &QCheckBox::toggled, this, + &SettingsDialog::onShiftGraphOptionsChanged); } void SettingsDialog::setupJobColorsPage() { - //TODO: add scroll area also to other pages like stops + // TODO: add scroll area also to other pages like stops QScrollArea *jobColors = new QScrollArea; ui->tabWidget->insertTab(3, jobColors, tr("Job Colors")); QWidget *jobColorsViewPort = new QWidget; - QVBoxLayout *jobColorsLay = new QVBoxLayout(jobColorsViewPort); + QVBoxLayout *jobColorsLay = new QVBoxLayout(jobColorsViewPort); - QGroupBox *freightBox = new QGroupBox(tr("Non Passenger")); - QFormLayout *freightLay = new QFormLayout(freightBox); + QGroupBox *freightBox = new QGroupBox(tr("Non Passenger")); + QFormLayout *freightLay = new QFormLayout(freightBox); - for(int cat = 0; cat < int(FirstPassengerCategory); cat++) + for (int cat = 0; cat < int(FirstPassengerCategory); cat++) { ColorView *color = new ColorView(this); connect(color, &ColorView::colorChanged, this, &SettingsDialog::onJobColorChanged); @@ -112,10 +133,10 @@ void SettingsDialog::setupJobColorsPage() } jobColorsLay->addWidget(freightBox); - QGroupBox *passengerBox = new QGroupBox(tr("Passenger")); + QGroupBox *passengerBox = new QGroupBox(tr("Passenger")); QFormLayout *passengerLay = new QFormLayout(passengerBox); - for(int cat = int(FirstPassengerCategory); cat < int(JobCategory::NCategories); cat++) + for (int cat = int(FirstPassengerCategory); cat < int(JobCategory::NCategories); cat++) { ColorView *color = new ColorView(this); connect(color, &ColorView::colorChanged, this, &SettingsDialog::onJobColorChanged); @@ -145,19 +166,19 @@ void SettingsDialog::setupLanguageBox() void SettingsDialog::setSheetLanguage(const QLocale &sheetLoc) { QTranslator *sheetTranslator = nullptr; - if(Session->getAppLanguage() != sheetLoc && sheetLoc != MeetingSession::embeddedLocale) + if (Session->getAppLanguage() != sheetLoc && sheetLoc != MeetingSession::embeddedLocale) { - //Sheet Language is different from original (currently loaded) App Language - //And it's not default language embedded in executable + // Sheet Language is different from original (currently loaded) App Language + // And it's not default language embedded in executable - //Sheet Export needs a different translation - if(Session->getSheetExportLocale() == sheetLoc) + // Sheet Export needs a different translation + if (Session->getSheetExportLocale() == sheetLoc) { - //Try to re-use old one + // Try to re-use old one sheetTranslator = Session->getSheetExportTranslator(); } - if(!sheetTranslator) + if (!sheetTranslator) sheetTranslator = utils::language::loadAppTranslator(sheetLoc); } @@ -182,14 +203,14 @@ void SettingsDialog::loadSettings() { auto &settings = AppSettings; - //General + // General QLocale loc = settings.getLanguage(); ui->appLanguageCombo->setCurrentIndex(languageModel->findMatchingRow(loc)); loc = Session->getSheetExportLocale(); ui->sheetLanguageCombo->setCurrentIndex(languageModel->findMatchingRow(loc)); - //Job Graph + // Job Graph set(ui->hourOffsetSpin, settings.getHourOffset()); set(ui->stationsOffsetSpin, settings.getStationOffset()); set(ui->platformsOffsetSpin, settings.getPlatformOffset()); @@ -200,24 +221,24 @@ void SettingsDialog::loadSettings() set(ui->jobLineWidthSpin, settings.getJobLineWidth()); set(ui->platformsLineWidthSpin, settings.getPlatformLineWidth()); - ui->hourTextColor-> setColor(settings.getHourTextColor()); - ui->hourLineColor-> setColor(settings.getHourLineColor()); - ui->stationTextColor-> setColor(settings.getStationTextColor()); - ui->mainPlatformColor-> setColor(settings.getMainPlatfColor()); + ui->hourTextColor->setColor(settings.getHourTextColor()); + ui->hourLineColor->setColor(settings.getHourLineColor()); + ui->stationTextColor->setColor(settings.getStationTextColor()); + ui->mainPlatformColor->setColor(settings.getMainPlatfColor()); ui->depotPlatformColor->setColor(settings.getDepotPlatfColor()); ui->followJobSelectionCheck->setChecked(settings.getFollowSelectionOnGraphChange()); ui->syncJobSelectionCheck->setChecked(settings.getSyncSelectionOnAllGraphs()); - //Job Colors - for(int cat = 0; cat < int(JobCategory::NCategories); cat++) + // Job Colors + for (int cat = 0; cat < int(JobCategory::NCategories); cat++) { QColor col = settings.getCategoryColor(cat); m_colorViews[cat]->setColor(col); } - //Stops - for(int cat = 0; cat < int(JobCategory::NCategories); cat++) + // Stops + for (int cat = 0; cat < int(JobCategory::NCategories); cat++) { m_timeSpinBoxArr[cat]->blockSignals(true); m_timeSpinBoxArr[cat]->setValue(settings.getDefaultStopMins(cat)); @@ -227,7 +248,7 @@ void SettingsDialog::loadSettings() ui->autoMoveLastCouplingsCheck->setChecked(settings.getAutoShiftLastStopCouplings()); ui->autoUncoupleAllAtLastStopCheck->setChecked(settings.getAutoUncoupleAtLastStop()); - //Shift Graph + // Shift Graph set(ui->shiftHourOffsetSpin, settings.getShiftHourOffset()); set(ui->shiftHorizOffsetSpin, settings.getShiftHorizOffset()); set(ui->shiftVertOffsetSpin, settings.getShiftVertOffset()); @@ -235,27 +256,27 @@ void SettingsDialog::loadSettings() set(ui->shiftJobRowSpaceSpin, settings.getShiftJobRowSpace()); ui->shiftHideSameStCheck->setChecked(settings.getShiftHideSameStations()); - //Rollingstock + // Rollingstock ui->mergeModelRemoveCheck->setChecked(settings.getRemoveMergedSourceModel()); ui->mergeOwnerRemoveCheck->setChecked(settings.getRemoveMergedSourceOwner()); - //RS Import + // RS Import set(ui->odsFirstRowSpin, settings.getODSFirstRow()); set(ui->odsNumColumnSpin, settings.getODSNumCol()); set(ui->odsModelColumnSpin, settings.getODSNameCol()); - //Sheet Export ODT + // Sheet Export ODT ui->sheetExportHeaderEdit->setText(settings.getSheetHeader()); ui->sheetExportFooterEdit->setText(settings.getSheetFooter()); ui->sheetMetadataCheckBox->setChecked(settings.getSheetStoreLocationDateInMeta()); - //Background Tasks + // Background Tasks ui->rsErrCheckAtFileOpen->setChecked(settings.getCheckRSWhenOpeningDB()); ui->rsErrCheckOnJobEdited->setChecked(settings.getCheckRSOnJobEdit()); ui->crossingErrCheckAtFileOpen->setChecked(settings.getCheckCrossingWhenOpeningDB()); ui->crossingErrCheckOnJobEdited->setChecked(settings.getCheckCrossingOnJobEdit()); - updateJobsColors = false; + updateJobsColors = false; updateJobGraphOptions = false; } @@ -263,16 +284,16 @@ void SettingsDialog::saveSettings() { auto &settings = AppSettings; - //General - int idx = ui->appLanguageCombo->currentIndex(); + // General + int idx = ui->appLanguageCombo->currentIndex(); QLocale appLoc = languageModel->getLocaleAt(idx); settings.setLanguage(appLoc); - idx = ui->sheetLanguageCombo->currentIndex(); + idx = ui->sheetLanguageCombo->currentIndex(); QLocale sheetLoc = languageModel->getLocaleAt(idx); setSheetLanguage(sheetLoc); - //Job Graph + // Job Graph settings.setHourOffset(ui->hourOffsetSpin->value()); settings.setStationOffset(ui->stationsOffsetSpin->value()); settings.setPlatformOffset(ui->platformsOffsetSpin->value()); @@ -292,18 +313,18 @@ void SettingsDialog::saveSettings() settings.setFollowSelectionOnGraphChange(ui->followJobSelectionCheck->isChecked()); settings.setSyncSelectionOnAllGraphs(ui->syncJobSelectionCheck->isChecked()); - //Job Colors - for(int cat = 0; cat < int(JobCategory::NCategories); cat++) + // Job Colors + for (int cat = 0; cat < int(JobCategory::NCategories); cat++) { settings.setCategoryColor(cat, m_colorViews[cat]->color()); } - //Stops - for(int cat = 0; cat < int(JobCategory::NCategories); cat++) + // Stops + for (int cat = 0; cat < int(JobCategory::NCategories); cat++) { settings.setDefaultStopMins(cat, m_timeSpinBoxArr[cat]->value()); } - bool newVal = ui->autoInsertTransitsCheckBox->isChecked(); + bool newVal = ui->autoInsertTransitsCheckBox->isChecked(); bool stopSetingsChanged = settings.getAutoInsertTransits() != newVal; settings.setAutoInsertTransits(newVal); @@ -315,7 +336,7 @@ void SettingsDialog::saveSettings() stopSetingsChanged |= settings.getAutoUncoupleAtLastStop() != newVal; settings.setAutoUncoupleAtLastStop(newVal); - //Shift Graph + // Shift Graph settings.setShiftHourOffset(ui->shiftHourOffsetSpin->value()); settings.setShiftHorizOffset(ui->shiftHorizOffsetSpin->value()); settings.setShiftVertOffset(ui->shiftVertOffsetSpin->value()); @@ -323,47 +344,47 @@ void SettingsDialog::saveSettings() settings.setShiftJobRowSpace(ui->shiftJobRowSpaceSpin->value()); settings.setShiftHideSameStations(ui->shiftHideSameStCheck->isChecked()); - //Rollingstock + // Rollingstock settings.setRemoveMergedSourceModel(ui->mergeModelRemoveCheck->isChecked()); settings.setRemoveMergedSourceOwner(ui->mergeOwnerRemoveCheck->isChecked()); - //RS Import + // RS Import settings.setODSFirstRow(ui->odsFirstRowSpin->value()); settings.setODSNumCol(ui->odsNumColumnSpin->value()); settings.setODSNameCol(ui->odsModelColumnSpin->value()); - //Sheet Export ODT + // Sheet Export ODT settings.setSheetHeader(ui->sheetExportHeaderEdit->text()); settings.setSheetFooter(ui->sheetExportFooterEdit->text()); settings.setSheetStoreLocationDateInMeta(ui->sheetMetadataCheckBox->isChecked()); - //Background Tasks + // Background Tasks settings.setCheckRSWhenOpeningDB(ui->rsErrCheckAtFileOpen->isChecked()); settings.setCheckRSOnJobEdit(ui->rsErrCheckOnJobEdited->isChecked()); settings.setCheckCrossingWhenOpeningDB(ui->crossingErrCheckAtFileOpen->isChecked()); settings.setCheckCrossingOnJobEdit(ui->crossingErrCheckOnJobEdited->isChecked()); - settings.saveSettings(); //Sync to file + settings.saveSettings(); // Sync to file - if(updateJobGraphOptions) + if (updateJobGraphOptions) { emit settings.jobGraphOptionsChanged(); updateJobGraphOptions = false; } - if(updateJobsColors) + if (updateJobsColors) { emit settings.jobColorsChanged(); updateJobsColors = false; } - if(updateShiftGraphOptions) + if (updateShiftGraphOptions) { emit settings.shiftGraphOptionsChanged(); updateShiftGraphOptions = false; } - if(stopSetingsChanged) + if (stopSetingsChanged) { emit settings.stopOptionsChanged(); } @@ -373,25 +394,23 @@ void SettingsDialog::restoreDefaults() { AppSettings.restoreDefaultSettings(); loadSettings(); - updateJobsColors = true; - updateJobGraphOptions = true; + updateJobsColors = true; + updateJobGraphOptions = true; updateShiftGraphOptions = true; saveSettings(); } void SettingsDialog::closeEvent(QCloseEvent *e) { - int ret = QMessageBox::question(this, - tr("Settings"), - tr("Do you want to save settings?"), + int ret = QMessageBox::question(this, tr("Settings"), tr("Do you want to save settings?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); - if(ret == QMessageBox::Cancel) + if (ret == QMessageBox::Cancel) { e->ignore(); return; } - if(ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) accept(); return QDialog::closeEvent(e); @@ -399,11 +418,10 @@ void SettingsDialog::closeEvent(QCloseEvent *e) void SettingsDialog::onRestore() { - int ret = QMessageBox::question(this, - tr("Settings"), - tr("Do you want to restore default settings?"), - QMessageBox::Yes | QMessageBox::No); - if(ret == QMessageBox::Yes) + int ret = + QMessageBox::question(this, tr("Settings"), tr("Do you want to restore default settings?"), + QMessageBox::Yes | QMessageBox::No); + if (ret == QMessageBox::Yes) { restoreDefaults(); } @@ -411,7 +429,7 @@ void SettingsDialog::onRestore() void SettingsDialog::resetSheetLanguage() { - //Set Sheet Language to same value of original Application Language + // Set Sheet Language to same value of original Application Language QLocale origAppLanguage = Session->getAppLanguage(); ui->sheetLanguageCombo->setCurrentIndex(languageModel->findMatchingRow(origAppLanguage)); } diff --git a/src/settings/settingsdialog.h b/src/settings/settingsdialog.h index 6172184..3795ef0 100644 --- a/src/settings/settingsdialog.h +++ b/src/settings/settingsdialog.h @@ -61,7 +61,7 @@ private slots: private: void setupLanguageBox(); - void setSheetLanguage(const QLocale& sheetLoc); + void setSheetLanguage(const QLocale &sheetLoc); private: Ui::SettingsDialog *ui; @@ -71,7 +71,7 @@ private: bool updateJobGraphOptions; bool updateShiftGraphOptions; - QSpinBox* m_timeSpinBoxArr[int(JobCategory::NCategories)]; + QSpinBox *m_timeSpinBoxArr[int(JobCategory::NCategories)]; ColorView *m_colorViews[int(JobCategory::NCategories)]; void setupJobColorsPage(); }; diff --git a/src/settings/type_utils.h b/src/settings/type_utils.h index 54d13ff..6e30c36 100644 --- a/src/settings/type_utils.h +++ b/src/settings/type_utils.h @@ -28,51 +28,47 @@ namespace utils { -template struct const_ref_t +template struct const_ref_t { - typedef const T& Type; + typedef const T &Type; }; -//Don't pass arithmetic types as reference +// Don't pass arithmetic types as reference template -struct const_ref_t::value>::type> { +struct const_ref_t::value>::type> +{ typedef T Type; }; -//Specialize QColor and QLocale so they are more legible in the .ini settigs file, instead of Qt own's representation +// Specialize QColor and QLocale so they are more legible in the .ini settigs file, instead of Qt +// own's representation -template -inline QVariant toVariant(typename const_ref_t::Type val) +template inline QVariant toVariant(typename const_ref_t::Type val) { return QVariant(val); } -template <> -inline QVariant toVariant(typename const_ref_t::Type val) +template <> inline QVariant toVariant(typename const_ref_t::Type val) { return QVariant(val.name(QColor::HexRgb)); } -template <> -inline QVariant toVariant(typename const_ref_t::Type val) +template <> inline QVariant toVariant(typename const_ref_t::Type val) { return QVariant(val.name()); } -template -inline T fromVariant(const QVariant& v) +template inline T fromVariant(const QVariant &v) { return v.value(); } -template <> -inline QColor fromVariant(const QVariant& v) +template <> inline QColor fromVariant(const QVariant &v) { return QColor(v.toString()); } -template <> -inline QLocale fromVariant(const QVariant& v) +template <> inline QLocale fromVariant(const QVariant &v) { return QLocale(v.toString()); } diff --git a/src/shifts/shiftcombomodel.cpp b/src/shifts/shiftcombomodel.cpp index 392ea83..7954e11 100644 --- a/src/shifts/shiftcombomodel.cpp +++ b/src/shifts/shiftcombomodel.cpp @@ -36,17 +36,17 @@ ShiftComboModel::ShiftComboModel(database &db, QObject *parent) : bool ShiftComboModel::event(QEvent *e) { - if(e->type() == ShiftResultEvent::_Type) + if (e->type() == ShiftResultEvent::_Type) { ShiftResultEvent *ev = static_cast(e); ev->setAccepted(true); isFetching = false; - if(totalCount < 0) - totalCount = -totalCount; //Now is positive + if (totalCount < 0) + totalCount = -totalCount; // Now is positive QModelIndex firstIdx = index(0, 0); - QModelIndex lastIdx = index(size - 1, NCols - 1); + QModelIndex lastIdx = index(size - 1, NCols - 1); emit dataChanged(firstIdx, lastIdx); emit resultsReady(false); @@ -61,41 +61,45 @@ void ShiftComboModel::refreshData() { int count = recalcRowCount(); - if(count != totalCount) //Invalidate cache and reset model + if (count != totalCount) // Invalidate cache and reset model { beginResetModel(); } - if(count > MaxMatchItems) + if (count > MaxMatchItems) { - size = MaxMatchItems + 2; //MaxItems + Empty + '...' - }else{ - size = count + 1; //Items + Empty + size = MaxMatchItems + 2; // MaxItems + Empty + '...' + } + else + { + size = count + 1; // Items + Empty } - if(count != totalCount) + if (count != totalCount) { endResetModel(); } - totalCount = -count; //Negative, clears cache + totalCount = -count; // Negative, clears cache } void ShiftComboModel::clearCache() { - if(totalCount > 0) + if (totalCount > 0) totalCount = -totalCount; } int ShiftComboModel::recalcRowCount() { - if(!mDb.db()) + if (!mDb.db()) return 0; query q(mDb); - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) { q.prepare("SELECT COUNT(1) FROM jobshifts"); - }else{ + } + else + { q.prepare("SELECT COUNT(1) FROM jobshifts WHERE name LIKE ?"); q.bind(1, mQuery); } @@ -106,10 +110,10 @@ int ShiftComboModel::recalcRowCount() void ShiftComboModel::fetchRow() { - if(!mDb.db() || isFetching) - return; //Already fetching + if (!mDb.db() || isFetching) + return; // Already fetching - //TODO: use a custom QRunnable + // TODO: use a custom QRunnable /* QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection); */ @@ -118,9 +122,9 @@ void ShiftComboModel::fetchRow() void ShiftComboModel::internalFetch() { - if(!mDb.db()) + if (!mDb.db()) { - //Error: database not open, empty result + // Error: database not open, empty result ShiftResultEvent *ev = new ShiftResultEvent; qApp->postEvent(this, ev); return; @@ -130,25 +134,25 @@ void ShiftComboModel::internalFetch() QByteArray sql = "SELECT id,name FROM jobshifts "; - if(!mQuery.isEmpty()) + if (!mQuery.isEmpty()) sql += "WHERE name LIKE ? "; sql += "ORDER BY name LIMIT " QT_STRINGIFY(MaxMatchItems); q.prepare(sql); - if(!mQuery.isEmpty()) + if (!mQuery.isEmpty()) q.bind(1, mQuery); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end && i < MaxMatchItems; ++it) + int i = 0; + for (; it != end && i < MaxMatchItems; ++it) { - auto r = *it; + auto r = *it; items[i].shiftId = r.get(0); - items[i].name = r.get(1); + items[i].name = r.get(1); i++; } @@ -165,32 +169,32 @@ QVariant ShiftComboModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(totalCount < 0) + if (totalCount < 0) { - //Fetch above or below current cach + // Fetch above or below current cach const_cast(this)->fetchRow(); - //Temporarily return null + // Temporarily return null return QVariant(); } - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } - if(isFetching) - break; //Don't acces data while fetching + if (isFetching) + break; // Don't acces data while fetching return items[idx.row()].name; } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -204,7 +208,7 @@ QVariant ShiftComboModel::data(const QModelIndex &idx, int role) const void ShiftComboModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -218,15 +222,15 @@ void ShiftComboModel::autoSuggest(const QString &text) QString ShiftComboModel::getName(db_id shiftId) const { - if(!mDb.db()) - return QString(); //Error: database not open + if (!mDb.db()) + return QString(); // Error: database not open QString shiftName; query q_getShift(mDb, "SELECT name FROM jobshifts WHERE id=?"); q_getShift.bind(1, shiftId); - if(q_getShift.step() == SQLITE_ROW) + if (q_getShift.step() == SQLITE_ROW) { - auto r = q_getShift.getRows(); + auto r = q_getShift.getRows(); shiftName = r.get(0); } return shiftName; diff --git a/src/shifts/shiftcombomodel.h b/src/shifts/shiftcombomodel.h index 02a501c..8b6f539 100644 --- a/src/shifts/shiftcombomodel.h +++ b/src/shifts/shiftcombomodel.h @@ -47,7 +47,7 @@ public: bool event(QEvent *e) override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; void refreshData() override; void clearCache() override; QString getName(db_id shiftId) const override; diff --git a/src/shifts/shiftgraph/jobchangeshiftdlg.cpp b/src/shifts/shiftgraph/jobchangeshiftdlg.cpp index cd5dc15..67db352 100644 --- a/src/shifts/shiftgraph/jobchangeshiftdlg.cpp +++ b/src/shifts/shiftgraph/jobchangeshiftdlg.cpp @@ -46,7 +46,7 @@ JobChangeShiftDlg::JobChangeShiftDlg(sqlite3pp::database &db, QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - label = new QLabel; + label = new QLabel; lay->addWidget(label); ShiftComboModel *shiftComboModel = new ShiftComboModel(db, this); @@ -67,17 +67,17 @@ JobChangeShiftDlg::JobChangeShiftDlg(sqlite3pp::database &db, QWidget *parent) : void JobChangeShiftDlg::done(int ret) { - if(ret == QDialog::Accepted) + if (ret == QDialog::Accepted) { db_id shiftId = 0; QString shiftName; shiftCombo->getData(shiftId, shiftName); - if(shiftId != originalShiftId) + if (shiftId != originalShiftId) { - if(shiftId) + if (shiftId) { - //Setting a new shift, check if we overlap with other jobs + // Setting a new shift, check if we overlap with other jobs sqlite3pp::query q(mDb); q.prepare("SELECT MIN(departure) FROM stops WHERE job_id=?"); q.bind(1, mJobId); @@ -93,7 +93,7 @@ void JobChangeShiftDlg::done(int ret) ShiftBusyModel model(mDb); model.loadData(shiftId, mJobId, start, end); - if(model.hasConcurrentJobs()) + if (model.hasConcurrentJobs()) { OwningQPointer dlg = new ShiftBusyDlg(this); dlg->setModel(&model); @@ -103,21 +103,20 @@ void JobChangeShiftDlg::done(int ret) } sqlite3pp::command cmd(mDb, "UPDATE jobs SET shift_id=? WHERE id=?"); - if(shiftId) + if (shiftId) cmd.bind(1, shiftId); else - cmd.bind(1); //Bind NULL + cmd.bind(1); // Bind NULL cmd.bind(2, mJobId); ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - //Error - QMessageBox::warning(this, tr("Shift Error"), - tr("Error while setting shift %1 to job %2.
" - "Msg: %3") - .arg(shiftName, - JobCategoryName::jobName(mJobId, mCategory), - mDb.error_msg())); + // Error + QMessageBox::warning( + this, tr("Shift Error"), + tr("Error while setting shift %1 to job %2.
" + "Msg: %3") + .arg(shiftName, JobCategoryName::jobName(mJobId, mCategory), mDb.error_msg())); return; } @@ -131,8 +130,8 @@ void JobChangeShiftDlg::done(int ret) void JobChangeShiftDlg::onJobChanged(db_id jobId, db_id oldJobId) { - //Update id/category - if(mJobId == oldJobId) + // Update id/category + if (mJobId == oldJobId) setJob(jobId); } @@ -140,7 +139,7 @@ void JobChangeShiftDlg::setJob(db_id jobId) { query q_getJobInfo(mDb, "SELECT shift_id,category FROM jobs WHERE id=?"); q_getJobInfo.bind(1, jobId); - if(q_getJobInfo.step() != SQLITE_ROW) + if (q_getJobInfo.step() != SQLITE_ROW) return; auto j = q_getJobInfo.getRows(); setJob(jobId, j.get(0), JobCategory(j.get(1))); @@ -148,9 +147,9 @@ void JobChangeShiftDlg::setJob(db_id jobId) void JobChangeShiftDlg::setJob(db_id jobId, db_id shiftId, JobCategory jobCat) { - mJobId = jobId; + mJobId = jobId; originalShiftId = shiftId; - mCategory = jobCat; + mCategory = jobCat; QString jobName = JobCategoryName::jobName(mJobId, mCategory); diff --git a/src/shifts/shiftgraph/model/shiftgraphscene.cpp b/src/shifts/shiftgraph/model/shiftgraphscene.cpp index 44a698f..454ac8c 100644 --- a/src/shifts/shiftgraph/model/shiftgraphscene.cpp +++ b/src/shifts/shiftgraph/model/shiftgraphscene.cpp @@ -37,27 +37,27 @@ static constexpr const char *sql_getStName = "SELECT name,short_name FROM statio static constexpr const char *sql_countJobs = "SELECT COUNT(1) FROM jobs" " WHERE jobs.shift_id=?"; -static constexpr const char *sql_getJobs = "SELECT jobs.id, jobs.category," - " MIN(s1.arrival), s1.station_id," - " MAX(s2.departure), s2.station_id" - " FROM jobs" - " JOIN stops s1 ON s1.job_id=jobs.id" - " JOIN stops s2 ON s2.job_id=jobs.id" - " WHERE jobs.shift_id=?" - " GROUP BY jobs.id" - " ORDER BY s1.arrival ASC"; +static constexpr const char *sql_getJobs = "SELECT jobs.id, jobs.category," + " MIN(s1.arrival), s1.station_id," + " MAX(s2.departure), s2.station_id" + " FROM jobs" + " JOIN stops s1 ON s1.job_id=jobs.id" + " JOIN stops s2 ON s2.job_id=jobs.id" + " WHERE jobs.shift_id=?" + " GROUP BY jobs.id" + " ORDER BY s1.arrival ASC"; ShiftGraphScene::ShiftGraphScene(sqlite3pp::database &db, QObject *parent) : IGraphScene(parent), mDb(db) { - connect(&AppSettings, &MRTPSettings::jobColorsChanged, - this, &ShiftGraphScene::redrawGraph); + connect(&AppSettings, &MRTPSettings::jobColorsChanged, this, &ShiftGraphScene::redrawGraph); - connect(&AppSettings, &MRTPSettings::shiftGraphOptionsChanged, - this, &ShiftGraphScene::updateShiftGraphOptions); + connect(&AppSettings, &MRTPSettings::shiftGraphOptionsChanged, this, + &ShiftGraphScene::updateShiftGraphOptions); - connect(Session, &MeetingSession::stationNameChanged, this, &ShiftGraphScene::onStationNameChanged); + connect(Session, &MeetingSession::stationNameChanged, this, + &ShiftGraphScene::onStationNameChanged); connect(Session, &MeetingSession::shiftNameChanged, this, &ShiftGraphScene::onShiftNameChanged); connect(Session, &MeetingSession::shiftRemoved, this, &ShiftGraphScene::onShiftRemoved); @@ -77,7 +77,7 @@ void ShiftGraphScene::renderContents(QPainter *painter, const QRectF &sceneRect) void ShiftGraphScene::renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient, double /*scroll*/) { - if(orient == Qt::Horizontal) + if (orient == Qt::Horizontal) drawHourHeader(painter, sceneRect); else drawShiftHeader(painter, sceneRect); @@ -99,83 +99,85 @@ void ShiftGraphScene::drawShifts(QPainter *painter, const QRectF &sceneRect) jobPen.setWidth(5); const double penMargin = jobPen.widthF() * 0.6; - //Transparent white as background to make text more readable + // Transparent white as background to make text more readable QColor textBGCol(255, 255, 255, 220); QPen textPen(Qt::black, 2); qreal y = vertOffset + rowSpaceOffset / 2; - for(const ShiftGraph& shift : qAsConst(m_shifts)) + for (const ShiftGraph &shift : qAsConst(m_shifts)) { const qreal top = y; - qreal jobY = top + shiftRowHeight / 2; - qreal bottomY = top + shiftRowHeight; - y = bottomY + rowSpaceOffset; + qreal jobY = top + shiftRowHeight / 2; + qreal bottomY = top + shiftRowHeight; + y = bottomY + rowSpaceOffset; - if(bottomY < sceneRect.top()) - continue; //Shift is above requested view - if(top > sceneRect.bottom()) - break; //Shift is below requested view and next will be out too + if (bottomY < sceneRect.top()) + continue; // Shift is above requested view + if (top > sceneRect.bottom()) + break; // Shift is below requested view and next will be out too - db_id lastStId = 0; + db_id lastStId = 0; - double prevJobNameLastX = horizOffset; + double prevJobNameLastX = horizOffset; double prevStationNameLastX = horizOffset; - for(const JobItem& item : shift.jobList) + for (const JobItem &item : shift.jobList) { double firstX = jobPos(item.start); - double lastX = jobPos(item.end); + double lastX = jobPos(item.end); - if(lastX < sceneRect.left()) - continue; //Job is at left of requested view + if (lastX < sceneRect.left()) + continue; // Job is at left of requested view - if(firstX > sceneRect.right()) - break; //Next Jobs are after in time so they will be out too + if (firstX > sceneRect.right()) + break; // Next Jobs are after in time so they will be out too jobPen.setColor(Session->colorForCat(item.job.category)); painter->setPen(jobPen); - //Draw Job line + // Draw Job line painter->drawLine(QPointF(firstX, jobY), QPointF(lastX, jobY)); painter->setPen(textPen); painter->setFont(jobFont); - //Draw Job Name above line + // Draw Job Name above line const QString jobName = JobCategoryName::jobName(item.job.jobId, item.job.category); QRectF textRect(firstX, top, lastX - firstX, shiftRowHeight / 4 - penMargin); QRectF jobNameRect = painter->boundingRect(textRect, jobName, jobTextOpt); - if(jobNameRect.left() < horizOffset) - jobNameRect.moveLeft(horizOffset); //Do not go under vertival header + if (jobNameRect.left() < horizOffset) + jobNameRect.moveLeft(horizOffset); // Do not go under vertival header - if(jobNameRect.left() > prevJobNameLastX || prevJobNameLastX == horizOffset) + if (jobNameRect.left() > prevJobNameLastX || prevJobNameLastX == horizOffset) { - //We do not collide with previous Job Name - //So we can take lower label row + // We do not collide with previous Job Name + // So we can take lower label row jobNameRect.moveBottom(jobY - penMargin); - //Store last edge for next Job Name + // Store last edge for next Job Name prevJobNameLastX = jobNameRect.right(); } painter->fillRect(jobNameRect, textBGCol); painter->drawText(jobNameRect, jobName, jobTextOpt); - //Draw Station names below line + // Draw Station names below line textRect.moveTop(jobY + jobPen.widthF()); - if(!hideSameStations || lastStId != item.fromStId) + if (!hideSameStations || lastStId != item.fromStId) { - //Origin is different from previous Job Destination - QString stName = m_stationCache.value(item.fromStId, StationCache()).shortNameOrFallback; + // Origin is different from previous Job Destination + QString stName = + m_stationCache.value(item.fromStId, StationCache()).shortNameOrFallback; - QRectF stationLabelRect = painter->boundingRect(textRect, stName, fromStationTextOpt); - if(stationLabelRect.width() > textRect.width()) + QRectF stationLabelRect = + painter->boundingRect(textRect, stName, fromStationTextOpt); + if (stationLabelRect.width() > textRect.width()) { - //Try to align rigth (so move to left because we are longer than Job) + // Try to align rigth (so move to left because we are longer than Job) double newLeft = qMax(prevStationNameLastX, lastX - stationLabelRect.width()); stationLabelRect.moveLeft(newLeft); } @@ -185,14 +187,14 @@ void ShiftGraphScene::drawShifts(QPainter *painter, const QRectF &sceneRect) painter->drawText(stationLabelRect, stName, fromStationTextOpt); } - //Draw destination station + // Draw destination station QString stName = m_stationCache.value(item.toStId, StationCache()).shortNameOrFallback; painter->setFont(destStFont); QRectF stationLabelRect = painter->boundingRect(textRect, stName, toStationTextOpt); - if(stationLabelRect.left() < prevStationNameLastX) + if (stationLabelRect.left() < prevStationNameLastX) { - //We collide with previous station, move lower + // We collide with previous station, move lower stationLabelRect.moveBottom(bottomY); } prevStationNameLastX = stationLabelRect.right(); @@ -203,7 +205,7 @@ void ShiftGraphScene::drawShifts(QPainter *painter, const QRectF &sceneRect) lastStId = item.toStId; } - //Draw line to separate from previous row + // Draw line to separate from previous row painter->setPen(textPen); qreal sepLineY = bottomY + rowSpaceOffset / 2; painter->drawLine(QLineF(sceneRect.right(), sepLineY, sceneRect.left(), sepLineY)); @@ -215,18 +217,18 @@ void ShiftGraphScene::drawHourLines(QPainter *painter, const QRectF &sceneRect) QPen hourTextPen(Qt::darkGray, 2); painter->setPen(hourTextPen); - qreal top = qMax(sceneRect.top(), vertOffset); + qreal top = qMax(sceneRect.top(), vertOffset); qreal bottom = sceneRect.bottom(); - qreal x = horizOffset; - for(int h = 0; h <= 24; h++) + qreal x = horizOffset; + for (int h = 0; h <= 24; h++) { qreal left = x; x += hourOffset; - if(left < sceneRect.left()) + if (left < sceneRect.left()) continue; - if(left > sceneRect.right()) + if (left > sceneRect.right()) break; painter->drawLine(QLineF(left, top, left, bottom)); @@ -249,16 +251,16 @@ void ShiftGraphScene::drawShiftHeader(QPainter *painter, const QRectF &rect) labelRect.setHeight(shiftRowHeight); qreal y = vertOffset + rowSpaceOffset / 2; - for(const ShiftGraph& shift : qAsConst(m_shifts)) + for (const ShiftGraph &shift : qAsConst(m_shifts)) { const qreal top = y; - qreal bottomY = top + shiftRowHeight; - y = bottomY + rowSpaceOffset; + qreal bottomY = top + shiftRowHeight; + y = bottomY + rowSpaceOffset; - if(bottomY < rect.top()) - continue; //Shift is above requested view - if(top > rect.bottom()) - break; //Shift is below requested view and next will be out too + if (bottomY < rect.top()) + continue; // Shift is above requested view + if (top > rect.bottom()) + break; // Shift is below requested view and next will be out too labelRect.moveTop(top); painter->drawText(labelRect, shift.shiftName, shiftTextOpt); @@ -284,15 +286,15 @@ void ShiftGraphScene::drawHourHeader(QPainter *painter, const QRectF &rect) qreal x = horizOffset - hourOffset / 2; - for(int h = 0; h <= 24; h++) + for (int h = 0; h <= 24; h++) { - qreal left = x; + qreal left = x; qreal right = left + hourOffset; - x = right; + x = right; - if(right < rect.left()) + if (right < rect.left()) continue; - if(left > rect.right()) + if (left > rect.right()) break; labelRect.moveLeft(left); @@ -300,28 +302,29 @@ void ShiftGraphScene::drawHourHeader(QPainter *painter, const QRectF &rect) } } -ShiftGraphScene::JobItem ShiftGraphScene::getJobAt(const QPointF &scenePos, QString &outShiftName) const +ShiftGraphScene::JobItem ShiftGraphScene::getJobAt(const QPointF &scenePos, + QString &outShiftName) const { JobItem job; const qreal y = scenePos.y() - vertOffset - rowSpaceOffset / 2; - int shiftIdx = qFloor(y / (shiftRowHeight + rowSpaceOffset)); - if(shiftIdx < 0 || shiftIdx >= m_shifts.size()) + int shiftIdx = qFloor(y / (shiftRowHeight + rowSpaceOffset)); + if (shiftIdx < 0 || shiftIdx >= m_shifts.size()) return job; const qreal x = scenePos.x() - horizOffset; - if(x < 0 || x > 24 * hourOffset) + if (x < 0 || x > 24 * hourOffset) return job; QTime t = QTime::fromMSecsSinceStartOfDay(qFloor(x / hourOffset * MSEC_PER_HOUR)); - const ShiftGraph& shift = m_shifts.at(shiftIdx); + const ShiftGraph &shift = m_shifts.at(shiftIdx); - for(const JobItem& item : shift.jobList) + for (const JobItem &item : shift.jobList) { - if(item.start <= t && item.end >= t) + if (item.start <= t && item.end >= t) { - job = item; + job = item; outShiftName = shift.shiftName; break; } @@ -341,9 +344,9 @@ bool ShiftGraphScene::loadShifts() q.step(); int count = q.getRows().get(0); - if(count == 0) + if (count == 0) { - //Nothing to load + // Nothing to load m_shifts.squeeze(); return true; } @@ -355,10 +358,10 @@ bool ShiftGraphScene::loadShifts() query q_getJobs(mDb, sql_getJobs); q.prepare("SELECT id,name FROM jobshifts ORDER BY name"); - for(auto shift : q) + for (auto shift : q) { ShiftGraph obj; - obj.shiftId = shift.get(0); + obj.shiftId = shift.get(0); obj.shiftName = shift.get(1); loadShiftRow(obj, q_getStName, q_countJobs, q_getJobs); @@ -374,16 +377,16 @@ bool ShiftGraphScene::loadShifts() void ShiftGraphScene::updateShiftGraphOptions() { - hourOffset = AppSettings.getShiftHourOffset(); - horizOffset = AppSettings.getShiftHorizOffset(); - vertOffset = AppSettings.getShiftVertOffset(); + hourOffset = AppSettings.getShiftHourOffset(); + horizOffset = AppSettings.getShiftHorizOffset(); + vertOffset = AppSettings.getShiftVertOffset(); - shiftRowHeight = AppSettings.getShiftJobRowHeight(); - rowSpaceOffset = AppSettings.getShiftJobRowSpace(); + shiftRowHeight = AppSettings.getShiftJobRowHeight(); + rowSpaceOffset = AppSettings.getShiftJobRowSpace(); hideSameStations = AppSettings.getShiftHideSameStations(); QSizeF headerSize(horizOffset, vertOffset); - if(headerSize != m_cachedHeaderSize) + if (headerSize != m_cachedHeaderSize) { m_cachedHeaderSize = headerSize; emit headersSizeChanged(); @@ -398,21 +401,21 @@ void ShiftGraphScene::onShiftNameChanged(db_id shiftId) { query q(mDb, "SELECT name FROM jobshifts WHERE id=?"); q.bind(1, shiftId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return; QString newName = q.getRows().get(0); - auto pos = lowerBound(shiftId, newName); + auto pos = lowerBound(shiftId, newName); - if(pos.first == -1) + if (pos.first == -1) { - //This shift is new, add it + // This shift is new, add it ShiftGraph obj; - obj.shiftId = shiftId; + obj.shiftId = shiftId; obj.shiftName = newName; - //Load jobs + // Load jobs query q_getStName(mDb, sql_getStName); query q_countJobs(mDb, sql_countJobs); query q_getJobs(mDb, sql_getJobs); @@ -424,9 +427,9 @@ void ShiftGraphScene::onShiftNameChanged(db_id shiftId) } else { - //Move shift to keep alphabetical order + // Move shift to keep alphabetical order m_shifts[pos.first].shiftName = newName; - if(pos.second > pos.first) + if (pos.second > pos.first) pos.second--; m_shifts.move(pos.first, pos.second); } @@ -436,9 +439,9 @@ void ShiftGraphScene::onShiftNameChanged(db_id shiftId) void ShiftGraphScene::onShiftRemoved(db_id shiftId) { - for(auto it = m_shifts.begin(); it != m_shifts.end(); it++) + for (auto it = m_shifts.begin(); it != m_shifts.end(); it++) { - if(it->shiftId == shiftId) + if (it->shiftId == shiftId) { m_shifts.erase(it); recalcContentSize(); @@ -451,9 +454,9 @@ void ShiftGraphScene::onShiftRemoved(db_id shiftId) void ShiftGraphScene::onStationNameChanged(db_id stationId) { - if(m_stationCache.contains(stationId)) + if (m_stationCache.contains(stationId)) { - //Reload name + // Reload name m_stationCache.remove(stationId); query q_getStName(mDb, sql_getStName); @@ -465,14 +468,14 @@ void ShiftGraphScene::onStationNameChanged(db_id stationId) void ShiftGraphScene::onShiftJobsChanged(db_id shiftId) { - //Reload single shift + // Reload single shift query q_getStName(mDb, sql_getStName); query q_countJobs(mDb, sql_countJobs); query q_getJobs(mDb, sql_getJobs); - for(ShiftGraph& shift : m_shifts) + for (ShiftGraph &shift : m_shifts) { - if(shift.shiftId == shiftId) + if (shift.shiftId == shiftId) { loadShiftRow(shift, q_getStName, q_countJobs, q_getJobs); break; @@ -484,24 +487,25 @@ void ShiftGraphScene::onShiftJobsChanged(db_id shiftId) void ShiftGraphScene::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 shifts + // If jobId is zero, it means all jobs have been deleted + // Reload all shifts loadShifts(); } void ShiftGraphScene::recalcContentSize() { - //Set a margin after last hour of half hour offset - double width = horizOffset + 24 * hourOffset + hourOffset / 2; - double height = vertOffset + (shiftRowHeight + rowSpaceOffset) * m_shifts.count(); + // Set a margin after last hour of half hour offset + double width = horizOffset + 24 * hourOffset + hourOffset / 2; + double height = vertOffset + (shiftRowHeight + rowSpaceOffset) * m_shifts.count(); m_cachedContentsSize = QSizeF(width, height); } -bool ShiftGraphScene::loadShiftRow(ShiftGraph &shiftObj, query &q_getStName, query &q_countJobs, sqlite3pp::query &q_getJobs) +bool ShiftGraphScene::loadShiftRow(ShiftGraph &shiftObj, query &q_getStName, query &q_countJobs, + sqlite3pp::query &q_getJobs) { shiftObj.jobList.clear(); @@ -510,27 +514,27 @@ bool ShiftGraphScene::loadShiftRow(ShiftGraph &shiftObj, query &q_getStName, que int count = q_countJobs.getRows().get(0); q_countJobs.reset(); - if(count == 0) + if (count == 0) { - //Nothing to load + // Nothing to load return true; } shiftObj.jobList.reserve(count); q_getJobs.bind(1, shiftObj.shiftId); - for(auto job : q_getJobs) + for (auto job : q_getJobs) { JobItem item; - item.job.jobId = job.get(0); + item.job.jobId = job.get(0); item.job.category = JobCategory(job.get(1)); - item.start = job.get(2); - item.fromStId = job.get(3); + item.start = job.get(2); + item.fromStId = job.get(3); - item.end = job.get(4); - item.toStId = job.get(5); + item.end = job.get(4); + item.toStId = job.get(5); loadStationName(item.fromStId, q_getStName); loadStationName(item.toStId, q_getStName); @@ -544,19 +548,19 @@ bool ShiftGraphScene::loadShiftRow(ShiftGraph &shiftObj, query &q_getStName, que void ShiftGraphScene::loadStationName(db_id stationId, sqlite3pp::query &q_getStName) { - if(!m_stationCache.contains(stationId)) + if (!m_stationCache.contains(stationId)) { q_getStName.bind(1, stationId); - if(q_getStName.step() != SQLITE_ROW) + if (q_getStName.step() != SQLITE_ROW) return; auto r = q_getStName.getRows(); StationCache st; - st.name = r.get(0); + st.name = r.get(0); st.shortNameOrFallback = r.get(1); - //If 'Short Name' is empty fallback to 'Full Name' - if(st.shortNameOrFallback.isEmpty()) + // If 'Short Name' is empty fallback to 'Full Name' + if (st.shortNameOrFallback.isEmpty()) st.shortNameOrFallback = st.name; m_stationCache.insert(stationId, st); @@ -566,31 +570,31 @@ void ShiftGraphScene::loadStationName(db_id stationId, sqlite3pp::query &q_getSt std::pair ShiftGraphScene::lowerBound(db_id shiftId, const QString &name) { - //Find old shift position + // Find old shift position int oldIdx = -1; - for(int i = 0; i < m_shifts.size(); i++) + for (int i = 0; i < m_shifts.size(); i++) { - if(m_shifts.at(i).shiftId == shiftId) + if (m_shifts.at(i).shiftId == shiftId) { oldIdx = i; break; } } - //Find new position to insert + // Find new position to insert int firstIdx = 0; - int len = m_shifts.size(); + int len = m_shifts.size(); while (len > 0) { - int half = len >> 1; - int middleIdx = firstIdx + half; + int half = len >> 1; + int middleIdx = firstIdx + half; - const ShiftGraph& obj = m_shifts.at(middleIdx); - if(obj.shiftId != shiftId && obj.shiftName < name) + const ShiftGraph &obj = m_shifts.at(middleIdx); + if (obj.shiftId != shiftId && obj.shiftName < name) { firstIdx = middleIdx + 1; - len = len - half - 1; + len = len - half - 1; } else { diff --git a/src/shifts/shiftgraph/model/shiftgraphscene.h b/src/shifts/shiftgraph/model/shiftgraphscene.h index ecbf8bf..bbc3f2f 100644 --- a/src/shifts/shiftgraph/model/shiftgraphscene.h +++ b/src/shifts/shiftgraph/model/shiftgraphscene.h @@ -31,7 +31,7 @@ namespace sqlite3pp { class database; class query; -} +} // namespace sqlite3pp /*! * \brief Class to store shift information @@ -45,13 +45,12 @@ class ShiftGraphScene : public IGraphScene { Q_OBJECT public: - struct JobItem { JobEntry job; db_id fromStId = 0; - db_id toStId = 0; + db_id toStId = 0; QTime start; QTime end; @@ -65,15 +64,15 @@ public: QVector jobList; }; - ShiftGraphScene(sqlite3pp::database& db, QObject *parent = nullptr); + ShiftGraphScene(sqlite3pp::database &db, QObject *parent = nullptr); - virtual void renderContents(QPainter *painter, const QRectF& sceneRect) override; - virtual void renderHeader(QPainter *painter, const QRectF& sceneRect, - Qt::Orientation orient, double scroll) override; + virtual void renderContents(QPainter *painter, const QRectF &sceneRect) override; + virtual void renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient, + double scroll) override; - void drawShifts(QPainter *painter, const QRectF& sceneRect); + void drawShifts(QPainter *painter, const QRectF &sceneRect); void drawHourLines(QPainter *painter, const QRectF &sceneRect); - void drawShiftHeader(QPainter *painter, const QRectF& rect); + void drawShiftHeader(QPainter *painter, const QRectF &rect); void drawHourHeader(QPainter *painter, const QRectF &rect); /*! @@ -82,12 +81,12 @@ public: * \param scenePos Point in scene coordinates * \param outShiftName If job is found, gets filled with its shift name */ - JobItem getJobAt(const QPointF& scenePos, QString& outShiftName) const; + JobItem getJobAt(const QPointF &scenePos, QString &outShiftName) const; inline QString getStationFullName(db_id stationId) const { auto st = m_stationCache.constFind(stationId); - if(st == m_stationCache.constEnd()) + if (st == m_stationCache.constEnd()) return QString(); return st.value().name; } @@ -96,58 +95,58 @@ public slots: bool loadShifts(); private slots: - //Settings + // Settings void updateShiftGraphOptions(); - //Shifts + // Shifts void onShiftNameChanged(db_id shiftId); void onShiftRemoved(db_id shiftId); - //Stations + // Stations void onStationNameChanged(db_id stationId); - //Jobs + // Jobs void onShiftJobsChanged(db_id shiftId); void onJobRemoved(db_id jobId); private: void recalcContentSize(); - bool loadShiftRow(ShiftGraph& shiftObj, sqlite3pp::query& q_getStName, - sqlite3pp::query& q_countJobs, sqlite3pp::query& q_getJobs); - void loadStationName(db_id stationId, sqlite3pp::query& q_getStName); + bool loadShiftRow(ShiftGraph &shiftObj, sqlite3pp::query &q_getStName, + sqlite3pp::query &q_countJobs, sqlite3pp::query &q_getJobs); + void loadStationName(db_id stationId, sqlite3pp::query &q_getStName); - std::pair lowerBound(db_id shiftId, const QString& name); + std::pair lowerBound(db_id shiftId, const QString &name); static constexpr qreal MSEC_PER_HOUR = 1000 * 60 * 60; - inline qreal jobPos(const QTime& t) + inline qreal jobPos(const QTime &t) { return t.msecsSinceStartOfDay() / MSEC_PER_HOUR * hourOffset + horizOffset; } private: - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; QVector m_shifts; struct StationCache { - //Full Name of station + // Full Name of station QString name; - //Short Name if available or fallback to Full Name + // Short Name if available or fallback to Full Name QString shortNameOrFallback; }; QHash m_stationCache; - //Options - qreal hourOffset = 150; - qreal shiftRowHeight = 50; - qreal rowSpaceOffset = 10; + // Options + qreal hourOffset = 150; + qreal shiftRowHeight = 50; + qreal rowSpaceOffset = 10; - qreal horizOffset = 50; - qreal vertOffset = 20; + qreal horizOffset = 50; + qreal vertOffset = 20; bool hideSameStations = true; }; diff --git a/src/shifts/shiftgraph/model/shiftgraphscenecollection.cpp b/src/shifts/shiftgraph/model/shiftgraphscenecollection.cpp index a4f40d5..bb0bf0b 100644 --- a/src/shifts/shiftgraph/model/shiftgraphscenecollection.cpp +++ b/src/shifts/shiftgraph/model/shiftgraphscenecollection.cpp @@ -25,18 +25,17 @@ ShiftGraphSceneCollection::ShiftGraphSceneCollection(sqlite3pp::database &db) : mDb(db), curIdx(-1) { - } qint64 ShiftGraphSceneCollection::getItemCount() { - //We have only 1 shift graph + // We have only 1 shift graph return 1; } bool ShiftGraphSceneCollection::startIteration() { - //There is not iteration for shift graph, fake it. + // There is not iteration for shift graph, fake it. curIdx = 0; return true; } @@ -44,17 +43,17 @@ bool ShiftGraphSceneCollection::startIteration() IGraphSceneCollection::SceneItem ShiftGraphSceneCollection::getNextItem() { SceneItem item; - if(curIdx != 0) - return item; //Tell caller we ended iteration + if (curIdx != 0) + return item; // Tell caller we ended iteration curIdx++; - //Create new scene without parent so ownership is passed to caller + // Create new scene without parent so ownership is passed to caller ShiftGraphScene *shiftScene = new ShiftGraphScene(mDb); shiftScene->loadShifts(); item.scene = shiftScene; - item.name = ShiftGraphScene::tr("Shift Graph"); - item.type = ShiftGraphScene::tr("shift_graph"); + item.name = ShiftGraphScene::tr("Shift Graph"); + item.type = ShiftGraphScene::tr("shift_graph"); return item; } diff --git a/src/shifts/shiftgraph/shiftgrapheditor.cpp b/src/shifts/shiftgraph/shiftgrapheditor.cpp index 0fcddf0..783a6f1 100644 --- a/src/shifts/shiftgraph/shiftgrapheditor.cpp +++ b/src/shifts/shiftgraph/shiftgrapheditor.cpp @@ -43,7 +43,6 @@ ShiftGraphEditor::ShiftGraphEditor(QWidget *parent) : toolBar->addAction(tr("Save PDF"), this, &ShiftGraphEditor::exportPDF); toolBar->addAction(tr("Save SVG"), this, &ShiftGraphEditor::exportSVG); - m_scene = new ShiftGraphScene(Session->m_Db, this); m_scene->loadShifts(); @@ -60,7 +59,6 @@ ShiftGraphEditor::ShiftGraphEditor(QWidget *parent) : ShiftGraphEditor::~ShiftGraphEditor() { - } void ShiftGraphEditor::redrawGraph() diff --git a/src/shifts/shiftgraph/view/shiftgraphprintdlg.cpp b/src/shifts/shiftgraph/view/shiftgraphprintdlg.cpp index c54c25b..5fb0c2a 100644 --- a/src/shifts/shiftgraph/view/shiftgraphprintdlg.cpp +++ b/src/shifts/shiftgraph/view/shiftgraphprintdlg.cpp @@ -43,28 +43,28 @@ ShiftGraphPrintDlg::ShiftGraphPrintDlg(sqlite3pp::database &db, QWidget *parent) { QVBoxLayout *lay = new QVBoxLayout(this); - //Setup Options Widget + // Setup Options Widget optionsWidget = new PrinterOptionsWidget; lay->addWidget(optionsWidget); - connect(optionsWidget, &PrinterOptionsWidget::completeChanged, - this, &ShiftGraphPrintDlg::updatePrintButton); + connect(optionsWidget, &PrinterOptionsWidget::completeChanged, this, + &ShiftGraphPrintDlg::updatePrintButton); - //Setup Progress Group Box - progressBox = new QGroupBox(tr("Progress:")); + // Setup Progress Group Box + progressBox = new QGroupBox(tr("Progress:")); QVBoxLayout *progLay = new QVBoxLayout(progressBox); - progressLabel = new QLabel; + progressLabel = new QLabel; progLay->addWidget(progressLabel); progressBar = new QProgressBar; progLay->addWidget(progressBar); lay->addWidget(progressBox); - //Dialog button box + // Dialog button box buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); lay->addWidget(buttonBox); - //Change 'Ok' button to 'Print' + // Change 'Ok' button to 'Print' buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Print")); connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); @@ -74,46 +74,47 @@ ShiftGraphPrintDlg::ShiftGraphPrintDlg(sqlite3pp::database &db, QWidget *parent) resize(500, 400); printTaskHandler = new PrintWorkerHandler(mDb, this); - connect(printTaskHandler, &PrintWorkerHandler::progressMaxChanged, - this, &ShiftGraphPrintDlg::progressMaxChanged); - connect(printTaskHandler, &PrintWorkerHandler::progressChanged, - this, &ShiftGraphPrintDlg::progressChanged); - connect(printTaskHandler, &PrintWorkerHandler::progressFinished, - this, &ShiftGraphPrintDlg::handleProgressFinished); + connect(printTaskHandler, &PrintWorkerHandler::progressMaxChanged, this, + &ShiftGraphPrintDlg::progressMaxChanged); + connect(printTaskHandler, &PrintWorkerHandler::progressChanged, this, + &ShiftGraphPrintDlg::progressChanged); + connect(printTaskHandler, &PrintWorkerHandler::progressFinished, this, + &ShiftGraphPrintDlg::handleProgressFinished); - //Initialize printer + // Initialize printer m_printer = new QPrinter; m_printer->setOutputFormat(QPrinter::PdfFormat); - //Initialize to a default pattern + // Initialize to a default pattern Print::PrintBasicOptions printOpt; - printOpt.fileNamePattern = Print::phNameUnderscore; - printOpt.useOneFileForEachScene = false; //We have only 1 scene, so 1 file + printOpt.fileNamePattern = Print::phNameUnderscore; + printOpt.useOneFileForEachScene = false; // We have only 1 scene, so 1 file printTaskHandler->setOptions(printOpt, m_printer); - //Remove page margins + // Remove page margins QPageLayout printerPageLay = m_printer->pageLayout(); printerPageLay.setMode(QPageLayout::FullPageMode); printerPageLay.setMargins(QMarginsF()); m_printer->setPageLayout(printerPageLay); - //Apply page size to scene layout + // Apply page size to scene layout Print::PageLayoutOpt scenePageLay; - PrintHelper::applyPageSize(printerPageLay.pageSize(), printerPageLay.orientation(), scenePageLay); + PrintHelper::applyPageSize(printerPageLay.pageSize(), printerPageLay.orientation(), + scenePageLay); printTaskHandler->setScenePageLay(scenePageLay); m_collection = new ShiftGraphSceneCollection(mDb); - //Init options + // Init options optionsWidget->setPrinter(m_printer); optionsWidget->setOptions(printOpt); optionsWidget->setScenePageLay(scenePageLay); - //Create scene + // Create scene m_collection->startIteration(); IGraphSceneCollection::SceneItem item = m_collection->getNextItem(); - item.scene->setParent(this); //Take ownership + item.scene->setParent(this); // Take ownership optionsWidget->setSourceScene(item.scene); updatePrintButton(); @@ -123,37 +124,37 @@ ShiftGraphPrintDlg::~ShiftGraphPrintDlg() { printTaskHandler->abortPrintTask(); - //Delete collection only after aborting + // Delete collection only after aborting delete m_collection; m_collection = nullptr; - //Reset scene + // Reset scene optionsWidget->setSourceScene(nullptr); } void ShiftGraphPrintDlg::setOutputType(Print::OutputType type) { Print::PrintBasicOptions printOpt = optionsWidget->getOptions(); - printOpt.outputType = type; + printOpt.outputType = type; optionsWidget->setOptions(printOpt); } void ShiftGraphPrintDlg::done(int res) { - //When we finish, we disable Cancel button - //If finished do not prompt about aborting printing - //Tasks is already cleaned up + // When we finish, we disable Cancel button + // If finished do not prompt about aborting printing + // Tasks is already cleaned up const bool printingFinished = !buttonBox->button(QDialogButtonBox::Cancel)->isEnabled(); - if(res == QDialog::Rejected && !printingFinished) + if (res == QDialog::Rejected && !printingFinished) { - if(!printTaskHandler->waitingForTaskToStop()) + if (!printTaskHandler->waitingForTaskToStop()) { - //Ask user if he wants to abort printing - if(!Print::askUserToAbortPrinting(printTaskHandler->taskIsRunning(), this)) + // Ask user if he wants to abort printing + if (!Print::askUserToAbortPrinting(printTaskHandler->taskIsRunning(), this)) return; - if(printTaskHandler->taskIsRunning()) + if (printTaskHandler->taskIsRunning()) { printTaskHandler->stopTaskGracefully(); return; @@ -161,38 +162,38 @@ void ShiftGraphPrintDlg::done(int res) } else { - if(printTaskHandler->taskIsRunning()) - return; //Already sent 'stop', just wait + if (printTaskHandler->taskIsRunning()) + return; // Already sent 'stop', just wait } } - else if(res == QDialog::Accepted && !printingFinished && !printTaskHandler->taskIsRunning()) + else if (res == QDialog::Accepted && !printingFinished && !printTaskHandler->taskIsRunning()) { - //Start printing - if(!optionsWidget->validateOptions()) - return; //User must set valid options + // Start printing + if (!optionsWidget->validateOptions()) + return; // User must set valid options printTaskHandler->setOptions(optionsWidget->getOptions(), m_printer); printTaskHandler->setScenePageLay(optionsWidget->getScenePageLay()); printTaskHandler->startPrintTask(m_printer, m_collection); - //Disable options and show progress + // Disable options and show progress optionsWidget->setEnabled(false); progressBox->setVisible(true); - //Disable 'Print' while printing + // Disable 'Print' while printing buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } - if(printTaskHandler->taskIsRunning()) - return; //Task is running, cannot quit now + if (printTaskHandler->taskIsRunning()) + return; // Task is running, cannot quit now QDialog::done(res); } void ShiftGraphPrintDlg::updatePrintButton() { - //Enable printing only if options is complete + // Enable printing only if options is complete buttonBox->button(QDialogButtonBox::Ok)->setEnabled(optionsWidget->isComplete()); } @@ -209,29 +210,29 @@ void ShiftGraphPrintDlg::progressChanged(int val, const QString &msg) void ShiftGraphPrintDlg::handleProgressFinished(bool success, const QString &errMsg) { - if(!success) + if (!success) { - if(Print::askUserToTryAgain(errMsg, this)) + if (Print::askUserToTryAgain(errMsg, this)) { - //Enable back options and hide progress + // Enable back options and hide progress optionsWidget->setEnabled(true); progressBox->setVisible(false); - //Enable 'Print' button again + // Enable 'Print' button again buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); return; } } - //When finished, disable Cancel button. + // When finished, disable Cancel button. buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); - //Enable button 'Ok' whith default test + // Enable button 'Ok' whith default test buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Ok")); buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); const Print::PrintBasicOptions printOpt = printTaskHandler->getOptions(); - if(printOpt.outputType != Print::OutputType::Native) + if (printOpt.outputType != Print::OutputType::Native) { utils::OpenFileInFolderDlg::askUser(tr("Shift Graph Saved"), printOpt.filePath, this); } diff --git a/src/shifts/shiftgraph/view/shiftgraphprintdlg.h b/src/shifts/shiftgraph/view/shiftgraphprintdlg.h index 01cb64b..ac79484 100644 --- a/src/shifts/shiftgraph/view/shiftgraphprintdlg.h +++ b/src/shifts/shiftgraph/view/shiftgraphprintdlg.h @@ -58,8 +58,8 @@ public: private slots: void updatePrintButton(); void progressMaxChanged(int max); - void progressChanged(int val, const QString& msg); - void handleProgressFinished(bool success, const QString& errMsg); + void progressChanged(int val, const QString &msg); + void handleProgressFinished(bool success, const QString &errMsg); private: sqlite3pp::database &mDb; diff --git a/src/shifts/shiftgraph/view/shiftgraphview.cpp b/src/shifts/shiftgraph/view/shiftgraphview.cpp index 0c07cc1..1668e5f 100644 --- a/src/shifts/shiftgraph/view/shiftgraphview.cpp +++ b/src/shifts/shiftgraph/view/shiftgraphview.cpp @@ -44,62 +44,61 @@ bool ShiftGraphView::viewportEvent(QEvent *e) { ShiftGraphScene *shiftScene = qobject_cast(scene()); - if(shiftScene && e->type() == QEvent::ToolTip) + if (shiftScene && e->type() == QEvent::ToolTip) { - QHelpEvent *ev = static_cast(e); + QHelpEvent *ev = static_cast(e); QPointF scenePos = mapToScene(ev->pos()); QString shiftName; ShiftGraphScene::JobItem item = shiftScene->getJobAt(scenePos, shiftName); - if(!item.job.jobId) + if (!item.job.jobId) { QToolTip::hideText(); } else { - QString msg = tr("" - "" - "" - "" - "" - "" - "" - "" - "
Job:%1
Shift:%2
From:%3at %4
To:%5at %6
") - .arg(JobCategoryName::jobName(item.job.jobId, item.job.category), - shiftName, - shiftScene->getStationFullName(item.fromStId), item.start.toString("HH:mm"), - shiftScene->getStationFullName(item.toStId), item.end.toString("HH:mm")); + QString msg = + tr("" + "" + "" + "" + "" + "" + "" + "" + "
Job:%1
Shift:%2
From:%3at %4
To:%5at %6
") + .arg(JobCategoryName::jobName(item.job.jobId, item.job.category), shiftName, + shiftScene->getStationFullName(item.fromStId), item.start.toString("HH:mm"), + shiftScene->getStationFullName(item.toStId), item.end.toString("HH:mm")); QToolTip::showText(ev->globalPos(), msg, viewport()); } return true; } - else if(shiftScene && e->type() == QEvent::ContextMenu) + else if (shiftScene && e->type() == QEvent::ContextMenu) { QContextMenuEvent *ev = static_cast(e); - QPointF scenePos = mapToScene(ev->pos()); + QPointF scenePos = mapToScene(ev->pos()); QString unusedShiftName; ShiftGraphScene::JobItem item = shiftScene->getJobAt(scenePos, unusedShiftName); - if(!item.job.jobId) + if (!item.job.jobId) return false; QMenu *menu = new QMenu(this); - menu->addAction(tr("Show Job in Graph"), this, [item]() + menu->addAction( + tr("Show Job in Graph"), this, + [item]() { Session->getViewManager()->requestJobSelection(item.job.jobId, true, true); }); + menu->addAction(tr("Show in Job Editor"), this, + [item]() { Session->getViewManager()->requestJobEditor(item.job.jobId); }); + menu->addAction(tr("Change Job Shift"), this, + [this, item]() { - Session->getViewManager()->requestJobSelection(item.job.jobId, true, true); - }); - menu->addAction(tr("Show in Job Editor"), this, [item]() - { - Session->getViewManager()->requestJobEditor(item.job.jobId); - }); - menu->addAction(tr("Change Job Shift"), this, [this, item]() - { - OwningQPointer dlg = new JobChangeShiftDlg(Session->m_Db, this); + OwningQPointer dlg = + new JobChangeShiftDlg(Session->m_Db, this); dlg->setJob(item.job.jobId); dlg->exec(); }); diff --git a/src/shifts/shiftjobsmodel.cpp b/src/shifts/shiftjobsmodel.cpp index 5e4970c..51b6db2 100644 --- a/src/shifts/shiftjobsmodel.cpp +++ b/src/shifts/shiftjobsmodel.cpp @@ -32,7 +32,7 @@ ShiftJobsModel::ShiftJobsModel(sqlite3pp::database &db, QObject *parent) : QVariant ShiftJobsModel::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) { @@ -51,7 +51,7 @@ QVariant ShiftJobsModel::headerData(int section, Qt::Orientation orientation, in } } return QAbstractTableModel::headerData(section, orientation, role); - } +} int ShiftJobsModel::rowCount(const QModelIndex &parent) const { @@ -65,10 +65,11 @@ int ShiftJobsModel::columnCount(const QModelIndex &parent) const QVariant ShiftJobsModel::data(const QModelIndex &idx, int role) const { - if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols || role != Qt::DisplayRole) + if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols + || role != Qt::DisplayRole) return QVariant(); - const ShiftJobItem& item = m_data.at(idx.row()); + const ShiftJobItem &item = m_data.at(idx.row()); switch (idx.column()) { @@ -108,16 +109,16 @@ void ShiftJobsModel::loadShiftJobs(db_id shiftId) q.bind(1, shiftId); - for(auto r : q) + for (auto r : q) { ShiftJobItem item; - item.jobId = r.get(0); - item.cat = JobCategory(r.get(1)); - item.start = r.get(2); - item.originStId = r.get(3); - item.end = r.get(4); - item.destinationStId = r.get(5); - item.originStName = r.get(6); + item.jobId = r.get(0); + item.cat = JobCategory(r.get(1)); + item.start = r.get(2); + item.originStId = r.get(3); + item.end = r.get(4); + item.destinationStId = r.get(5); + item.originStName = r.get(6); item.desinationStName = r.get(7); m_data.append(item); } @@ -129,7 +130,7 @@ void ShiftJobsModel::loadShiftJobs(db_id shiftId) db_id ShiftJobsModel::getJobAt(int row) { - if(row < m_data.size()) + if (row < m_data.size()) return m_data.at(row).jobId; return 0; } diff --git a/src/shifts/shiftjobsmodel.h b/src/shifts/shiftjobsmodel.h index 04c10c5..5da023d 100644 --- a/src/shifts/shiftjobsmodel.h +++ b/src/shifts/shiftjobsmodel.h @@ -62,7 +62,8 @@ public: ShiftJobsModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -75,7 +76,7 @@ public: db_id getJobAt(int row); private: - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; QVector m_data; }; diff --git a/src/shifts/shiftmanager.cpp b/src/shifts/shiftmanager.cpp index b01cb01..e60e512 100644 --- a/src/shifts/shiftmanager.cpp +++ b/src/shifts/shiftmanager.cpp @@ -52,14 +52,14 @@ ShiftManager::ShiftManager(QWidget *parent) : { QVBoxLayout *l = new QVBoxLayout(this); - toolBar = new QToolBar(this); + toolBar = new QToolBar(this); l->addWidget(toolBar); view = new QTableView(this); view->setSelectionMode(QTableView::SingleSelection); l->addWidget(view); - //Custom filtering + // Custom filtering FilterHeaderView *header = new FilterHeaderView(view); header->installOnTable(view); @@ -78,24 +78,23 @@ ShiftManager::ShiftManager(QWidget *parent) : act_New = toolBar->addAction(tr("New"), this, &ShiftManager::onNewShift); act_Remove = toolBar->addAction(tr("Remove"), this, &ShiftManager::onRemoveShift); toolBar->addSeparator(); - act_displayShift = toolBar->addAction(tr("View Shift"), this, &ShiftManager::onViewShift); - act_Sheet = toolBar->addAction(tr("Sheet"), this, &ShiftManager::onSaveSheet); + act_displayShift = toolBar->addAction(tr("View Shift"), this, &ShiftManager::onViewShift); + act_Sheet = toolBar->addAction(tr("Sheet"), this, &ShiftManager::onSaveSheet); toolBar->addSeparator(); - act_Graph = toolBar->addAction(tr("Graph"), this, &ShiftManager::displayGraph); + act_Graph = toolBar->addAction(tr("Graph"), this, &ShiftManager::displayGraph); actionGroup = new QActionGroup(this); actionGroup->addAction(act_New); actionGroup->addAction(act_Remove); - connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &ShiftManager::onShiftSelectionChanged); - connect(model, &QAbstractItemModel::modelReset, - this, &ShiftManager::onShiftSelectionChanged); + connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &ShiftManager::onShiftSelectionChanged); + connect(model, &QAbstractItemModel::modelReset, this, &ShiftManager::onShiftSelectionChanged); connect(model, &ShiftsModel::modelError, this, &ShiftManager::onModelError); setReadOnly(false); - //Action Tooltips + // Action Tooltips act_New->setToolTip(tr("Create new Job Shift")); act_Remove->setToolTip(tr("Remove selected Job Shift")); act_displayShift->setToolTip(tr("Show selected Job Shift plan")); @@ -114,14 +113,14 @@ void ShiftManager::showEvent(QShowEvent *e) void ShiftManager::setReadOnly(bool readOnly) { - if(m_readOnly == readOnly) + if (m_readOnly == readOnly) return; m_readOnly = readOnly; actionGroup->setEnabled(!m_readOnly); - if(m_readOnly) + if (m_readOnly) { view->setEditTriggers(QTableView::NoEditTriggers); } @@ -134,7 +133,7 @@ void ShiftManager::setReadOnly(bool readOnly) void ShiftManager::onNewShift() { DEBUG_ENTRY; - if(m_readOnly) + if (m_readOnly) return; OwningQPointer dlg = new QInputDialog(this); @@ -142,41 +141,41 @@ void ShiftManager::onNewShift() dlg->setLabelText(tr("Please choose a name for the new shift.")); dlg->setTextValue(QString()); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Shift name cannot be empty.")); - continue; //Second chance + continue; // Second chance } - if(model->addShift(name)) + if (model->addShift(name)) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); } void ShiftManager::onRemoveShift() { DEBUG_ENTRY; - if(m_readOnly || !view->selectionModel()->hasSelection()) + if (m_readOnly || !view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); - //Ask confirmation + // Ask confirmation int ret = QMessageBox::question(this, tr("Remove Shift?"), tr("Are you sure you want to remove Job Shift %1?") - .arg(model->shiftNameAtRow(idx.row()))); - if(ret != QMessageBox::Yes) + .arg(model->shiftNameAtRow(idx.row()))); + if (ret != QMessageBox::Yes) return; model->removeShiftAt(idx.row()); @@ -185,11 +184,11 @@ void ShiftManager::onRemoveShift() void ShiftManager::onViewShift() { DEBUG_ENTRY; - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; db_id shiftId = model->shiftAtRow(view->currentIndex().row()); - if(!shiftId) + if (!shiftId) return; qDebug() << "Display Shift:" << shiftId; @@ -220,12 +219,12 @@ void ShiftManager::onSaveSheet() const QString shiftSheetDirKey = QLatin1String("shift_sheet_dir"); DEBUG_ENTRY; - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); - db_id shiftId = model->shiftAtRow(idx.row()); - if(!shiftId) + db_id shiftId = model->shiftAtRow(idx.row()); + if (!shiftId) return; QString shiftName = model->shiftNameAtRow(idx.row()); @@ -241,11 +240,11 @@ void ShiftManager::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(shiftSheetDirKey, fileName); diff --git a/src/shifts/shiftmanager.h b/src/shifts/shiftmanager.h index 040297b..0ce20f6 100644 --- a/src/shifts/shiftmanager.h +++ b/src/shifts/shiftmanager.h @@ -54,7 +54,7 @@ private slots: void onShiftSelectionChanged(); - void onModelError(const QString& msg); + void onModelError(const QString &msg); private: QToolBar *toolBar; diff --git a/src/shifts/shiftresultevent.cpp b/src/shifts/shiftresultevent.cpp index e1434ed..fa73053 100644 --- a/src/shifts/shiftresultevent.cpp +++ b/src/shifts/shiftresultevent.cpp @@ -22,5 +22,4 @@ ShiftResultEvent::ShiftResultEvent() : QEvent(_Type) { - } diff --git a/src/shifts/shiftsmodel.cpp b/src/shifts/shiftsmodel.cpp index d388450..8d7c268 100644 --- a/src/shifts/shiftsmodel.cpp +++ b/src/shifts/shiftsmodel.cpp @@ -30,20 +30,17 @@ using namespace sqlite3pp; #include -//Error messages -static constexpr char errorNameAlreadyUsedText[] - = QT_TRANSLATE_NOOP("ShiftsModel", - "There is already another job shift with same name: %1"); +// Error messages +static constexpr char errorNameAlreadyUsedText[] = + QT_TRANSLATE_NOOP("ShiftsModel", "There is already another job shift with same name: %1"); -static constexpr char errorGenericAddText[] - = QT_TRANSLATE_NOOP("ShiftsModel", - "An error occurred while adding a new shift: %1
" - "%2"); +static constexpr char errorGenericAddText[] = + QT_TRANSLATE_NOOP("ShiftsModel", "An error occurred while adding a new shift: %1
" + "%2"); -static constexpr char errorShiftInUseCannotDeleteText[] - = QT_TRANSLATE_NOOP("ShiftsModel", - "Shift %1 is used by some jobs.
" - "To remove it, transfer those jobs to a different shift or remove them."); +static constexpr char errorShiftInUseCannotDeleteText[] = QT_TRANSLATE_NOOP( + "ShiftsModel", "Shift %1 is used by some jobs.
" + "To remove it, transfer those jobs to a different shift or remove them."); ShiftsModel::ShiftsModel(database &db, QObject *parent) : BaseClass(500, db, parent) @@ -53,9 +50,9 @@ ShiftsModel::ShiftsModel(database &db, QObject *parent) : QVariant ShiftsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (section) { @@ -77,12 +74,12 @@ QVariant ShiftsModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cach + // Fetch above or below current cach const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } @@ -91,7 +88,7 @@ QVariant ShiftsModel::data(const QModelIndex &idx, int role) const case Qt::DisplayRole: case Qt::EditRole: { - const ShiftItem& item = cache.at(idx.row() - cacheFirstRow); + const ShiftItem &item = cache.at(idx.row() - cacheFirstRow); switch (idx.column()) { @@ -107,8 +104,9 @@ QVariant ShiftsModel::data(const QModelIndex &idx, int role) const bool ShiftsModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid ShiftItem &item = cache[row - cacheFirstRow]; @@ -121,24 +119,24 @@ bool ShiftsModel::setData(const QModelIndex &idx, const QVariant &value, int rol case ShiftName: { QString newName = value.toString().simplified(); - if(item.shiftName == newName) - return false; //No change + if (item.shiftName == newName) + return false; // No change command set_name(mDb, "UPDATE jobshifts SET name=? WHERE id=?"); - if(newName.isEmpty()) - set_name.bind(1); //Bind NULL + if (newName.isEmpty()) + set_name.bind(1); // Bind NULL else set_name.bind(1, newName); set_name.bind(2, item.shiftId); int ret = set_name.execute(); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(newName)); return false; } - else if(ret != SQLITE_OK) + else if (ret != SQLITE_OK) { qDebug() << "Shift Error:" << ret << mDb.error_msg(); return false; @@ -147,9 +145,9 @@ bool ShiftsModel::setData(const QModelIndex &idx, const QVariant &value, int rol item.shiftName = newName; emit Session->shiftNameChanged(item.shiftId); - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -169,7 +167,7 @@ Qt::ItemFlags ShiftsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) return f; return f | Qt::ItemIsEditable; @@ -179,7 +177,7 @@ qint64 ShiftsModel::recalcTotalItemCount() { QByteArray sql = "SELECT COUNT(1) FROM jobshifts"; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { sql.append(" WHERE jobshifts.name LIKE ?1"); } @@ -187,7 +185,7 @@ qint64 ShiftsModel::recalcTotalItemCount() query q(mDb, sql); QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -221,8 +219,8 @@ bool ShiftsModel::setFilterAtCol(int col, const QString &str) { case ShiftName: { - if(isNull) - return false; //Cannot have NULL Name + if (isNull) + return false; // Cannot have NULL Name m_nameFilter = str; break; } @@ -234,7 +232,8 @@ bool ShiftsModel::setFilterAtCol(int col, const QString &str) return true; } -void ShiftsModel::internalFetch(int first, int /*sortColumn*/, int /*valRow*/, const QVariant &/*val*/) +void ShiftsModel::internalFetch(int first, int /*sortColumn*/, int /*valRow*/, + const QVariant & /*val*/) { query q(mDb); @@ -244,23 +243,23 @@ void ShiftsModel::internalFetch(int first, int /*sortColumn*/, int /*valRow*/, c QByteArray sql = "SELECT id,name FROM jobshifts"; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { sql.append(" WHERE name LIKE ?3"); } sql += " ORDER BY name LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -272,43 +271,43 @@ void ShiftsModel::internalFetch(int first, int /*sortColumn*/, int /*valRow*/, c QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; + auto r = *it; ShiftItem &item = vec[i]; - item.shiftId = r.get(0); - item.shiftName = r.get(1); + item.shiftId = r.get(0); + item.shiftName = r.get(1); i++; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); } -bool ShiftsModel::removeShift(db_id shiftId, const QString& name) +bool ShiftsModel::removeShift(db_id shiftId, const QString &name) { - if(!shiftId) + if (!shiftId) return false; command cmd(mDb, "DELETE FROM jobshifts WHERE id=?"); cmd.bind(1, shiftId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qWarning() << "ShiftModel: error removing shift" << ret << mDb.error_msg(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { ret = mDb.extended_error_code(); - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { QString tmp = name; - if(name.isNull()) + if (name.isNull()) { query q(mDb, "SELECT name FROM jobshifts WHERE id=?"); q.bind(1, shiftId); @@ -329,20 +328,20 @@ bool ShiftsModel::removeShift(db_id shiftId, const QString& name) emit Session->shiftRemoved(shiftId); - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } bool ShiftsModel::removeShiftAt(int row) { - if(row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (row >= curItemCount || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - const ShiftItem& item = cache.at(row - cacheFirstRow); + const ShiftItem &item = cache.at(row - cacheFirstRow); return removeShift(item.shiftId, item.shiftName); } -db_id ShiftsModel::addShift(const QString& shiftName) +db_id ShiftsModel::addShift(const QString &shiftName) { db_id shiftId = 0; @@ -352,34 +351,34 @@ db_id ShiftsModel::addShift(const QString& shiftName) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); int ret = cmd.execute(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) { shiftId = mDb.last_insert_rowid(); } sqlite3_mutex_leave(mutex); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qDebug() << "Shift Error adding:" << ret << mDb.error_msg(); - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(shiftName)); return false; } - //Generic Error + // Generic Error emit modelError(tr(errorGenericAddText).arg(shiftName, mDb.error_msg())); } - //Reset filter + // Reset filter m_nameFilter.clear(); m_nameFilter.squeeze(); emit filterChanged(); - refreshData(); //Recalc row count + refreshData(); // Recalc row count - if(shiftId) + if (shiftId) emit Session->shiftAdded(shiftId); return shiftId; diff --git a/src/shifts/shiftsmodel.h b/src/shifts/shiftsmodel.h index 1413121..2c45163 100644 --- a/src/shifts/shiftsmodel.h +++ b/src/shifts/shiftsmodel.h @@ -42,7 +42,10 @@ class ShiftsModel : public IPagedItemModelImpl Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; enum Columns { @@ -58,21 +61,21 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel - //Filter + // Filter std::pair getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // ShiftModel @@ -84,16 +87,16 @@ public: // Convinience inline db_id shiftAtRow(int row) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Not fetched yet or invalid + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return 0; // Not fetched yet or invalid return cache.at(row - cacheFirstRow).shiftId; } inline QString shiftNameAtRow(int row) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QString(); //Not fetched yet or invalid + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + return QString(); // Not fetched yet or invalid return cache.at(row - cacheFirstRow).shiftName; } diff --git a/src/shifts/shiftviewer.cpp b/src/shifts/shiftviewer.cpp index 4e0e8e9..3b7e87e 100644 --- a/src/shifts/shiftviewer.cpp +++ b/src/shifts/shiftviewer.cpp @@ -38,7 +38,7 @@ ShiftViewer::ShiftViewer(QWidget *parent) : { QVBoxLayout *l = new QVBoxLayout(this); - view = new QTableView(this); + view = new QTableView(this); l->addWidget(view); setMinimumSize(600, 200); @@ -51,15 +51,14 @@ ShiftViewer::ShiftViewer(QWidget *parent) : ShiftViewer::~ShiftViewer() { - } void ShiftViewer::updateName() { q_shiftName.bind(1, shiftId); - if(q_shiftName.step() != SQLITE_ROW) + if (q_shiftName.step() != SQLITE_ROW) { - //Error + // Error } else { @@ -79,23 +78,23 @@ void ShiftViewer::updateJobsModel() model->loadShiftJobs(shiftId); } -void ShiftViewer::showContextMenu(const QPoint& pos) +void ShiftViewer::showContextMenu(const QPoint &pos) { QModelIndex idx = view->indexAt(pos); - if(!idx.isValid()) + if (!idx.isValid()) return; - db_id jobId = model->getJobAt(idx.row()); + db_id jobId = model->getJobAt(idx.row()); OwningQPointer menu = new QMenu(this); - QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); + QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); menu->addAction(showInJobEditor); QAction *act = menu->exec(view->viewport()->mapToGlobal(pos)); - if(act == showInJobEditor) + if (act == showInJobEditor) { - //TODO: requestJobEditor() doesn't select item in graph + // TODO: requestJobEditor() doesn't select item in graph Session->getViewManager()->requestJobSelection(jobId, true, true); } } diff --git a/src/sqlconsole/sqlconsole.cpp b/src/sqlconsole/sqlconsole.cpp index d6c4220..4eac1c1 100644 --- a/src/sqlconsole/sqlconsole.cpp +++ b/src/sqlconsole/sqlconsole.cpp @@ -19,16 +19,16 @@ #ifdef ENABLE_USER_QUERY -#include "sqlconsole.h" +# include "sqlconsole.h" -#include -#include -#include -#include +# include +# include +# include +# include -#include +# include -#include "sqlviewer.h" +# include "sqlviewer.h" SQLConsole::SQLConsole(QWidget *parent) : QDialog(parent), @@ -36,22 +36,22 @@ SQLConsole::SQLConsole(QWidget *parent) : { setWindowTitle(QStringLiteral("SQL Console")); - edit = new QPlainTextEdit; - viewer = new SQLViewer(nullptr); + edit = new QPlainTextEdit; + viewer = new SQLViewer(nullptr); QPushButton *clearBut = new QPushButton("Clear"); - QPushButton *runBut = new QPushButton("Run"); + QPushButton *runBut = new QPushButton("Run"); - intervalSpin = new QSpinBox; + intervalSpin = new QSpinBox; intervalSpin->setMinimum(0); intervalSpin->setMaximum(10); intervalSpin->setSuffix(" seconds"); QGridLayout *lay = new QGridLayout(this); - lay->addWidget(edit, 0, 0, 1, 3); - lay->addWidget(runBut, 1, 0, 1, 1); + lay->addWidget(edit, 0, 0, 1, 3); + lay->addWidget(runBut, 1, 0, 1, 1); lay->addWidget(clearBut, 1, 1, 1, 1); - lay->addWidget(intervalSpin, 1, 2, 1, 1); - lay->addWidget(viewer, 2, 0, 1, 3); + lay->addWidget(intervalSpin, 1, 2, 1, 1); + lay->addWidget(viewer, 2, 0, 1, 3); connect(clearBut, &QPushButton::clicked, edit, &QPlainTextEdit::clear); connect(runBut, &QPushButton::clicked, this, &SQLConsole::executeQuery); @@ -64,20 +64,19 @@ SQLConsole::SQLConsole(QWidget *parent) : SQLConsole::~SQLConsole() { - } void SQLConsole::setInterval(int secs) { - if(secs == 0 && timer) + if (secs == 0 && timer) { timer->stop(); timer->deleteLater(); timer = nullptr; } - else if(secs != 0) + else if (secs != 0) { - if(!timer) + if (!timer) { timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &SQLConsole::timedExec); @@ -90,7 +89,7 @@ void SQLConsole::setInterval(int secs) void SQLConsole::onIntervalChangedUser() { int secs = intervalSpin->value(); - if(timer && timer->interval() == secs) + if (timer && timer->interval() == secs) return; setInterval(secs); } @@ -98,7 +97,7 @@ void SQLConsole::onIntervalChangedUser() bool SQLConsole::executeQuery() { QString sql = edit->toPlainText(); - if(!viewer->prepare(sql.toUtf8())) + if (!viewer->prepare(sql.toUtf8())) return false; viewer->execQuery(); @@ -107,9 +106,9 @@ bool SQLConsole::executeQuery() void SQLConsole::timedExec() { - if(!viewer->execQuery()) + if (!viewer->execQuery()) { - setInterval(0); //Abort timer + setInterval(0); // Abort timer return; } viewer->timedExec(); diff --git a/src/sqlconsole/sqlconsole.h b/src/sqlconsole/sqlconsole.h index 944398c..b0eb7cb 100644 --- a/src/sqlconsole/sqlconsole.h +++ b/src/sqlconsole/sqlconsole.h @@ -22,7 +22,7 @@ #ifdef ENABLE_USER_QUERY -#include +# include class SQLViewer; class QPlainTextEdit; @@ -45,6 +45,7 @@ private slots: void onIntervalChangedUser(); void timedExec(); + private: QPlainTextEdit *edit; SQLViewer *viewer; diff --git a/src/sqlconsole/sqlresultmodel.cpp b/src/sqlconsole/sqlresultmodel.cpp index cf801b5..dcdc9f3 100644 --- a/src/sqlconsole/sqlresultmodel.cpp +++ b/src/sqlconsole/sqlresultmodel.cpp @@ -19,22 +19,20 @@ #ifdef ENABLE_USER_QUERY -#include "sqlresultmodel.h" +# include "sqlresultmodel.h" -#include +# include -#include "app/session.h" +# include "app/session.h" SQLResultModel::SQLResultModel(QObject *parent) : QAbstractTableModel(parent), colCount(0) { - } SQLResultModel::~SQLResultModel() { - } int SQLResultModel::rowCount(const QModelIndex &parent) const @@ -49,16 +47,16 @@ int SQLResultModel::columnCount(const QModelIndex &parent) const QVariant SQLResultModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid() || !colCount || idx.row() >= (m_data.size() / colCount)) + if (!idx.isValid() || !colCount || idx.row() >= (m_data.size() / colCount)) return QVariant(); - if(role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { int i = idx.row() * colCount + idx.column(); return m_data.at(i); } - if(role == Qt::BackgroundRole) + if (role == Qt::BackgroundRole) { return backGround; } @@ -68,7 +66,7 @@ QVariant SQLResultModel::data(const QModelIndex &idx, int role) const QVariant SQLResultModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal && role == Qt::DisplayRole) + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { return colNames.value(section, "ERR"); } @@ -96,7 +94,7 @@ bool SQLResultModel::initFromQuery(sqlite3pp::query *q) m_data.squeeze(); m_data.reserve(colCount); - for(int i = 0; i < colCount; i++) + for (int i = 0; i < colCount; i++) { colNames.append(q->column_name(i)); } @@ -104,7 +102,7 @@ bool SQLResultModel::initFromQuery(sqlite3pp::query *q) int ret = q->step(); while (ret == SQLITE_ROW) { - for(int c = 0; c < colCount; c++) + for (int c = 0; c < colCount; c++) { auto r = q->getRows(); QVariant val; @@ -148,7 +146,7 @@ bool SQLResultModel::initFromQuery(sqlite3pp::query *q) endResetModel(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit error(ret, Session->m_Db.extended_error_code(), Session->m_Db.error_msg()); return false; diff --git a/src/sqlconsole/sqlresultmodel.h b/src/sqlconsole/sqlresultmodel.h index 4098dde..20a5b54 100644 --- a/src/sqlconsole/sqlresultmodel.h +++ b/src/sqlconsole/sqlresultmodel.h @@ -22,8 +22,8 @@ #ifdef ENABLE_USER_QUERY -#include -#include +# include +# include namespace sqlite3pp { class query; @@ -38,17 +38,17 @@ public: // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int columnCount(const QModelIndex& parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - void setBackground(const QColor& col); + void setBackground(const QColor &col); bool initFromQuery(sqlite3pp::query *q); signals: - void error(int err, int extendedErr, const QString& msg); + void error(int err, int extendedErr, const QString &msg); private: QStringList colNames; diff --git a/src/sqlconsole/sqlviewer.cpp b/src/sqlconsole/sqlviewer.cpp index 88df2ea..0a8fba5 100644 --- a/src/sqlconsole/sqlviewer.cpp +++ b/src/sqlconsole/sqlviewer.cpp @@ -19,23 +19,23 @@ #ifdef ENABLE_USER_QUERY -#include "sqlviewer.h" +# include "sqlviewer.h" -#include "app/session.h" +# include "app/session.h" -#include "sqlresultmodel.h" -#include +# include "sqlresultmodel.h" +# include -#include -#include -#include +# include +# include +# include -#include +# include -#include +# include SQLViewer::SQLViewer(sqlite3pp::query *q, QWidget *parent) : - QWidget (parent), + QWidget(parent), model(nullptr), mQuery(nullptr), view(nullptr), @@ -43,7 +43,7 @@ SQLViewer::SQLViewer(sqlite3pp::query *q, QWidget *parent) : { setQuery(q); setWindowTitle(QStringLiteral("SQL Viewer")); - view = new QTableView(this); + view = new QTableView(this); QVBoxLayout *l = new QVBoxLayout(this); l->addWidget(view); @@ -58,7 +58,7 @@ SQLViewer::SQLViewer(sqlite3pp::query *q, QWidget *parent) : SQLViewer::~SQLViewer() { - if(deleteQuery) + if (deleteQuery) delete mQuery; } @@ -90,33 +90,34 @@ void SQLViewer::onError(int err, int extended, const QString &msg) showErrorMsg(tr("Query Error"), msg, err, extended); } -void SQLViewer::showErrorMsg(const QString& title, const QString& msg, int err, int extendedErr) +void SQLViewer::showErrorMsg(const QString &title, const QString &msg, int err, int extendedErr) { QMessageBox::warning(this, title, tr("SQLite Error: %1\n" "Extended: %2\n" "Message: %3") - .arg(err) - .arg(extendedErr) - .arg(msg)); + .arg(err) + .arg(extendedErr) + .arg(msg)); } void SQLViewer::setQuery(sqlite3pp::query *query) { - if(deleteQuery) + if (deleteQuery) delete mQuery; - mQuery = query; + mQuery = query; deleteQuery = !mQuery; - if(!mQuery) + if (!mQuery) mQuery = new sqlite3pp::query(Session->m_Db); } -bool SQLViewer::prepare(const QByteArray& sql) +bool SQLViewer::prepare(const QByteArray &sql) { int ret = mQuery->prepare(sql); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - showErrorMsg(tr("Preparation Failed"), Session->m_Db.error_msg(), ret, Session->m_Db.extended_error_code()); + showErrorMsg(tr("Preparation Failed"), Session->m_Db.error_msg(), ret, + Session->m_Db.extended_error_code()); return false; } return true; diff --git a/src/sqlconsole/sqlviewer.h b/src/sqlconsole/sqlviewer.h index 2ff7d0b..24247f7 100644 --- a/src/sqlconsole/sqlviewer.h +++ b/src/sqlconsole/sqlviewer.h @@ -22,7 +22,7 @@ #ifdef ENABLE_USER_QUERY -#include +# include class QTableView; class SQLResultModel; @@ -47,7 +47,7 @@ public slots: void timedExec(); void resetColor(); - void onError(int err, int extended, const QString& msg); + void onError(int err, int extended, const QString &msg); private: SQLResultModel *model; diff --git a/src/sqlite3pp/sqlite3pp.h b/src/sqlite3pp/sqlite3pp.h index 4484e20..60ac1cc 100644 --- a/src/sqlite3pp/sqlite3pp.h +++ b/src/sqlite3pp/sqlite3pp.h @@ -44,7 +44,7 @@ #ifndef SQLITE3PP_H #define SQLITE3PP_H -#define SQLITE3PP_VERSION "1.0.6" +#define SQLITE3PP_VERSION "1.0.6" #define SQLITE3PP_VERSION_MAJOR 1 #define SQLITE3PP_VERSION_MINOR 0 #define SQLITE3PP_VERSION_PATCH 6 @@ -59,66 +59,70 @@ #include #include -namespace sqlite3pp +namespace sqlite3pp { +namespace ext { +class function; +class aggregate; +} // namespace ext + +template struct convert { - namespace ext - { - class function; - class aggregate; - } - - template - struct convert { using to_int = int; - }; +}; - class null_type {}; +class null_type +{ +}; - class noncopyable - { - protected: - noncopyable() = default; - ~noncopyable() = default; +class noncopyable +{ +protected: + noncopyable() = default; + ~noncopyable() = default; - noncopyable(noncopyable&&) = default; - noncopyable& operator=(noncopyable&&) = default; + noncopyable(noncopyable &&) = default; + noncopyable &operator=(noncopyable &&) = default; - noncopyable(noncopyable const&) = delete; - noncopyable& operator=(noncopyable const&) = delete; - }; + noncopyable(noncopyable const &) = delete; + noncopyable &operator=(noncopyable const &) = delete; +}; - class database : noncopyable - { +class database : noncopyable +{ friend class statement; friend class database_error; friend class ext::function; friend class ext::aggregate; - public: - using busy_handler = std::function; - using commit_handler = std::function; - using rollback_handler = std::function; - using update_handler = std::function; - using authorize_handler = std::function; - using backup_handler = std::function; +public: + using busy_handler = std::function; + using commit_handler = std::function; + using rollback_handler = std::function; + using update_handler = std::function; + using authorize_handler = + std::function; + using backup_handler = std::function; - explicit database(char const* dbname = nullptr, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, const char* vfs = nullptr); + explicit database(char const *dbname = nullptr, + int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, + const char *vfs = nullptr); - database(database&& db); - database& operator=(database&& db); + database(database &&db); + database &operator=(database &&db); ~database(); - int connect(char const* dbname, int flags, const char* vfs = nullptr); + int connect(char const *dbname, int flags, const char *vfs = nullptr); int disconnect(); - int attach(char const* dbname, char const* name); - int detach(char const* name); + int attach(char const *dbname, char const *name); + int detach(char const *name); - int backup(database& destdb, backup_handler h = {}); - int backup(char const* dbname, database& destdb, char const* destdbname, backup_handler h, int step_page = 5); + int backup(database &destdb, backup_handler h = {}); + int backup(char const *dbname, database &destdb, char const *destdbname, backup_handler h, + int step_page = 5); - //NOTE: use inside sqlite3_db_mutex + // NOTE: use inside sqlite3_db_mutex long long int last_insert_rowid() const; int enable_foreign_keys(bool enable = true); @@ -129,10 +133,10 @@ namespace sqlite3pp int error_code() const; int extended_error_code() const; - char const* error_msg() const; + char const *error_msg() const; - int execute(char const* sql); - int executef(char const* sql, ...); + int execute(char const *sql); + int executef(char const *sql, ...); int set_busy_timeout(int ms); @@ -147,65 +151,69 @@ namespace sqlite3pp return db_; } - private: - sqlite3* db_; +private: + sqlite3 *db_; busy_handler bh_; commit_handler ch_; rollback_handler rh_; update_handler uh_; authorize_handler ah_; - }; +}; - class database_error : public std::runtime_error - { - public: - explicit database_error(char const* msg); - explicit database_error(database& db); - }; +class database_error : public std::runtime_error +{ +public: + explicit database_error(char const *msg); + explicit database_error(database &db); +}; - enum copy_semantic { copy, nocopy }; +enum copy_semantic +{ + copy, + nocopy +}; - class statement : noncopyable - { - public: - int prepare(char const* stmt); +class statement : noncopyable +{ +public: + int prepare(char const *stmt); int finish(); int bind(int idx, int value); int bind(int idx, double value); int bind(int idx, long long int value); - int bind(int idx, char const* value, copy_semantic fcopy); - int bind(int idx, void const* value, int n, copy_semantic fcopy); - int bind(int idx, std::string const& value, copy_semantic fcopy); + int bind(int idx, char const *value, copy_semantic fcopy); + int bind(int idx, void const *value, int n, copy_semantic fcopy); + int bind(int idx, std::string const &value, copy_semantic fcopy); int bind(int idx); int bind(int idx, null_type); - int bind(char const* name, int value); - int bind(char const* name, double value); - int bind(char const* name, long long int value); - int bind(char const* name, char const* value, copy_semantic fcopy); - int bind(char const* name, void const* value, int n, copy_semantic fcopy); - int bind(char const* name, std::string const& value, copy_semantic fcopy); - int bind(char const* name); - int bind(char const* name, null_type); + int bind(char const *name, int value); + int bind(char const *name, double value); + int bind(char const *name, long long int value); + int bind(char const *name, char const *value, copy_semantic fcopy); + int bind(char const *name, void const *value, int n, copy_semantic fcopy); + int bind(char const *name, std::string const &value, copy_semantic fcopy); + int bind(char const *name); + int bind(char const *name, null_type); - inline int bind(int idx, const QTime& t) + inline int bind(int idx, const QTime &t) { - int minutes = t.msecsSinceStartOfDay() / 60000; //msecs to minutes + int minutes = t.msecsSinceStartOfDay() / 60000; // msecs to minutes return bind(idx, minutes); } - //BIG TODO: is this function better? - //Binding 0 or NULL is the same? + // BIG TODO: is this function better? + // Binding 0 or NULL is the same? inline int bindOrNull(int idx, long long int value) { - if(value) + if (value) return bind(idx, value); - return bind(idx); //Bind null + return bind(idx); // Bind null } - int bind(int idx, const QString& str) + int bind(int idx, const QString &str) { QByteArray arr = str.toUtf8(); return sqlite3_bind_text(stmt_, idx, arr.data(), arr.size(), SQLITE_TRANSIENT); @@ -219,162 +227,166 @@ namespace sqlite3pp return stmt_; } - explicit statement(database& db, char const* stmt = nullptr); + explicit statement(database &db, char const *stmt = nullptr); ~statement(); - protected: +protected: + int prepare_impl(char const *stmt); + int finish_impl(sqlite3_stmt *stmt); +protected: + database &db_; + sqlite3_stmt *stmt_; + char const *tail_; +}; - int prepare_impl(char const* stmt); - int finish_impl(sqlite3_stmt* stmt); - - protected: - database& db_; - sqlite3_stmt* stmt_; - char const* tail_; - }; - - class command : public statement - { - public: +class command : public statement +{ +public: class bindstream { - public: - bindstream(command& cmd, int idx); + public: + bindstream(command &cmd, int idx); - template - bindstream& operator << (T value) { - auto rc = cmd_.bind(idx_, value); - if (rc != SQLITE_OK) { - throw database_error(cmd_.db_); + template bindstream &operator<<(T value) + { + auto rc = cmd_.bind(idx_, value); + if (rc != SQLITE_OK) + { + throw database_error(cmd_.db_); + } + ++idx_; + return *this; } - ++idx_; - return *this; - } - bindstream& operator << (char const* value) { - auto rc = cmd_.bind(idx_, value, copy); - if (rc != SQLITE_OK) { - throw database_error(cmd_.db_); + bindstream &operator<<(char const *value) + { + auto rc = cmd_.bind(idx_, value, copy); + if (rc != SQLITE_OK) + { + throw database_error(cmd_.db_); + } + ++idx_; + return *this; } - ++idx_; - return *this; - } - bindstream& operator << (std::string const& value) { - auto rc = cmd_.bind(idx_, value, copy); - if (rc != SQLITE_OK) { - throw database_error(cmd_.db_); + bindstream &operator<<(std::string const &value) + { + auto rc = cmd_.bind(idx_, value, copy); + if (rc != SQLITE_OK) + { + throw database_error(cmd_.db_); + } + ++idx_; + return *this; } - ++idx_; - return *this; - } - private: - command& cmd_; - int idx_; + private: + command &cmd_; + int idx_; }; - explicit command(database& db, char const* stmt = nullptr); + explicit command(database &db, char const *stmt = nullptr); bindstream binder(int idx = 1); int execute(); int execute_all(); - }; +}; - class query : public statement - { - public: +class query : public statement +{ +public: class rows { - public: - class getstream - { - public: - getstream(rows* rws, int idx); + public: + class getstream + { + public: + getstream(rows *rws, int idx); - template - getstream& operator >> (T& value) { - value = rws_->get(idx_, T()); - ++idx_; - return *this; + template getstream &operator>>(T &value) + { + value = rws_->get(idx_, T()); + ++idx_; + return *this; + } + + private: + rows *rws_; + int idx_; + }; + + explicit rows(sqlite3_stmt *stmt); + + int data_count() const; + int column_type(int idx) const; + + int column_bytes(int idx) const; + + // FIXME: use directly templates + template T get(int idx) const + { + return get(idx, T()); } - private: - rows* rws_; - int idx_; - }; + // FIXME: remove + template + std::tuple get_columns(typename convert::to_int... idxs) const + { + return std::make_tuple(get(idxs, Ts())...); + } - explicit rows(sqlite3_stmt* stmt); + getstream getter(int idx = 0); - int data_count() const; - int column_type(int idx) const; + private: + int get(int idx, int) const; + double get(int idx, double) const; + long long int get(int idx, long long int) const; + char const *get(int idx, char const *) const; + std::string get(int idx, std::string) const; + void const *get(int idx, void const *) const; + null_type get(int idx, null_type) const; - int column_bytes(int idx) const; + inline QString get(int idx, QString) const + { + const int len = sqlite3_column_bytes(stmt_, idx); + const char *text = reinterpret_cast(sqlite3_column_text(stmt_, idx)); + return QString::fromUtf8(text, len); + } - //FIXME: use directly templates - template T get(int idx) const { - return get(idx, T()); - } + inline QTime get(int idx, QTime) const + { + const int msecs = get(idx) * 60000; // Minutes to msecs + return QTime::fromMSecsSinceStartOfDay(msecs); + } - //FIXME: remove - template - std::tuple get_columns(typename convert::to_int... idxs) const { - return std::make_tuple(get(idxs, Ts())...); - } - - getstream getter(int idx = 0); - - private: - int get(int idx, int) const; - double get(int idx, double) const; - long long int get(int idx, long long int) const; - char const* get(int idx, char const*) const; - std::string get(int idx, std::string) const; - void const* get(int idx, void const*) const; - null_type get(int idx, null_type) const; - - inline QString get(int idx, QString) const - { - const int len = sqlite3_column_bytes(stmt_, idx); - const char *text = reinterpret_cast(sqlite3_column_text(stmt_, idx)); - return QString::fromUtf8(text, len); - } - - inline QTime get(int idx, QTime) const - { - const int msecs = get(idx) * 60000; //Minutes to msecs - return QTime::fromMSecsSinceStartOfDay(msecs); - } - - private: - sqlite3_stmt* stmt_; + private: + sqlite3_stmt *stmt_; }; - class query_iterator - : public std::iterator + class query_iterator : public std::iterator { - public: - query_iterator(); - explicit query_iterator(query* cmd); + public: + query_iterator(); + explicit query_iterator(query *cmd); - bool operator==(query_iterator const&) const; - bool operator!=(query_iterator const&) const; + bool operator==(query_iterator const &) const; + bool operator!=(query_iterator const &) const; - query_iterator& operator++(); + query_iterator &operator++(); - value_type operator*() const; + value_type operator*() const; - private: - query* cmd_; - int rc_; + private: + query *cmd_; + int rc_; }; - explicit query(database& db, char const* stmt = nullptr); + explicit query(database &db, char const *stmt = nullptr); int column_count() const; - char const* column_name(int idx) const; - char const* column_decltype(int idx) const; + char const *column_name(int idx) const; + char const *column_decltype(int idx) const; using iterator = query_iterator; @@ -385,21 +397,21 @@ namespace sqlite3pp { return rows(stmt_); } - }; +}; - class transaction : noncopyable - { - public: - explicit transaction(database& db, bool fcommit = false, bool freserve = false); +class transaction : noncopyable +{ +public: + explicit transaction(database &db, bool fcommit = false, bool freserve = false); ~transaction(); int commit(); int rollback(); - private: - database* db_; +private: + database *db_; bool fcommit_; - }; +}; } // namespace sqlite3pp diff --git a/src/sqlite3pp/sqlite3pp.ipp b/src/sqlite3pp/sqlite3pp.ipp index 5bc6e80..66b894f 100644 --- a/src/sqlite3pp/sqlite3pp.ipp +++ b/src/sqlite3pp/sqlite3pp.ipp @@ -25,587 +25,618 @@ #include #include -namespace sqlite3pp +namespace sqlite3pp { + +namespace { +null_type ignore; + +int busy_handler_impl(void *p, int cnt) { + auto h = static_cast(p); + return (*h)(cnt); +} - namespace - { - null_type ignore; +int commit_hook_impl(void *p) +{ + auto h = static_cast(p); + return (*h)(); +} - int busy_handler_impl(void* p, int cnt) +void rollback_hook_impl(void *p) +{ + auto h = static_cast(p); + (*h)(); +} + +void update_hook_impl(void *p, int opcode, char const *dbname, char const *tablename, + long long int rowid) +{ + auto h = static_cast(p); + (*h)(opcode, dbname, tablename, rowid); +} + +int authorizer_impl(void *p, int evcode, char const *p1, char const *p2, char const *dbname, + char const *tvname) +{ + auto h = static_cast(p); + return (*h)(evcode, p1, p2, dbname, tvname); +} + +} // namespace + +inline database::database(char const *dbname, int flags, char const *vfs) : + db_(nullptr) +{ + if (dbname) { - auto h = static_cast(p); - return (*h)(cnt); + auto rc = connect(dbname, flags, vfs); + if (rc != SQLITE_OK) + throw database_error("can't connect database"); } +} - int commit_hook_impl(void* p) - { - auto h = static_cast(p); - return (*h)(); - } - - void rollback_hook_impl(void* p) - { - auto h = static_cast(p); - (*h)(); - } - - void update_hook_impl(void* p, int opcode, char const* dbname, char const* tablename, long long int rowid) - { - auto h = static_cast(p); - (*h)(opcode, dbname, tablename, rowid); - } - - int authorizer_impl(void* p, int evcode, char const* p1, char const* p2, char const* dbname, char const* tvname) - { - auto h = static_cast(p); - return (*h)(evcode, p1, p2, dbname, tvname); - } - - } // namespace - - inline database::database(char const* dbname, int flags, char const* vfs) : db_(nullptr) - { - if (dbname) { - auto rc = connect(dbname, flags, vfs); - if (rc != SQLITE_OK) - throw database_error("can't connect database"); - } - } - - inline database::database(database&& db) : db_(std::move(db.db_)), +inline database::database(database &&db) : + db_(std::move(db.db_)), bh_(std::move(db.bh_)), ch_(std::move(db.ch_)), rh_(std::move(db.rh_)), uh_(std::move(db.uh_)), ah_(std::move(db.ah_)) - { +{ db.db_ = nullptr; - } +} - inline database& database::operator=(database&& db) - { - db_ = std::move(db.db_); +inline database &database::operator=(database &&db) +{ + db_ = std::move(db.db_); db.db_ = nullptr; - bh_ = std::move(db.bh_); - ch_ = std::move(db.ch_); - rh_ = std::move(db.rh_); - uh_ = std::move(db.uh_); - ah_ = std::move(db.ah_); + bh_ = std::move(db.bh_); + ch_ = std::move(db.ch_); + rh_ = std::move(db.rh_); + uh_ = std::move(db.uh_); + ah_ = std::move(db.ah_); return *this; - } +} - inline database::~database() - { +inline database::~database() +{ disconnect(); - } +} - inline int database::connect(char const* dbname, int flags, char const* vfs) - { +inline int database::connect(char const *dbname, int flags, char const *vfs) +{ disconnect(); return sqlite3_open_v2(dbname, &db_, flags, vfs); - } +} - inline int database::disconnect() - { +inline int database::disconnect() +{ auto rc = SQLITE_OK; - if (db_) { - rc = sqlite3_close(db_); - if (rc == SQLITE_OK) { - db_ = nullptr; - } + if (db_) + { + rc = sqlite3_close(db_); + if (rc == SQLITE_OK) + { + db_ = nullptr; + } } return rc; - } +} - inline int database::attach(char const* dbname, char const* name) - { +inline int database::attach(char const *dbname, char const *name) +{ return executef("ATTACH '%q' AS '%q'", dbname, name); - } +} - inline int database::detach(char const* name) - { +inline int database::detach(char const *name) +{ return executef("DETACH '%q'", name); - } +} - inline int database::backup(database& destdb, backup_handler h) - { +inline int database::backup(database &destdb, backup_handler h) +{ return backup("main", destdb, "main", h); - } +} - inline int database::backup(char const* dbname, database& destdb, char const* destdbname, backup_handler h, int step_page) - { - sqlite3_backup* bkup = sqlite3_backup_init(destdb.db_, destdbname, db_, dbname); - if (!bkup) { - return error_code(); +inline int database::backup(char const *dbname, database &destdb, char const *destdbname, + backup_handler h, int step_page) +{ + sqlite3_backup *bkup = sqlite3_backup_init(destdb.db_, destdbname, db_, dbname); + if (!bkup) + { + return error_code(); } auto rc = SQLITE_OK; - do { - rc = sqlite3_backup_step(bkup, step_page); - if (h) { - h(sqlite3_backup_remaining(bkup), sqlite3_backup_pagecount(bkup), rc); - } + do + { + rc = sqlite3_backup_step(bkup, step_page); + if (h) + { + h(sqlite3_backup_remaining(bkup), sqlite3_backup_pagecount(bkup), rc); + } } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED); sqlite3_backup_finish(bkup); return rc; - } +} - inline void database::set_busy_handler(busy_handler h) - { +inline void database::set_busy_handler(busy_handler h) +{ bh_ = h; sqlite3_busy_handler(db_, bh_ ? busy_handler_impl : 0, &bh_); - } +} - inline void database::set_commit_handler(commit_handler h) - { +inline void database::set_commit_handler(commit_handler h) +{ ch_ = h; sqlite3_commit_hook(db_, ch_ ? commit_hook_impl : 0, &ch_); - } +} - inline void database::set_rollback_handler(rollback_handler h) - { +inline void database::set_rollback_handler(rollback_handler h) +{ rh_ = h; sqlite3_rollback_hook(db_, rh_ ? rollback_hook_impl : 0, &rh_); - } +} - inline void database::set_update_handler(update_handler h) - { +inline void database::set_update_handler(update_handler h) +{ uh_ = h; sqlite3_update_hook(db_, uh_ ? update_hook_impl : 0, &uh_); - } +} - inline void database::set_authorize_handler(authorize_handler h) - { +inline void database::set_authorize_handler(authorize_handler h) +{ ah_ = h; sqlite3_set_authorizer(db_, ah_ ? authorizer_impl : 0, &ah_); - } +} - inline long long int database::last_insert_rowid() const - { +inline long long int database::last_insert_rowid() const +{ return sqlite3_last_insert_rowid(db_); - } +} - inline int database::enable_foreign_keys(bool enable) - { +inline int database::enable_foreign_keys(bool enable) +{ return sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_FKEY, enable ? 1 : 0, nullptr); - } +} - inline int database::enable_triggers(bool enable) - { +inline int database::enable_triggers(bool enable) +{ return sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_TRIGGER, enable ? 1 : 0, nullptr); - } +} - inline int database::enable_extended_result_codes(bool enable) - { +inline int database::enable_extended_result_codes(bool enable) +{ return sqlite3_extended_result_codes(db_, enable ? 1 : 0); - } +} - inline int database::changes() const - { +inline int database::changes() const +{ return sqlite3_changes(db_); - } +} - inline int database::error_code() const - { +inline int database::error_code() const +{ return sqlite3_errcode(db_); - } +} - inline int database::extended_error_code() const - { +inline int database::extended_error_code() const +{ return sqlite3_extended_errcode(db_); - } +} - inline char const* database::error_msg() const - { +inline char const *database::error_msg() const +{ return sqlite3_errmsg(db_); - } +} - inline int database::execute(char const* sql) - { +inline int database::execute(char const *sql) +{ return sqlite3_exec(db_, sql, 0, 0, 0); - } +} - inline int database::executef(char const* sql, ...) - { +inline int database::executef(char const *sql, ...) +{ va_list ap; va_start(ap, sql); std::shared_ptr msql(sqlite3_vmprintf(sql, ap), sqlite3_free); va_end(ap); return execute(msql.get()); - } +} - inline int database::set_busy_timeout(int ms) - { +inline int database::set_busy_timeout(int ms) +{ return sqlite3_busy_timeout(db_, ms); - } +} - - inline statement::statement(database& db, char const* stmt) : db_(db), stmt_(0), tail_(0) - { - if (stmt) { - auto rc = prepare(stmt); - if (rc != SQLITE_OK) - throw database_error(db_); +inline statement::statement(database &db, char const *stmt) : + db_(db), + stmt_(0), + tail_(0) +{ + if (stmt) + { + auto rc = prepare(stmt); + if (rc != SQLITE_OK) + throw database_error(db_); } - } +} - inline statement::~statement() - { +inline statement::~statement() +{ // finish() can return error. If you want to check the error, call // finish() explicitly before this object is destructed. finish(); - } +} - inline int statement::prepare(char const* stmt) - { +inline int statement::prepare(char const *stmt) +{ auto rc = finish(); if (rc != SQLITE_OK) - return rc; + return rc; return prepare_impl(stmt); - } +} - inline int statement::prepare_impl(char const* stmt) - { - //return sqlite3_prepare(db_.db_, stmt, std::strlen(stmt), &stmt_, &tail_); -- NOTE: DEPRECATED +inline int statement::prepare_impl(char const *stmt) +{ + // return sqlite3_prepare(db_.db_, stmt, std::strlen(stmt), &stmt_, &tail_); -- NOTE: DEPRECATED return sqlite3_prepare_v2(db_.db_, stmt, std::strlen(stmt), &stmt_, &tail_); - } +} - inline int statement::finish() - { +inline int statement::finish() +{ auto rc = SQLITE_OK; - if (stmt_) { - rc = finish_impl(stmt_); - stmt_ = nullptr; + if (stmt_) + { + rc = finish_impl(stmt_); + stmt_ = nullptr; } tail_ = nullptr; return rc; - } +} - inline int statement::finish_impl(sqlite3_stmt* stmt) - { +inline int statement::finish_impl(sqlite3_stmt *stmt) +{ return sqlite3_finalize(stmt); - } +} - inline int statement::step() - { +inline int statement::step() +{ return sqlite3_step(stmt_); - } +} - inline int statement::reset() - { +inline int statement::reset() +{ return sqlite3_reset(stmt_); - } +} - inline int statement::bind(int idx, int value) - { +inline int statement::bind(int idx, int value) +{ return sqlite3_bind_int(stmt_, idx, value); - } +} - inline int statement::bind(int idx, double value) - { +inline int statement::bind(int idx, double value) +{ return sqlite3_bind_double(stmt_, idx, value); - } +} - inline int statement::bind(int idx, long long int value) - { +inline int statement::bind(int idx, long long int value) +{ return sqlite3_bind_int64(stmt_, idx, value); - } +} - inline int statement::bind(int idx, char const* value, copy_semantic fcopy) - { - return sqlite3_bind_text(stmt_, idx, value, std::strlen(value), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - } +inline int statement::bind(int idx, char const *value, copy_semantic fcopy) +{ + return sqlite3_bind_text(stmt_, idx, value, std::strlen(value), + fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC); +} - inline int statement::bind(int idx, void const* value, int n, copy_semantic fcopy) - { - return sqlite3_bind_blob(stmt_, idx, value, n, fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - } +inline int statement::bind(int idx, void const *value, int n, copy_semantic fcopy) +{ + return sqlite3_bind_blob(stmt_, idx, value, n, + fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC); +} - inline int statement::bind(int idx, std::string const& value, copy_semantic fcopy) - { - return sqlite3_bind_text(stmt_, idx, value.c_str(), value.size(), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - } +inline int statement::bind(int idx, std::string const &value, copy_semantic fcopy) +{ + return sqlite3_bind_text(stmt_, idx, value.c_str(), value.size(), + fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC); +} - inline int statement::bind(int idx) - { +inline int statement::bind(int idx) +{ return sqlite3_bind_null(stmt_, idx); - } +} - inline int statement::bind(int idx, null_type) - { +inline int statement::bind(int idx, null_type) +{ return bind(idx); - } +} - inline int statement::bind(char const* name, int value) - { +inline int statement::bind(char const *name, int value) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value); - } +} - inline int statement::bind(char const* name, double value) - { +inline int statement::bind(char const *name, double value) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value); - } +} - inline int statement::bind(char const* name, long long int value) - { +inline int statement::bind(char const *name, long long int value) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value); - } +} - inline int statement::bind(char const* name, char const* value, copy_semantic fcopy) - { +inline int statement::bind(char const *name, char const *value, copy_semantic fcopy) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value, fcopy); - } +} - inline int statement::bind(char const* name, void const* value, int n, copy_semantic fcopy) - { +inline int statement::bind(char const *name, void const *value, int n, copy_semantic fcopy) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value, n, fcopy); - } +} - inline int statement::bind(char const* name, std::string const& value, copy_semantic fcopy) - { +inline int statement::bind(char const *name, std::string const &value, copy_semantic fcopy) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx, value, fcopy); - } +} - inline int statement::bind(char const* name) - { +inline int statement::bind(char const *name) +{ auto idx = sqlite3_bind_parameter_index(stmt_, name); return bind(idx); - } +} - inline int statement::bind(char const* name, null_type) - { +inline int statement::bind(char const *name, null_type) +{ return bind(name); - } +} +inline command::bindstream::bindstream(command &cmd, int idx) : + cmd_(cmd), + idx_(idx) +{ +} - inline command::bindstream::bindstream(command& cmd, int idx) : cmd_(cmd), idx_(idx) - { - } +inline command::command(database &db, char const *stmt) : + statement(db, stmt) +{ +} - inline command::command(database& db, char const* stmt) : statement(db, stmt) - { - } - - inline command::bindstream command::binder(int idx) - { +inline command::bindstream command::binder(int idx) +{ return bindstream(*this, idx); - } +} - inline int command::execute() - { +inline int command::execute() +{ auto rc = step(); - if (rc == SQLITE_DONE) rc = SQLITE_OK; + if (rc == SQLITE_DONE) + rc = SQLITE_OK; return rc; - } +} - inline int command::execute_all() - { +inline int command::execute_all() +{ auto rc = execute(); - if (rc != SQLITE_OK) return rc; + if (rc != SQLITE_OK) + return rc; - char const* sql = tail_; + char const *sql = tail_; - while (std::strlen(sql) > 0) { // sqlite3_complete() is broken. - sqlite3_stmt* old_stmt = stmt_; + while (std::strlen(sql) > 0) + { // sqlite3_complete() is broken. + sqlite3_stmt *old_stmt = stmt_; - if ((rc = prepare_impl(sql)) != SQLITE_OK) return rc; + if ((rc = prepare_impl(sql)) != SQLITE_OK) + return rc; - if ((rc = sqlite3_transfer_bindings(old_stmt, stmt_)) != SQLITE_OK) return rc; + if ((rc = sqlite3_transfer_bindings(old_stmt, stmt_)) != SQLITE_OK) + return rc; - finish_impl(old_stmt); + finish_impl(old_stmt); - if ((rc = execute()) != SQLITE_OK) return rc; + if ((rc = execute()) != SQLITE_OK) + return rc; - sql = tail_; + sql = tail_; } return rc; - } +} +inline query::rows::getstream::getstream(rows *rws, int idx) : + rws_(rws), + idx_(idx) +{ +} - inline query::rows::getstream::getstream(rows* rws, int idx) : rws_(rws), idx_(idx) - { - } +inline query::rows::rows(sqlite3_stmt *stmt) : + stmt_(stmt) +{ +} - inline query::rows::rows(sqlite3_stmt* stmt) : stmt_(stmt) - { - } - - inline int query::rows::data_count() const - { +inline int query::rows::data_count() const +{ return sqlite3_data_count(stmt_); - } +} - inline int query::rows::column_type(int idx) const - { +inline int query::rows::column_type(int idx) const +{ return sqlite3_column_type(stmt_, idx); - } +} - inline int query::rows::column_bytes(int idx) const - { +inline int query::rows::column_bytes(int idx) const +{ return sqlite3_column_bytes(stmt_, idx); - } +} - inline int query::rows::get(int idx, int) const - { +inline int query::rows::get(int idx, int) const +{ return sqlite3_column_int(stmt_, idx); - } +} - inline double query::rows::get(int idx, double) const - { +inline double query::rows::get(int idx, double) const +{ return sqlite3_column_double(stmt_, idx); - } +} - inline long long int query::rows::get(int idx, long long int) const - { +inline long long int query::rows::get(int idx, long long int) const +{ return sqlite3_column_int64(stmt_, idx); - } +} - inline char const* query::rows::get(int idx, char const*) const - { - return reinterpret_cast(sqlite3_column_text(stmt_, idx)); - } +inline char const *query::rows::get(int idx, char const *) const +{ + return reinterpret_cast(sqlite3_column_text(stmt_, idx)); +} - inline std::string query::rows::get(int idx, std::string) const - { - return get(idx, (char const*)0); - } +inline std::string query::rows::get(int idx, std::string) const +{ + return get(idx, (char const *)0); +} - inline void const* query::rows::get(int idx, void const*) const - { +inline void const *query::rows::get(int idx, void const *) const +{ return sqlite3_column_blob(stmt_, idx); - } +} - inline null_type query::rows::get(int /*idx*/, null_type) const - { +inline null_type query::rows::get(int /*idx*/, null_type) const +{ return ignore; - } - - inline query::rows::getstream query::rows::getter(int idx) - { +} + +inline query::rows::getstream query::rows::getter(int idx) +{ return getstream(this, idx); - } +} - inline query::query_iterator::query_iterator() : cmd_(0) - { +inline query::query_iterator::query_iterator() : + cmd_(0) +{ rc_ = SQLITE_DONE; - } +} - inline query::query_iterator::query_iterator(query* cmd) : cmd_(cmd) - { +inline query::query_iterator::query_iterator(query *cmd) : + cmd_(cmd) +{ rc_ = cmd_->step(); if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE) - throw database_error(cmd_->db_); - } + throw database_error(cmd_->db_); +} - inline bool query::query_iterator::operator==(query::query_iterator const& other) const - { +inline bool query::query_iterator::operator==(query::query_iterator const &other) const +{ return rc_ == other.rc_; - } +} - inline bool query::query_iterator::operator!=(query::query_iterator const& other) const - { +inline bool query::query_iterator::operator!=(query::query_iterator const &other) const +{ return rc_ != other.rc_; - } +} - inline query::query_iterator& query::query_iterator::operator++() - { +inline query::query_iterator &query::query_iterator::operator++() +{ rc_ = cmd_->step(); if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE) - throw database_error(cmd_->db_); + throw database_error(cmd_->db_); return *this; - } +} - inline query::query_iterator::value_type query::query_iterator::operator*() const - { +inline query::query_iterator::value_type query::query_iterator::operator*() const +{ return rows(cmd_->stmt_); - } +} - inline query::query(database& db, char const* stmt) : statement(db, stmt) - { - } +inline query::query(database &db, char const *stmt) : + statement(db, stmt) +{ +} - inline int query::column_count() const - { +inline int query::column_count() const +{ return sqlite3_column_count(stmt_); - } +} - inline char const* query::column_name(int idx) const - { +inline char const *query::column_name(int idx) const +{ return sqlite3_column_name(stmt_, idx); - } +} - inline char const* query::column_decltype(int idx) const - { +inline char const *query::column_decltype(int idx) const +{ return sqlite3_column_decltype(stmt_, idx); - } +} - - inline query::iterator query::begin() - { +inline query::iterator query::begin() +{ return query_iterator(this); - } +} - inline query::iterator query::end() - { +inline query::iterator query::end() +{ return query_iterator(); - } +} - - inline transaction::transaction(database& db, bool fcommit, bool freserve) : db_(&db), fcommit_(fcommit) - { +inline transaction::transaction(database &db, bool fcommit, bool freserve) : + db_(&db), + fcommit_(fcommit) +{ int rc = db_->execute(freserve ? "BEGIN IMMEDIATE" : "BEGIN"); if (rc != SQLITE_OK) - throw database_error(*db_); - } + throw database_error(*db_); +} - inline transaction::~transaction() - { - if (db_) { - // execute() can return error. If you want to check the error, - // call commit() or rollback() explicitly before this object is - // destructed. - db_->execute(fcommit_ ? "COMMIT" : "ROLLBACK"); +inline transaction::~transaction() +{ + if (db_) + { + // execute() can return error. If you want to check the error, + // call commit() or rollback() explicitly before this object is + // destructed. + db_->execute(fcommit_ ? "COMMIT" : "ROLLBACK"); } - } +} - inline int transaction::commit() - { +inline int transaction::commit() +{ auto db = db_; - db_ = nullptr; - int rc = db->execute("COMMIT"); + db_ = nullptr; + int rc = db->execute("COMMIT"); return rc; - } +} - inline int transaction::rollback() - { +inline int transaction::rollback() +{ auto db = db_; - db_ = nullptr; - int rc = db->execute("ROLLBACK"); + db_ = nullptr; + int rc = db->execute("ROLLBACK"); return rc; - } +} +inline database_error::database_error(char const *msg) : + std::runtime_error(msg) +{ +} - inline database_error::database_error(char const* msg) : std::runtime_error(msg) - { - } - - inline database_error::database_error(database& db) : std::runtime_error(sqlite3_errmsg(db.db_)) - { - } +inline database_error::database_error(database &db) : + std::runtime_error(sqlite3_errmsg(db.db_)) +{ +} } // namespace sqlite3pp diff --git a/src/sqlite3pp/sqlite3ppext.h b/src/sqlite3pp/sqlite3ppext.h index 94523d2..966bd6c 100644 --- a/src/sqlite3pp/sqlite3ppext.h +++ b/src/sqlite3pp/sqlite3ppext.h @@ -53,197 +53,189 @@ #include "sqlite3pp.h" -namespace sqlite3pp +namespace sqlite3pp { +namespace { +template struct Apply { - namespace - { - template - struct Apply { - template - static inline auto apply(F&& f, T&& t, A&&... a) - -> decltype(Apply::apply(std::forward(f), - std::forward(t), - std::get(std::forward(t)), - std::forward(a)...)) - { - return Apply::apply(std::forward(f), - std::forward(t), - std::get(std::forward(t)), - std::forward(a)...); - } - }; - - template<> - struct Apply<0> { - template - static inline auto apply(F&& f, T&&, A&&... a) - -> decltype(std::forward(f)(std::forward(a)...)) - { - return std::forward(f)(std::forward(a)...); - } - }; - - template - inline auto apply(F&& f, T&& t) - -> decltype(Apply::type>::value>::apply(std::forward(f), std::forward(t))) + template + static inline auto apply(F &&f, T &&t, A &&...a) + -> decltype(Apply::apply(std::forward(f), std::forward(t), + std::get(std::forward(t)), std::forward(a)...)) { - return Apply::type>::value>::apply( - std::forward(f), std::forward(t)); + return Apply::apply(std::forward(f), std::forward(t), + std::get(std::forward(t)), std::forward(a)...); } - } +}; - - namespace ext - { - - class context : noncopyable +template <> struct Apply<0> +{ + template + static inline auto apply(F &&f, T &&, A &&...a) + -> decltype(std::forward(f)(std::forward(a)...)) { - public: - explicit context(sqlite3_context* ctx, int nargs = 0, sqlite3_value** values = nullptr); + return std::forward(f)(std::forward(a)...); + } +}; - int args_count() const; - int args_bytes(int idx) const; - int args_type(int idx) const; +template +inline auto apply(F &&f, T &&t) + -> decltype(Apply::type>::value>::apply( + std::forward(f), std::forward(t))) +{ + return Apply::type>::value>::apply(std::forward(f), + std::forward(t)); +} +} // namespace - template T get(int idx) const { +namespace ext { + +class context : noncopyable +{ +public: + explicit context(sqlite3_context *ctx, int nargs = 0, sqlite3_value **values = nullptr); + + int args_count() const; + int args_bytes(int idx) const; + int args_type(int idx) const; + + template T get(int idx) const + { return get(idx, T()); - } + } - void result(int value); - void result(double value); - void result(long long int value); - void result(std::string const& value); - void result(char const* value, bool fcopy); - void result(void const* value, int n, bool fcopy); - void result(); - void result(null_type); - void result_copy(int idx); - void result_error(char const* msg); + void result(int value); + void result(double value); + void result(long long int value); + void result(std::string const &value); + void result(char const *value, bool fcopy); + void result(void const *value, int n, bool fcopy); + void result(); + void result(null_type); + void result_copy(int idx); + void result_error(char const *msg); - void* aggregate_data(int size); - int aggregate_count(); + void *aggregate_data(int size); + int aggregate_count(); - template - std::tuple to_tuple() { + template std::tuple to_tuple() + { return to_tuple_impl(0, *this, std::tuple()); - } + } - private: - int get(int idx, int) const; - double get(int idx, double) const; - long long int get(int idx, long long int) const; - char const* get(int idx, char const*) const; - std::string get(int idx, std::string) const; - void const* get(int idx, void const*) const; +private: + int get(int idx, int) const; + double get(int idx, double) const; + long long int get(int idx, long long int) const; + char const *get(int idx, char const *) const; + std::string get(int idx, std::string) const; + void const *get(int idx, void const *) const; - template - static inline std::tuple to_tuple_impl(int index, const context& c, std::tuple&&) - { + template + static inline std::tuple to_tuple_impl(int index, const context &c, + std::tuple &&) + { auto h = std::make_tuple(c.context::get(index)); return std::tuple_cat(h, to_tuple_impl(++index, c, std::tuple())); - } - static inline std::tuple<> to_tuple_impl(int /*index*/, const context& /*c*/, std::tuple<>&&) - { - return std::tuple<>(); - } - - private: - sqlite3_context* ctx_; - int nargs_; - sqlite3_value** values_; - }; - - namespace + } + static inline std::tuple<> to_tuple_impl(int /*index*/, const context & /*c*/, std::tuple<> &&) { - template - void functionx_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values) - { - context c(ctx, nargs, values); - auto f = static_cast*>(sqlite3_user_data(ctx)); - c.result(apply(*f, c.to_tuple())); - } + return std::tuple<>(); } - class function : noncopyable +private: + sqlite3_context *ctx_; + int nargs_; + sqlite3_value **values_; +}; + +namespace { +template +void functionx_impl(sqlite3_context *ctx, int nargs, sqlite3_value **values) +{ + context c(ctx, nargs, values); + auto f = static_cast *>(sqlite3_user_data(ctx)); + c.result(apply(*f, c.to_tuple())); +} +} // namespace + +class function : noncopyable +{ +public: + using function_handler = std::function; + using pfunction_base = std::shared_ptr; + + explicit function(database &db); + + int create(char const *name, function_handler h, int nargs = 0); + + template int create(char const *name, std::function h) { - public: - using function_handler = std::function; - using pfunction_base = std::shared_ptr; - - explicit function(database& db); - - int create(char const* name, function_handler h, int nargs = 0); - - template int create(char const* name, std::function h) { fh_[name] = std::shared_ptr(new std::function(h)); return create_function_impl()(db_, fh_[name].get(), name); - } - - private: - - template - struct create_function_impl; - - template - struct create_function_impl - { - int operator()(sqlite3* db, void* fh, char const* name) { - return sqlite3_create_function(db, name, sizeof...(Ps), SQLITE_UTF8, fh, - functionx_impl, - 0, 0); - } - }; - - private: - sqlite3* db_; - - std::map fh_; - }; - - namespace - { - template - void stepx_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values) - { - context c(ctx, nargs, values); - T* t = static_cast(c.aggregate_data(sizeof(T))); - if (c.aggregate_count() == 1) new (t) T; - apply([](T* tt, Ps... ps){tt->step(ps...);}, - std::tuple_cat(std::make_tuple(t), c.to_tuple())); - } - - template - void finishN_impl(sqlite3_context* ctx) - { - context c(ctx); - T* t = static_cast(c.aggregate_data(sizeof(T))); - c.result(t->finish()); - t->~T(); - } } - class aggregate : noncopyable +private: + template struct create_function_impl; + + template struct create_function_impl { - public: - using function_handler = std::function; - using pfunction_base = std::shared_ptr; - - explicit aggregate(database& db); - - int create(char const* name, function_handler s, function_handler f, int nargs = 1); - - template - int create(char const* name) { - return sqlite3_create_function(db_, name, sizeof...(Ps), SQLITE_UTF8, 0, 0, stepx_impl, finishN_impl); - } - - private: - sqlite3* db_; - - std::map > ah_; + int operator()(sqlite3 *db, void *fh, char const *name) + { + return sqlite3_create_function(db, name, sizeof...(Ps), SQLITE_UTF8, fh, + functionx_impl, 0, 0); + } }; - } // namespace ext +private: + sqlite3 *db_; + + std::map fh_; +}; + +namespace { +template +void stepx_impl(sqlite3_context *ctx, int nargs, sqlite3_value **values) +{ + context c(ctx, nargs, values); + T *t = static_cast(c.aggregate_data(sizeof(T))); + if (c.aggregate_count() == 1) + new (t) T; + apply([](T *tt, Ps... ps) { tt->step(ps...); }, + std::tuple_cat(std::make_tuple(t), c.to_tuple())); +} + +template void finishN_impl(sqlite3_context *ctx) +{ + context c(ctx); + T *t = static_cast(c.aggregate_data(sizeof(T))); + c.result(t->finish()); + t->~T(); +} +} // namespace + +class aggregate : noncopyable +{ +public: + using function_handler = std::function; + using pfunction_base = std::shared_ptr; + + explicit aggregate(database &db); + + int create(char const *name, function_handler s, function_handler f, int nargs = 1); + + template int create(char const *name) + { + return sqlite3_create_function(db_, name, sizeof...(Ps), SQLITE_UTF8, 0, 0, + stepx_impl, finishN_impl); + } + +private: + sqlite3 *db_; + + std::map> ah_; +}; + +} // namespace ext } // namespace sqlite3pp diff --git a/src/sqlite3pp/sqlite3ppext.ipp b/src/sqlite3pp/sqlite3ppext.ipp index 2b683bc..c85e2bb 100644 --- a/src/sqlite3pp/sqlite3ppext.ipp +++ b/src/sqlite3pp/sqlite3ppext.ipp @@ -24,172 +24,175 @@ #include -namespace sqlite3pp +namespace sqlite3pp { +namespace ext { + +namespace { + +void function_impl(sqlite3_context *ctx, int nargs, sqlite3_value **values) { - namespace ext - { + auto f = static_cast(sqlite3_user_data(ctx)); + context c(ctx, nargs, values); + (*f)(c); +} - namespace - { +void step_impl(sqlite3_context *ctx, int nargs, sqlite3_value **values) +{ + auto p = static_cast *>( + sqlite3_user_data(ctx)); + auto s = static_cast((*p).first.get()); + context c(ctx, nargs, values); + ((function::function_handler &)*s)(c); +} - void function_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values) - { - auto f = static_cast(sqlite3_user_data(ctx)); - context c(ctx, nargs, values); - (*f)(c); - } +void finalize_impl(sqlite3_context *ctx) +{ + auto p = static_cast *>( + sqlite3_user_data(ctx)); + auto f = static_cast((*p).second.get()); + context c(ctx); + ((function::function_handler &)*f)(c); +} - void step_impl(sqlite3_context* ctx, int nargs, sqlite3_value** values) - { - auto p = static_cast*>(sqlite3_user_data(ctx)); - auto s = static_cast((*p).first.get()); - context c(ctx, nargs, values); - ((function::function_handler&)*s)(c); - } +} // namespace - void finalize_impl(sqlite3_context* ctx) - { - auto p = static_cast*>(sqlite3_user_data(ctx)); - auto f = static_cast((*p).second.get()); - context c(ctx); - ((function::function_handler&)*f)(c); - } +inline context::context(sqlite3_context *ctx, int nargs, sqlite3_value **values) : + ctx_(ctx), + nargs_(nargs), + values_(values) +{ +} - } // namespace +inline int context::args_count() const +{ + return nargs_; +} +inline int context::args_bytes(int idx) const +{ + return sqlite3_value_bytes(values_[idx]); +} - inline context::context(sqlite3_context* ctx, int nargs, sqlite3_value** values) - : ctx_(ctx), nargs_(nargs), values_(values) - { - } +inline int context::args_type(int idx) const +{ + return sqlite3_value_type(values_[idx]); +} - inline int context::args_count() const - { - return nargs_; - } +inline int context::get(int idx, int) const +{ + return sqlite3_value_int(values_[idx]); +} - inline int context::args_bytes(int idx) const - { - return sqlite3_value_bytes(values_[idx]); - } +inline double context::get(int idx, double) const +{ + return sqlite3_value_double(values_[idx]); +} - inline int context::args_type(int idx) const - { - return sqlite3_value_type(values_[idx]); - } +inline long long int context::get(int idx, long long int) const +{ + return sqlite3_value_int64(values_[idx]); +} - inline int context::get(int idx, int) const - { - return sqlite3_value_int(values_[idx]); - } +inline char const *context::get(int idx, char const *) const +{ + return reinterpret_cast(sqlite3_value_text(values_[idx])); +} - inline double context::get(int idx, double) const - { - return sqlite3_value_double(values_[idx]); - } +inline std::string context::get(int idx, std::string) const +{ + return get(idx, (char const *)0); +} - inline long long int context::get(int idx, long long int) const - { - return sqlite3_value_int64(values_[idx]); - } +inline void const *context::get(int idx, void const *) const +{ + return sqlite3_value_blob(values_[idx]); +} - inline char const* context::get(int idx, char const*) const - { - return reinterpret_cast(sqlite3_value_text(values_[idx])); - } +inline void context::result(int value) +{ + sqlite3_result_int(ctx_, value); +} - inline std::string context::get(int idx, std::string) const - { - return get(idx, (char const*)0); - } +inline void context::result(double value) +{ + sqlite3_result_double(ctx_, value); +} - inline void const* context::get(int idx, void const*) const - { - return sqlite3_value_blob(values_[idx]); - } +inline void context::result(long long int value) +{ + sqlite3_result_int64(ctx_, value); +} +inline void context::result(std::string const &value) +{ + result(value.c_str(), false); +} +inline void context::result(char const *value, bool fcopy) +{ + sqlite3_result_text(ctx_, value, std::strlen(value), fcopy ? SQLITE_TRANSIENT : SQLITE_STATIC); +} - inline void context::result(int value) - { - sqlite3_result_int(ctx_, value); - } +inline void context::result(void const *value, int n, bool fcopy) +{ + sqlite3_result_blob(ctx_, value, n, fcopy ? SQLITE_TRANSIENT : SQLITE_STATIC); +} - inline void context::result(double value) - { - sqlite3_result_double(ctx_, value); - } +inline void context::result() +{ + sqlite3_result_null(ctx_); +} - inline void context::result(long long int value) - { - sqlite3_result_int64(ctx_, value); - } +inline void context::result(null_type) +{ + sqlite3_result_null(ctx_); +} - inline void context::result(std::string const& value) - { - result(value.c_str(), false); - } +inline void context::result_copy(int idx) +{ + sqlite3_result_value(ctx_, values_[idx]); +} - inline void context::result(char const* value, bool fcopy) - { - sqlite3_result_text(ctx_, value, std::strlen(value), fcopy ? SQLITE_TRANSIENT : SQLITE_STATIC); - } +inline void context::result_error(char const *msg) +{ + sqlite3_result_error(ctx_, msg, std::strlen(msg)); +} - inline void context::result(void const* value, int n, bool fcopy) - { - sqlite3_result_blob(ctx_, value, n, fcopy ? SQLITE_TRANSIENT : SQLITE_STATIC ); - } +inline void *context::aggregate_data(int size) +{ + return sqlite3_aggregate_context(ctx_, size); +} - inline void context::result() - { - sqlite3_result_null(ctx_); - } +inline int context::aggregate_count() +{ + return sqlite3_aggregate_count(ctx_); +} - inline void context::result(null_type) - { - sqlite3_result_null(ctx_); - } +inline function::function(database &db) : + db_(db.db_) +{ +} - inline void context::result_copy(int idx) - { - sqlite3_result_value(ctx_, values_[idx]); - } +inline int function::create(char const *name, function_handler h, int nargs) +{ + fh_[name] = pfunction_base(new function_handler(h)); + return sqlite3_create_function(db_, name, nargs, SQLITE_UTF8, fh_[name].get(), function_impl, 0, + 0); +} - inline void context::result_error(char const* msg) - { - sqlite3_result_error(ctx_, msg, std::strlen(msg)); - } +inline aggregate::aggregate(database &db) : + db_(db.db_) +{ +} - inline void* context::aggregate_data(int size) - { - return sqlite3_aggregate_context(ctx_, size); - } +inline int aggregate::create(char const *name, function_handler s, function_handler f, int nargs) +{ + ah_[name] = std::make_pair(pfunction_base(new function_handler(s)), + pfunction_base(new function_handler(f))); + return sqlite3_create_function(db_, name, nargs, SQLITE_UTF8, &ah_[name], 0, step_impl, + finalize_impl); +} - inline int context::aggregate_count() - { - return sqlite3_aggregate_count(ctx_); - } - - inline function::function(database& db) : db_(db.db_) - { - } - - inline int function::create(char const* name, function_handler h, int nargs) - { - fh_[name] = pfunction_base(new function_handler(h)); - return sqlite3_create_function(db_, name, nargs, SQLITE_UTF8, fh_[name].get(), function_impl, 0, 0); - } - - inline aggregate::aggregate(database& db) : db_(db.db_) - { - } - - inline int aggregate::create(char const* name, function_handler s, function_handler f, int nargs) - { - ah_[name] = std::make_pair(pfunction_base(new function_handler(s)), pfunction_base(new function_handler(f))); - return sqlite3_create_function(db_, name, nargs, SQLITE_UTF8, &ah_[name], 0, step_impl, finalize_impl); - } - - } // namespace ext +} // namespace ext } // namespace sqlite3pp diff --git a/src/stations/importer/model/importstationmodel.cpp b/src/stations/importer/model/importstationmodel.cpp index 42add1f..58b174d 100644 --- a/src/stations/importer/model/importstationmodel.cpp +++ b/src/stations/importer/model/importstationmodel.cpp @@ -36,7 +36,7 @@ ImportStationModel::ImportStationModel(sqlite3pp::database &db, QObject *parent) QVariant ImportStationModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -64,7 +64,7 @@ QVariant ImportStationModel::headerData(int section, Qt::Orientation orientation } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -78,16 +78,16 @@ QVariant ImportStationModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -125,7 +125,7 @@ QVariant ImportStationModel::data(const QModelIndex &idx, int role) const qint64 ImportStationModel::recalcTotalItemCount() { QByteArray sql = "SELECT COUNT(id) FROM stations"; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { sql += " WHERE name LIKE ?1 OR short_name LIKE ?1"; } @@ -133,7 +133,7 @@ qint64 ImportStationModel::recalcTotalItemCount() query q(mDb, sql); QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -150,14 +150,14 @@ qint64 ImportStationModel::recalcTotalItemCount() void ImportStationModel::setSortingColumn(int col) { - if(sortColumn == col || (col != NameCol && col != TypeCol)) + if (sortColumn == col || (col != NameCol && col != TypeCol)) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -180,8 +180,8 @@ bool ImportStationModel::setFilterAtCol(int col, const QString &str) { case NameCol: { - if(isNull) - return false; //Cannot have NULL Name + if (isNull) + return false; // Cannot have NULL Name m_nameFilter = str; break; } @@ -197,25 +197,26 @@ void ImportStationModel::internalFetch(int first, int sortCol, int valRow, const { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT id,name,short_name,type FROM stations"; + QByteArray sql = "SELECT id,name,short_name,type FROM stations"; switch (sortCol) { case NameCol: { - whereCol = "name"; //Order by 1 column, no where clause + whereCol = "name"; // Order by 1 column, no where clause break; } case TypeCol: @@ -225,7 +226,7 @@ void ImportStationModel::internalFetch(int first, int sortCol, int valRow, const } } - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { sql += " WHERE name LIKE ?3 OR short_name LIKE ?3"; } @@ -233,20 +234,20 @@ void ImportStationModel::internalFetch(int first, int sortCol, int valRow, const sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -270,27 +271,27 @@ void ImportStationModel::internalFetch(int first, int sortCol, int valRow, const QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = reverse ? BatchSize - 1 : 0; + int i = reverse ? BatchSize - 1 : 0; const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; + auto r = *it; StationItem &item = vec[i]; - item.stationId = r.get(0); - item.name = r.get(1); - item.shortName = r.get(2); - item.type = utils::StationType(r.get(3)); + item.stationId = r.get(0); + item.name = r.get(1); + item.shortName = r.get(2); + item.type = utils::StationType(r.get(3)); i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/stations/importer/model/importstationmodel.h b/src/stations/importer/model/importstationmodel.h index 01c6cda..e860943 100644 --- a/src/stations/importer/model/importstationmodel.h +++ b/src/stations/importer/model/importstationmodel.h @@ -38,10 +38,13 @@ class ImportStationModel : public IPagedItemModelImpl getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // Convinience inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); return item.stationId; } inline QString getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QString(); //Invalid + return QString(); // Invalid - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); return item.name; } diff --git a/src/stations/importer/pages/selectstationpage.cpp b/src/stations/importer/pages/selectstationpage.cpp index 5257926..d679286 100644 --- a/src/stations/importer/pages/selectstationpage.cpp +++ b/src/stations/importer/pages/selectstationpage.cpp @@ -36,7 +36,6 @@ #include "utils/delegates/sql/modelpageswitcher.h" #include "stations/importer/model/importstationmodel.h" - SelectStationPage::SelectStationPage(StationImportWizard *w) : QWizardPage(w), mWizard(w), @@ -44,13 +43,13 @@ SelectStationPage::SelectStationPage(StationImportWizard *w) : { QVBoxLayout *lay = new QVBoxLayout(this); - toolBar = new QToolBar; + toolBar = new QToolBar; lay->addWidget(toolBar); view = new QTableView; lay->addWidget(view); - //Custom colun sorting and filtering + // Custom colun sorting and filtering FilterHeaderView *header = new FilterHeaderView(view); header->installOnTable(view); @@ -58,7 +57,8 @@ SelectStationPage::SelectStationPage(StationImportWizard *w) : lay->addWidget(pageSwitcher); actOpenStDlg = toolBar->addAction(tr("View Info"), this, &SelectStationPage::openStationDlg); - actOpenSVGPlan = toolBar->addAction(tr("SVG Plan"), this, &SelectStationPage::openStationSVGPlan); + actOpenSVGPlan = + toolBar->addAction(tr("SVG Plan"), this, &SelectStationPage::openStationSVGPlan); toolBar->addSeparator(); actImportSt = toolBar->addAction(tr("Import"), this, &SelectStationPage::importSelectedStation); } @@ -69,7 +69,7 @@ void SelectStationPage::setupModel(ImportStationModel *m) view->setModel(stationsModel); pageSwitcher->setModel(stationsModel); - //Refresh model + // Refresh model stationsModel->refreshData(true); } @@ -78,7 +78,7 @@ void SelectStationPage::finalizeModel() view->setModel(nullptr); pageSwitcher->setModel(nullptr); - if(stationsModel) + if (stationsModel) { delete stationsModel; stationsModel = nullptr; @@ -87,15 +87,15 @@ void SelectStationPage::finalizeModel() void SelectStationPage::openStationDlg() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); db_id stationId = stationsModel->getIdAtRow(idx.row()); - if(!stationId) + if (!stationId) return; - const QString stName = stationsModel->getNameAtRow(idx.row()); + const QString stName = stationsModel->getNameAtRow(idx.row()); OwningQPointer dlg = new StationEditDialog(*mWizard->getTempDB(), this); dlg->setStationExternalEditingEnabled(false); @@ -109,25 +109,25 @@ void SelectStationPage::openStationDlg() void SelectStationPage::openStationSVGPlan() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); db_id stationId = stationsModel->getIdAtRow(idx.row()); - if(!stationId) + if (!stationId) return; const QString stName = stationsModel->getNameAtRow(idx.row()); std::unique_ptr dev; dev.reset(StationSVGHelper::loadImage(*mWizard->getTempDB(), stationId)); - if(!dev || !dev->open(QIODevice::ReadOnly)) + if (!dev || !dev->open(QIODevice::ReadOnly)) return; OwningQPointer dlg = new QDialog(this); - QVBoxLayout *lay = new QVBoxLayout(dlg); + QVBoxLayout *lay = new QVBoxLayout(dlg); - StationSVGPlanDlg *svg = new StationSVGPlanDlg(*mWizard->getTempDB(), this); + StationSVGPlanDlg *svg = new StationSVGPlanDlg(*mWizard->getTempDB(), this); lay->addWidget(svg); svg->reloadSVG(dev.get()); @@ -139,65 +139,66 @@ void SelectStationPage::openStationSVGPlan() void SelectStationPage::importSelectedStation() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); db_id stationId = stationsModel->getIdAtRow(idx.row()); - if(!stationId) + if (!stationId) return; const QString stName = stationsModel->getNameAtRow(idx.row()); - //Allow changing name + // Allow changing name OwningQPointer dlg = new QInputDialog(this); dlg->setWindowTitle(tr("Import Station")); dlg->setLabelText(tr("Please choose a name for the new station.")); - dlg->setTextValue(stName); //Initial value to original name + dlg->setTextValue(stName); // Initial value to original name - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Station name cannot be empty.")); - continue; //Second chance + continue; // Second chance } QString shortName; - if(!mWizard->checkNames(stationId, name, shortName)) + if (!mWizard->checkNames(stationId, name, shortName)) { - QMessageBox::warning(this, tr("Name Already Exists"), - tr("Station name %1 (%2) already exists in current session.
" - "Please choose a different name.") - .arg(name, shortName)); - continue; //Second chance + QMessageBox::warning( + this, tr("Name Already Exists"), + tr("Station name %1 (%2) already exists in current session.
" + "Please choose a different name.") + .arg(name, shortName)); + continue; // Second chance } - if(!mWizard->addStation(stationId, name, shortName)) + if (!mWizard->addStation(stationId, name, shortName)) { QMessageBox::warning(this, tr("Import Error"), tr("Could not import station %1.").arg(name)); - continue; //Second chance + continue; // Second chance } - //Done! + // Done! QMessageBox::information(this, tr("Importation Done"), tr("Station succesfully imported in current session:
" "Name: %1
" "Short: %2
" "You can now select another station to import.") - .arg(name, shortName)); + .arg(name, shortName)); break; - } - while (true); + } while (true); - //Reset selection + // Reset selection view->clearSelection(); } diff --git a/src/stations/importer/stationimportwizard.cpp b/src/stations/importer/stationimportwizard.cpp index 4cc52d5..ed336ba 100644 --- a/src/stations/importer/stationimportwizard.cpp +++ b/src/stations/importer/stationimportwizard.cpp @@ -44,7 +44,7 @@ StationImportWizard::StationImportWizard(QWidget *parent) : fileFormats << FileFormats::tr(FileFormats::sqliteFormat); fileFormats << FileFormats::tr(FileFormats::allFiles); - //Setup Pages + // Setup Pages QWizardPage *optionsPage = new QWizardPage; optionsPage->setTitle(tr("Import Stations")); optionsPage->setSubTitle(tr("Follow the steps to import stations")); @@ -57,7 +57,6 @@ StationImportWizard::StationImportWizard(QWidget *parent) : setPage(ChooseFileIdx, chooseFilePage); setPage(SelectStationIdx, new SelectStationPage(this)); - setWindowTitle(tr("Import Stations")); resize(700, 500); } @@ -66,7 +65,7 @@ StationImportWizard::~StationImportWizard() { closeDatabase(); - if(mTempDB) + if (mTempDB) { delete mTempDB; mTempDB = nullptr; @@ -84,15 +83,15 @@ bool StationImportWizard::createDatabase(bool inMemory, const QString &fileName) SelectStationPage *p = static_cast(page(SelectStationIdx)); - int flags = SQLITE_OPEN_READWRITE; - if(inMemory) + int flags = SQLITE_OPEN_READWRITE; + if (inMemory) flags |= SQLITE_OPEN_MEMORY; int ret = mTempDB->connect(fileName.toUtf8(), flags); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; - mInMemory = inMemory; + mInMemory = inMemory; ImportStationModel *m = new ImportStationModel(*mTempDB, this); p->setupModel(m); @@ -101,7 +100,7 @@ bool StationImportWizard::createDatabase(bool inMemory, const QString &fileName) bool StationImportWizard::closeDatabase() { - if(!mTempDB) + if (!mTempDB) return true; SelectStationPage *p = static_cast(page(SelectStationIdx)); @@ -110,9 +109,10 @@ bool StationImportWizard::closeDatabase() return mTempDB->disconnect() == SQLITE_OK; } -bool StationImportWizard::checkNames(db_id sourceStId, const QString &newName, QString &outShortName) +bool StationImportWizard::checkNames(db_id sourceStId, const QString &newName, + QString &outShortName) { - if(!mTempDB || !mTempDB->db()) + if (!mTempDB || !mTempDB->db()) return false; database &destDB = Session->m_Db; @@ -120,37 +120,38 @@ bool StationImportWizard::checkNames(db_id sourceStId, const QString &newName, Q query q(*mTempDB, "SELECT name, short_name FROM stations WHERE id=?"); q.bind(1, sourceStId); int ret = q.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) return false; auto sourceSt = q.getRows(); - QString name = sourceSt.get(0); - outShortName = sourceSt.get(1); + QString name = sourceSt.get(0); + outShortName = sourceSt.get(1); q.finish(); - if(!newName.isEmpty()) - name = newName; //Override name + if (!newName.isEmpty()) + name = newName; // Override name query q_nameExists(destDB, "SELECT id FROM stations WHERE name=?1 OR short_name=?1 LIMIT 1"); q_nameExists.bind(1, name); - if(q_nameExists.step() == SQLITE_ROW) - return false; //Name exists + if (q_nameExists.step() == SQLITE_ROW) + return false; // Name exists - if(!outShortName.isEmpty()) + if (!outShortName.isEmpty()) { q_nameExists.reset(); q_nameExists.bind(1, outShortName); - if(q_nameExists.step() == SQLITE_ROW) - outShortName.clear(); //Name exists, remove short name + if (q_nameExists.step() == SQLITE_ROW) + outShortName.clear(); // Name exists, remove short name } q_nameExists.finish(); return true; } -bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, const QString& shortName) +bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, + const QString &shortName) { - if(!mTempDB || !mTempDB->db()) + if (!mTempDB || !mTempDB->db()) return false; database &destDB = Session->m_Db; @@ -158,7 +159,7 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, query q(*mTempDB, "SELECT type FROM stations WHERE id=?"); q.bind(1, sourceStId); int ret = q.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) return false; utils::StationType type = utils::StationType(q.getRows().get(0)); @@ -166,20 +167,20 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, transaction stTranaction(destDB); - //Insert station - //NOTE: do not import phone number as it's UNIQUE for our session so it may already exist for a different station - //Set phone number to NULL, it can be set by the user afterwards if needed + // Insert station + // NOTE: do not import phone number as it's UNIQUE for our session so it may already exist for a + // different station Set phone number to NULL, it can be set by the user afterwards if needed command cmd(destDB, "INSERT INTO stations(id,name,short_name,type,phone_number,svg_data)" "VALUES(NULL,?,?,?,?,NULL)"); cmd.bind(1, fullName); - if(shortName.isEmpty()) - cmd.bind(2); //Bind NULL + if (shortName.isEmpty()) + cmd.bind(2); // Bind NULL else cmd.bind(2, shortName); cmd.bind(3, int(type)); - cmd.bind(4); //Bind NULL phone number + cmd.bind(4); // Bind NULL phone number ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) return false; db_id destStId = destDB.last_insert_rowid(); @@ -187,28 +188,29 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, QHash gateMapping; QHash trackMapping; - //Copy tracks + // Copy tracks const QRgb whiteColor = qRgb(255, 255, 255); cmd.prepare("INSERT INTO station_tracks(id,station_id,pos,type," "track_length_cm,platf_length_cm,freight_length_cm, max_axes,color_rgb,name)" "VALUES(NULL,?,?,?, ?,?,?, ?,?,?)"); q.prepare("SELECT id,pos,type," - "track_length_cm,platf_length_cm,freight_length_cm, max_axes,color_rgb,name FROM station_tracks" + "track_length_cm,platf_length_cm,freight_length_cm, max_axes,color_rgb,name FROM " + "station_tracks" " WHERE station_id=? ORDER BY pos ASC"); q.bind(1, sourceStId); - for(auto track : q) + for (auto track : q) { - db_id sourceTrackId = track.get(0); - int pos = track.get(1); + db_id sourceTrackId = track.get(0); + int pos = track.get(1); utils::StationTrackType trackType = utils::StationTrackType(track.get(2)); - int trackLength_cm = track.get(3); - int platfLength_cm = track.get(4); - int freightLength_cm = track.get(5); - int maxAxes = track.get(6); + int trackLength_cm = track.get(3); + int platfLength_cm = track.get(4); + int freightLength_cm = track.get(5); + int maxAxes = track.get(6); - QRgb colorRGB = whiteColor; - if(track.column_type(7) != SQLITE_NULL) + QRgb colorRGB = whiteColor; + if (track.column_type(7) != SQLITE_NULL) colorRGB = QRgb(track.get(7)); QString trackName = track.get(8); @@ -221,57 +223,58 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, cmd.bind(6, freightLength_cm); cmd.bind(7, maxAxes); - if(colorRGB == whiteColor) - cmd.bind(8); //Bind NULL + if (colorRGB == whiteColor) + cmd.bind(8); // Bind NULL else cmd.bind(8, int(colorRGB)); cmd.bind(9, trackName); - ret = cmd.execute(); + ret = cmd.execute(); db_id destTrackId = destDB.last_insert_rowid(); cmd.reset(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) trackMapping.insert(sourceTrackId, destTrackId); } - //Copy gates - cmd.prepare("INSERT INTO station_gates(id,station_id,out_track_count,type,def_in_platf_id,name,side)" - "VALUES(NULL,?,?,?,?,?,?)"); + // Copy gates + cmd.prepare( + "INSERT INTO station_gates(id,station_id,out_track_count,type,def_in_platf_id,name,side)" + "VALUES(NULL,?,?,?,?,?,?)"); q.prepare("SELECT id,out_track_count,type,def_in_platf_id,name,side FROM station_gates" " WHERE station_id=? ORDER BY name ASC"); q.bind(1, sourceStId); - for(auto gate : q) + for (auto gate : q) { - db_id sourceGateId = gate.get(0); - int outTrkCount = gate.get(1); + db_id sourceGateId = gate.get(0); + int outTrkCount = gate.get(1); utils::GateType gateType = utils::GateType(gate.get(2)); - db_id defPlatfId = gate.get(3); - QString gateName = gate.get(4); - utils::Side side = utils::Side(gate.get(5)); + db_id defPlatfId = gate.get(3); + QString gateName = gate.get(4); + utils::Side side = utils::Side(gate.get(5)); - //Map track ID if not NULL - if(defPlatfId) + // Map track ID if not NULL + if (defPlatfId) defPlatfId = trackMapping.value(defPlatfId, 0); cmd.bind(1, destStId); cmd.bind(2, outTrkCount); cmd.bind(3, int(gateType)); - if(defPlatfId) + if (defPlatfId) cmd.bind(4, defPlatfId); else - cmd.bind(4); //Bind NULL + cmd.bind(4); // Bind NULL cmd.bind(5, gateName); cmd.bind(6, int(side)); - ret = cmd.execute(); + ret = cmd.execute(); db_id destGateId = destDB.last_insert_rowid(); cmd.reset(); - if(ret == SQLITE_OK) + if (ret == SQLITE_OK) gateMapping.insert(sourceGateId, destGateId); } - //Copy Gate connections + // Copy Gate connections cmd.prepare("INSERT INTO station_gate_connections(id,track_id,track_side,gate_id,gate_track)" "VALUES(NULL,?,?,?,?)"); q.prepare("SELECT c.track_id, c.track_side, c.gate_id, c.gate_track" @@ -279,19 +282,19 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, " JOIN station_gates g ON g.id=c.gate_id" " WHERE g.station_id=?"); q.bind(1, sourceStId); - for(auto conn : q) + for (auto conn : q) { - db_id trackId = conn.get(0); + db_id trackId = conn.get(0); utils::Side trackSide = utils::Side(conn.get(1)); - db_id gateId = conn.get(2); - int gateTrk = conn.get(3); + db_id gateId = conn.get(2); + int gateTrk = conn.get(3); - //Map track and gate ID + // Map track and gate ID trackId = trackMapping.value(trackId, 0); - gateId = gateMapping.value(gateId, 0); + gateId = gateMapping.value(gateId, 0); - if(!trackId || !gateId) - continue; //Error: could not map IDs, skip item + if (!trackId || !gateId) + continue; // Error: could not map IDs, skip item cmd.bind(1, trackId); cmd.bind(2, int(trackSide)); @@ -301,7 +304,7 @@ bool StationImportWizard::addStation(db_id sourceStId, const QString &fullName, cmd.reset(); } - //Copy SVG blob + // Copy SVG blob copySVGData(sourceStId, destStId); stTranaction.commit(); @@ -312,7 +315,7 @@ struct SQLiteBlobDeleter { static inline void cleanup(sqlite3_blob *pointer) { - if(pointer) + if (pointer) sqlite3_blob_close(pointer); } }; @@ -321,77 +324,82 @@ bool StationImportWizard::copySVGData(db_id sourceStId, db_id destStId) { database &destDB = Session->m_Db; - //Copy SVG blob + // Copy SVG blob sqlite3_blob *ptr = nullptr; int ret = sqlite3_blob_open(mTempDB->db(), "main", "stations", "svg_data", sourceStId, 0, &ptr); - if(ret != SQLITE_OK || !ptr) + if (ret != SQLITE_OK || !ptr) { - qWarning() << "Station Import: cannot open source BLOB" << sourceStId << mTempDB->error_msg() << ret; + qWarning() << "Station Import: cannot open source BLOB" << sourceStId + << mTempDB->error_msg() << ret; return false; } QScopedPointer mSourceBlob(ptr); - ptr = nullptr; + ptr = nullptr; const int svgSize = sqlite3_blob_bytes(mSourceBlob.get()); - if(svgSize <= 0) + if (svgSize <= 0) { - return true; //Nothing to copy + return true; // Nothing to copy } - //Allocate SVG space + // Allocate SVG space command cmd(destDB, "UPDATE stations SET svg_data=? WHERE id=?"); sqlite3_bind_zeroblob(cmd.stmt(), 1, svgSize); cmd.bind(2, destStId); ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Station Import: cannot allocate BLOB" << destStId << destDB.error_msg() << ret; + qWarning() << "Station Import: cannot allocate BLOB" << destStId << destDB.error_msg() + << ret; return false; } ret = sqlite3_blob_open(destDB.db(), "main", "stations", "svg_data", destStId, 1, &ptr); - if(ret != SQLITE_OK || !ptr) + if (ret != SQLITE_OK || !ptr) { - qWarning() << "Station Import: cannot open destination BLOB" << destStId << destDB.error_msg() << ret; + qWarning() << "Station Import: cannot open destination BLOB" << destStId + << destDB.error_msg() << ret; return false; } QScopedPointer mDestBlob(ptr); - ptr = nullptr; + ptr = nullptr; constexpr int SVG_BUF_SIZE = 8192; - char svgBuf[SVG_BUF_SIZE] = {0}; - void *svgBufPtr = reinterpret_cast(svgBuf); - int offset = 0; - while(true) + char svgBuf[SVG_BUF_SIZE] = {0}; + void *svgBufPtr = reinterpret_cast(svgBuf); + int offset = 0; + while (true) { int maxLen = SVG_BUF_SIZE; - if(maxLen + offset >= svgSize) + if (maxLen + offset >= svgSize) maxLen = svgSize - offset; - if(maxLen <= 0) + if (maxLen <= 0) break; ret = sqlite3_blob_read(mSourceBlob.get(), svgBufPtr, maxLen, offset); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Station Import: cannot read BLOB" << sourceStId << mTempDB->error_msg() << ret; + qWarning() << "Station Import: cannot read BLOB" << sourceStId << mTempDB->error_msg() + << ret; break; } ret = sqlite3_blob_write(mDestBlob.get(), svgBufPtr, maxLen, offset); - if(ret != SQLITE_OK || !mDestBlob) + if (ret != SQLITE_OK || !mDestBlob) { - qWarning() << "Station Import: cannot write BLOB" << destStId << destDB.error_msg() << ret; + qWarning() << "Station Import: cannot write BLOB" << destStId << destDB.error_msg() + << ret; break; } offset += maxLen; } - //Close blobs + // Close blobs mSourceBlob.reset(); mDestBlob.reset(); diff --git a/src/stations/importer/stationimportwizard.h b/src/stations/importer/stationimportwizard.h index da4ed37..9df7eeb 100644 --- a/src/stations/importer/stationimportwizard.h +++ b/src/stations/importer/stationimportwizard.h @@ -41,18 +41,21 @@ public: explicit StationImportWizard(QWidget *parent = nullptr); ~StationImportWizard(); - inline sqlite3pp::database *getTempDB() const { return mTempDB; } + inline sqlite3pp::database *getTempDB() const + { + return mTempDB; + } private slots: - void onFileChosen(const QString& fileName); + void onFileChosen(const QString &fileName); private: - bool createDatabase(bool inMemory, const QString& fileName); + bool createDatabase(bool inMemory, const QString &fileName); bool closeDatabase(); friend class SelectStationPage; - bool checkNames(db_id sourceStId, const QString& newName, QString &outShortName); - bool addStation(db_id sourceStId, const QString& fullName, const QString &shortName); + bool checkNames(db_id sourceStId, const QString &newName, QString &outShortName); + bool addStation(db_id sourceStId, const QString &fullName, const QString &shortName); bool copySVGData(db_id sourceStId, db_id destStId); diff --git a/src/stations/manager/free_rs_viewer/stationfreersmodel.cpp b/src/stations/manager/free_rs_viewer/stationfreersmodel.cpp index 3c7c875..b87e480 100644 --- a/src/stations/manager/free_rs_viewer/stationfreersmodel.cpp +++ b/src/stations/manager/free_rs_viewer/stationfreersmodel.cpp @@ -33,12 +33,11 @@ StationFreeRSModel::StationFreeRSModel(sqlite3pp::database &db, QObject *parent) sortCol(RSNameCol), mDb(db) { - } QVariant StationFreeRSModel::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) { @@ -70,10 +69,11 @@ int StationFreeRSModel::columnCount(const QModelIndex &parent) const QVariant StationFreeRSModel::data(const QModelIndex &idx, int role) const { - if (role != Qt::DisplayRole || !idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols) + if (role != Qt::DisplayRole || !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 (idx.column()) { @@ -84,11 +84,11 @@ QVariant StationFreeRSModel::data(const QModelIndex &idx, int role) const case FreeUpToTimeCol: return item.to; case FromJobCol: - if(item.fromJob) + if (item.fromJob) return JobCategoryName::jobName(item.fromJob, item.fromJobCat); break; case ToJobCol: - if(item.toJob) + if (item.toJob) return JobCategoryName::jobName(item.toJob, item.toJobCat); break; } @@ -96,9 +96,9 @@ QVariant StationFreeRSModel::data(const QModelIndex &idx, int role) const return QVariant(); } -const StationFreeRSModel::Item* StationFreeRSModel::getItemAt(int row) const +const StationFreeRSModel::Item *StationFreeRSModel::getItemAt(int row) const { - if(row < m_data.size()) + if (row < m_data.size()) return &m_data.at(row); return nullptr; } @@ -116,15 +116,15 @@ void StationFreeRSModel::setTime(QTime time) } template -void insertSorted(Container &vec, const ItemType& item, const LessThan& cmp) +void insertSorted(Container &vec, const ItemType &item, const LessThan &cmp) { std::ptrdiff_t len = vec.size(); - auto first = vec.begin(); + auto first = vec.begin(); while (len > 0) { std::ptrdiff_t half = len >> 1; - auto middle = first + half; + auto middle = first + half; if (cmp(item, *middle)) len = half; else @@ -145,83 +145,91 @@ void StationFreeRSModel::reloadData() m_data.clear(); QHash tempLookup; - query q(mDb, "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type," - "MAX(stops.arrival),stops.job_id,jobs.category,stops.id" - " FROM coupling" - " JOIN stops ON stops.id=coupling.stop_id" - " JOIN jobs ON jobs.id=stops.job_id" - " JOIN rs_list ON rs_list.id=coupling.rs_id" - " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" - " WHERE stops.station_id=? AND stops.arrival<=?" //Less than OR equal (this includes RS uncoupled exactly at that time) + query q(mDb, + "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type," + "MAX(stops.arrival),stops.job_id,jobs.category,stops.id" + " FROM coupling" + " JOIN stops ON stops.id=coupling.stop_id" + " JOIN jobs ON jobs.id=stops.job_id" + " JOIN rs_list ON rs_list.id=coupling.rs_id" + " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" + " WHERE stops.station_id=? AND stops.arrival<=?" // Less than OR equal (this includes RS + // uncoupled exactly at that time) " GROUP BY coupling.rs_id" " HAVING coupling.operation=0"); q.bind(1, m_stationId); q.bind(2, m_time); - //Select uncoupled before m_time - for(auto r : q) + // Select uncoupled before m_time + for (auto r : q) { Item item; - item.rsId = r.get(0); + item.rsId = r.get(0); - int number = r.get(1); - int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); + int number = r.get(1); + int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); + const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); - int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); - RsType type = RsType(sqlite3_column_int(q.stmt(), 4)); + int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); + RsType type = RsType(sqlite3_column_int(q.stmt(), 4)); - item.from = r.get(5); - item.fromJob = r.get(6); - item.fromJobCat = JobCategory(r.get(7)); - item.fromStopId = r.get(8); - item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, modelSuffixLen, type); + item.from = r.get(5); + item.fromJob = r.get(6); + item.fromJobCat = JobCategory(r.get(7)); + item.fromStopId = r.get(8); + item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); tempLookup.insert(item.rsId, item); } - q.prepare("SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type," - "MIN(stops.arrival),stops.job_id,jobs.category,stops.id" - " FROM coupling" - " JOIN stops ON stops.id=coupling.stop_id" - " JOIN jobs ON jobs.id=stops.job_id" - " JOIN rs_list ON rs_list.id=coupling.rs_id" - " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" - " WHERE stops.station_id=? AND stops.arrival>?" //Greater than NOT equal (this exclude RS coupled at exactly that time) - " GROUP BY coupling.rs_id" - " HAVING coupling.operation=1"); + q.prepare( + "SELECT coupling.rs_id,rs_list.number,rs_models.name,rs_models.suffix,rs_models.type," + "MIN(stops.arrival),stops.job_id,jobs.category,stops.id" + " FROM coupling" + " JOIN stops ON stops.id=coupling.stop_id" + " JOIN jobs ON jobs.id=stops.job_id" + " JOIN rs_list ON rs_list.id=coupling.rs_id" + " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" + " WHERE stops.station_id=? AND stops.arrival>?" // Greater than NOT equal (this exclude RS + // coupled at exactly that time) + " GROUP BY coupling.rs_id" + " HAVING coupling.operation=1"); q.bind(1, m_stationId); q.bind(2, m_time); - //Select coupled after m_time - for(auto r : q) + // Select coupled after m_time + for (auto r : q) { db_id rsId = r.get(0); - Item& item = tempLookup[rsId]; //Create entry if key doesn't exist - if(!item.rsId) + Item &item = tempLookup[rsId]; // Create entry if key doesn't exist + if (!item.rsId) { - item.rsId = rsId; + item.rsId = rsId; - int number = r.get(1); + int number = r.get(1); int modelNameLen = sqlite3_column_bytes(q.stmt(), 2); - const char *modelName = reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); + const char *modelName = + reinterpret_cast(sqlite3_column_text(q.stmt(), 2)); int modelSuffixLen = sqlite3_column_bytes(q.stmt(), 3); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); + const char *modelSuffix = + reinterpret_cast(sqlite3_column_text(q.stmt(), 3)); RsType type = RsType(sqlite3_column_int(q.stmt(), 4)); - item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, modelSuffixLen, type); + item.name = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); } - item.to = r.get(5); - item.toJob = r.get(6); + item.to = r.get(5); + item.toJob = r.get(6); item.toJobCat = JobCategory(r.get(7)); item.toStopId = r.get(8); } m_data.reserve(tempLookup.size()); - //Insert and sort + // Insert and sort switch (sortCol) { default: @@ -230,13 +238,13 @@ void StationFreeRSModel::reloadData() class NameLessThan { public: - inline bool operator()(const Item& lhs, const Item& rhs) const + inline bool operator()(const Item &lhs, const Item &rhs) const { return lhs.name < rhs.name; } }; - for(const Item &it : qAsConst(tempLookup)) + for (const Item &it : qAsConst(tempLookup)) { insertSorted(m_data, it, NameLessThan()); } @@ -247,13 +255,13 @@ void StationFreeRSModel::reloadData() class FromTimeLessThan { public: - inline bool operator()(const Item& lhs, const Item& rhs) const + inline bool operator()(const Item &lhs, const Item &rhs) const { return lhs.from < rhs.from || (lhs.from == rhs.from && lhs.name < rhs.name); } }; - for(const Item &it : qAsConst(tempLookup)) + for (const Item &it : qAsConst(tempLookup)) { insertSorted(m_data, it, FromTimeLessThan()); } @@ -264,13 +272,13 @@ void StationFreeRSModel::reloadData() class UpToTimeLessThan { public: - inline bool operator()(const Item& lhs, const Item& rhs) const + inline bool operator()(const Item &lhs, const Item &rhs) const { return lhs.to < rhs.to || (lhs.to == rhs.to && lhs.name < rhs.name); } }; - for(const Item &it : qAsConst(tempLookup)) + for (const Item &it : qAsConst(tempLookup)) { insertSorted(m_data, it, UpToTimeLessThan()); } @@ -281,13 +289,14 @@ void StationFreeRSModel::reloadData() class FromJobLessThan { public: - inline bool operator()(const Item& lhs, const Item& rhs) const + inline bool operator()(const Item &lhs, const Item &rhs) const { - return lhs.fromJob < rhs.fromJob || (lhs.fromJob == rhs.fromJob && lhs.name < rhs.name); + return lhs.fromJob < rhs.fromJob + || (lhs.fromJob == rhs.fromJob && lhs.name < rhs.name); } }; - for(const Item &it : qAsConst(tempLookup)) + for (const Item &it : qAsConst(tempLookup)) { insertSorted(m_data, it, FromJobLessThan()); } @@ -298,13 +307,13 @@ void StationFreeRSModel::reloadData() class ToJobLessThan { public: - inline bool operator()(const Item& lhs, const Item& rhs) const + inline bool operator()(const Item &lhs, const Item &rhs) const { return lhs.toJob < rhs.toJob || (lhs.toJob == rhs.toJob && lhs.name < rhs.name); } }; - for(const Item &it : qAsConst(tempLookup)) + for (const Item &it : qAsConst(tempLookup)) { insertSorted(m_data, it, ToJobLessThan()); } @@ -350,23 +359,24 @@ StationFreeRSModel::ErrorCodes StationFreeRSModel::getNextOpTime(QTime &time) q_getNextOpTime.bind(1, m_stationId); q_getNextOpTime.bind(2, m_time); - if(q_getNextOpTime.step() == SQLITE_ROW) + if (q_getNextOpTime.step() == SQLITE_ROW) { auto r = q_getNextOpTime.getRows(); - if(r.column_type(1) != SQLITE_NULL) + if (r.column_type(1) != SQLITE_NULL) { time = r.get(1); } else { - //There aren't operations next to m_time + // There aren't operations next to m_time err = NoOperationFound; } } else { - //Error - qDebug() << __PRETTY_FUNCTION__ << "DB Error:" << mDb.error_code() << mDb.error_msg() << mDb.extended_error_code(); + // Error + qDebug() << __PRETTY_FUNCTION__ << "DB Error:" << mDb.error_code() << mDb.error_msg() + << mDb.extended_error_code(); err = DBError; } @@ -376,7 +386,7 @@ StationFreeRSModel::ErrorCodes StationFreeRSModel::getNextOpTime(QTime &time) StationFreeRSModel::ErrorCodes StationFreeRSModel::getPrevOpTime(QTime &time) { - //TODO: if on last/first operation increment by 1 to see after/before prev, last operation + // TODO: if on last/first operation increment by 1 to see after/before prev, last operation ErrorCodes err = NoError; query q_getPrevOpTime(mDb, "SELECT coupling.rs_id, MAX(stops.arrival) FROM coupling" @@ -385,29 +395,30 @@ StationFreeRSModel::ErrorCodes StationFreeRSModel::getPrevOpTime(QTime &time) q_getPrevOpTime.bind(1, m_stationId); q_getPrevOpTime.bind(2, m_time); - if(q_getPrevOpTime.step() == SQLITE_ROW) + if (q_getPrevOpTime.step() == SQLITE_ROW) { auto r = q_getPrevOpTime.getRows(); - if(r.column_type(1) != SQLITE_NULL) + if (r.column_type(1) != SQLITE_NULL) { time = r.get(1); } else { - //There aren't operations previous to m_time - //But because RS uncoupled before m_time are taken with 'less than OR equal' - //we should show also the situation before this time. + // There aren't operations previous to m_time + // But because RS uncoupled before m_time are taken with 'less than OR equal' + // we should show also the situation before this time. - //err = NoOperationFound; + // err = NoOperationFound; - //Fake operation at first morning + // Fake operation at first morning time = QTime(0, 0); } } else { - //Error - qDebug() << __PRETTY_FUNCTION__ << "DB Error:" << mDb.error_code() << mDb.error_msg() << mDb.extended_error_code(); + // Error + qDebug() << __PRETTY_FUNCTION__ << "DB Error:" << mDb.error_code() << mDb.error_msg() + << mDb.extended_error_code(); err = DBError; } @@ -417,7 +428,7 @@ StationFreeRSModel::ErrorCodes StationFreeRSModel::getPrevOpTime(QTime &time) bool StationFreeRSModel::sortByColumn(int col) { - if(col == sortCol || col < 0 || col >= NCols) + if (col == sortCol || col < 0 || col >= NCols) return false; sortCol = col; @@ -431,7 +442,7 @@ bool StationFreeRSModel::sortByColumn(int col) class CompName : public std::binary_function { public: - inline bool operator()(const Item& l, const Item& r) + inline bool operator()(const Item &l, const Item &r) { return l.name < r.name; } @@ -445,9 +456,9 @@ bool StationFreeRSModel::sortByColumn(int col) class CompFrom : public std::binary_function { public: - inline bool operator()(const Item& l, const Item& r) + inline bool operator()(const Item &l, const Item &r) { - if(l.from == r.from) + if (l.from == r.from) return l.name < r.name; return l.from < r.from; } @@ -461,9 +472,9 @@ bool StationFreeRSModel::sortByColumn(int col) class CompTo : public std::binary_function { public: - inline bool operator()(const Item& l, const Item& r) + inline bool operator()(const Item &l, const Item &r) { - if(l.to == r.to) + if (l.to == r.to) return l.name < r.name; return l.to < r.to; } @@ -477,9 +488,9 @@ bool StationFreeRSModel::sortByColumn(int col) class CompJobFrom : public std::binary_function { public: - inline bool operator()(const Item& l, const Item& r) + inline bool operator()(const Item &l, const Item &r) { - if(l.fromJob == r.fromJob) + if (l.fromJob == r.fromJob) return l.name < r.name; return l.fromJob < r.fromJob; } @@ -493,9 +504,9 @@ bool StationFreeRSModel::sortByColumn(int col) class CompJobTo : public std::binary_function { public: - inline bool operator()(const Item& l, const Item& r) + inline bool operator()(const Item &l, const Item &r) { - if(l.toJob == r.toJob) + if (l.toJob == r.toJob) return l.name < r.name; return l.toJob < r.toJob; } diff --git a/src/stations/manager/free_rs_viewer/stationfreersmodel.h b/src/stations/manager/free_rs_viewer/stationfreersmodel.h index 8cfd486..6fcdf10 100644 --- a/src/stations/manager/free_rs_viewer/stationfreersmodel.h +++ b/src/stations/manager/free_rs_viewer/stationfreersmodel.h @@ -30,13 +30,14 @@ #include "utils/types.h" -//TODO: on-demand load and let SQL do the sorting +// TODO: on-demand load and let SQL do the sorting class StationFreeRSModel : public QAbstractTableModel { Q_OBJECT public: - enum Columns { + enum Columns + { RSNameCol = 0, FreeFromTimeCol, FreeUpToTimeCol, @@ -48,13 +49,13 @@ public: struct Item { db_id rsId = 0; - QTime from; //Time at which RS is uncoupled (from now it's free) - QTime to; //Time at which is coupled (not free anymore) + QTime from; // Time at which RS is uncoupled (from now it's free) + QTime to; // Time at which is coupled (not free anymore) QString name; - db_id fromJob = 0; + db_id fromJob = 0; db_id fromStopId = 0; - db_id toJob = 0; - db_id toStopId = 0; + db_id toJob = 0; + db_id toStopId = 0; JobCategory fromJobCat; JobCategory toJobCat; }; @@ -62,7 +63,8 @@ public: StationFreeRSModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -83,7 +85,7 @@ public: }; ErrorCodes getNextOpTime(QTime &time); - ErrorCodes getPrevOpTime(QTime& time); + ErrorCodes getPrevOpTime(QTime &time); QTime getTime() const; db_id getStationId() const; @@ -104,7 +106,7 @@ private: QVector m_data; - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; }; #endif // STATIONFREERSMODEL_H diff --git a/src/stations/manager/free_rs_viewer/stationfreersviewer.cpp b/src/stations/manager/free_rs_viewer/stationfreersviewer.cpp index b0ffaa5..b59f671 100644 --- a/src/stations/manager/free_rs_viewer/stationfreersviewer.cpp +++ b/src/stations/manager/free_rs_viewer/stationfreersviewer.cpp @@ -37,13 +37,13 @@ /* Widget to view in a list all free rollingstock pieces at a given time m_time * in a given time m_stationId -*/ + */ StationFreeRSViewer::StationFreeRSViewer(QWidget *parent) : QWidget(parent) { QGridLayout *lay = new QGridLayout(this); - refreshBut = new QPushButton(tr("Refresh")); + refreshBut = new QPushButton(tr("Refresh")); lay->addWidget(refreshBut, 0, 0, 1, 2); QLabel *l = new QLabel(tr("Time:")); @@ -67,16 +67,18 @@ StationFreeRSViewer::StationFreeRSViewer(QWidget *parent) : view->setModel(model); connect(refreshBut, &QPushButton::clicked, model, &StationFreeRSModel::reloadData); - connect(timeEdit, &QTimeEdit::editingFinished, this, &StationFreeRSViewer::onTimeEditingFinished); + connect(timeEdit, &QTimeEdit::editingFinished, this, + &StationFreeRSViewer::onTimeEditingFinished); connect(nextOpBut, &QPushButton::clicked, this, &StationFreeRSViewer::goToNext); connect(prevOpBut, &QPushButton::clicked, this, &StationFreeRSViewer::goToPrev); - connect(view, &QTableView::customContextMenuRequested, this, &StationFreeRSViewer::showContextMenu); + connect(view, &QTableView::customContextMenuRequested, this, + &StationFreeRSViewer::showContextMenu); - //FIXME: move to FilterHeaderView and IPagedItemModel - //Custom colun sorting - //NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work + // FIXME: move to FilterHeaderView and IPagedItemModel + // Custom colun sorting + // NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work QHeaderView *header = view->horizontalHeader(); disconnect(header, SIGNAL(sectionPressed(int)), view, SLOT(selectColumn(int))); disconnect(header, SIGNAL(sectionEntered(int)), view, SLOT(_q_selectColumn(int))); @@ -85,7 +87,8 @@ StationFreeRSViewer::StationFreeRSViewer(QWidget *parent) : header->setSortIndicatorShown(true); header->setSortIndicator(StationFreeRSModel::RSNameCol, Qt::AscendingOrder); - header->setSectionResizeMode(StationFreeRSModel::FreeFromTimeCol, QHeaderView::ResizeToContents); + header->setSectionResizeMode(StationFreeRSModel::FreeFromTimeCol, + QHeaderView::ResizeToContents); setMinimumSize(100, 200); } @@ -115,25 +118,24 @@ void StationFreeRSViewer::onTimeEditingFinished() * Find the first operation after m_time. * If found set m_time to this new value and rebuild the list. * This is useful to jump between operation withuot having to guess times. -*/ + */ void StationFreeRSViewer::goToNext() { QTime time; StationFreeRSModel::ErrorCodes err = model->getNextOpTime(time); - if(err == StationFreeRSModel::DBError) + if (err == StationFreeRSModel::DBError) { - QMessageBox::warning(this, tr("Error"), - tr("Database error. Try again.")); + QMessageBox::warning(this, tr("Error"), tr("Database error. Try again.")); return; } - if(err == StationFreeRSModel::NoOperationFound) + if (err == StationFreeRSModel::NoOperationFound) { - QMessageBox::information(this, tr("No Operation Found"), - tr("No operation found in station %1 after %2!") - .arg(model->getStationName(), - model->getTime().toString("HH:mm"))); + QMessageBox::information( + this, tr("No Operation Found"), + tr("No operation found in station %1 after %2!") + .arg(model->getStationName(), model->getTime().toString("HH:mm"))); return; } @@ -146,25 +148,24 @@ void StationFreeRSViewer::goToNext() * If found set m_time to this new value and rebuild the list. * This is useful to jump between operation withuot having to guess times. * See 'void StationFreeRSViewer::goToNext()' -*/ + */ void StationFreeRSViewer::goToPrev() { QTime time; StationFreeRSModel::ErrorCodes err = model->getPrevOpTime(time); - if(err == StationFreeRSModel::DBError) + if (err == StationFreeRSModel::DBError) { - QMessageBox::warning(this, tr("Error"), - tr("Database error. Try again.")); + QMessageBox::warning(this, tr("Error"), tr("Database error. Try again.")); return; } - if(err == StationFreeRSModel::NoOperationFound) + if (err == StationFreeRSModel::NoOperationFound) { - QMessageBox::information(this, tr("No Operation Found"), - tr("No operation found in station %1 before %2!") - .arg(model->getStationName(), - model->getTime().toString("HH:mm"))); + QMessageBox::information( + this, tr("No Operation Found"), + tr("No operation found in station %1 before %2!") + .arg(model->getStationName(), model->getTime().toString("HH:mm"))); return; } @@ -172,32 +173,32 @@ void StationFreeRSViewer::goToPrev() model->setTime(time); } -void StationFreeRSViewer::showContextMenu(const QPoint& pos) +void StationFreeRSViewer::showContextMenu(const QPoint &pos) { QModelIndex idx = view->indexAt(pos); - if(!idx.isValid()) + if (!idx.isValid()) return; const StationFreeRSModel::Item *item = model->getItemAt(idx.row()); - OwningQPointer menu = new QMenu(this); - QAction *showRSPlan = menu->addAction(tr("Show RS Plan")); - QAction *showFromJobInEditor = menu->addAction(tr("Show Job A in JobEditor")); - QAction *showToJobInEditor = menu->addAction(tr("Show Job B in JobEditor")); + OwningQPointer menu = new QMenu(this); + QAction *showRSPlan = menu->addAction(tr("Show RS Plan")); + QAction *showFromJobInEditor = menu->addAction(tr("Show Job A in JobEditor")); + QAction *showToJobInEditor = menu->addAction(tr("Show Job B in JobEditor")); showFromJobInEditor->setEnabled(item->fromJob); showToJobInEditor->setEnabled(item->toJob); QAction *act = menu->exec(view->viewport()->mapToGlobal(pos)); - if(act == showRSPlan) + if (act == showRSPlan) { Session->getViewManager()->requestRSInfo(item->rsId); } - else if(act == showFromJobInEditor) + else if (act == showFromJobInEditor) { Session->getViewManager()->requestJobEditor(item->fromJob, item->fromStopId); } - else if(act == showToJobInEditor) + else if (act == showToJobInEditor) { Session->getViewManager()->requestJobEditor(item->toJob, item->toStopId); } diff --git a/src/stations/manager/lines/dialogs/choosesegmentdlg.cpp b/src/stations/manager/lines/dialogs/choosesegmentdlg.cpp index ebdab42..b7027d1 100644 --- a/src/stations/manager/lines/dialogs/choosesegmentdlg.cpp +++ b/src/stations/manager/lines/dialogs/choosesegmentdlg.cpp @@ -38,11 +38,11 @@ ChooseSegmentDlg::ChooseSegmentDlg(sqlite3pp::database &db, QWidget *parent) : QFormLayout *lay = new QFormLayout(this); fromStationMatch = new StationsMatchModel(db, this); - fromStationEdit = new CustomCompletionLineEdit(fromStationMatch); + fromStationEdit = new CustomCompletionLineEdit(fromStationMatch); fromStationEdit->setPlaceholderText(tr("Filter...")); lay->addRow(tr("From station:"), fromStationEdit); - gateMatch = new StationGatesMatchModel(db, this); + gateMatch = new StationGatesMatchModel(db, this); outGateEdit = new CustomCompletionLineEdit(gateMatch); outGateEdit->setPlaceholderText(tr("Select...")); lay->addRow(tr("Segment:"), outGateEdit); @@ -53,8 +53,10 @@ ChooseSegmentDlg::ChooseSegmentDlg(sqlite3pp::database &db, QWidget *parent) : connect(box, &QDialogButtonBox::accepted, this, &ChooseSegmentDlg::accept); connect(box, &QDialogButtonBox::rejected, this, &ChooseSegmentDlg::reject); - connect(fromStationEdit, &CustomCompletionLineEdit::dataIdChanged, this, &ChooseSegmentDlg::onStationChanged); - connect(outGateEdit, &CustomCompletionLineEdit::indexSelected, this, &ChooseSegmentDlg::onSegmentSelected); + connect(fromStationEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &ChooseSegmentDlg::onStationChanged); + connect(outGateEdit, &CustomCompletionLineEdit::indexSelected, this, + &ChooseSegmentDlg::onSegmentSelected); setWindowTitle(tr("Choose Railway Segment")); setMinimumSize(300, 100); @@ -62,14 +64,13 @@ ChooseSegmentDlg::ChooseSegmentDlg(sqlite3pp::database &db, QWidget *parent) : void ChooseSegmentDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { db_id segmentId = 0; QString tmp; - if(!outGateEdit->getData(segmentId, tmp)) + if (!outGateEdit->getData(segmentId, tmp)) { - QMessageBox::warning(this, tr("Error"), - tr("Invalid railway segment.")); + QMessageBox::warning(this, tr("Error"), tr("Invalid railway segment.")); return; } } @@ -80,7 +81,7 @@ void ChooseSegmentDlg::done(int res) void ChooseSegmentDlg::setFilter(db_id fromStationId, db_id exceptSegment) { lockFromStationId = fromStationId; - excludeSegmentId = exceptSegment; + excludeSegmentId = exceptSegment; selectedSegmentId = 0; fromStationEdit->setData(lockFromStationId); @@ -94,7 +95,7 @@ bool ChooseSegmentDlg::getData(db_id &outSegId, QString &segName, bool &outIsRev { db_id tmpGateId = 0; outGateEdit->getData(tmpGateId, segName); - outSegId = selectedSegmentId; + outSegId = selectedSegmentId; outIsReversed = isReversed; return outSegId != 0; } @@ -104,16 +105,16 @@ void ChooseSegmentDlg::onStationChanged() QString tmp; fromStationEdit->getData(lockFromStationId, tmp); - //Reset segment + // Reset segment outGateEdit->setData(0); gateMatch->setFilter(lockFromStationId, true, excludeSegmentId, true); isReversed = false; } -void ChooseSegmentDlg::onSegmentSelected(const QModelIndex& idx) +void ChooseSegmentDlg::onSegmentSelected(const QModelIndex &idx) { - isReversed = false; + isReversed = false; selectedSegmentId = gateMatch->getSegmentIdAtRow(idx.row()); - if(selectedSegmentId) + if (selectedSegmentId) isReversed = gateMatch->isSegmentReversedAtRow(idx.row()); } diff --git a/src/stations/manager/lines/dialogs/choosesegmentdlg.h b/src/stations/manager/lines/dialogs/choosesegmentdlg.h index 0e6e671..75e7227 100644 --- a/src/stations/manager/lines/dialogs/choosesegmentdlg.h +++ b/src/stations/manager/lines/dialogs/choosesegmentdlg.h @@ -42,14 +42,13 @@ public: DoNotLock = 0 }; - explicit ChooseSegmentDlg(sqlite3pp::database &db, - QWidget *parent = nullptr); + explicit ChooseSegmentDlg(sqlite3pp::database &db, QWidget *parent = nullptr); virtual void done(int res) override; void setFilter(db_id fromStationId, db_id exceptSegment); - bool getData(db_id& outSegId, QString& segName, bool &outIsReversed); + bool getData(db_id &outSegId, QString &segName, bool &outIsReversed); private slots: void onStationChanged(); diff --git a/src/stations/manager/lines/dialogs/editlinedlg.cpp b/src/stations/manager/lines/dialogs/editlinedlg.cpp index 2b3e862..91b92f7 100644 --- a/src/stations/manager/lines/dialogs/editlinedlg.cpp +++ b/src/stations/manager/lines/dialogs/editlinedlg.cpp @@ -37,18 +37,17 @@ #include "utils/owningqpointer.h" - EditLineDlg::EditLineDlg(sqlite3pp::database &db, QWidget *parent) : QDialog(parent), mDb(db) { model = new LineSegmentsModel(mDb, this); - //Details Tab - QWidget *detailsTab = new QWidget; + // Details Tab + QWidget *detailsTab = new QWidget; QFormLayout *detailsTabLay = new QFormLayout(detailsTab); - lineNameEdit = new QLineEdit; + lineNameEdit = new QLineEdit; lineNameEdit->setPlaceholderText(tr("Name...")); detailsTabLay->addRow(tr("Name:"), lineNameEdit); @@ -56,12 +55,12 @@ EditLineDlg::EditLineDlg(sqlite3pp::database &db, QWidget *parent) : lineStartKmSpin->setPrefix(tr("Km ")); detailsTabLay->addRow(tr("Start at:"), lineStartKmSpin); - //Path Tab - QWidget *pathTab = new QWidget; + // Path Tab + QWidget *pathTab = new QWidget; QVBoxLayout *pathTabLay = new QVBoxLayout(pathTab); - //Buttons - QHBoxLayout *toolsLay = new QHBoxLayout; + // Buttons + QHBoxLayout *toolsLay = new QHBoxLayout; QToolButton *addStationBut = new QToolButton; addStationBut->setText(tr("Add station")); @@ -78,7 +77,7 @@ EditLineDlg::EditLineDlg(sqlite3pp::database &db, QWidget *parent) : pathTabLay->addWidget(view); - QVBoxLayout *lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); QTabWidget *tabWidget = new QTabWidget; tabWidget->addTab(detailsTab, tr("Details")); tabWidget->addTab(pathTab, tr("Path")); @@ -101,23 +100,23 @@ EditLineDlg::EditLineDlg(sqlite3pp::database &db, QWidget *parent) : void EditLineDlg::done(int res) { - //FIXME: cannot cancel editings made to path so always accept + // FIXME: cannot cancel editings made to path so always accept res = QDialog::Accepted; - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { QString lineName = lineNameEdit->text().simplified(); - int startMeters = lineStartKmSpin->value(); + int startMeters = lineStartKmSpin->value(); - if(lineName.isEmpty()) + if (lineName.isEmpty()) { onModelError(tr("Line name cannot be empty.")); return; } - if(!model->setLineInfo(lineName, startMeters)) + if (!model->setLineInfo(lineName, startMeters)) { - return; //Error + return; // Error } } @@ -128,12 +127,12 @@ void EditLineDlg::setLineId(db_id lineId) { model->setLine(lineId); - //Reload UI + // Reload UI QString lineName; int startMeters = 0; - if(!model->getLineInfo(lineName, startMeters)) + if (!model->getLineInfo(lineName, startMeters)) { - return; //Error + return; // Error } lineNameEdit->setText(lineName); @@ -147,13 +146,13 @@ void EditLineDlg::onModelError(const QString &msg) void EditLineDlg::addStation() { - if(model->getSegmentCount() >= MaxSegmentsPerLine) + if (model->getSegmentCount() >= MaxSegmentsPerLine) { QMessageBox::warning(this, tr("Error"), tr("Cannot add another segment to line %1.
" "Each line can have a maximum of %2 segments.") - .arg(lineNameEdit->text()) - .arg(MaxSegmentsPerLine)); + .arg(lineNameEdit->text()) + .arg(MaxSegmentsPerLine)); return; } @@ -163,14 +162,14 @@ void EditLineDlg::addStation() OwningQPointer dlg(new ChooseSegmentDlg(mDb, this)); dlg->setFilter(lastStationId, lastSegmentId); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; db_id segmentId = 0; QString segmentName; bool isReversed = false; - if(dlg->getData(segmentId, segmentName, isReversed)) + if (dlg->getData(segmentId, segmentName, isReversed)) { model->addStation(segmentId, isReversed); } @@ -178,7 +177,7 @@ void EditLineDlg::addStation() void EditLineDlg::removeAfterCurrentPos() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) { onModelError(tr("Please select a segment to remove.\n" "All segments after it are also removed.")); @@ -186,25 +185,24 @@ void EditLineDlg::removeAfterCurrentPos() } QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; - int pos = model->getItemIndex(idx.row()); + int pos = model->getItemIndex(idx.row()); const int segmentCount = model->getSegmentCount(); - if(pos >= segmentCount) - pos = segmentCount - 1; //Remove only the last one + if (pos >= segmentCount) + pos = segmentCount - 1; // Remove only the last one const QString stationName = model->getStationNameAt(pos); const QString msg = - tr("Remove last %1 segments?" - "%2") - .arg(segmentCount - pos) - .arg(stationName.isEmpty() - ? QString() - : tr("
(From station %1)").arg(stationName)); + tr("Remove last %1 segments?" + "%2") + .arg(segmentCount - pos) + .arg(stationName.isEmpty() ? QString() + : tr("
(From station %1)").arg(stationName)); int ret = QMessageBox::question(this, tr("Are you sure?"), msg); - if(ret != QMessageBox::Yes) + if (ret != QMessageBox::Yes) return; model->removeSegmentsAfterPosInclusive(pos); diff --git a/src/stations/manager/lines/dialogs/editlinedlg.h b/src/stations/manager/lines/dialogs/editlinedlg.h index 584d3ad..5994111 100644 --- a/src/stations/manager/lines/dialogs/editlinedlg.h +++ b/src/stations/manager/lines/dialogs/editlinedlg.h @@ -45,12 +45,12 @@ public: void setLineId(db_id lineId); private slots: - void onModelError(const QString& msg); + void onModelError(const QString &msg); void addStation(); void removeAfterCurrentPos(); private: - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; LineSegmentsModel *model; QTableView *view; diff --git a/src/stations/manager/lines/model/linesegmentsmodel.cpp b/src/stations/manager/lines/model/linesegmentsmodel.cpp index 61ad41a..5affc94 100644 --- a/src/stations/manager/lines/model/linesegmentsmodel.cpp +++ b/src/stations/manager/lines/model/linesegmentsmodel.cpp @@ -37,7 +37,10 @@ class LineSegmentsModelResultEvent : public QEvent { public: static constexpr Type _Type = Type(CustomEvents::LineSegmentsModelResult); - inline LineSegmentsModelResultEvent() : QEvent(_Type) {} + inline LineSegmentsModelResultEvent() : + QEvent(_Type) + { + } QVector items; }; @@ -52,16 +55,16 @@ LineSegmentsModel::LineSegmentsModel(sqlite3pp::database &db, QObject *parent) : bool LineSegmentsModel::event(QEvent *e) { - if(e->type() == LineSegmentsModelResultEvent::_Type) + if (e->type() == LineSegmentsModelResultEvent::_Type) { LineSegmentsModelResultEvent *ev = static_cast(e); ev->setAccepted(true); - segments = ev->items; - isFetching = false; //Done fetching + segments = ev->items; + isFetching = false; // Done fetching QModelIndex firstIdx = index(0, 0); - QModelIndex lastIdx = index(totalItemsCount - 1, NCols - 1); + QModelIndex lastIdx = index(totalItemsCount - 1, NCols - 1); emit dataChanged(firstIdx, lastIdx); emit itemsReady(0, totalItemsCount - 1); @@ -73,7 +76,7 @@ bool LineSegmentsModel::event(QEvent *e) QVariant LineSegmentsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -94,15 +97,15 @@ QVariant LineSegmentsModel::headerData(int section, Qt::Orientation orientation, } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { - //Vertical row numbers + // Vertical row numbers - //Station rows: show station index position (start from 1) - if(getRowType(section) == StationRow) + // Station rows: show station index position (start from 1) + if (getRowType(section) == StationRow) return section / 2 + 1; - return QVariant(); //Hide number on segment rows + return QVariant(); // Hide number on segment rows } return QAbstractTableModel::headerData(section, orientation, role); @@ -125,13 +128,13 @@ QVariant LineSegmentsModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= totalItemsCount || idx.column() >= NCols) return QVariant(); - if(segments.isEmpty()) + if (segments.isEmpty()) { const_cast(this)->fetchRows(); return QVariant(); } - const LineSegmentItem& item = segments.at(segmentIdx); + const LineSegmentItem &item = segments.at(segmentIdx); switch (getRowType(idx.row())) { @@ -152,7 +155,7 @@ QVariant LineSegmentsModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - //Station names in bold + // Station names in bold switch (idx.column()) { case StationOrSegmentNameCol: @@ -175,8 +178,8 @@ QVariant LineSegmentsModel::data(const QModelIndex &idx, int role) const } case Qt::BackgroundRole: { - //Light cyan background for stations - return QBrush(qRgb(158, 226, 255)); //#9EE2FF + // Light cyan background for stations + return QBrush(qRgb(158, 226, 255)); // #9EE2FF } } break; @@ -200,12 +203,12 @@ QVariant LineSegmentsModel::data(const QModelIndex &idx, int role) const } case Qt::DecorationRole: { - //Draw a small blue square for electified segments + // Draw a small blue square for electified segments switch (idx.column()) { case StationOrSegmentNameCol: { - if(item.segmentType.testFlag(utils::RailwaySegmentType::Electrified)) + if (item.segmentType.testFlag(utils::RailwaySegmentType::Electrified)) return QColor(Qt::blue); } } @@ -215,21 +218,21 @@ QVariant LineSegmentsModel::data(const QModelIndex &idx, int role) const { QStringList tips; - //Electrification - if(item.segmentType.testFlag(utils::RailwaySegmentType::Electrified)) + // Electrification + if (item.segmentType.testFlag(utils::RailwaySegmentType::Electrified)) tips.append(tr("Electrified")); else tips.append(tr("Non electrified")); - //Direction - if(item.reversed) + // Direction + if (item.reversed) tips.append(tr("Segment is reversed.")); return tr("Segment %1
%2").arg(item.segmentName, tips.join("
")); } case Qt::TextAlignmentRole: { - //Align segment names to right + // Align segment names to right switch (idx.column()) { case StationOrSegmentNameCol: @@ -255,33 +258,33 @@ void LineSegmentsModel::clearCache() void LineSegmentsModel::refreshData(bool forceUpdate) { - //NOTE: custom implementation - if(!mDb.db()) + // NOTE: custom implementation + if (!mDb.db()) return; - emit itemsReady(-1, -1); //Notify we are about to refresh + emit itemsReady(-1, -1); // Notify we are about to refresh - //TODO: consider filters + // TODO: consider filters query q(mDb, "SELECT COUNT(1) FROM line_segments WHERE line_id=?"); q.bind(1, m_lineId); q.step(); - //Store segment count + // Store segment count curItemCount = q.getRows().get(0); - //Each segment has 2 row + 1 extra row for last station + // Each segment has 2 row + 1 extra row for last station int actualRowCount = curItemCount * 2 + 1; - if(curItemCount == 0) - actualRowCount = 0; //No segments -> Line is Empty + if (curItemCount == 0) + actualRowCount = 0; // No segments -> Line is Empty - if(actualRowCount != totalItemsCount || forceUpdate) + if (actualRowCount != totalItemsCount || forceUpdate) { beginResetModel(); clearCache(); totalItemsCount = actualRowCount; - //Always 1 page + // Always 1 page pageCount = 1; emit totalItemsCountChanged(totalItemsCount); @@ -301,10 +304,10 @@ bool LineSegmentsModel::getLineInfo(QString &nameOut, int &startMetersOut) const { query q(mDb, "SELECT name, start_meters FROM lines WHERE id=?"); q.bind(1, m_lineId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - nameOut = q.getRows().get(0); + nameOut = q.getRows().get(0); startMetersOut = q.getRows().get(1); return true; } @@ -315,13 +318,13 @@ bool LineSegmentsModel::setLineInfo(const QString &name, int startMeters) cmd.bind(1, name); cmd.bind(2, startMeters); cmd.bind(3, m_lineId); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) { emit modelError(mDb.error_msg()); return false; } - //Update model km field + // Update model km field refreshData(true); return true; } @@ -331,7 +334,7 @@ bool LineSegmentsModel::removeSegmentsAfterPosInclusive(int pos) command cmd(mDb, "DELETE FROM line_segments WHERE line_id=? AND pos>=?"); cmd.bind(1, m_lineId); cmd.bind(2, pos); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) { emit modelError(mDb.error_msg()); return false; @@ -343,24 +346,25 @@ bool LineSegmentsModel::removeSegmentsAfterPosInclusive(int pos) bool LineSegmentsModel::addStation(db_id railwaySegmentId, bool reverse) { - //FIXME: check if valid (if adjacent to previous, if should be reversed or not) + // FIXME: check if valid (if adjacent to previous, if should be reversed or not) query q(mDb, "SELECT MAX(pos) FROM line_segments WHERE line_id=?"); q.bind(1, m_lineId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - int nextPos = 0; //If it's the first segment - if(q.getRows().column_type(0) != SQLITE_NULL) + int nextPos = 0; // If it's the first segment + if (q.getRows().column_type(0) != SQLITE_NULL) nextPos = q.getRows().get(0) + 1; - command cmd(mDb, "INSERT INTO line_segments(id,line_id,seg_id,direction,pos) VALUES(NULL, ?, ?, ?, ?)"); + command cmd( + mDb, "INSERT INTO line_segments(id,line_id,seg_id,direction,pos) VALUES(NULL, ?, ?, ?, ?)"); cmd.bind(1, m_lineId); cmd.bind(2, railwaySegmentId); cmd.bind(3, reverse ? 1 : 0); cmd.bind(4, nextPos); - if(cmd.execute() != SQLITE_OK) + if (cmd.execute() != SQLITE_OK) { emit modelError(mDb.error_msg()); return false; @@ -372,26 +376,26 @@ bool LineSegmentsModel::addStation(db_id railwaySegmentId, bool reverse) void LineSegmentsModel::fetchRows() { - if(!mDb.db()) + if (!mDb.db()) return; - //Prevent multiple requests - if(isFetching) + // Prevent multiple requests + if (isFetching) return; isFetching = true; - //FIXME: consider also station types - //and gate names and rail track connections count + // FIXME: consider also station types + // and gate names and rail track connections count query q(mDb, "SELECT start_meters FROM lines WHERE id=?"); q.bind(1, m_lineId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) { qWarning() << "INVALID LINE:" << m_lineId; } - //First station of the line has this position + // First station of the line has this position int currentPosMeters = q.getRows().get(0); q.prepare("SELECT ls.id, ls.seg_id, ls.direction," @@ -408,7 +412,7 @@ void LineSegmentsModel::fetchRows() q.bind(1, m_lineId); - //Reserve for 1 extra item (which will hold last station) + // Reserve for 1 extra item (which will hold last station) QVector vec; vec.reserve(curItemCount + 1); @@ -416,42 +420,42 @@ void LineSegmentsModel::fetchRows() db_id lastStationId = 0; QString lastStationName; - for(auto seg : q) + for (auto seg : q) { LineSegmentItem item; - item.lineSegmentId = seg.get(0); + item.lineSegmentId = seg.get(0); item.railwaySegmentId = seg.get(1); - item.reversed = seg.get(2) != 0; + item.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 - item.fromStationId = seg.get(7); + // Store first segment end + item.fromStationId = seg.get(7); item.fromStationName = seg.get(8); - //Store also the other end of segment for last item - db_id otherStationId = seg.get(9); + // Store also the other end of segment for last item + db_id otherStationId = seg.get(9); QString otherStationName = seg.get(10); - if(item.reversed) + if (item.reversed) { - //Swap segments ends + // Swap segments ends qSwap(item.fromStationId, otherStationId); qSwap(item.fromStationName, otherStationName); } - if(lastStationId && item.fromStationId != lastStationId) + if (lastStationId && item.fromStationId != lastStationId) { qWarning() << "Line segments are not adjacent, ID:" << item.lineSegmentId << "LINE:" << m_lineId; } - lastStationId = otherStationId; - lastStationName = otherStationName; + lastStationId = otherStationId; + lastStationName = otherStationName; item.fromPosMeters = currentPosMeters; currentPosMeters += item.distanceMeters; @@ -459,31 +463,31 @@ void LineSegmentsModel::fetchRows() vec.append(item); } - if(lastStationId) + if (lastStationId) { - //Add a fake item to show last station (other end of last segment) - //This item is shown without a SegmentRow + // Add a fake item to show last station (other end of last segment) + // This item is shown without a SegmentRow LineSegmentItem lastItem; - lastItem.fromStationId = lastStationId; + lastItem.fromStationId = lastStationId; lastItem.fromStationName = lastStationName; - lastItem.fromPosMeters = currentPosMeters; - //Fields relevant only for SegmentRow so we don't use them - lastItem.lineSegmentId = 0; + lastItem.fromPosMeters = currentPosMeters; + // Fields relevant only for SegmentRow so we don't use them + lastItem.lineSegmentId = 0; lastItem.railwaySegmentId = 0; - lastItem.distanceMeters = 0; - lastItem.maxSpeedKmH = 0; - lastItem.reversed = false; + lastItem.distanceMeters = 0; + lastItem.maxSpeedKmH = 0; + lastItem.reversed = false; vec.append(lastItem); } - //NOTE: Send items in queued event - //We are called from inside data() - //If we update directly the rowCount() will change - //while the view is traversing the model -> BAD - //By sending in queue we ensure no view is currently traversing the model + // NOTE: Send items in queued event + // We are called from inside data() + // If we update directly the rowCount() will change + // while the view is traversing the model -> BAD + // By sending in queue we ensure no view is currently traversing the model LineSegmentsModelResultEvent *ev = new LineSegmentsModelResultEvent; - ev->items = vec; + ev->items = vec; qApp->postEvent(this, ev); } diff --git a/src/stations/manager/lines/model/linesegmentsmodel.h b/src/stations/manager/lines/model/linesegmentsmodel.h index 492dbdc..d2243ff 100644 --- a/src/stations/manager/lines/model/linesegmentsmodel.h +++ b/src/stations/manager/lines/model/linesegmentsmodel.h @@ -33,8 +33,10 @@ /* NOTE: LineSegmentsModel should be loaded in signle batch * * Loading on demand has problems: - * - You must be careful on row counting like exclude/include last row which is a station without next segment - * - You must tell the user that there is a page after the current one otherwise he may think the line ends there. + * - You must be careful on row counting like exclude/include last row which is a station without + * next segment + * - You must tell the user that there is a page after the current one otherwise he may think the + * line ends there. * - You cannot easily calculate the position of first page item * (You must always start from first segment which may be on a previous page) * @@ -52,11 +54,14 @@ class LineSegmentsModel : public IPagedItemModel Q_OBJECT public: + enum + { + BatchSize = MaxSegmentsPerLine + }; - enum { BatchSize = MaxSegmentsPerLine }; - - enum Columns { - SegmentPosCol = -1, //Invisible (Vertical header) + enum Columns + { + SegmentPosCol = -1, // Invisible (Vertical header) StationOrSegmentNameCol = 0, KmPosCol, MaxSpeedCol, @@ -83,7 +88,8 @@ public: bool event(QEvent *e) override; // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -94,7 +100,7 @@ public: // IPagedItemModel // Cached rows management - //NOTE: custom implementation + // NOTE: custom implementation virtual void clearCache() override; virtual void refreshData(bool forceUpdate = false) override; @@ -104,25 +110,28 @@ public: bool getLineInfo(QString &nameOut, int &startMetersOut) const; bool setLineInfo(const QString &name, int startMeters); - inline int getSegmentCount() const { return curItemCount; } + inline int getSegmentCount() const + { + return curItemCount; + } inline db_id getLastStation() const { - //Use fake last segment which contains last station - if(segments.size() < 1) + // Use fake last segment which contains last station + if (segments.size() < 1) return 0; return segments.last().fromStationId; } inline db_id getLastRailwaySegment() const { - //Use ONE BUT LAST segment which contains last railway segment - if(segments.size() < 2) + // Use ONE BUT LAST segment which contains last railway segment + if (segments.size() < 2) return 0; return segments[segments.size() - 2].railwaySegmentId; } inline QString getStationNameAt(int itemPos) const { - //Use ONE BUT LAST segment which contains last railway segment - if(itemPos >= segments.size()) + // Use ONE BUT LAST segment which contains last railway segment + if (itemPos >= segments.size()) return QString(); return segments[itemPos].fromStationName; } @@ -130,16 +139,23 @@ public: bool removeSegmentsAfterPosInclusive(int pos); bool addStation(db_id railwaySegmentId, bool reverse); - //Row Type - //Event: stations - //Odd: segments - enum RowType { + // Row Type + // Event: stations + // Odd: segments + enum RowType + { StationRow, SegmentRow }; - inline RowType getRowType(int row) const { return (row % 2) == 0 ? StationRow : SegmentRow; } - inline int getItemIndex(int row) const { return (row - (row % 2)) / 2; } + inline RowType getRowType(int row) const + { + return (row % 2) == 0 ? StationRow : SegmentRow; + } + inline int getItemIndex(int row) const + { + return (row - (row % 2)) / 2; + } private: void fetchRows(); diff --git a/src/stations/manager/lines/model/linesmodel.cpp b/src/stations/manager/lines/model/linesmodel.cpp index 88247ac..cfc4615 100644 --- a/src/stations/manager/lines/model/linesmodel.cpp +++ b/src/stations/manager/lines/model/linesmodel.cpp @@ -30,15 +30,13 @@ using namespace sqlite3pp; #include -//Error messages +// Error messages static constexpr char errorNameAlreadyUsedText[] = - QT_TRANSLATE_NOOP("LinesModel", - "The name %1 is already used by another line.
" - "Please choose a different name for each railway line."); + QT_TRANSLATE_NOOP("LinesModel", "The name %1 is already used by another line.
" + "Please choose a different name for each railway line."); static constexpr char errorLineInUseText[] = - QT_TRANSLATE_NOOP("LinesModel", - "Cannot delete %1 line because it is stille referenced."); + QT_TRANSLATE_NOOP("LinesModel", "Cannot delete %1 line because it is stille referenced."); LinesModel::LinesModel(sqlite3pp::database &db, QObject *parent) : BaseClass(500, db, parent) @@ -48,7 +46,7 @@ LinesModel::LinesModel(sqlite3pp::database &db, QObject *parent) : QVariant LinesModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -65,7 +63,7 @@ QVariant LinesModel::headerData(int section, Qt::Orientation orientation, int ro } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -79,16 +77,16 @@ QVariant LinesModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const LineItem& item = cache.at(row - cacheFirstRow); + const LineItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -130,7 +128,7 @@ QVariant LinesModel::data(const QModelIndex &idx, int role) const bool LinesModel::addLine(const QString &name, db_id *outLineId) { - if(name.isEmpty()) + if (name.isEmpty()) return false; command q_newStation(mDb, "INSERT INTO lines(id,name,start_meters)" @@ -139,18 +137,18 @@ bool LinesModel::addLine(const QString &name, db_id *outLineId) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - int ret = q_newStation.execute(); + int ret = q_newStation.execute(); db_id lineId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newStation.reset(); - if((ret != SQLITE_OK && ret != SQLITE_DONE) || lineId == 0) + if ((ret != SQLITE_OK && ret != SQLITE_DONE) || lineId == 0) { - //Error - if(outLineId) + // Error + if (outLineId) *outLineId = 0; - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(name)); } @@ -161,12 +159,12 @@ bool LinesModel::addLine(const QString &name, db_id *outLineId) return false; } - if(outLineId) + if (outLineId) *outLineId = lineId; - refreshData(); //Recalc row count + refreshData(); // Recalc row count setSortingColumn(NameCol); - switchToPage(0); //Reset to first page and so it is shown as first row + switchToPage(0); // Reset to first page and so it is shown as first row emit Session->lineAdded(lineId); @@ -181,14 +179,14 @@ bool LinesModel::removeLine(db_id lineId) int ret = q_removeStation.execute(); q_removeStation.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { - //TODO: show more information to the user, like where it's still referenced + // TODO: show more information to the user, like where it's still referenced query q(mDb, "SELECT name FROM lines WHERE id=?"); q.bind(1, lineId); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { const QString name = q.getRows().get(0); emit modelError(tr(errorLineInUseText).arg(name)); @@ -204,14 +202,14 @@ bool LinesModel::removeLine(db_id lineId) emit Session->lineRemoved(lineId); - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } qint64 LinesModel::recalcTotalItemCount() { - //TODO: consider filters + // TODO: consider filters query q(mDb, "SELECT COUNT(1) FROM lines"); q.step(); const qint64 count = q.getRows().get(0); @@ -222,34 +220,35 @@ void LinesModel::internalFetch(int first, int sortCol, int valRow, const QVarian { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT id,name,start_meters FROM lines"; + QByteArray sql = "SELECT id,name,start_meters FROM lines"; switch (sortCol) { case NameCol: { - whereCol = "name"; //Order by 1 column, no where clause + whereCol = "name"; // Order by 1 column, no where clause break; } } - if(val.isValid()) + if (val.isValid()) { sql += " WHERE "; sql += whereCol; - if(reverse) + if (reverse) sql += "?3"; @@ -258,16 +257,16 @@ void LinesModel::internalFetch(int first, int sortCol, int valRow, const QVarian sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); // if(val.isValid()) @@ -284,26 +283,26 @@ void LinesModel::internalFetch(int first, int sortCol, int valRow, const QVarian QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = reverse ? BatchSize - 1 : 0; + int i = reverse ? BatchSize - 1 : 0; const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - LineItem &item = vec[i]; - item.lineId = r.get(0); - item.name = r.get(1); + auto r = *it; + LineItem &item = vec[i]; + item.lineId = r.get(0); + item.name = r.get(1); item.startMeters = r.get(2); i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/stations/manager/lines/model/linesmodel.h b/src/stations/manager/lines/model/linesmodel.h index c46d2b3..c0263c9 100644 --- a/src/stations/manager/lines/model/linesmodel.h +++ b/src/stations/manager/lines/model/linesmodel.h @@ -36,9 +36,13 @@ class LinesModel : public IPagedItemModelImpl Q_OBJECT public: - enum { BatchSize = 100 }; + enum + { + BatchSize = 100 + }; - enum Columns { + enum Columns + { NameCol = 0, StartKm, NCols @@ -52,7 +56,8 @@ public: // QAbstractTableModel // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; @@ -60,25 +65,25 @@ public: // IPagedItemModel // LinesModel - bool addLine(const QString& name, db_id *outLineId = nullptr); + bool addLine(const QString &name, db_id *outLineId = nullptr); bool removeLine(db_id lineId); // Convinience inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const LineItem& item = cache.at(row - cacheFirstRow); + const LineItem &item = cache.at(row - cacheFirstRow); return item.lineId; } inline QString getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QString(); //Invalid + return QString(); // Invalid - const LineItem& item = cache.at(row - cacheFirstRow); + const LineItem &item = cache.at(row - cacheFirstRow); return item.name; } diff --git a/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.cpp b/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.cpp index 4de2038..863381c 100644 --- a/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.cpp +++ b/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.cpp @@ -31,13 +31,14 @@ #include "utils/delegates/kmspinbox/spinboxeditorfactory.h" #include -EditRailwayConnectionDlg::EditRailwayConnectionDlg(RailwaySegmentConnectionsModel *m, QWidget *parent) : +EditRailwayConnectionDlg::EditRailwayConnectionDlg(RailwaySegmentConnectionsModel *m, + QWidget *parent) : QDialog(parent), model(m) { - QVBoxLayout *lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); - QHBoxLayout *toolLay = new QHBoxLayout; + QHBoxLayout *toolLay = new QHBoxLayout; QToolButton *addConnBut = new QToolButton; addConnBut->setText(tr("Add")); @@ -76,15 +77,16 @@ EditRailwayConnectionDlg::EditRailwayConnectionDlg(RailwaySegmentConnectionsMode toTrackFactory->setSpecialValueText(tr("NULL")); auto toTrackDelegate = new QStyledItemDelegate(this); toTrackDelegate->setItemEditorFactory(toTrackFactory); - view->setItemDelegateForColumn(RailwaySegmentConnectionsModel::ToGateTrackCol, - toTrackDelegate); + view->setItemDelegateForColumn(RailwaySegmentConnectionsModel::ToGateTrackCol, toTrackDelegate); connect(addConnBut, &QToolButton::clicked, this, &EditRailwayConnectionDlg::addTrackConn); - connect(removeConnBut, &QToolButton::clicked, this, &EditRailwayConnectionDlg::removeSelectedTrackConn); - connect(addDefaultConnBut, &QToolButton::clicked, this, &EditRailwayConnectionDlg::addDefaultConnections); + connect(removeConnBut, &QToolButton::clicked, this, + &EditRailwayConnectionDlg::removeSelectedTrackConn); + connect(addDefaultConnBut, &QToolButton::clicked, this, + &EditRailwayConnectionDlg::addDefaultConnections); - connect(model, &RailwaySegmentConnectionsModel::modelError, - this, &EditRailwayConnectionDlg::onModelError); + connect(model, &RailwaySegmentConnectionsModel::modelError, this, + &EditRailwayConnectionDlg::onModelError); connect(box, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(box, &QDialogButtonBox::rejected, this, &QDialog::reject); @@ -102,15 +104,14 @@ EditRailwayConnectionDlg::~EditRailwayConnectionDlg() void EditRailwayConnectionDlg::done(int res) { - if(!model->isReadOnly() && model->getActualCount() == 0 && res == QDialog::Accepted) + if (!model->isReadOnly() && model->getActualCount() == 0 && res == QDialog::Accepted) { - QMessageBox::warning(this, tr("Error"), - tr("Add at least 1 segment track connection.")); + QMessageBox::warning(this, tr("Error"), tr("Add at least 1 segment track connection.")); return; } - //Prevent rejecting because it's done by main dialog but let user close - //even if no connection was created for this segment to avoid getting stuck on errors + // Prevent rejecting because it's done by main dialog but let user close + // even if no connection was created for this segment to avoid getting stuck on errors Q_UNUSED(res) QDialog::done(QDialog::Accepted); } @@ -124,7 +125,7 @@ void EditRailwayConnectionDlg::addTrackConn() { int row = 0; model->addNewConnection(&row); - if(row < 0) + if (row < 0) return; QModelIndex idx = model->index(row, 0); @@ -134,11 +135,11 @@ void EditRailwayConnectionDlg::addTrackConn() void EditRailwayConnectionDlg::removeSelectedTrackConn() { - if(!view->selectionModel()->hasSelection()) + if (!view->selectionModel()->hasSelection()) return; QModelIndex idx = view->currentIndex(); - if(!idx.isValid()) + if (!idx.isValid()) return; model->removeAtRow(idx.row()); diff --git a/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.h b/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.h index dfa3cd0..0577aa0 100644 --- a/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.h +++ b/src/stations/manager/segments/dialogs/editrailwayconnectiondlg.h @@ -39,7 +39,7 @@ public: void setReadOnly(bool readOnly); private slots: - void onModelError(const QString& msg); + void onModelError(const QString &msg); void addTrackConn(); void removeSelectedTrackConn(); void addDefaultConnections(); diff --git a/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.cpp b/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.cpp index e455826..fd54750 100644 --- a/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.cpp +++ b/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.cpp @@ -53,34 +53,34 @@ EditRailwaySegmentDlg::EditRailwaySegmentDlg(sqlite3pp::database &db, manuallyApply(false) { fromStationMatch = new StationsMatchModel(db, this); - toStationMatch = new StationsMatchModel(db, this); + toStationMatch = new StationsMatchModel(db, this); - fromGateMatch = new StationGatesMatchModel(db, this); - toGateMatch = new StationGatesMatchModel(db, this); + fromGateMatch = new StationGatesMatchModel(db, this); + toGateMatch = new StationGatesMatchModel(db, this); - //Ensure filter are initialized to avoid crash if user clicks completion before setting station + // Ensure filter are initialized to avoid crash if user clicks completion before setting station fromGateMatch->setFilter(0, true, 0); toGateMatch->setFilter(0, true, 0); fromStationEdit = new CustomCompletionLineEdit(fromStationMatch); - fromGateEdit = new CustomCompletionLineEdit(fromGateMatch); - connect(fromStationEdit, &CustomCompletionLineEdit::dataIdChanged, - this, &EditRailwaySegmentDlg::onFromStationChanged); - connect(fromGateEdit, &CustomCompletionLineEdit::completionDone, - this, &EditRailwaySegmentDlg::updateTrackConnectionModel); + fromGateEdit = new CustomCompletionLineEdit(fromGateMatch); + connect(fromStationEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &EditRailwaySegmentDlg::onFromStationChanged); + connect(fromGateEdit, &CustomCompletionLineEdit::completionDone, this, + &EditRailwaySegmentDlg::updateTrackConnectionModel); toStationEdit = new CustomCompletionLineEdit(toStationMatch); - toGateEdit = new CustomCompletionLineEdit(toGateMatch); - connect(toStationEdit, &CustomCompletionLineEdit::dataIdChanged, - this, &EditRailwaySegmentDlg::onToStationChanged); - connect(toGateEdit, &CustomCompletionLineEdit::completionDone, - this, &EditRailwaySegmentDlg::updateTrackConnectionModel); + toGateEdit = new CustomCompletionLineEdit(toGateMatch); + connect(toStationEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &EditRailwaySegmentDlg::onToStationChanged); + connect(toGateEdit, &CustomCompletionLineEdit::completionDone, this, + &EditRailwaySegmentDlg::updateTrackConnectionModel); helper = new RailwaySegmentHelper(db); - //If no connection model passed, create a new one + // If no connection model passed, create a new one connModel = conn; - if(!connModel) + if (!connModel) connModel = new RailwaySegmentConnectionsModel(db, this); segmentNameEdit = new QLineEdit; @@ -88,25 +88,25 @@ EditRailwaySegmentDlg::EditRailwaySegmentDlg(sqlite3pp::database &db, distanceSpin = new KmSpinBox; distanceSpin->setPrefix(tr("Km ")); - distanceSpin->setMinimum(100); //At least 100 meters, 0.1 km + distanceSpin->setMinimum(100); // At least 100 meters, 0.1 km maxSpeedSpin = new QSpinBox; maxSpeedSpin->setRange(10, 999); maxSpeedSpin->setSuffix(tr(" km/h")); - electifiedCheck = new QCheckBox; + electifiedCheck = new QCheckBox; - fromBox = new QGroupBox(tr("From:")); + fromBox = new QGroupBox(tr("From:")); QFormLayout *fromLay = new QFormLayout(fromBox); fromLay->addRow(tr("Station:"), fromStationEdit); fromLay->addRow(tr("Gate:"), fromGateEdit); - toBox = new QGroupBox(tr("To:")); + toBox = new QGroupBox(tr("To:")); QFormLayout *toLay = new QFormLayout(toBox); toLay->addRow(tr("Station:"), toStationEdit); toLay->addRow(tr("Gate:"), toGateEdit); - QGroupBox *segmentBox = new QGroupBox(tr("Segment")); + QGroupBox *segmentBox = new QGroupBox(tr("Segment")); QFormLayout *segmentLay = new QFormLayout(segmentBox); segmentLay->addRow(tr("Name:"), segmentNameEdit); segmentLay->addRow(tr("Distance:"), distanceSpin); @@ -114,7 +114,8 @@ EditRailwaySegmentDlg::EditRailwaySegmentDlg(sqlite3pp::database &db, segmentLay->addRow(tr("Electrified:"), electifiedCheck); QPushButton *editConnBut = new QPushButton(tr("Edit")); - connect(editConnBut, &QPushButton::clicked, this, &EditRailwaySegmentDlg::editSegmentTrackConnections); + connect(editConnBut, &QPushButton::clicked, this, + &EditRailwaySegmentDlg::editSegmentTrackConnections); segmentLay->addRow(tr("Track connections:"), editConnBut); QGridLayout *lay = new QGridLayout(this); @@ -122,8 +123,8 @@ EditRailwaySegmentDlg::EditRailwaySegmentDlg(sqlite3pp::database &db, lay->addWidget(toBox, 0, 1); lay->addWidget(segmentBox, 1, 0, 1, 2); - QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, - Qt::Horizontal); + QDialogButtonBox *box = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); connect(box, &QDialogButtonBox::rejected, this, &QDialog::reject); connect(box, &QDialogButtonBox::accepted, this, &QDialog::accept); lay->addWidget(box, 2, 0, 1, 2); @@ -139,14 +140,14 @@ EditRailwaySegmentDlg::~EditRailwaySegmentDlg() void EditRailwaySegmentDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { - if(!checkValues()) + if (!checkValues()) return; - if(!manuallyApply) + if (!manuallyApply) { - if(!applyChanges()) + if (!applyChanges()) return; } } @@ -156,54 +157,54 @@ void EditRailwaySegmentDlg::done(int res) void EditRailwaySegmentDlg::setSegment(db_id segmentId, db_id lockStId, db_id lockGateId) { - m_segmentId = segmentId; + m_segmentId = segmentId; m_lockStationId = lockStId; - m_lockGateId = lockGateId; - reversed = false; + m_lockGateId = lockGateId; + reversed = false; - if(m_lockStationId == LockToCurrentValue) + if (m_lockStationId == LockToCurrentValue) { - //Not supported on station - //Because we need to know if segment is reversed + // Not supported on station + // Because we need to know if segment is reversed m_lockStationId = DoNotLock; } - if(m_lockStationId == DoNotLock) - m_lockGateId = DoNotLock; //Cannot lock gate without locking station + if (m_lockStationId == DoNotLock) + m_lockGateId = DoNotLock; // Cannot lock gate without locking station utils::RailwaySegmentInfo info; - info.segmentId = m_segmentId; + info.segmentId = m_segmentId; info.from.stationId = m_lockStationId; - info.from.gateId = m_lockGateId; + info.from.gateId = m_lockGateId; - if(m_segmentId) + if (m_segmentId) { - if(!helper->getSegmentInfo(info)) + if (!helper->getSegmentInfo(info)) { - return; //TODO: error reporting + return; // TODO: error reporting } - if(m_lockStationId == info.to.stationId) + if (m_lockStationId == info.to.stationId) { - //Reverse segment - //Locked station must appear as 'From:' + // Reverse segment + // Locked station must appear as 'From:' qSwap(info.from, info.to); reversed = true; } - else if(m_lockStationId != info.from.stationId) + else if (m_lockStationId != info.from.stationId) { - //It's neither normal nor reversed + // It's neither normal nor reversed m_lockStationId = DoNotLock; - m_lockGateId = DoNotLock; + m_lockGateId = DoNotLock; } - if(m_lockGateId == LockToCurrentValue) + if (m_lockGateId == LockToCurrentValue) { - //Lock to current gate + // Lock to current gate m_lockGateId = info.from.gateId; } - else if(m_lockGateId != info.from.gateId) + else if (m_lockGateId != info.from.gateId) { - //User passed different gate, do not lock + // User passed different gate, do not lock m_lockGateId = DoNotLock; } } @@ -213,7 +214,7 @@ void EditRailwaySegmentDlg::setSegment(db_id segmentId, db_id lockStId, db_id lo void EditRailwaySegmentDlg::setSegmentInfo(const utils::RailwaySegmentInfo &info) { - m_segmentId = info.segmentId; + m_segmentId = info.segmentId; QFlags type = info.type; @@ -221,14 +222,14 @@ void EditRailwaySegmentDlg::setSegmentInfo(const utils::RailwaySegmentInfo &info distanceSpin->setValue(info.distanceMeters); maxSpeedSpin->setValue(info.maxSpeedKmH); electifiedCheck->setChecked(type.testFlag(utils::RailwaySegmentType::Electrified)); - //FIXME: add support for other types + // FIXME: add support for other types fromStationEdit->setData(info.from.stationId); fromGateEdit->setData(info.from.gateId); toStationEdit->setData(info.to.stationId); toGateEdit->setData(info.to.gateId); - if(m_lockStationId == DoNotLock) + if (m_lockStationId == DoNotLock) { fromStationMatch->setFilter(0); fromStationMatch->refreshData(); @@ -236,12 +237,12 @@ void EditRailwaySegmentDlg::setSegmentInfo(const utils::RailwaySegmentInfo &info } else { - //Filter out 'From:' station + // Filter out 'From:' station toStationMatch->setFilter(info.from.stationId); } toStationMatch->refreshData(); - //If origin is locked prevent editing + // If origin is locked prevent editing fromStationEdit->setReadOnly(m_lockStationId != DoNotLock); fromGateEdit->setReadOnly(m_lockGateId != DoNotLock); @@ -250,13 +251,13 @@ void EditRailwaySegmentDlg::setSegmentInfo(const utils::RailwaySegmentInfo &info updateTrackConnectionModel(); - if(m_segmentId) + if (m_segmentId) { setWindowTitle(tr("Edit Railway Segment")); } else { - //It's a new segment + // It's a new segment setWindowTitle(tr("New Railway Segment")); } } @@ -274,47 +275,43 @@ bool EditRailwaySegmentDlg::checkValues() utils::RailwaySegmentInfo info; fillSegInfo(info); - if(!info.from.stationId) + if (!info.from.stationId) { - QMessageBox::warning(this, tr("Error"), - tr("Origin station must be valid.")); + QMessageBox::warning(this, tr("Error"), tr("Origin station must be valid.")); return false; } - if(!info.from.gateId) + if (!info.from.gateId) { - QMessageBox::warning(this, tr("Error"), - tr("Origin station gate must be valid.")); + QMessageBox::warning(this, tr("Error"), tr("Origin station gate must be valid.")); return false; } - if(!info.to.stationId) + if (!info.to.stationId) { - QMessageBox::warning(this, tr("Error"), - tr("Destination station must be valid.")); + QMessageBox::warning(this, tr("Error"), tr("Destination station must be valid.")); return false; } - if(!info.to.gateId) + if (!info.to.gateId) { - QMessageBox::warning(this, tr("Error"), - tr("Destination station gate must be valid.")); + QMessageBox::warning(this, tr("Error"), tr("Destination station gate must be valid.")); return false; } - if(info.segmentName.isEmpty()) + if (info.segmentName.isEmpty()) { - QMessageBox::warning(this, tr("Error"), - tr("Segment name must not be empty.")); + QMessageBox::warning(this, tr("Error"), tr("Segment name must not be empty.")); - //Try to make a default name - QString possibleName = fromStationEdit->text() + QStringLiteral("-") + toStationEdit->text(); + // Try to make a default name + QString possibleName = + fromStationEdit->text() + QStringLiteral("-") + toStationEdit->text(); possibleName = possibleName.simplified(); - if(possibleName.size() > 1) + if (possibleName.size() > 1) { - int ret = QMessageBox::question(this, tr("Default Name"), - tr("Apply default segment name %1?") - .arg(possibleName)); - if(ret == QMessageBox::Yes) + int ret = + QMessageBox::question(this, tr("Default Name"), + tr("Apply default segment name %1?").arg(possibleName)); + if (ret == QMessageBox::Yes) { - //Apply default name and return success + // Apply default name and return success segmentNameEdit->setText(possibleName); return true; } @@ -331,13 +328,11 @@ bool EditRailwaySegmentDlg::applyChanges() fillSegInfo(info); QString errMsg; - if(!helper->setSegmentInfo(m_segmentId, m_segmentId == 0, - info.segmentName, info.type, - info.distanceMeters, info.maxSpeedKmH, - info.from.gateId, info.to.gateId, &errMsg)) + if (!helper->setSegmentInfo(m_segmentId, m_segmentId == 0, info.segmentName, info.type, + info.distanceMeters, info.maxSpeedKmH, info.from.gateId, + info.to.gateId, &errMsg)) { - QMessageBox::warning(this, tr("Error"), - tr("Database error: %1").arg(errMsg)); + QMessageBox::warning(this, tr("Error"), tr("Database error: %1").arg(errMsg)); return false; } @@ -348,37 +343,37 @@ bool EditRailwaySegmentDlg::applyChanges() bool EditRailwaySegmentDlg::fillSegInfo(utils::RailwaySegmentInfo &info) { - info.segmentId = m_segmentId; - info.segmentName = segmentNameEdit->text().simplified(); + info.segmentId = m_segmentId; + info.segmentName = segmentNameEdit->text().simplified(); info.distanceMeters = distanceSpin->value(); - info.maxSpeedKmH = maxSpeedSpin->value(); + info.maxSpeedKmH = maxSpeedSpin->value(); QFlags type; - if(electifiedCheck->isChecked()) //FIXME: other types also + if (electifiedCheck->isChecked()) // FIXME: other types also type.setFlag(utils::RailwaySegmentType::Electrified); info.type = utils::RailwaySegmentType(int(type)); QString tmp; - if(!fromStationEdit->getData(info.from.stationId, info.from.stationName)) + if (!fromStationEdit->getData(info.from.stationId, info.from.stationName)) return false; - if(!fromGateEdit->getData(info.from.gateId, tmp)) + if (!fromGateEdit->getData(info.from.gateId, tmp)) return false; - if(tmp.size()) + if (tmp.size()) info.from.gateLetter = tmp.front(); - if(!toStationEdit->getData(info.to.stationId, info.to.stationName)) + if (!toStationEdit->getData(info.to.stationId, info.to.stationName)) return false; - if(!toGateEdit->getData(info.to.gateId, tmp)) + if (!toGateEdit->getData(info.to.gateId, tmp)) return false; - if(tmp.size()) + if (tmp.size()) info.to.gateLetter = tmp.front(); - if(reversed) + if (reversed) { - //Revert to original + // Revert to original qSwap(info.from, info.to); } @@ -393,25 +388,25 @@ void EditRailwaySegmentDlg::setManuallyApply(bool val) void EditRailwaySegmentDlg::onFromStationChanged(db_id stationId) { fromGateMatch->setFilter(stationId, true, m_segmentId); - fromGateEdit->setData(0); //Clear gate + fromGateEdit->setData(0); // Clear gate } void EditRailwaySegmentDlg::onToStationChanged(db_id stationId) { toGateMatch->setFilter(stationId, true, m_segmentId); - toGateEdit->setData(0); //Clear gate + toGateEdit->setData(0); // Clear gate } void EditRailwaySegmentDlg::updateTrackConnectionModel() { QString tmp; db_id fromGateId = 0; - db_id toGateId = 0; + db_id toGateId = 0; fromGateEdit->getData(fromGateId, tmp); toGateEdit->getData(toGateId, tmp); - if(!fromGateId || !toGateId) + if (!fromGateId || !toGateId) { connModel->clear(); return; @@ -419,7 +414,7 @@ void EditRailwaySegmentDlg::updateTrackConnectionModel() connModel->setSegment(m_segmentId, fromGateId, toGateId, reversed); connModel->resetData(); - if(connModel->getActualCount() == 0) + if (connModel->getActualCount() == 0) connModel->createDefaultConnections(); } diff --git a/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.h b/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.h index d479164..24c6171 100644 --- a/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.h +++ b/src/stations/manager/segments/dialogs/editrailwaysegmentdlg.h @@ -43,14 +43,13 @@ class QSpinBox; class QCheckBox; class QLineEdit; - class EditRailwaySegmentDlg : public QDialog { Q_OBJECT public: enum LockField { - DoNotLock = 0, + DoNotLock = 0, LockToCurrentValue = -1 }; @@ -70,15 +69,14 @@ public: * * \sa RailwaySegmentConnectionsModel */ - EditRailwaySegmentDlg(sqlite3pp::database &db, - RailwaySegmentConnectionsModel *conn = nullptr, + EditRailwaySegmentDlg(sqlite3pp::database &db, RailwaySegmentConnectionsModel *conn = nullptr, QWidget *parent = nullptr); ~EditRailwaySegmentDlg(); virtual void done(int res) override; void setSegment(db_id segmentId, db_id lockStId, db_id lockGateId); - void setSegmentInfo(const utils::RailwaySegmentInfo& info); + void setSegmentInfo(const utils::RailwaySegmentInfo &info); void setGatesReadOnly(bool val); diff --git a/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.cpp b/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.cpp index 813dac9..a1f2edf 100644 --- a/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.cpp +++ b/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.cpp @@ -45,28 +45,28 @@ SplitRailwaySegmentDlg::SplitRailwaySegmentDlg(sqlite3pp::database &db, QWidget QDialog(parent), mDb(db) { - stationsModel = new StationsMatchModel(mDb, this); - middleInGateModel = new StationGatesMatchModel(mDb, this); + stationsModel = new StationsMatchModel(mDb, this); + middleInGateModel = new StationGatesMatchModel(mDb, this); middleOutGateModel = new StationGatesMatchModel(mDb, this); stationsModel->setFilter(0); origSegConnModel = new RailwaySegmentConnectionsModel(mDb, this); - newSegConnModel = new RailwaySegmentConnectionsModel(mDb, this); + newSegConnModel = new RailwaySegmentConnectionsModel(mDb, this); QVBoxLayout *lay = new QVBoxLayout(this); - //Segment: + // Segment: selectSegBut = new QPushButton("Select Segment"); lay->addWidget(selectSegBut); segmentLabel = new QLabel; lay->addWidget(segmentLabel); - //From: - fromBox = new QGroupBox(tr("From:")); + // From: + fromBox = new QGroupBox(tr("From:")); QFormLayout *formLay = new QFormLayout(fromBox); - fromStationLabel = new QLabel; + fromStationLabel = new QLabel; formLay->addRow(tr("Station:"), fromStationLabel); fromGateLabel = new QLabel; @@ -76,18 +76,18 @@ SplitRailwaySegmentDlg::SplitRailwaySegmentDlg(sqlite3pp::database &db, QWidget editOldSegBut = new QPushButton(tr("Edit First Segment")); lay->addWidget(editOldSegBut); - //Middle: + // Middle: middleBox = new QGroupBox(tr("Middle:")); - formLay = new QFormLayout(middleBox); + formLay = new QFormLayout(middleBox); - //Segment Out Gate is Middle Station In Gate + // Segment Out Gate is Middle Station In Gate middleInGateEdit = new CustomCompletionLineEdit(middleInGateModel); formLay->addRow(tr("In Gate:"), middleInGateEdit); middleStationEdit = new CustomCompletionLineEdit(stationsModel); formLay->addRow(tr("Station:"), middleStationEdit); - //Middle Station Out Gate is New Segment In Gate + // Middle Station Out Gate is New Segment In Gate middleOutGateEdit = new CustomCompletionLineEdit(middleOutGateModel); formLay->addRow(tr("Out Gate:"), middleOutGateEdit); lay->addWidget(middleBox); @@ -95,9 +95,9 @@ SplitRailwaySegmentDlg::SplitRailwaySegmentDlg(sqlite3pp::database &db, QWidget editNewSegBut = new QPushButton(tr("Edit Second Segment")); lay->addWidget(editNewSegBut); - //To: - toBox = new QGroupBox(tr("To:")); - formLay = new QFormLayout(toBox); + // To: + toBox = new QGroupBox(tr("To:")); + formLay = new QFormLayout(toBox); toGateLabel = new QLabel; formLay->addRow(tr("Gate:"), toGateLabel); @@ -115,14 +115,14 @@ SplitRailwaySegmentDlg::SplitRailwaySegmentDlg(sqlite3pp::database &db, QWidget connect(editOldSegBut, &QPushButton::clicked, this, &SplitRailwaySegmentDlg::editOldSegment); connect(editNewSegBut, &QPushButton::clicked, this, &SplitRailwaySegmentDlg::editNewSegment); - connect(middleStationEdit, &CustomCompletionLineEdit::completionDone, - this, &SplitRailwaySegmentDlg::onStationSelected); - connect(middleInGateEdit, &CustomCompletionLineEdit::completionDone, - this, &SplitRailwaySegmentDlg::onMiddleInCompletionDone); - connect(middleOutGateEdit, &CustomCompletionLineEdit::completionDone, - this, &SplitRailwaySegmentDlg::onMiddleOutCompletionDone); + connect(middleStationEdit, &CustomCompletionLineEdit::completionDone, this, + &SplitRailwaySegmentDlg::onStationSelected); + connect(middleInGateEdit, &CustomCompletionLineEdit::completionDone, this, + &SplitRailwaySegmentDlg::onMiddleInCompletionDone); + connect(middleOutGateEdit, &CustomCompletionLineEdit::completionDone, this, + &SplitRailwaySegmentDlg::onMiddleOutCompletionDone); - //Reset segment + // Reset segment setMainSegment(0); setMinimumSize(200, 200); @@ -132,21 +132,20 @@ SplitRailwaySegmentDlg::SplitRailwaySegmentDlg(sqlite3pp::database &db, QWidget SplitRailwaySegmentDlg::~SplitRailwaySegmentDlg() { - } void SplitRailwaySegmentDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { - if(!origSegInfo.to.stationId) + if (!origSegInfo.to.stationId) { QMessageBox::warning(this, tr("No Station"), tr("You must choose a station to put in the middle.")); return; } - if(!origSegInfo.to.gateId || !newSegInfo.from.gateId) + if (!origSegInfo.to.gateId || !newSegInfo.from.gateId) { QMessageBox::warning(this, tr("No Gates"), tr("You must choose in and out gates for middle Station.")); @@ -155,10 +154,9 @@ void SplitRailwaySegmentDlg::done(int res) RailwaySegmentSplitHelper helper(mDb, origSegConnModel, newSegConnModel); helper.setInfo(origSegInfo, newSegInfo); - if(!helper.split()) + if (!helper.split()) { - QMessageBox::warning(this, tr("Error"), - tr("Split of segment failed.")); + QMessageBox::warning(this, tr("Error"), tr("Split of segment failed.")); return; } } @@ -174,7 +172,7 @@ void SplitRailwaySegmentDlg::selectSegment() dlg->setDescription(tr("Choose a Railway Segment to split in 2 parts.\n" "A station will be inserted in the middle.")); dlg->setPlaceholder(tr("Segment...")); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; const db_id segmentId = dlg->getItemId(); @@ -192,29 +190,27 @@ void SplitRailwaySegmentDlg::onStationSelected() void SplitRailwaySegmentDlg::editOldSegment() { - OwningQPointer dlg = new EditRailwaySegmentDlg(mDb, - origSegConnModel, - this); + OwningQPointer dlg = + new EditRailwaySegmentDlg(mDb, origSegConnModel, this); dlg->setManuallyApply(true); dlg->setSegmentInfo(origSegInfo); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; - //Get info back + // Get info back dlg->fillSegInfo(origSegInfo); } void SplitRailwaySegmentDlg::editNewSegment() { - OwningQPointer dlg = new EditRailwaySegmentDlg(mDb, - newSegConnModel, - this); + OwningQPointer dlg = + new EditRailwaySegmentDlg(mDb, newSegConnModel, this); dlg->setManuallyApply(true); dlg->setSegmentInfo(newSegInfo); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; - //Get info back + // Get info back dlg->fillSegInfo(newSegInfo); } @@ -222,7 +218,7 @@ void SplitRailwaySegmentDlg::onMiddleInCompletionDone() { QString tmp; middleInGateEdit->getData(origSegInfo.to.gateId, tmp); - if(tmp.size()) + if (tmp.size()) origSegInfo.to.gateLetter = tmp.front(); } @@ -230,7 +226,7 @@ void SplitRailwaySegmentDlg::onMiddleOutCompletionDone() { QString tmp; middleOutGateEdit->getData(newSegInfo.from.gateId, tmp); - if(tmp.size()) + if (tmp.size()) newSegInfo.from.gateLetter = tmp.front(); } @@ -238,42 +234,42 @@ void SplitRailwaySegmentDlg::setMainSegment(db_id segmentId) { origSegInfo.segmentId = segmentId; - //Reset outer info + // Reset outer info origSegInfo.from = newSegInfo.to = utils::RailwaySegmentGateInfo(); utils::RailwaySegmentInfo info; info.segmentId = origSegInfo.segmentId; RailwaySegmentHelper helper(mDb); - if(origSegInfo.segmentId && helper.getSegmentInfo(info)) + if (origSegInfo.segmentId && helper.getSegmentInfo(info)) { - origSegInfo.segmentName = info.segmentName; + origSegInfo.segmentName = info.segmentName; origSegInfo.distanceMeters = info.distanceMeters; - origSegInfo.maxSpeedKmH = info.maxSpeedKmH; - origSegInfo.type = info.type; + origSegInfo.maxSpeedKmH = info.maxSpeedKmH; + origSegInfo.type = info.type; - //Split segment info in 2 parts + // Split segment info in 2 parts origSegInfo.from = info.from; - newSegInfo.to = info.to; + newSegInfo.to = info.to; - //Get station names + // Get station names origSegInfo.from.stationName = stationsModel->getName(origSegInfo.from.stationId); - newSegInfo.to.stationName = stationsModel->getName(newSegInfo.to.stationId); + newSegInfo.to.stationName = stationsModel->getName(newSegInfo.to.stationId); - //Get gate names + // Get gate names QString tmp = middleInGateModel->getName(origSegInfo.from.gateId); - if(tmp.size()) + if (tmp.size()) origSegInfo.from.gateLetter = tmp.front(); tmp = middleInGateModel->getName(newSegInfo.to.gateId); - if(tmp.size()) + if (tmp.size()) newSegInfo.to.gateLetter = tmp.front(); newSegInfo.type = origSegInfo.type; } else { - //Failed to reteive info + // Failed to reteive info origSegInfo.segmentId = 0; } @@ -285,31 +281,30 @@ void SplitRailwaySegmentDlg::setMainSegment(db_id segmentId) toStationLabel->setText(newSegInfo.to.stationName); toGateLabel->setText(newSegInfo.to.gateLetter); - //Allow setting middle station only after settin main segment + // Allow setting middle station only after settin main segment middleStationEdit->setEnabled(origSegInfo.segmentId != 0); butBox->button(QDialogButtonBox::Ok)->setEnabled(origSegInfo.segmentId != 0); - //Reset middle station + // Reset middle station setMiddleStation(0); } void SplitRailwaySegmentDlg::setMiddleStation(db_id stationId) { - //Reset station + // Reset station origSegInfo.to = newSegInfo.from = utils::RailwaySegmentGateInfo(); origSegInfo.to.stationId = newSegInfo.from.stationId = stationId; - const QString middleStName = stationsModel->getName(stationId); + const QString middleStName = stationsModel->getName(stationId); origSegInfo.to.stationName = newSegInfo.from.stationName = middleStName; - if(middleStName.isEmpty()) + if (middleStName.isEmpty()) newSegInfo.segmentName.clear(); else setNewSegmentName(newSegInfo.from.stationName + '-' + newSegInfo.to.stationName); - middleStationEdit->setData(stationId, middleStName); middleInGateEdit->setData(0); middleOutGateEdit->setData(0); @@ -317,7 +312,7 @@ void SplitRailwaySegmentDlg::setMiddleStation(db_id stationId) middleInGateModel->setFilter(stationId, true, 0); middleOutGateModel->setFilter(stationId, true, 0); - //Allow selecting Gates and Edit Segment only after Middle Station is set + // Allow selecting Gates and Edit Segment only after Middle Station is set middleInGateEdit->setEnabled(stationId != 0); middleOutGateEdit->setEnabled(stationId != 0); editOldSegBut->setEnabled(stationId != 0); @@ -326,20 +321,20 @@ void SplitRailwaySegmentDlg::setMiddleStation(db_id stationId) void SplitRailwaySegmentDlg::setNewSegmentName(const QString &possibleName) { - //Find available segment name + // Find available segment name query q(mDb, "SELECT id FROM railway_segments WHERE name=? LIMIT 1"); const QString fmt = QLatin1String("%1_%2"); - QString name = possibleName; - for(int i = 0; i < 10; i++) + QString name = possibleName; + for (int i = 0; i < 10; i++) { - if(i != 0) + if (i != 0) name = fmt.arg(possibleName).arg(i); q.bind(1, name); int ret = q.step(); - if(ret == SQLITE_OK || ret == SQLITE_DONE) + if (ret == SQLITE_OK || ret == SQLITE_DONE) { - //Found available name + // Found available name newSegInfo.segmentName = name; break; } diff --git a/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.h b/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.h index c66f0da..137a916 100644 --- a/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.h +++ b/src/stations/manager/segments/dialogs/splitrailwaysegmentdlg.h @@ -62,29 +62,29 @@ private slots: private: void setMiddleStation(db_id stationId); - void setNewSegmentName(const QString& possibleName); + void setNewSegmentName(const QString &possibleName); private: sqlite3pp::database &mDb; - //Original Segment + // Original Segment QLabel *segmentLabel; QPushButton *selectSegBut; - //From + // From QGroupBox *fromBox; QLabel *fromStationLabel; QLabel *fromGateLabel; QPushButton *editOldSegBut; - //Middle insert + // Middle insert QGroupBox *middleBox; CustomCompletionLineEdit *middleStationEdit; CustomCompletionLineEdit *middleInGateEdit; CustomCompletionLineEdit *middleOutGateEdit; QPushButton *editNewSegBut; - //To + // To QGroupBox *toBox; QLabel *toGateLabel; QLabel *toStationLabel; diff --git a/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.cpp b/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.cpp index cb59fea..0d2d075 100644 --- a/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.cpp +++ b/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.cpp @@ -26,26 +26,22 @@ using namespace sqlite3pp; #include -//Error messages +// Error messages static constexpr char errorNegativeNumber[] = - QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", - "Cannot set negative number as track."); + QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", "Cannot set negative number as track."); static constexpr char errorOutOfBound[] = - QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", - "Track number out of bound.
" - "Gate has only %1 tracks."); + QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", "Track number out of bound.
" + "Gate has only %1 tracks."); -static constexpr char errorAlreadyConnectedFrom[] = - QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", - "Track %1 is already connected to track %2."); +static constexpr char errorAlreadyConnectedFrom[] = QT_TRANSLATE_NOOP( + "RailwaySegmentConnectionsModel", "Track %1 is already connected to track %2."); -static constexpr char errorAlreadyConnectedTo[] = - QT_TRANSLATE_NOOP("RailwaySegmentConnectionsModel", - "Track %1 is already connected from track %2."); +static constexpr char errorAlreadyConnectedTo[] = QT_TRANSLATE_NOOP( + "RailwaySegmentConnectionsModel", "Track %1 is already connected from track %2."); - -RailwaySegmentConnectionsModel::RailwaySegmentConnectionsModel(sqlite3pp::database &db, QObject *parent) : +RailwaySegmentConnectionsModel::RailwaySegmentConnectionsModel(sqlite3pp::database &db, + QObject *parent) : QAbstractTableModel(parent), mDb(db), m_segmentId(0), @@ -58,12 +54,12 @@ RailwaySegmentConnectionsModel::RailwaySegmentConnectionsModel(sqlite3pp::databa m_reversed(0), readOnly(false) { - } -QVariant RailwaySegmentConnectionsModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant RailwaySegmentConnectionsModel::headerData(int section, Qt::Orientation orientation, + int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -109,13 +105,13 @@ QVariant RailwaySegmentConnectionsModel::data(const QModelIndex &idx, int role) { case FromGateTrackCol: { - if(item.fromTrack == InvalidTrack) + if (item.fromTrack == InvalidTrack) return tr("NULL"); return item.fromTrack; } case ToGateTrackCol: { - if(item.toTrack == InvalidTrack) + if (item.toTrack == InvalidTrack) return tr("NULL"); return item.toTrack; } @@ -160,7 +156,7 @@ QVariant RailwaySegmentConnectionsModel::data(const QModelIndex &idx, int role) switch (item.state) { case NoChange: - return QVariant(); //No background + return QVariant(); // No background case AddedButNotComplete: color = Qt::cyan; break; @@ -181,41 +177,44 @@ QVariant RailwaySegmentConnectionsModel::data(const QModelIndex &idx, int role) return QVariant(); } -bool RailwaySegmentConnectionsModel::setData(const QModelIndex &idx, const QVariant &value, int role) +bool RailwaySegmentConnectionsModel::setData(const QModelIndex &idx, const QVariant &value, + int role) { if (readOnly || !idx.isValid() || idx.column() >= NCols || role != Qt::EditRole) return false; - RailwayTrack& item = items[idx.row()]; - if(item.state == ToRemove) + RailwayTrack &item = items[idx.row()]; + if (item.state == ToRemove) return false; - bool ok = false; + bool ok = false; int trackNum = value.toInt(&ok); - if(!ok || trackNum < 0) + if (!ok || trackNum < 0) { emit modelError(tr(errorNegativeNumber)); return false; } - if(idx.column() == FromGateTrackCol) + if (idx.column() == FromGateTrackCol) { - if(trackNum == item.fromTrack) - return false; //No change + if (trackNum == item.fromTrack) + return false; // No change - if(trackNum >= m_fromGateTrackCount) + if (trackNum >= m_fromGateTrackCount) { - //Out of bound + // Out of bound emit modelError(tr(errorOutOfBound).arg(m_fromGateTrackCount)); return false; } - for(const RailwayTrack& other : qAsConst(items)) + for (const RailwayTrack &other : qAsConst(items)) { - if(other.state != ToRemove && other.state != AddedButNotComplete && other.fromTrack == trackNum) + if (other.state != ToRemove && other.state != AddedButNotComplete + && other.fromTrack == trackNum) { - //Already connected - emit modelError(tr(errorAlreadyConnectedFrom).arg(item.fromTrack).arg(item.toTrack)); + // Already connected + emit modelError( + tr(errorAlreadyConnectedFrom).arg(item.fromTrack).arg(item.toTrack)); return false; } } @@ -224,21 +223,22 @@ bool RailwaySegmentConnectionsModel::setData(const QModelIndex &idx, const QVari } else { - if(trackNum == item.toTrack) - return false; //No change + if (trackNum == item.toTrack) + return false; // No change - if(trackNum >= m_toGateTrackCount) + if (trackNum >= m_toGateTrackCount) { - //Out of bound + // Out of bound emit modelError(tr(errorOutOfBound).arg(m_toGateTrackCount)); return false; } - for(const RailwayTrack& other : qAsConst(items)) + for (const RailwayTrack &other : qAsConst(items)) { - if(other.state != ToRemove && other.state != AddedButNotComplete && other.toTrack == trackNum) + if (other.state != ToRemove && other.state != AddedButNotComplete + && other.toTrack == trackNum) { - //Already connected + // Already connected emit modelError(tr(errorAlreadyConnectedTo).arg(item.toTrack).arg(item.fromTrack)); return false; } @@ -247,20 +247,20 @@ bool RailwaySegmentConnectionsModel::setData(const QModelIndex &idx, const QVari item.toTrack = trackNum; } - if(item.state == NoChange) + if (item.state == NoChange) { item.state = Edited; } - else if(item.state == AddedButNotComplete) + else if (item.state == AddedButNotComplete) { - if(item.fromTrack > InvalidTrack && item.toTrack > InvalidTrack) + if (item.fromTrack > InvalidTrack && item.toTrack > InvalidTrack) { - //Now it's complete so reset + // Now it's complete so reset incompleteRowAdded = -1; - if(item.connId) - item.state = Edited; //Was recycled from ToRemove + if (item.connId) + item.state = Edited; // Was recycled from ToRemove else - item.state = ToAdd; //New to add + item.state = ToAdd; // New to add } } @@ -275,20 +275,21 @@ Qt::ItemFlags RailwaySegmentConnectionsModel::flags(const QModelIndex &idx) cons Qt::ItemFlags f = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - //Prevent editing in removed rows + // Prevent editing in removed rows const RailwayTrack &item = items.at(idx.row()); - if(!readOnly && item.state != ToRemove) + if (!readOnly && item.state != ToRemove) f.setFlag(Qt::ItemIsEditable); return f; } -void RailwaySegmentConnectionsModel::setSegment(db_id segmentId, db_id fromGateId, db_id toGateId, bool reversed) +void RailwaySegmentConnectionsModel::setSegment(db_id segmentId, db_id fromGateId, db_id toGateId, + bool reversed) { - m_segmentId = segmentId; + m_segmentId = segmentId; m_fromGateId = fromGateId; - m_toGateId = toGateId; - m_reversed = reversed; + m_toGateId = toGateId; + m_reversed = reversed; query q(mDb, "SELECT out_track_count FROM station_gates WHERE id=?"); q.bind(1, m_fromGateId); @@ -306,35 +307,36 @@ void RailwaySegmentConnectionsModel::resetData() beginResetModel(); items.clear(); - actualCount = 0; + actualCount = 0; incompleteRowAdded = -1; query q(mDb, "SELECT COUNT(1) FROM railway_connections WHERE seg_id=?"); q.bind(1, m_segmentId); q.step(); int count = q.getRows().get(0); - if(!count) + if (!count) { endResetModel(); return; } - q.prepare("SELECT id,in_track,out_track FROM railway_connections WHERE seg_id=? ORDER BY in_track"); + q.prepare( + "SELECT id,in_track,out_track FROM railway_connections WHERE seg_id=? ORDER BY in_track"); q.bind(1, m_segmentId); const int fromTrackCol = m_reversed ? 2 : 1; - const int toTrackCol = m_reversed ? 1 : 2; + const int toTrackCol = m_reversed ? 1 : 2; - for(auto conn : q) + for (auto conn : q) { RailwayTrack track; - track.connId = conn.get(0); + track.connId = conn.get(0); track.fromTrack = conn.get(fromTrackCol); - track.toTrack = conn.get(toTrackCol); + track.toTrack = conn.get(toTrackCol); - if(track.fromTrack >= m_fromGateTrackCount || track.toTrack >= m_toGateTrackCount) + if (track.fromTrack >= m_fromGateTrackCount || track.toTrack >= m_toGateTrackCount) { - //Must remove this connection + // Must remove this connection track.state = ToRemove; } else @@ -353,40 +355,40 @@ void RailwaySegmentConnectionsModel::clear() { beginResetModel(); items.clear(); - actualCount = 0; + actualCount = 0; incompleteRowAdded = -1; endResetModel(); } void RailwaySegmentConnectionsModel::createDefaultConnections() { - if(readOnly || m_fromGateTrackCount == 0 || m_toGateTrackCount == 0) + if (readOnly || m_fromGateTrackCount == 0 || m_toGateTrackCount == 0) return; RailwayTrack track; - track.connId = 0; - track.state = ToAdd; + track.connId = 0; + track.state = ToAdd; track.fromTrack = 0; - if(m_toGateTrackCount == 2 && m_fromGateTrackCount == 2) + if (m_toGateTrackCount == 2 && m_fromGateTrackCount == 2) { - //This is a double track line - //Connect 0 -> 1 and 1 -> 0 - //Think it like elctonic pole ('+' -> '-' and '-' -> '+') + // This is a double track line + // Connect 0 -> 1 and 1 -> 0 + // Think it like elctonic pole ('+' -> '-' and '-' -> '+') - //0 -> 1 + // 0 -> 1 track.toTrack = 1; insertOrReplace(track); - //1 -> 0 + // 1 -> 0 track.fromTrack = 1; - track.toTrack = 0; + track.toTrack = 0; insertOrReplace(track); } else { - //In every other case just connect first track to first track - //0 -> 0 + // In every other case just connect first track to first track + // 0 -> 0 track.toTrack = 0; insertOrReplace(track); } @@ -394,16 +396,16 @@ void RailwaySegmentConnectionsModel::createDefaultConnections() void RailwaySegmentConnectionsModel::removeAtRow(int row) { - if(readOnly || row < 0 || row >= items.size()) + if (readOnly || row < 0 || row >= items.size()) return; RailwayTrack &track = items[row]; - if(track.state == AddedButNotComplete) - incompleteRowAdded = -1; //Reset + if (track.state == AddedButNotComplete) + incompleteRowAdded = -1; // Reset - if(track.state == ToAdd || (track.state == AddedButNotComplete && !track.connId)) + if (track.state == ToAdd || (track.state == AddedButNotComplete && !track.connId)) { - //This track is not yet in the database so remove it + // This track is not yet in the database so remove it beginRemoveRows(QModelIndex(), row, row); items.removeAt(row); actualCount--; @@ -411,166 +413,166 @@ void RailwaySegmentConnectionsModel::removeAtRow(int row) } else { - //This track is already in the database so mark it - if(track.state != ToRemove) + // This track is already in the database so mark it + if (track.state != ToRemove) actualCount--; track.state = ToRemove; - emit dataChanged(index(row, FromGateTrackCol), - index(row, ToGateTrackCol)); + emit dataChanged(index(row, FromGateTrackCol), index(row, ToGateTrackCol)); } } void RailwaySegmentConnectionsModel::addNewConnection(int *outRow) { - if(readOnly) + if (readOnly) { - if(outRow) + if (outRow) *outRow = -1; return; } - if(incompleteRowAdded >= 0) + if (incompleteRowAdded >= 0) { - //Already added and incomplete - if(outRow) + // Already added and incomplete + if (outRow) *outRow = incompleteRowAdded; return; } RailwayTrack track; track.fromTrack = InvalidTrack; - track.toTrack = InvalidTrack; - int row = insertOrReplace(track); - if(row < 0) - row = items.size() - 1; //Last (was appended) + track.toTrack = InvalidTrack; + int row = insertOrReplace(track); + if (row < 0) + row = items.size() - 1; // Last (was appended) - items[row].state = AddedButNotComplete; + items[row].state = AddedButNotComplete; incompleteRowAdded = row; - if(outRow) + if (outRow) *outRow = row; } bool RailwaySegmentConnectionsModel::applyChanges(db_id overrideSegmentId) { - if(readOnly) + if (readOnly) return false; - if(incompleteRowAdded >= 0) + if (incompleteRowAdded >= 0) { - RailwayTrack& item = items[incompleteRowAdded]; - if(item.fromTrack == InvalidTrack || item.toTrack == InvalidTrack) + RailwayTrack &item = items[incompleteRowAdded]; + if (item.fromTrack == InvalidTrack || item.toTrack == InvalidTrack) { - //Item is still invalid - if(item.connId) + // Item is still invalid + if (item.connId) { - //Item was recycled so remove it + // Item was recycled so remove it item.state = ToRemove; } } } - //First remove all ToRemove + // First remove all ToRemove command cmd(mDb, "DELETE FROM railway_connections WHERE id=?"); - for(const RailwayTrack& item : qAsConst(items)) + for (const RailwayTrack &item : qAsConst(items)) { - if(item.state == ToRemove) + if (item.state == ToRemove) { cmd.bind(1, item.connId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error removing track conn ID:" << item.connId << "Segment:" << m_segmentId - << "From:" << item.fromTrack << "To:" << item.toTrack - << mDb.error_msg(); + qWarning() << "Error removing track conn ID:" << item.connId + << "Segment:" << m_segmentId << "From:" << item.fromTrack + << "To:" << item.toTrack << mDb.error_msg(); } cmd.reset(); } } - //Then edit all Edited + // Then edit all Edited cmd.prepare("UPDATE railway_connections SET in_track=?, out_track=? WHERE id=?"); const int fromTrackCol = m_reversed ? 2 : 1; - const int toTrackCol = m_reversed ? 1 : 2; - for(const RailwayTrack& item : qAsConst(items)) + const int toTrackCol = m_reversed ? 1 : 2; + for (const RailwayTrack &item : qAsConst(items)) { - if(item.state == Edited) + if (item.state == Edited) { cmd.bind(fromTrackCol, item.fromTrack); cmd.bind(toTrackCol, item.toTrack); cmd.bind(3, item.connId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - qWarning() << "Error editing track conn ID:" << item.connId << "Segment:" << m_segmentId - << "New From:" << item.fromTrack << "New To:" << item.toTrack - << mDb.error_msg(); + qWarning() << "Error editing track conn ID:" << item.connId + << "Segment:" << m_segmentId << "New From:" << item.fromTrack + << "New To:" << item.toTrack << mDb.error_msg(); } cmd.reset(); } } - //Lock to retreive inserted ID + // Lock to retreive inserted ID sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - //Finally add all ToAdd - cmd.prepare("INSERT INTO railway_connections(id,seg_id,in_track,out_track) VALUES(NULL,?3,?1,?2)"); - for(RailwayTrack& item : items) + // Finally add all ToAdd + cmd.prepare( + "INSERT INTO railway_connections(id,seg_id,in_track,out_track) VALUES(NULL,?3,?1,?2)"); + for (RailwayTrack &item : items) { - if(item.state == ToAdd) + if (item.state == ToAdd) { cmd.bind(fromTrackCol, item.fromTrack); cmd.bind(toTrackCol, item.toTrack); cmd.bind(3, overrideSegmentId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { qWarning() << "Error adding track conn to Segment:" << m_segmentId - << "From:" << item.fromTrack << "To:" << item.toTrack - << mDb.error_msg(); + << "From:" << item.fromTrack << "To:" << item.toTrack << mDb.error_msg(); } item.connId = mDb.last_insert_rowid(); cmd.reset(); } } - //Unlock database + // Unlock database sqlite3_mutex_leave(mutex); return true; } -int RailwaySegmentConnectionsModel::insertOrReplace(const RailwaySegmentConnectionsModel::RailwayTrack &newTrack) +int RailwaySegmentConnectionsModel::insertOrReplace( + const RailwaySegmentConnectionsModel::RailwayTrack &newTrack) { - //Check if track is already connected - for(const RailwayTrack& other : qAsConst(items)) + // Check if track is already connected + for (const RailwayTrack &other : qAsConst(items)) { - if(other.state == ToRemove || other.state == AddedButNotComplete) - continue; //Ignore these items + if (other.state == ToRemove || other.state == AddedButNotComplete) + continue; // Ignore these items - if(other.fromTrack == newTrack.fromTrack || other.toTrack == newTrack.toTrack) + if (other.fromTrack == newTrack.fromTrack || other.toTrack == newTrack.toTrack) { - //Track is already connected, cannot connect twice + // Track is already connected, cannot connect twice return TrackAlreadyConnected; } } - actualCount++; //We will have one more row + actualCount++; // We will have one more row - //Reuse removed rows if any - for(int i = 0; i < items.size(); i++) + // Reuse removed rows if any + for (int i = 0; i < items.size(); i++) { - if(items.at(i).state == ToRemove) + if (items.at(i).state == ToRemove) { RailwayTrack &track = items[i]; - //Copy track numbers + // Copy track numbers track.fromTrack = newTrack.fromTrack; - track.toTrack = newTrack.toTrack; + track.toTrack = newTrack.toTrack; - //Set as edited so doesn't get removed + // Set as edited so doesn't get removed track.state = Edited; emit dataChanged(index(i, FromGateTrackCol), index(i, ToGateTrackCol)); @@ -579,11 +581,11 @@ int RailwaySegmentConnectionsModel::insertOrReplace(const RailwaySegmentConnecti } } - //No removed row found, insert new + // No removed row found, insert new beginInsertRows(QModelIndex(), items.size(), items.size()); items.append(newTrack); items.last().connId = 0; - items.last().state = ToAdd; + items.last().state = ToAdd; endInsertRows(); return NewTrackAdded; } diff --git a/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.h b/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.h index 5550352..43f6efc 100644 --- a/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.h +++ b/src/stations/manager/segments/model/railwaysegmentconnectionsmodel.h @@ -35,13 +35,15 @@ class RailwaySegmentConnectionsModel : public QAbstractTableModel Q_OBJECT public: - enum Columns { + enum Columns + { FromGateTrackCol = 0, ToGateTrackCol, NCols }; - enum ItemState { + enum ItemState + { NoChange = 0, AddedButNotComplete, ToAdd, @@ -57,14 +59,15 @@ public: ItemState state; }; - static constexpr const int InvalidTrack = -1; - static constexpr const int NewTrackAdded = -1; + static constexpr const int InvalidTrack = -1; + static constexpr const int NewTrackAdded = -1; static constexpr const int TrackAlreadyConnected = -2; RailwaySegmentConnectionsModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -73,21 +76,35 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; void setSegment(db_id segmentId, db_id fromGateId, db_id toGateId, bool reversed); void resetData(); void clear(); - inline int getActualCount() const { return actualCount; } - inline void setReadOnly(bool val) { readOnly = val; } - inline bool isReadOnly() const { return readOnly; } + inline int getActualCount() const + { + return actualCount; + } + inline void setReadOnly(bool val) + { + readOnly = val; + } + inline bool isReadOnly() const + { + return readOnly; + } - inline int getFromGateTrackCount() const { return m_fromGateTrackCount; } - inline int getToGateTrackCount() const { return m_toGateTrackCount; } + inline int getFromGateTrackCount() const + { + return m_fromGateTrackCount; + } + inline int getToGateTrackCount() const + { + return m_toGateTrackCount; + } void createDefaultConnections(); @@ -97,10 +114,10 @@ public: bool applyChanges(db_id overrideSegmentId); signals: - void modelError(const QString& msg); + void modelError(const QString &msg); private: - int insertOrReplace(const RailwayTrack& newTrack); + int insertOrReplace(const RailwayTrack &newTrack); private: sqlite3pp::database &mDb; diff --git a/src/stations/manager/segments/model/railwaysegmenthelper.cpp b/src/stations/manager/segments/model/railwaysegmenthelper.cpp index 5b226e5..ac66935 100644 --- a/src/stations/manager/segments/model/railwaysegmenthelper.cpp +++ b/src/stations/manager/segments/model/railwaysegmenthelper.cpp @@ -26,22 +26,20 @@ using namespace sqlite3pp; #include -//Error messages +// Error messages class RailwaySegmentHelperStrings { Q_DECLARE_TR_FUNCTIONS(RailwaySegmentHelperStrings) }; -static constexpr char - errorSegmentInUseText[] = - QT_TRANSLATE_NOOP("RailwaySegmentHelperStrings", - "Cannot delete segment %1 because it is still referenced.
" - "Please delete all jobs travelling on this segment or change their path."); +static constexpr char errorSegmentInUseText[] = + QT_TRANSLATE_NOOP("RailwaySegmentHelperStrings", + "Cannot delete segment %1 because it is still referenced.
" + "Please delete all jobs travelling on this segment or change their path."); RailwaySegmentHelper::RailwaySegmentHelper(sqlite3pp::database &db) : mDb(db) { - } bool RailwaySegmentHelper::getSegmentInfo(utils::RailwaySegmentInfo &info) @@ -54,20 +52,20 @@ bool RailwaySegmentHelper::getSegmentInfo(utils::RailwaySegmentInfo &info) " JOIN station_gates g2 ON g2.id=s.out_gate_id" " WHERE s.id=?"); q.bind(1, info.segmentId); - if(q.step() != SQLITE_ROW) - return false; //FIXME: show error to user + if (q.step() != SQLITE_ROW) + return false; // FIXME: show error to user - auto r = q.getRows(); - info.segmentName = r.get(0); - info.maxSpeedKmH = r.get(1); - info.type = utils::RailwaySegmentType(r.get(2)); + auto r = q.getRows(); + info.segmentName = r.get(0); + info.maxSpeedKmH = r.get(1); + info.type = utils::RailwaySegmentType(r.get(2)); info.distanceMeters = r.get(3); - info.from.gateId = r.get(4); + info.from.gateId = r.get(4); info.from.stationId = r.get(5); - info.to.gateId = r.get(6); - info.to.stationId = r.get(7); + info.to.gateId = r.get(6); + info.to.stationId = r.get(7); return true; } @@ -84,45 +82,46 @@ bool RailwaySegmentHelper::getSegmentInfoFromGate(db_id gateId, utils::RailwaySe " JOIN stations st2 ON st2.id=g2.station_id" " WHERE g1.id=?1 OR g2.id=?1"); q.bind(1, gateId); - if(q.step() != SQLITE_ROW) - return false; //FIXME: show error to user + if (q.step() != SQLITE_ROW) + return false; // FIXME: show error to user - auto r = q.getRows(); - info.segmentId = r.get(0); - info.segmentName = r.get(1); - info.maxSpeedKmH = r.get(2); - info.type = utils::RailwaySegmentType(r.get(3)); - info.distanceMeters = r.get(4); + auto r = q.getRows(); + info.segmentId = r.get(0); + info.segmentName = r.get(1); + info.maxSpeedKmH = r.get(2); + info.type = utils::RailwaySegmentType(r.get(3)); + info.distanceMeters = r.get(4); - info.from.gateId = r.get(5); - info.from.gateLetter = r.get(6)[0]; - info.from.stationId = r.get(7); + info.from.gateId = r.get(5); + info.from.gateLetter = r.get(6)[0]; + info.from.stationId = r.get(7); info.from.stationName = r.get(8); - info.to.gateId = r.get(9); - info.to.gateLetter = r.get(10)[0]; - info.to.stationId = r.get(11); - info.to.stationName = r.get(12); + info.to.gateId = r.get(9); + info.to.gateLetter = r.get(10)[0]; + info.to.stationId = r.get(11); + info.to.stationName = r.get(12); return true; } -bool RailwaySegmentHelper::setSegmentInfo(db_id &segmentId, bool create, - const QString &name, utils::RailwaySegmentType type, - int distance, int speed, - db_id fromGateId, db_id toGateId, - QString *outErrMsg) +bool RailwaySegmentHelper::setSegmentInfo(db_id &segmentId, bool create, const QString &name, + utils::RailwaySegmentType type, int distance, int speed, + db_id fromGateId, db_id toGateId, QString *outErrMsg) { command cmd(mDb); - if(create) + if (create) { cmd.prepare("INSERT INTO railway_segments" "(id, in_gate_id, out_gate_id, name, max_speed_kmh, type, distance_meters)" " VALUES(NULL,?1,?2,?3,?4,?5,?6)"); - }else{ - cmd.prepare("UPDATE railway_segments SET" - " in_gate_id=?1, out_gate_id=?2, name=?3, max_speed_kmh=?4, type=?5, distance_meters=?6" - " WHERE id=?7"); + } + else + { + cmd.prepare( + "UPDATE railway_segments SET" + " in_gate_id=?1, out_gate_id=?2, name=?3, max_speed_kmh=?4, type=?5, distance_meters=?6" + " WHERE id=?7"); cmd.bind(7, segmentId); } @@ -134,14 +133,14 @@ bool RailwaySegmentHelper::setSegmentInfo(db_id &segmentId, bool create, cmd.bind(6, distance); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(outErrMsg) + if (outErrMsg) *outErrMsg = mDb.error_msg(); - return false; //FIXME: show error to user + return false; // FIXME: show error to user } - if(create) + if (create) { segmentId = mDb.last_insert_rowid(); emit Session->segmentAdded(segmentId); @@ -152,27 +151,28 @@ bool RailwaySegmentHelper::setSegmentInfo(db_id &segmentId, bool create, bool RailwaySegmentHelper::removeSegment(db_id segmentId, QString *outErrMsg) { - //Use transaction so if one query fails, the other is restored + // Use transaction so if one query fails, the other is restored sqlite3pp::transaction t(mDb); - //First remove all connections belonging to this segments + // First remove all connections belonging to this segments command cmd(mDb, "DELETE FROM railway_connections WHERE seg_id=?"); cmd.bind(1, segmentId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(outErrMsg) + if (outErrMsg) { - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { - //Get name + // Get name query q(mDb, "SELECT name FROM railway_segments WHERE id=?"); q.bind(1, segmentId); q.step(); QString segName = q.getRows().get(0); q.finish(); - *outErrMsg = RailwaySegmentHelperStrings::tr(errorSegmentInUseText).arg(segName.toHtmlEscaped()); + *outErrMsg = RailwaySegmentHelperStrings::tr(errorSegmentInUseText) + .arg(segName.toHtmlEscaped()); } else { @@ -182,13 +182,13 @@ bool RailwaySegmentHelper::removeSegment(db_id segmentId, QString *outErrMsg) return false; } - //Then remove actual segment + // Then remove actual segment cmd.prepare("DELETE FROM railway_segments WHERE id=?"); cmd.bind(1, segmentId); ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(outErrMsg) + if (outErrMsg) *outErrMsg = mDb.error_msg(); return false; } @@ -202,20 +202,20 @@ bool RailwaySegmentHelper::removeSegment(db_id segmentId, QString *outErrMsg) bool RailwaySegmentHelper::findFirstLineOrSegment(db_id &graphObjId, bool &isLine) { - //Try to find first Railway Line + // Try to find first Railway Line query q(mDb, "SELECT id, MIN(name) FROM lines"); - if(q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL) + if (q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL) { - isLine = true; + isLine = true; graphObjId = q.getRows().get(0); return true; } - //Try with Railway Segment + // Try with Railway Segment q.prepare("SELECT id, MIN(name) FROM railway_segments"); - if(q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL) + if (q.step() == SQLITE_ROW && q.getRows().column_type(0) != SQLITE_NULL) { - isLine = false; + isLine = false; graphObjId = q.getRows().get(0); return true; } diff --git a/src/stations/manager/segments/model/railwaysegmenthelper.h b/src/stations/manager/segments/model/railwaysegmenthelper.h index 7b710de..3296eb0 100644 --- a/src/stations/manager/segments/model/railwaysegmenthelper.h +++ b/src/stations/manager/segments/model/railwaysegmenthelper.h @@ -34,15 +34,13 @@ class RailwaySegmentHelper public: RailwaySegmentHelper(sqlite3pp::database &db); - bool getSegmentInfo(utils::RailwaySegmentInfo& info); + bool getSegmentInfo(utils::RailwaySegmentInfo &info); - bool getSegmentInfoFromGate(db_id gateId, utils::RailwaySegmentInfo& info); + bool getSegmentInfoFromGate(db_id gateId, utils::RailwaySegmentInfo &info); - bool setSegmentInfo(db_id& segmentId, bool create, - const QString &name, utils::RailwaySegmentType type, - int distance, int speed, - db_id fromGateId, db_id toGateId, - QString *outErrMsg); + bool setSegmentInfo(db_id &segmentId, bool create, const QString &name, + utils::RailwaySegmentType type, int distance, int speed, db_id fromGateId, + db_id toGateId, QString *outErrMsg); bool removeSegment(db_id segmentId, QString *outErrMsg); diff --git a/src/stations/manager/segments/model/railwaysegmentsmodel.cpp b/src/stations/manager/segments/model/railwaysegmentsmodel.cpp index 1ddf181..93d6d00 100644 --- a/src/stations/manager/segments/model/railwaysegmentsmodel.cpp +++ b/src/stations/manager/segments/model/railwaysegmentsmodel.cpp @@ -44,7 +44,7 @@ RailwaySegmentsModel::RailwaySegmentsModel(sqlite3pp::database &db, QObject *par QVariant RailwaySegmentsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -73,7 +73,7 @@ QVariant RailwaySegmentsModel::headerData(int section, Qt::Orientation orientati } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -87,16 +87,16 @@ QVariant RailwaySegmentsModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const RailwaySegmentItem& item = cache.at(row - cacheFirstRow); + const RailwaySegmentItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -128,7 +128,7 @@ QVariant RailwaySegmentsModel::data(const QModelIndex &idx, int role) const case FromStationCol: case ToStationCol: { - if(item.reversed) + if (item.reversed) return tr("Segment %1 is shown reversed.").arg(item.segmentName); break; } @@ -155,9 +155,9 @@ QVariant RailwaySegmentsModel::data(const QModelIndex &idx, int role) const case FromStationCol: case ToStationCol: { - if(item.reversed) + if (item.reversed) { - //Light red + // Light red QBrush b(qRgb(255, 110, 110)); return b; } @@ -171,7 +171,8 @@ QVariant RailwaySegmentsModel::data(const QModelIndex &idx, int role) const switch (idx.column()) { case IsElectrifiedCol: - return item.type.testFlag(utils::RailwaySegmentType::Electrified) ? Qt::Checked : Qt::Unchecked; + return item.type.testFlag(utils::RailwaySegmentType::Electrified) ? Qt::Checked + : Qt::Unchecked; } break; } @@ -186,10 +187,10 @@ Qt::ItemFlags RailwaySegmentsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == IsElectrifiedCol) + if (idx.column() == IsElectrifiedCol) f.setFlag(Qt::ItemIsUserCheckable); return f; @@ -197,14 +198,14 @@ Qt::ItemFlags RailwaySegmentsModel::flags(const QModelIndex &idx) const void RailwaySegmentsModel::setSortingColumn(int col) { - if(sortColumn == col || col == FromGateCol || col == ToGateCol || col == IsElectrifiedCol) + if (sortColumn == col || col == FromGateCol || col == ToGateCol || col == IsElectrifiedCol) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -222,14 +223,16 @@ void RailwaySegmentsModel::setFilterFromStationId(const db_id &value) qint64 RailwaySegmentsModel::recalcTotalItemCount() { query q(mDb); - if(filterFromStationId) + if (filterFromStationId) { q.prepare("SELECT COUNT(1) 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 g1.station_id=?1 OR g2.station_id=?1"); q.bind(1, filterFromStationId); - }else{ + } + else + { q.prepare("SELECT COUNT(1) FROM railway_segments"); } @@ -242,33 +245,34 @@ void RailwaySegmentsModel::internalFetch(int first, int sortCol, int valRow, con { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT s.id, s.name, s.max_speed_kmh, s.type, s.distance_meters," - "g1.station_id, g2.station_id," - "s.in_gate_id, g1.name, st1.name," - "s.out_gate_id,g2.name, st2.name" - " 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" - " JOIN stations st1 ON st1.id=g1.station_id" - " JOIN stations st2 ON st2.id=g2.station_id"; + QByteArray sql = "SELECT s.id, s.name, s.max_speed_kmh, s.type, s.distance_meters," + "g1.station_id, g2.station_id," + "s.in_gate_id, g1.name, st1.name," + "s.out_gate_id,g2.name, st2.name" + " 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" + " JOIN stations st1 ON st1.id=g1.station_id" + " JOIN stations st2 ON st2.id=g2.station_id"; switch (sortCol) { case NameCol: { - whereCol = "s.name"; //Order by 1 column, no where clause + whereCol = "s.name"; // Order by 1 column, no where clause break; } case FromStationCol: @@ -293,17 +297,17 @@ void RailwaySegmentsModel::internalFetch(int first, int sortCol, int valRow, con } } - if(val.isValid()) + if (val.isValid()) { sql += " WHERE "; sql += whereCol; - if(reverse) + if (reverse) sql += "?3"; } - if(filterFromStationId) + if (filterFromStationId) { sql += " WHERE g1.station_id=?4 OR g2.station_id=?4"; } @@ -311,19 +315,19 @@ void RailwaySegmentsModel::internalFetch(int first, int sortCol, int valRow, con sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); - if(filterFromStationId) + if (filterFromStationId) q.bind(4, filterFromStationId); // if(val.isValid()) @@ -340,54 +344,54 @@ void RailwaySegmentsModel::internalFetch(int first, int sortCol, int valRow, con QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = reverse ? BatchSize - 1 : 0; + int i = reverse ? BatchSize - 1 : 0; const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; + auto r = *it; RailwaySegmentItem &item = vec[i]; - item.segmentId = r.get(0); - item.segmentName = r.get(1); - item.maxSpeedKmH = r.get(2); - item.type = utils::RailwaySegmentType(r.get(3)); - item.distanceMeters = r.get(4); + item.segmentId = r.get(0); + item.segmentName = r.get(1); + item.maxSpeedKmH = r.get(2); + item.type = utils::RailwaySegmentType(r.get(3)); + item.distanceMeters = r.get(4); - item.fromStationId = r.get(5); - item.toStationId = r.get(6); + item.fromStationId = r.get(5); + item.toStationId = r.get(6); - item.fromGateId = r.get(7); - item.fromGateLetter = sqlite3_column_text(q.stmt(), 8)[0]; - item.fromStationName = r.get(9); + item.fromGateId = r.get(7); + item.fromGateLetter = sqlite3_column_text(q.stmt(), 8)[0]; + item.fromStationName = r.get(9); - item.toGateId = r.get(10); - item.toGateLetter = sqlite3_column_text(q.stmt(), 11)[0]; - item.toStationName = r.get(12); - item.reversed = false; + item.toGateId = r.get(10); + item.toGateLetter = sqlite3_column_text(q.stmt(), 11)[0]; + item.toStationName = r.get(12); + item.reversed = false; - if(filterFromStationId) + if (filterFromStationId) { - if(filterFromStationId == item.toStationId) + if (filterFromStationId == item.toStationId) { - //Always show filter station as 'From' + // Always show filter station as 'From' qSwap(item.fromStationId, item.toStationId); qSwap(item.fromGateId, item.toGateId); qSwap(item.fromStationName, item.toStationName); qSwap(item.fromGateLetter, item.toGateLetter); item.reversed = true; } - //item.fromStationName.clear(); //Save some memory??? + // item.fromStationName.clear(); //Save some memory??? } i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); diff --git a/src/stations/manager/segments/model/railwaysegmentsmodel.h b/src/stations/manager/segments/model/railwaysegmentsmodel.h index 1099b2f..1c692e8 100644 --- a/src/stations/manager/segments/model/railwaysegmentsmodel.h +++ b/src/stations/manager/segments/model/railwaysegmentsmodel.h @@ -46,16 +46,20 @@ struct RailwaySegmentsModelItem bool reversed; }; -class RailwaySegmentsModel : public IPagedItemModelImpl +class RailwaySegmentsModel + : public IPagedItemModelImpl { Q_OBJECT public: + enum + { + BatchSize = 100 + }; - enum { BatchSize = 100 }; - - enum Columns { - NameCol = 0, + enum Columns + { + NameCol = 0, FromStationCol = 1, FromGateCol, ToStationCol, @@ -72,11 +76,12 @@ public: RailwaySegmentsModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel @@ -91,18 +96,18 @@ public: inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const RailwaySegmentItem& item = cache.at(row - cacheFirstRow); + const RailwaySegmentItem &item = cache.at(row - cacheFirstRow); return item.segmentId; } inline QString getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QString(); //Invalid + return QString(); // Invalid - const RailwaySegmentItem& item = cache.at(row - cacheFirstRow); + const RailwaySegmentItem &item = cache.at(row - cacheFirstRow); return item.segmentName; } diff --git a/src/stations/manager/segments/model/railwaysegmentsplithelper.cpp b/src/stations/manager/segments/model/railwaysegmentsplithelper.cpp index 902c050..be1e7db 100644 --- a/src/stations/manager/segments/model/railwaysegmentsplithelper.cpp +++ b/src/stations/manager/segments/model/railwaysegmentsplithelper.cpp @@ -31,11 +31,11 @@ using namespace sqlite3pp; #include -//Error messages TODO -//class RailwaySegmentSplitHelperStrings +// Error messages TODO +// class RailwaySegmentSplitHelperStrings //{ -// Q_DECLARE_TR_FUNCTIONS(RailwaySegmentSplitHelperStrings) -//}; +// Q_DECLARE_TR_FUNCTIONS(RailwaySegmentSplitHelperStrings) +// }; RailwaySegmentSplitHelper::RailwaySegmentSplitHelper(sqlite3pp::database &db, RailwaySegmentConnectionsModel *origSegConn, @@ -44,15 +44,13 @@ RailwaySegmentSplitHelper::RailwaySegmentSplitHelper(sqlite3pp::database &db, origSegConnModel(origSegConn), newSegConnModel(newSegConn) { - } - void RailwaySegmentSplitHelper::setInfo(const utils::RailwaySegmentInfo &origInfo, const utils::RailwaySegmentInfo &newInfo) { origSegInfo = origInfo; - newSegInfo = newInfo; + newSegInfo = newInfo; } bool RailwaySegmentSplitHelper::split() @@ -62,12 +60,11 @@ bool RailwaySegmentSplitHelper::split() QString errMsg; RailwaySegmentHelper helper(mDb); - //Update previous segment and set Out Gate - if(!helper.setSegmentInfo(origSegInfo.segmentId, false, - origSegInfo.segmentName, origSegInfo.type, - origSegInfo.distanceMeters, origSegInfo.maxSpeedKmH, - origSegInfo.from.gateId, origSegInfo.to.gateId, - &errMsg)) + // Update previous segment and set Out Gate + if (!helper.setSegmentInfo(origSegInfo.segmentId, false, origSegInfo.segmentName, + origSegInfo.type, origSegInfo.distanceMeters, + origSegInfo.maxSpeedKmH, origSegInfo.from.gateId, + origSegInfo.to.gateId, &errMsg)) { qWarning() << "RailwaySegmentSplitHelper: cannot set out gate" << origSegInfo.to.gateId << errMsg; @@ -76,12 +73,10 @@ bool RailwaySegmentSplitHelper::split() origSegConnModel->applyChanges(origSegInfo.segmentId); - //Create new segment - if(!helper.setSegmentInfo(newSegInfo.segmentId, true, - newSegInfo.segmentName, newSegInfo.type, + // Create new segment + if (!helper.setSegmentInfo(newSegInfo.segmentId, true, newSegInfo.segmentName, newSegInfo.type, newSegInfo.distanceMeters, newSegInfo.maxSpeedKmH, - newSegInfo.from.gateId, newSegInfo.to.gateId, - &errMsg)) + newSegInfo.from.gateId, newSegInfo.to.gateId, &errMsg)) { qWarning() << "RailwaySegmentSplitHelper: cannot create segment" << errMsg; return false; @@ -89,15 +84,15 @@ bool RailwaySegmentSplitHelper::split() newSegConnModel->applyChanges(newSegInfo.segmentId); - //Update Railway Lines - if(!updateLines()) + // Update Railway Lines + if (!updateLines()) return false; - //FIXME: also update/delete jobs + // FIXME: also update/delete jobs t.commit(); - //Refresh graphs and station views + // Refresh graphs and station views QSet stationsToUpdate; stationsToUpdate.insert(origSegInfo.from.stationId); stationsToUpdate.insert(origSegInfo.to.stationId); @@ -114,73 +109,74 @@ bool RailwaySegmentSplitHelper::updateLines() { query q_getMaxSegPos(mDb, "SELECT MAX(pos) FROM line_segments WHERE line_id=?"); command q_setPos(mDb, "UPDATE line_segments SET pos=? WHERE id=?"); - command q_moveSegBy(mDb, "UPDATE line_segments SET pos=pos+? WHERE line_id=? AND pos>=? AND pos<=?"); + command q_moveSegBy(mDb, + "UPDATE line_segments SET pos=pos+? WHERE line_id=? AND pos>=? AND pos<=?"); command q_newSeg(mDb, "INSERT INTO line_segments(id,line_id,seg_id,direction,pos)" " VALUES(NULL,?,?,?,?)"); query q(mDb, "SELECT id,line_id,direction,pos FROM line_segments WHERE seg_id=?"); q.bind(1, origSegInfo.segmentId); - for(auto line : q) + for (auto line : q) { db_id lineSegId = line.get(0); - db_id lineId = line.get(1); - bool reversed = line.get(2) != 0; - int segPos = line.get(3); + db_id lineId = line.get(1); + bool reversed = line.get(2) != 0; + int segPos = line.get(3); - //Get segment max position to avoid triggering UNIQUE constraint + // Get segment max position to avoid triggering UNIQUE constraint q_getMaxSegPos.bind(1, lineId); q_getMaxSegPos.step(); const int maxPos = q_getMaxSegPos.getRows().get(0); q_getMaxSegPos.reset(); - //Shift to 2 after max position to avoid UNIQUE(line_id,pos) constraint - //1 after max + 1 new pos wich will be added + // Shift to 2 after max position to avoid UNIQUE(line_id,pos) constraint + // 1 after max + 1 new pos wich will be added const int shiftPos = maxPos + 2; - int prevSegPos = segPos; - int newSegPos = segPos + 1; - if(reversed) + int prevSegPos = segPos; + int newSegPos = segPos + 1; + if (reversed) qSwap(newSegPos, prevSegPos); - if(maxPos > segPos) + if (maxPos > segPos) { - //Shift next segments by maxPos + // Shift next segments by maxPos q_moveSegBy.bind(1, shiftPos); q_moveSegBy.bind(2, lineId); - q_moveSegBy.bind(3, newSegPos); //Move from newSegPos and after + q_moveSegBy.bind(3, newSegPos); // Move from newSegPos and after q_moveSegBy.bind(4, maxPos); - if(q_moveSegBy.execute() != SQLITE_OK) + if (q_moveSegBy.execute() != SQLITE_OK) return false; q_moveSegBy.reset(); } - if(prevSegPos != segPos) + if (prevSegPos != segPos) { - //Set new pos to original segment + // Set new pos to original segment q_setPos.bind(1, prevSegPos); q_setPos.bind(2, lineSegId); - if(q_setPos.execute() != SQLITE_OK) + if (q_setPos.execute() != SQLITE_OK) return false; q_setPos.reset(); } - //Create new segment + // Create new segment q_newSeg.bind(1, lineId); q_newSeg.bind(2, newSegInfo.segmentId); q_newSeg.bind(3, reversed ? 1 : 0); q_newSeg.bind(4, newSegPos); - if(q_newSeg.execute() != SQLITE_OK) + if (q_newSeg.execute() != SQLITE_OK) return false; q_newSeg.reset(); - if(maxPos > segPos) + if (maxPos > segPos) { - //Move segments back but +1 for new segment slot + // Move segments back but +1 for new segment slot q_moveSegBy.bind(1, -shiftPos + 1); q_moveSegBy.bind(2, lineId); - q_moveSegBy.bind(3, shiftPos); //First moved - q_moveSegBy.bind(4, maxPos + shiftPos); //Last moved - if(q_moveSegBy.execute() != SQLITE_OK) + q_moveSegBy.bind(3, shiftPos); // First moved + q_moveSegBy.bind(4, maxPos + shiftPos); // Last moved + if (q_moveSegBy.execute() != SQLITE_OK) return false; q_moveSegBy.reset(); } diff --git a/src/stations/manager/segments/model/railwaysegmentsplithelper.h b/src/stations/manager/segments/model/railwaysegmentsplithelper.h index 53347e2..276eb07 100644 --- a/src/stations/manager/segments/model/railwaysegmentsplithelper.h +++ b/src/stations/manager/segments/model/railwaysegmentsplithelper.h @@ -34,12 +34,11 @@ class RailwaySegmentConnectionsModel; class RailwaySegmentSplitHelper { public: - RailwaySegmentSplitHelper(sqlite3pp::database &db, - RailwaySegmentConnectionsModel *origSegConn, + RailwaySegmentSplitHelper(sqlite3pp::database &db, RailwaySegmentConnectionsModel *origSegConn, RailwaySegmentConnectionsModel *newSegConn); - void setInfo(const utils::RailwaySegmentInfo& origInfo, - const utils::RailwaySegmentInfo& newInfo); + void setInfo(const utils::RailwaySegmentInfo &origInfo, + const utils::RailwaySegmentInfo &newInfo); bool split(); diff --git a/src/stations/manager/stationjobview.cpp b/src/stations/manager/stationjobview.cpp index e856719..e0619e1 100644 --- a/src/stations/manager/stationjobview.cpp +++ b/src/stations/manager/stationjobview.cpp @@ -49,15 +49,16 @@ StationJobView::StationJobView(QWidget *parent) : ui->tableView->setModel(model); - ui->tableView->setColumnWidth(0, 60); //Arrival - ui->tableView->setColumnWidth(1, 60); //Departure - ui->tableView->setColumnWidth(2, 55); //Platform - ui->tableView->setColumnWidth(3, 90); //Job - ui->tableView->setColumnWidth(4, 115); //Notes + ui->tableView->setColumnWidth(0, 60); // Arrival + ui->tableView->setColumnWidth(1, 60); // Departure + ui->tableView->setColumnWidth(2, 55); // Platform + ui->tableView->setColumnWidth(3, 90); // Job + ui->tableView->setColumnWidth(4, 115); // Notes ui->tableView->setSelectionBehavior(QTableView::SelectRows); ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->tableView, &QTableView::customContextMenuRequested, this, &StationJobView::showContextMenu); + connect(ui->tableView, &QTableView::customContextMenuRequested, this, + &StationJobView::showContextMenu); connect(ui->sheetButton, &QPushButton::pressed, this, &StationJobView::onSaveSheet); connect(ui->updateButt, &QPushButton::clicked, this, &StationJobView::updateInfo); @@ -95,35 +96,35 @@ void StationJobView::updateJobsList() model->loadPlan(m_stationId); } -void StationJobView::showContextMenu(const QPoint& pos) +void StationJobView::showContextMenu(const QPoint &pos) { DEBUG_ENTRY; QModelIndex idx = ui->tableView->indexAt(pos); - if(!idx.isValid()) + if (!idx.isValid()) return; - StPlanItem item = model->getItemAt(idx.row()); + StPlanItem item = model->getItemAt(idx.row()); OwningQPointer menu = new QMenu(this); - QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); - QAction *selectJobInGraph = new QAction(tr("Show job in graph"), menu); - QAction *showSVGPlan = new QAction(tr("Show Station SVG Plan"), menu); + QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); + QAction *selectJobInGraph = new QAction(tr("Show job in graph"), menu); + QAction *showSVGPlan = new QAction(tr("Show Station SVG Plan"), menu); menu->addAction(showInJobEditor); menu->addAction(selectJobInGraph); menu->addAction(showSVGPlan); QAction *act = menu->exec(ui->tableView->viewport()->mapToGlobal(pos)); - if(act == showInJobEditor) + if (act == showInJobEditor) { Session->getViewManager()->requestJobEditor(item.jobId, item.stopId); } - else if(act == selectJobInGraph) + else if (act == selectJobInGraph) { Session->getViewManager()->requestJobSelection(item.jobId, true, true); } - else if(act == showSVGPlan) + else if (act == showSVGPlan) { Session->getViewManager()->requestStSVGPlan(m_stationId, true, item.arrival); } @@ -135,7 +136,7 @@ void StationJobView::onSaveSheet() const QLatin1String station_sheet_key = QLatin1String("station_sheet_dir"); - OwningQPointer dlg = new QFileDialog(this, tr("Save Station Sheet")); + OwningQPointer dlg = new QFileDialog(this, tr("Save Station Sheet")); dlg->setFileMode(QFileDialog::AnyFile); dlg->setAcceptMode(QFileDialog::AcceptSave); dlg->setDirectory(RecentDirStore::getDir(station_sheet_key, RecentDirStore::Documents)); @@ -145,12 +146,12 @@ void StationJobView::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(station_sheet_key, fileName); diff --git a/src/stations/manager/stationplanmodel.cpp b/src/stations/manager/stationplanmodel.cpp index 254625b..0da4d9d 100644 --- a/src/stations/manager/stationplanmodel.cpp +++ b/src/stations/manager/stationplanmodel.cpp @@ -50,7 +50,7 @@ StationPlanModel::StationPlanModel(sqlite3pp::database &db, QObject *parent) : QVariant StationPlanModel::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) { @@ -86,7 +86,7 @@ QVariant StationPlanModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols) return QVariant(); - const StPlanItem& item = m_data.at(idx.row()); + const StPlanItem &item = m_data.at(idx.row()); switch (role) { @@ -97,8 +97,8 @@ QVariant StationPlanModel::data(const QModelIndex &idx, int role) const { case Arrival: { - if(item.type == StPlanItem::ItemType::Departure) - break; //Don't repeat arrival also in the second row. + if (item.type == StPlanItem::ItemType::Departure) + break; // Don't repeat arrival also in the second row. return item.arrival; } case Departure: @@ -109,12 +109,13 @@ QVariant StationPlanModel::data(const QModelIndex &idx, int role) const return JobCategoryName::jobName(item.jobId, item.cat); case Notes: { - if(item.type == StPlanItem::ItemType::Departure) - return StationPlanModel::tr("Departure"); //Don't repeat description also in the second row. + if (item.type == StPlanItem::ItemType::Departure) + return StationPlanModel::tr( + "Departure"); // Don't repeat description also in the second row. - if(item.reversesDirection) + if (item.reversesDirection) return tr("Reverse direction"); - if(item.type == StPlanItem::ItemType::Transit) + if (item.type == StPlanItem::ItemType::Transit) return tr("Transit"); break; } @@ -123,13 +124,13 @@ QVariant StationPlanModel::data(const QModelIndex &idx, int role) const } case Qt::ForegroundRole: { - if(item.type == StPlanItem::ItemType::Transit) - return QColor(0, 0, 255); //Transit in blue + if (item.type == StPlanItem::ItemType::Transit) + return QColor(0, 0, 255); // Transit in blue break; } case Qt::ToolTipRole: { - if(item.type == StPlanItem::ItemType::Transit) + if (item.type == StPlanItem::ItemType::Transit) return tr("Transit"); break; } @@ -157,41 +158,42 @@ void StationPlanModel::loadPlan(db_id stId) int count = q_countPlanItems.getRows().get(0); q_countPlanItems.reset(); - if(count > 0) + if (count > 0) { - QMap stopMap; //Order by Departure ASC + QMap stopMap; // Order by Departure ASC m_data.reserve(count); q_selectPlan.bind(1, stId); - for(auto r : q_selectPlan) + for (auto r : q_selectPlan) { StPlanItem curStop; - curStop.stopId = r.get(0); - curStop.jobId = r.get(1); - curStop.cat = JobCategory(r.get(2)); - curStop.arrival = r.get(3); + curStop.stopId = r.get(0); + curStop.jobId = r.get(1); + curStop.cat = JobCategory(r.get(2)); + curStop.arrival = r.get(3); curStop.departure = r.get(4); - curStop.type = StPlanItem::ItemType::Normal; + curStop.type = StPlanItem::ItemType::Normal; StopType stopType = StopType(r.get(5)); - curStop.platform = r.get(6); - if(curStop.platform.isEmpty()) - curStop.platform = r.get(7); //Use out gate to get track name + curStop.platform = r.get(6); + if (curStop.platform.isEmpty()) + curStop.platform = r.get(7); // Use out gate to get track name - utils::Side entranceSide = utils::Side(r.get(8)); - utils::Side exitSide = utils::Side(r.get(9)); + utils::Side entranceSide = utils::Side(r.get(8)); + utils::Side exitSide = utils::Side(r.get(9)); curStop.reversesDirection = false; - if(entranceSide == exitSide && r.column_type(8) != SQLITE_NULL && r.column_type(9) != SQLITE_NULL) - curStop.reversesDirection = true; //Train enters and leaves from same track side + if (entranceSide == exitSide && r.column_type(8) != SQLITE_NULL + && r.column_type(9) != SQLITE_NULL) + curStop.reversesDirection = true; // Train enters and leaves from same track side - for(auto stop = stopMap.begin(); stop != stopMap.end(); /*nothing because of erase */) + for (auto stop = stopMap.begin(); stop != stopMap.end(); /*nothing because of erase */) { - if(stop->departure <= curStop.arrival) + if (stop->departure <= curStop.arrival) { m_data.append(stop.value()); m_data.last().type = StPlanItem::ItemType::Departure; - stop = stopMap.erase(stop); + stop = stopMap.erase(stop); } else { @@ -200,20 +202,20 @@ void StationPlanModel::loadPlan(db_id stId) } m_data.append(curStop); - if(stopType == StopType::Transit) + if (stopType == StopType::Transit) { m_data.last().type = StPlanItem::ItemType::Transit; } else { - //Transit should not be repeated + // Transit should not be repeated curStop.type = StPlanItem::ItemType::Departure; stopMap.insert(curStop.departure, std::move(curStop)); } } q_selectPlan.reset(); - for(const StPlanItem& stop : stopMap) + for (const StPlanItem &stop : stopMap) { m_data.append(stop); } diff --git a/src/stations/manager/stationplanmodel.h b/src/stations/manager/stationplanmodel.h index 24857ac..be0af6a 100644 --- a/src/stations/manager/stationplanmodel.h +++ b/src/stations/manager/stationplanmodel.h @@ -63,10 +63,11 @@ public: Notes, NCols }; - StationPlanModel(sqlite3pp::database& db, QObject *parent = nullptr); + StationPlanModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -80,7 +81,7 @@ public: inline StPlanItem getItemAt(int row) const { - if(row < m_data.size()) + if (row < m_data.size()) { return m_data.at(row); } @@ -90,7 +91,7 @@ public: private: QVector m_data; - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; sqlite3pp::query q_countPlanItems; sqlite3pp::query q_selectPlan; }; diff --git a/src/stations/manager/stations/dialogs/newtrackconndlg.cpp b/src/stations/manager/stations/dialogs/newtrackconndlg.cpp index a0142e4..d021a11 100644 --- a/src/stations/manager/stations/dialogs/newtrackconndlg.cpp +++ b/src/stations/manager/stations/dialogs/newtrackconndlg.cpp @@ -37,9 +37,7 @@ #include "stations/station_name_utils.h" - -NewTrackConnDlg::NewTrackConnDlg(ISqlFKMatchModel *tracks, - StationGatesMatchModel *gates, +NewTrackConnDlg::NewTrackConnDlg(ISqlFKMatchModel *tracks, StationGatesMatchModel *gates, QWidget *parent) : QDialog(parent), trackMatchModel(tracks), @@ -47,33 +45,33 @@ NewTrackConnDlg::NewTrackConnDlg(ISqlFKMatchModel *tracks, { QStringList sideTypeEnum; sideTypeEnum.reserve(int(utils::Side::NSides)); - for(int i = 0; i < int(utils::Side::NSides); i++) + for (int i = 0; i < int(utils::Side::NSides); i++) sideTypeEnum.append(utils::StationUtils::name(utils::Side(i))); trackMatchModel->setHasEmptyRow(false); gatesMatchModel->setHasEmptyRow(false); - QGridLayout *mainLay = new QGridLayout(this); + QGridLayout *mainLay = new QGridLayout(this); - QGroupBox *trackBox = new QGroupBox(tr("Track")); + QGroupBox *trackBox = new QGroupBox(tr("Track")); QFormLayout *trackLay = new QFormLayout(trackBox); - trackEdit = new CustomCompletionLineEdit(trackMatchModel); + trackEdit = new CustomCompletionLineEdit(trackMatchModel); trackLay->addRow(trackEdit); trackSideCombo = new QComboBox; trackSideCombo->addItems(sideTypeEnum); trackSideCombo->setCurrentIndex(0); - connect(trackSideCombo, QOverload::of(&QComboBox::activated), - this, &NewTrackConnDlg::onTrackSideChanged); + connect(trackSideCombo, QOverload::of(&QComboBox::activated), this, + &NewTrackConnDlg::onTrackSideChanged); trackLay->addRow(tr("Track Side:"), trackSideCombo); - QGroupBox *gateBox = new QGroupBox(tr("Gate")); + QGroupBox *gateBox = new QGroupBox(tr("Gate")); QFormLayout *gateLay = new QFormLayout(gateBox); - gateEdit = new CustomCompletionLineEdit(gatesMatchModel); - connect(gateEdit, &CustomCompletionLineEdit::dataIdChanged, - this, &NewTrackConnDlg::onGateChanged); + gateEdit = new CustomCompletionLineEdit(gatesMatchModel); + connect(gateEdit, &CustomCompletionLineEdit::dataIdChanged, this, + &NewTrackConnDlg::onGateChanged); gateLay->addRow(gateEdit); gateTrackSpin = new QSpinBox; @@ -83,8 +81,8 @@ NewTrackConnDlg::NewTrackConnDlg(ISqlFKMatchModel *tracks, mainLay->addWidget(trackBox, 0, 0); mainLay->addWidget(gateBox, 0, 1); - QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, - Qt::Horizontal); + QDialogButtonBox *box = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); connect(box, &QDialogButtonBox::accepted, this, &NewTrackConnDlg::accept); connect(box, &QDialogButtonBox::rejected, this, &NewTrackConnDlg::reject); mainLay->addWidget(box, 1, 0, 1, 2); @@ -96,19 +94,19 @@ NewTrackConnDlg::NewTrackConnDlg(ISqlFKMatchModel *tracks, void NewTrackConnDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { - //Prevent closing if data is not valid + // Prevent closing if data is not valid db_id tmpId; QString tmpName; - if(m_mode != GateToAllTracks && !trackEdit->getData(tmpId, tmpName)) + if (m_mode != GateToAllTracks && !trackEdit->getData(tmpId, tmpName)) { QMessageBox::warning(this, tr("Track Connection Error"), tr("Please set a valid track.")); return; } - if(m_mode != TrackToAllGates && !gateEdit->getData(tmpId, tmpName)) + if (m_mode != TrackToAllGates && !gateEdit->getData(tmpId, tmpName)) { QMessageBox::warning(this, tr("Track Connection Error"), tr("Please set a valid gate.")); @@ -119,7 +117,8 @@ void NewTrackConnDlg::done(int res) QDialog::done(res); } -void NewTrackConnDlg::getData(db_id &trackOut, utils::Side &trackSideOut, db_id &gateOut, int &gateTrackOut) +void NewTrackConnDlg::getData(db_id &trackOut, utils::Side &trackSideOut, db_id &gateOut, + int &gateTrackOut) { QString tmp; trackEdit->getData(trackOut, tmp); @@ -132,12 +131,12 @@ void NewTrackConnDlg::setMode(NewTrackConnDlg::Mode mode) { m_mode = mode; - if(m_mode == GateToAllTracks) + if (m_mode == GateToAllTracks) { trackEdit->setPlaceholderText(tr("All Tracks")); trackEdit->setData(0); trackEdit->setReadOnly(true); - //Gate decides which side + // Gate decides which side trackSideCombo->setEnabled(false); } else @@ -147,11 +146,11 @@ void NewTrackConnDlg::setMode(NewTrackConnDlg::Mode mode) trackSideCombo->setEnabled(true); } - if(m_mode == TrackToAllGates) + if (m_mode == TrackToAllGates) { gateEdit->setData(0); gateEdit->setReadOnly(true); - //Force update placeholder text + // Force update placeholder text onTrackSideChanged(); } else @@ -176,21 +175,21 @@ void NewTrackConnDlg::setMode(NewTrackConnDlg::Mode mode) void NewTrackConnDlg::onGateChanged(db_id gateId) { - //NOTE HACK: - //CustomCompletionLineEdit doesn't allow getting custom data - //Ask model directly before it's cleared by CustomCompletionLineEdit + // NOTE HACK: + // CustomCompletionLineEdit doesn't allow getting custom data + // Ask model directly before it's cleared by CustomCompletionLineEdit int outTrackCount = 0; - if(gateId) + if (gateId) outTrackCount = gatesMatchModel->getOutTrackCount(gateId); - if(outTrackCount == 0) - outTrackCount = 1000; //Set to some value + if (outTrackCount == 0) + outTrackCount = 1000; // Set to some value gateTrackSpin->setMaximum(outTrackCount - 1); - if(m_mode == GateToAllTracks) + if (m_mode == GateToAllTracks) { - //The side is deduced by gate side + // The side is deduced by gate side utils::Side gateSide = gatesMatchModel->getGateSide(gateId); trackSideCombo->setCurrentIndex(int(gateSide)); } @@ -198,12 +197,11 @@ void NewTrackConnDlg::onGateChanged(db_id gateId) void NewTrackConnDlg::onTrackSideChanged() { - if(m_mode == TrackToAllGates) + if (m_mode == TrackToAllGates) { - //Will connect to all gates on this side - int idx = trackSideCombo->currentIndex(); + // Will connect to all gates on this side + int idx = trackSideCombo->currentIndex(); utils::Side side = utils::Side(idx); - gateEdit->setPlaceholderText(tr("All Gates %1 Side") - .arg(utils::StationUtils::name(side))); + gateEdit->setPlaceholderText(tr("All Gates %1 Side").arg(utils::StationUtils::name(side))); } } diff --git a/src/stations/manager/stations/dialogs/newtrackconndlg.h b/src/stations/manager/stations/dialogs/newtrackconndlg.h index 14e700b..22eb833 100644 --- a/src/stations/manager/stations/dialogs/newtrackconndlg.h +++ b/src/stations/manager/stations/dialogs/newtrackconndlg.h @@ -32,13 +32,12 @@ class CustomCompletionLineEdit; class QComboBox; class QSpinBox; -//FIXME: add feature Add Track to All West/East gates -// and Add Gate To all tracks (West/East side) +// FIXME: add feature Add Track to All West/East gates +// and Add Gate To all tracks (West/East side) class NewTrackConnDlg : public QDialog { Q_OBJECT public: - enum Mode { SingleConnection, @@ -46,14 +45,12 @@ public: GateToAllTracks }; - NewTrackConnDlg(ISqlFKMatchModel *tracks, - StationGatesMatchModel *gates, + NewTrackConnDlg(ISqlFKMatchModel *tracks, StationGatesMatchModel *gates, QWidget *parent = nullptr); virtual void done(int res) override; - void getData(db_id &trackOut, utils::Side &trackSideOut, - db_id &gateOut, int &gateTrackOut); + void getData(db_id &trackOut, utils::Side &trackSideOut, db_id &gateOut, int &gateTrackOut); void setMode(Mode mode); diff --git a/src/stations/manager/stations/dialogs/stationeditdialog.cpp b/src/stations/manager/stations/dialogs/stationeditdialog.cpp index 3bd9616..6bdf21e 100644 --- a/src/stations/manager/stations/dialogs/stationeditdialog.cpp +++ b/src/stations/manager/stations/dialogs/stationeditdialog.cpp @@ -58,12 +58,13 @@ const QLatin1String station_svg_key = QLatin1String("station_svg_dir"); void setupView(QTableView *view, IPagedItemModel *model) { - //Custom colun sorting - //NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work + // Custom colun sorting + // NOTE: leave disconnect() in the old SIGLAL()/SLOT() version in order to work QHeaderView *header = view->horizontalHeader(); QObject::disconnect(header, SIGNAL(sectionPressed(int)), view, SLOT(selectColumn(int))); QObject::disconnect(header, SIGNAL(sectionEntered(int)), view, SLOT(_q_selectColumn(int))); - QObject::connect(header, &QHeaderView::sectionClicked, model, [model, header](int section) + QObject::connect(header, &QHeaderView::sectionClicked, model, + [model, header](int section) { model->setSortingColumn(section); header->setSortIndicator(model->getSortingColumn(), Qt::AscendingOrder); @@ -81,18 +82,18 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : { ui->setupUi(this); - //Enum names + // Enum names QStringList stationTypeEnum; stationTypeEnum.reserve(int(utils::StationType::NTypes)); - for(int i = 0; i < int(utils::StationType::NTypes); i++) + for (int i = 0; i < int(utils::StationType::NTypes); i++) stationTypeEnum.append(utils::StationUtils::name(utils::StationType(i))); QStringList sideTypeEnum; sideTypeEnum.reserve(int(utils::Side::NSides)); - for(int i = 0; i < int(utils::Side::NSides); i++) + for (int i = 0; i < int(utils::Side::NSides); i++) sideTypeEnum.append(utils::StationUtils::name(utils::Side(i))); - //Delegate Factories + // Delegate Factories trackLengthSpinFactory = new SpinBoxEditorFactory; trackLengthSpinFactory->setRange(1, 9999); trackLengthSpinFactory->setSuffix(" cm"); @@ -101,7 +102,7 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : trackFactory = new StationTracksMatchFactory(mDb, this); gatesFactory = new StationGatesMatchFactory(mDb, this); - //Station Tab + // Station Tab ui->stationTypeCombo->addItems(stationTypeEnum); connect(ui->addSVGBut, &QPushButton::clicked, this, &StationEditDialog::addSVGImage); @@ -110,13 +111,15 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : connect(ui->importConnBut, &QPushButton::clicked, this, &StationEditDialog::importConnFromSVG); connect(ui->saveXMLBut, &QPushButton::clicked, this, &StationEditDialog::saveXmlPlan); - ui->importConnBut->setToolTip(tr("Import connections between gates and station tracks from SVG image.\n" - "NOTE: image must contain track data")); + ui->importConnBut->setToolTip( + tr("Import connections between gates and station tracks from SVG image.\n" + "NOTE: image must contain track data")); - //Gates Tab + // Gates Tab gatesModel = new StationGatesModel(mDb, this); connect(gatesModel, &IPagedItemModel::modelError, this, &StationEditDialog::modelError); - connect(gatesModel, &StationGatesModel::gateNameChanged, this, &StationEditDialog::onGatesChanged); + connect(gatesModel, &StationGatesModel::gateNameChanged, this, + &StationEditDialog::onGatesChanged); connect(gatesModel, &StationGatesModel::gateRemoved, this, &StationEditDialog::onGatesChanged); ModelPageSwitcher *ps = new ModelPageSwitcher(false, this); @@ -130,13 +133,16 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : new SqlFKFieldDelegate(trackFactory, gatesModel, this)); connect(ui->addGateButton, &QToolButton::clicked, this, &StationEditDialog::addGate); - connect(ui->removeGateButton, &QToolButton::clicked, this, &StationEditDialog::removeSelectedGate); + connect(ui->removeGateButton, &QToolButton::clicked, this, + &StationEditDialog::removeSelectedGate); - //Tracks Tab + // Tracks Tab tracksModel = new StationTracksModel(mDb, this); connect(tracksModel, &IPagedItemModel::modelError, this, &StationEditDialog::modelError); - connect(tracksModel, &StationTracksModel::trackNameChanged, this, &StationEditDialog::onTracksChanged); - connect(tracksModel, &StationTracksModel::trackRemoved, this, &StationEditDialog::onTracksChanged); + connect(tracksModel, &StationTracksModel::trackNameChanged, this, + &StationEditDialog::onTracksChanged); + connect(tracksModel, &StationTracksModel::trackRemoved, this, + &StationEditDialog::onTracksChanged); ps = new ModelPageSwitcher(false, this); ui->tracksLayout->addWidget(ps); @@ -146,51 +152,53 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : auto trackLengthDelegate = new QStyledItemDelegate(this); trackLengthDelegate->setItemEditorFactory(trackLengthSpinFactory); - ui->trackView->setItemDelegateForColumn(StationTracksModel::TrackLengthCol, trackLengthDelegate); - ui->trackView->setItemDelegateForColumn(StationTracksModel::PassengerLegthCol, trackLengthDelegate); - ui->trackView->setItemDelegateForColumn(StationTracksModel::FreightLengthCol, trackLengthDelegate); + ui->trackView->setItemDelegateForColumn(StationTracksModel::TrackLengthCol, + trackLengthDelegate); + ui->trackView->setItemDelegateForColumn(StationTracksModel::PassengerLegthCol, + trackLengthDelegate); + ui->trackView->setItemDelegateForColumn(StationTracksModel::FreightLengthCol, + trackLengthDelegate); connect(ui->addTrackButton, &QToolButton::clicked, this, &StationEditDialog::addTrack); - connect(ui->removeTrackButton, &QToolButton::clicked, this, &StationEditDialog::removeSelectedTrack); + connect(ui->removeTrackButton, &QToolButton::clicked, this, + &StationEditDialog::removeSelectedTrack); ui->moveTrackUpBut->setToolTip(tr("Hold shift to move selected track to the top.")); ui->moveTrackDownBut->setToolTip(tr("Hold shift to move selected track to the bottom.")); connect(ui->moveTrackUpBut, &QToolButton::clicked, this, &StationEditDialog::moveTrackUp); connect(ui->moveTrackDownBut, &QToolButton::clicked, this, &StationEditDialog::moveTrackDown); - //Track Connections Tab + // Track Connections Tab trackConnModel = new StationTrackConnectionsModel(mDb, this); connect(trackConnModel, &IPagedItemModel::modelError, this, &StationEditDialog::modelError); - connect(trackConnModel, &StationTrackConnectionsModel::trackConnRemoved, - this, &StationEditDialog::onTrackConnRemoved); + connect(trackConnModel, &StationTrackConnectionsModel::trackConnRemoved, this, + &StationEditDialog::onTrackConnRemoved); ps = new ModelPageSwitcher(false, this); ui->trackConnLayout->addWidget(ps); ps->setModel(trackConnModel); setupView(ui->trackConnView, trackConnModel); - ui->trackConnView->setItemDelegateForColumn(StationTrackConnectionsModel::TrackSideCol, - new ComboDelegate(sideTypeEnum, Qt::EditRole, this)); - ui->trackConnView->setItemDelegateForColumn(StationTrackConnectionsModel::TrackCol, - new SqlFKFieldDelegate(trackFactory, trackConnModel, this)); - ui->trackConnView->setItemDelegateForColumn(StationTrackConnectionsModel::GateCol, - new SqlFKFieldDelegate(gatesFactory, trackConnModel, this)); + ui->trackConnView->setItemDelegateForColumn( + StationTrackConnectionsModel::TrackSideCol, + new ComboDelegate(sideTypeEnum, Qt::EditRole, this)); + ui->trackConnView->setItemDelegateForColumn( + StationTrackConnectionsModel::TrackCol, + new SqlFKFieldDelegate(trackFactory, trackConnModel, this)); + ui->trackConnView->setItemDelegateForColumn( + StationTrackConnectionsModel::GateCol, + new SqlFKFieldDelegate(gatesFactory, trackConnModel, this)); - connect(ui->removeTrackConnBut, &QToolButton::clicked, this, &StationEditDialog::removeSelectedTrackConn); - connect(ui->addTrackConnBut, &QToolButton::clicked, this, [this]() - { - addTrackConnInternal(NewTrackConnDlg::SingleConnection); - }); - connect(ui->trackToAllGatesBut, &QToolButton::clicked, this, [this]() - { - addTrackConnInternal(NewTrackConnDlg::TrackToAllGates); - }); - connect(ui->gateToAllTracksBut, &QToolButton::clicked, this, [this]() - { - addTrackConnInternal(NewTrackConnDlg::GateToAllTracks); - }); + connect(ui->removeTrackConnBut, &QToolButton::clicked, this, + &StationEditDialog::removeSelectedTrackConn); + connect(ui->addTrackConnBut, &QToolButton::clicked, this, + [this]() { addTrackConnInternal(NewTrackConnDlg::SingleConnection); }); + connect(ui->trackToAllGatesBut, &QToolButton::clicked, this, + [this]() { addTrackConnInternal(NewTrackConnDlg::TrackToAllGates); }); + connect(ui->gateToAllTracksBut, &QToolButton::clicked, this, + [this]() { addTrackConnInternal(NewTrackConnDlg::GateToAllTracks); }); - //Gate Connections Tab + // Gate Connections Tab gateConnModel = new RailwaySegmentsModel(mDb, this); connect(gateConnModel, &IPagedItemModel::modelError, this, &StationEditDialog::modelError); @@ -198,12 +206,14 @@ StationEditDialog::StationEditDialog(sqlite3pp::database &db, QWidget *parent) : ui->gateConnLayout->addWidget(ps); ps->setModel(gateConnModel); setupView(ui->gateConnView, gateConnModel); - //From station column shows always our station, because of filetering, so hide it + // From station column shows always our station, because of filetering, so hide it ui->gateConnView->hideColumn(RailwaySegmentsModel::FromStationCol); connect(ui->addGateConnBut, &QToolButton::clicked, this, &StationEditDialog::addGateConnection); - connect(ui->editGateConnBut, &QToolButton::clicked, this, &StationEditDialog::editGateConnection); - connect(ui->removeGateConnBut, &QToolButton::clicked, this, &StationEditDialog::removeSelectedGateConnection); + connect(ui->editGateConnBut, &QToolButton::clicked, this, + &StationEditDialog::editGateConnection); + connect(ui->removeGateConnBut, &QToolButton::clicked, this, + &StationEditDialog::removeSelectedGateConnection); } StationEditDialog::~StationEditDialog() @@ -214,36 +224,36 @@ StationEditDialog::~StationEditDialog() bool StationEditDialog::setStation(db_id stationId) { - //Update models - if(!gatesModel->setStation(stationId)) + // Update models + if (!gatesModel->setStation(stationId)) return false; tracksModel->setStation(stationId); trackConnModel->setStation(stationId); gateConnModel->setFilterFromStationId(stationId); - //Update factories + // Update factories trackFactory->setStationId(stationId); gatesFactory->setStationId(stationId); - //Update station details + // Update station details QString stationName; QString shortName; utils::StationType type = utils::StationType::Normal; - qint64 phoneNumber = -1; - bool hasImage = false; - if(!gatesModel->getStationInfo(stationName, shortName, type, phoneNumber, hasImage)) + qint64 phoneNumber = -1; + bool hasImage = false; + if (!gatesModel->getStationInfo(stationName, shortName, type, phoneNumber, hasImage)) return false; ui->stationNameEdit->setText(stationName); ui->shortNameEdit->setText(shortName); ui->stationTypeCombo->setCurrentIndex(int(type)); - if(phoneNumber == -1) + if (phoneNumber == -1) ui->phoneEdit->setText(QString()); else ui->phoneEdit->setText(QString::number(phoneNumber)); - //Update title + // Update title setWindowTitle(stationName.isEmpty() ? tr("New Station") : stationName); updateSVGButtons(hasImage); @@ -260,7 +270,7 @@ void StationEditDialog::setStationInternalEditingEnabled(bool enable) { mEnableInternalEdititing = enable; - //Gates, Tracks, Track connections + // Gates, Tracks, Track connections gatesModel->setEditable(enable); tracksModel->setEditable(enable); trackConnModel->setEditable(enable); @@ -278,23 +288,23 @@ void StationEditDialog::setStationInternalEditingEnabled(bool enable) ui->trackToAllGatesBut->setEnabled(enable); ui->gateToAllTracksBut->setEnabled(enable); - //Station Details (but not phone) + // Station Details (but not phone) ui->stationNameEdit->setEnabled(enable); ui->shortNameEdit->setEnabled(enable); ui->stationTypeCombo->setEnabled(enable); - //SVG Image + // SVG Image updateSVGButtons(false); } void StationEditDialog::setStationExternalEditingEnabled(bool enable) { - //Gate connections + // Gate connections ui->addGateConnBut->setEnabled(enable); ui->editGateConnBut->setEnabled(enable); ui->removeGateConnBut->setEnabled(enable); - //Phone number + // Phone number ui->phoneEdit->setEnabled(enable); } @@ -303,55 +313,56 @@ void StationEditDialog::setGateConnectionsVisible(bool enable) int idx = ui->tabWidget->indexOf(ui->gateConnectionsTab); ui->tabWidget->setTabVisible(idx, enable); - //Refresh model + // Refresh model gateConnModel->clearCache(); gateConnModel->refreshData(); } void StationEditDialog::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { - const QString stationName = ui->stationNameEdit->text().simplified(); - const QString shortName = ui->shortNameEdit->text().simplified(); + const QString stationName = ui->stationNameEdit->text().simplified(); + const QString shortName = ui->shortNameEdit->text().simplified(); const utils::StationType type = utils::StationType(ui->stationTypeCombo->currentIndex()); - qint64 phoneNumber = -1; - const QString phoneNumberStr = ui->phoneEdit->text().simplified(); - if(!phoneNumberStr.isEmpty()) + qint64 phoneNumber = -1; + const QString phoneNumberStr = ui->phoneEdit->text().simplified(); + if (!phoneNumberStr.isEmpty()) { - bool ok = false; + bool ok = false; phoneNumber = phoneNumberStr.toLongLong(&ok); - if(!ok) + if (!ok) phoneNumber = -1; } - if(stationName.isEmpty()) + if (stationName.isEmpty()) { modelError(tr("Station name cannot be empty.")); return; } - if(stationName == shortName) + if (stationName == shortName) { modelError(tr("Station short name cannot be equal to full name.\n" "Leave empty if you want to use the full name in all places.")); return; } - //FIXME: StationsModel does other checks on names and outputs better error messages - if(!gatesModel->setStationInfo(stationName, shortName, type, phoneNumber)) + // FIXME: StationsModel does other checks on names and outputs better error messages + if (!gatesModel->setStationInfo(stationName, shortName, type, phoneNumber)) { - modelError(tr("Check station name, short name and phone number to be unique for this station.")); + modelError(tr("Check station name, short name and phone number to " + "be unique for this station.")); return; } - if(!gatesModel->hasAtLeastOneGate()) + if (!gatesModel->hasAtLeastOneGate()) { - //TODO: provide a way to delete the station to exit dialog + // TODO: provide a way to delete the station to exit dialog modelError(tr("A station should at least have 1 gate")); return; } - if(!tracksModel->hasAtLeastOneTrack()) + if (!tracksModel->hasAtLeastOneTrack()) { modelError(tr("A station should at least have 1 track")); return; @@ -359,11 +370,11 @@ void StationEditDialog::done(int res) } else { - //Warning rejecting dialog - //TODO: this is because modification to gates/tacks/connections - //Are applied immediatley so closing dialog always "saves" changes. - //Hitting cancel one would expect not to see the changes applied. - //FIXME: find a way to hold changes and apply only if accepting dialog + // Warning rejecting dialog + // TODO: this is because modification to gates/tacks/connections + // Are applied immediatley so closing dialog always "saves" changes. + // Hitting cancel one would expect not to see the changes applied. + // FIXME: find a way to hold changes and apply only if accepting dialog modelError(tr("Cannot cancel changes. Changes will be applied.")); } @@ -377,13 +388,13 @@ void StationEditDialog::modelError(const QString &msg) void StationEditDialog::onGatesChanged() { - //A gate was removed or changed name + // A gate was removed or changed name - //Update platform connections + // Update platform connections //(refresh because some may be deleted) trackConnModel->refreshData(true); - //Update gate connections + // Update gate connections gateConnModel->refreshData(true); } @@ -394,36 +405,35 @@ void StationEditDialog::addGate() dlg->setLabelText(tr("Please choose a letter for the new station gate.")); dlg->setTextValue(QString()); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Gate name cannot be empty.")); - continue; //Second chance + continue; // Second chance } - - if(gatesModel->addGate(name.at(0))) + if (gatesModel->addGate(name.at(0))) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); } void StationEditDialog::removeSelectedGate() { - if(!ui->gatesView->selectionModel()->hasSelection()) + if (!ui->gatesView->selectionModel()->hasSelection()) return; db_id gateId = gatesModel->getIdAtRow(ui->gatesView->currentIndex().row()); - if(!gateId) + if (!gateId) return; gatesModel->removeGate(gateId); @@ -431,12 +441,12 @@ void StationEditDialog::removeSelectedGate() void StationEditDialog::onTracksChanged() { - //A track was removed or changed name + // A track was removed or changed name - //Update gates (has a Default Platform column) + // Update gates (has a Default Platform column) gatesModel->refreshData(true); - //Update platform connections + // Update platform connections //(refresh because some may be deleted) trackConnModel->refreshData(true); } @@ -448,36 +458,35 @@ void StationEditDialog::addTrack() dlg->setLabelText(tr("Please choose a name for the new station track.")); dlg->setTextValue(QString()); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Track name cannot be empty.")); - continue; //Second chance + continue; // Second chance } - - if(tracksModel->addTrack(-1, name)) + if (tracksModel->addTrack(-1, name)) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); } void StationEditDialog::removeSelectedTrack() { - if(!ui->trackView->selectionModel()->hasSelection()) + if (!ui->trackView->selectionModel()->hasSelection()) return; db_id trackId = tracksModel->getIdAtRow(ui->trackView->currentIndex().row()); - if(!trackId) + if (!trackId) return; tracksModel->removeTrack(trackId); @@ -485,17 +494,17 @@ void StationEditDialog::removeSelectedTrack() void StationEditDialog::moveTrackUp() { - if(!ui->trackView->selectionModel()->hasSelection()) + if (!ui->trackView->selectionModel()->hasSelection()) return; QModelIndex idx = ui->trackView->currentIndex(); - db_id trackId = tracksModel->getIdAtRow(idx.row()); - if(!trackId) + db_id trackId = tracksModel->getIdAtRow(idx.row()); + if (!trackId) return; bool top = QGuiApplication::keyboardModifiers() & Qt::ShiftModifier; - if(!tracksModel->moveTrackUpDown(trackId, true, top)) + if (!tracksModel->moveTrackUpDown(trackId, true, top)) return; idx = idx.siblingAtRow(top ? 0 : idx.row() - 1); @@ -504,17 +513,17 @@ void StationEditDialog::moveTrackUp() void StationEditDialog::moveTrackDown() { - if(!ui->trackView->selectionModel()->hasSelection()) + if (!ui->trackView->selectionModel()->hasSelection()) return; QModelIndex idx = ui->trackView->currentIndex(); - db_id trackId = tracksModel->getIdAtRow(idx.row()); - if(!trackId) + db_id trackId = tracksModel->getIdAtRow(idx.row()); + if (!trackId) return; bool bottom = QGuiApplication::keyboardModifiers() & Qt::ShiftModifier; - if(!tracksModel->moveTrackUpDown(trackId, false, bottom)) + if (!tracksModel->moveTrackUpDown(trackId, false, bottom)) return; idx = idx.siblingAtRow(bottom ? tracksModel->rowCount() - 1 : idx.row() + 1); @@ -523,9 +532,9 @@ void StationEditDialog::moveTrackDown() void StationEditDialog::onTrackConnRemoved() { - //A track connection was removed + // A track connection was removed - //Update gates (has a Default Platform column) + // Update gates (has a Default Platform column) gatesModel->refreshData(true); } @@ -536,22 +545,22 @@ void StationEditDialog::addTrackConnInternal(int mode) QScopedPointer tracks(trackFactory->createModel()); QScopedPointer gates(gatesFactory->createModel()); - OwningQPointer dlg = new NewTrackConnDlg(tracks.get(), - static_cast(gates.get()), - this); + OwningQPointer dlg = + new NewTrackConnDlg(tracks.get(), static_cast(gates.get()), this); dlg->setMode(dlgMode); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } - db_id trackId = 0; + db_id trackId = 0; utils::Side trackSide = utils::Side::East; - db_id gateId = 0; - int gateTrack = 0; + db_id gateId = 0; + int gateTrack = 0; dlg->getData(trackId, trackSide, gateId, gateTrack); bool success = false; @@ -568,12 +577,11 @@ void StationEditDialog::addTrackConnInternal(int mode) break; } - if(success) + if (success) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); } void StationEditDialog::updateSVGButtons(bool hasImage) @@ -586,11 +594,11 @@ void StationEditDialog::updateSVGButtons(bool hasImage) void StationEditDialog::removeSelectedTrackConn() { - if(!ui->trackConnView->selectionModel()->hasSelection()) + if (!ui->trackConnView->selectionModel()->hasSelection()) return; db_id connId = trackConnModel->getIdAtRow(ui->trackConnView->currentIndex().row()); - if(!connId) + if (!connId) return; trackConnModel->removeTrackConnection(connId); @@ -601,48 +609,48 @@ void StationEditDialog::addGateConnection() OwningQPointer dlg(new EditRailwaySegmentDlg(mDb, nullptr, this)); dlg->setSegment(0, getStation(), EditRailwaySegmentDlg::DoNotLock); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - gateConnModel->refreshData(); //Recalc row count + gateConnModel->refreshData(); // Recalc row count } void StationEditDialog::editGateConnection() { - if(!ui->gateConnView->selectionModel()->hasSelection()) + if (!ui->gateConnView->selectionModel()->hasSelection()) return; db_id segId = gateConnModel->getIdAtRow(ui->gateConnView->currentIndex().row()); - if(!segId) + if (!segId) return; OwningQPointer dlg(new EditRailwaySegmentDlg(mDb, nullptr, this)); dlg->setSegment(segId, getStation(), EditRailwaySegmentDlg::LockToCurrentValue); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - gateConnModel->refreshData(true); //Refresh fields + gateConnModel->refreshData(true); // Refresh fields } void StationEditDialog::removeSelectedGateConnection() { - if(!ui->gateConnView->selectionModel()->hasSelection()) + if (!ui->gateConnView->selectionModel()->hasSelection()) return; db_id segId = gateConnModel->getIdAtRow(ui->gateConnView->currentIndex().row()); - if(!segId) + if (!segId) return; QString errMsg; RailwaySegmentHelper helper(mDb); - if(!helper.removeSegment(segId, &errMsg)) + if (!helper.removeSegment(segId, &errMsg)) { QMessageBox::warning(this, tr("Error"), errMsg); return; } - gateConnModel->refreshData(); //Recalc row count + gateConnModel->refreshData(); // Recalc row count } void StationEditDialog::addSVGImage() @@ -657,25 +665,25 @@ void StationEditDialog::addSVGImage() 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(station_svg_key, fileName); QFile f(fileName); - if(!f.open(QFile::ReadOnly)) + if (!f.open(QFile::ReadOnly)) { QMessageBox::warning(this, tr("Cannot Read File"), f.errorString()); return; } QString errMsg; - if(!StationSVGHelper::addImage(mDb, getStation(), &f, &errMsg)) + if (!StationSVGHelper::addImage(mDb, getStation(), &f, &errMsg)) { QMessageBox::warning(this, tr("Error Adding SVG"), errMsg); return; @@ -688,11 +696,11 @@ void StationEditDialog::removeSVGImage() { int ret = QMessageBox::question(this, tr("Delete Image?"), tr("Are you sure to delete SVG plan of this station?")); - if(ret != QMessageBox::Yes) + if (ret != QMessageBox::Yes) return; QString errMsg; - if(!StationSVGHelper::removeImage(mDb, getStation(), &errMsg)) + if (!StationSVGHelper::removeImage(mDb, getStation(), &errMsg)) { QMessageBox::warning(this, tr("Error Deleting SVG"), errMsg); return; @@ -713,24 +721,24 @@ void StationEditDialog::saveSVGToFile() 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(station_svg_key, fileName); QFile f(fileName); - if(!f.open(QFile::WriteOnly)) + if (!f.open(QFile::WriteOnly)) { QMessageBox::warning(this, tr("Cannot Save File"), f.errorString()); return; } QString errMsg; - if(!StationSVGHelper::saveImage(mDb, getStation(), &f, &errMsg)) + if (!StationSVGHelper::saveImage(mDb, getStation(), &f, &errMsg)) { QMessageBox::warning(this, tr("Error Saving SVG"), errMsg); } @@ -741,27 +749,26 @@ void StationEditDialog::importConnFromSVG() std::unique_ptr dev; dev.reset(StationSVGHelper::loadImage(mDb, getStation())); - if(!dev || !dev->open(QIODevice::ReadOnly)) + if (!dev || !dev->open(QIODevice::ReadOnly)) { - QMessageBox::warning(this, tr("Import Error"), - tr("Could not open SVG image. Make sure you added one to this station.")); + QMessageBox::warning( + this, tr("Import Error"), + tr("Could not open SVG image. Make sure you added one to this station.")); return; } bool ret = StationSVGHelper::importTrackConnFromSVGDev(mDb, getStation(), dev.get()); - if(ret) + if (ret) { QMessageBox::information(this, tr("Done Importation"), tr("Track to gate connections have been successfully imported.")); } else { - QMessageBox::warning(this, tr("Import Error"), - tr("Generic error")); - + QMessageBox::warning(this, tr("Import Error"), tr("Generic error")); } - trackConnModel->refreshData(); //Recalc row count + trackConnModel->refreshData(); // Recalc row count } void StationEditDialog::saveXmlPlan() @@ -776,23 +783,23 @@ void StationEditDialog::saveXmlPlan() 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(station_svg_key, fileName); QFile f(fileName); - if(!f.open(QFile::WriteOnly)) + if (!f.open(QFile::WriteOnly)) { QMessageBox::warning(this, tr("Cannot Save File"), f.errorString()); return; } - if(!StationSVGHelper::writeStationXmlFromDB(mDb, getStation(), &f)) + if (!StationSVGHelper::writeStationXmlFromDB(mDb, getStation(), &f)) { QMessageBox::warning(this, tr("Error Saving XML"), tr("Unknow error")); } diff --git a/src/stations/manager/stations/dialogs/stationeditdialog.h b/src/stations/manager/stations/dialogs/stationeditdialog.h index 4f8b4a4..4e9cf29 100644 --- a/src/stations/manager/stations/dialogs/stationeditdialog.h +++ b/src/stations/manager/stations/dialogs/stationeditdialog.h @@ -60,36 +60,36 @@ public slots: void done(int res) override; private slots: - void modelError(const QString& msg); + void modelError(const QString &msg); - //Gates + // Gates void onGatesChanged(); void addGate(); void removeSelectedGate(); - //Tracks + // Tracks void onTracksChanged(); void addTrack(); void removeSelectedTrack(); void moveTrackUp(); void moveTrackDown(); - //Track Connections + // Track Connections void onTrackConnRemoved(); void removeSelectedTrackConn(); - //Gate Connections + // Gate Connections void addGateConnection(); void editGateConnection(); void removeSelectedGateConnection(); - //SVG Image + // SVG Image void addSVGImage(); void removeSVGImage(); void saveSVGToFile(); void importConnFromSVG(); - //Xml Plan + // Xml Plan void saveXmlPlan(); private: diff --git a/src/stations/manager/stations/dialogs/stationsvgplandlg.cpp b/src/stations/manager/stations/dialogs/stationsvgplandlg.cpp index 2024b52..11e8f08 100644 --- a/src/stations/manager/stations/dialogs/stationsvgplandlg.cpp +++ b/src/stations/manager/stations/dialogs/stationsvgplandlg.cpp @@ -55,18 +55,19 @@ StationSVGPlanDlg::StationSVGPlanDlg(sqlite3pp::database &db, QWidget *parent) : mJobTimer(0), m_zoom(100) { - QVBoxLayout *lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); - mSvg = new QSvgRenderer(this); - m_plan = new ssplib::StationPlan; - m_station = new StationSVGJobStops; + mSvg = new QSvgRenderer(this); + m_plan = new ssplib::StationPlan; + m_station = new StationSVGJobStops; m_station->stationId = 0; - view = new ssplib::SSPViewer(m_plan); + view = new ssplib::SSPViewer(m_plan); view->setRenderer(mSvg); connect(view, &ssplib::SSPViewer::labelClicked, this, &StationSVGPlanDlg::onLabelClicked); connect(view, &ssplib::SSPViewer::trackClicked, this, &StationSVGPlanDlg::onTrackClicked); - connect(view, &ssplib::SSPViewer::trackConnClicked, this, &StationSVGPlanDlg::onTrackConnClicked); + connect(view, &ssplib::SSPViewer::trackConnClicked, this, + &StationSVGPlanDlg::onTrackConnClicked); toolBar = new QToolBar; lay->addWidget(toolBar); @@ -77,13 +78,14 @@ StationSVGPlanDlg::StationSVGPlanDlg(sqlite3pp::database &db, QWidget *parent) : scrollArea->setWidget(view); lay->addWidget(scrollArea); - //Actions + // Actions toolBar->addAction(tr("Reload"), this, &StationSVGPlanDlg::reloadPlan); toolBar->addSeparator(); QSpinBox *zoomSpin = new QSpinBox; zoomSpin->setRange(25, 400); - connect(zoomSpin, qOverload(&QSpinBox::valueChanged), this, &StationSVGPlanDlg::setZoom_slot); + connect(zoomSpin, qOverload(&QSpinBox::valueChanged), this, + &StationSVGPlanDlg::setZoom_slot); connect(this, &StationSVGPlanDlg::zoomChanged, zoomSpin, &QSpinBox::setValue); QAction *zoomAction = toolBar->addWidget(zoomSpin); @@ -105,12 +107,14 @@ StationSVGPlanDlg::StationSVGPlanDlg(sqlite3pp::database &db, QWidget *parent) : act_timeEdit->setVisible(m_showJobs); act_prevTime = toolBar->addAction(tr("Previous")); - act_prevTime->setToolTip(tr("Update time to go to previous Job arrival or departure in this station")); + act_prevTime->setToolTip( + tr("Update time to go to previous Job arrival or departure in this station")); connect(act_prevTime, &QAction::triggered, this, &StationSVGPlanDlg::goToPrevStop); act_prevTime->setVisible(m_showJobs); act_nextTime = toolBar->addAction(tr("Next")); - act_nextTime->setToolTip(tr("Update time to go to next Job arrival or departure in this station")); + act_nextTime->setToolTip( + tr("Update time to go to next Job arrival or departure in this station")); connect(act_nextTime, &QAction::triggered, this, &StationSVGPlanDlg::goToNextStop); act_nextTime->setVisible(m_showJobs); @@ -134,7 +138,7 @@ StationSVGPlanDlg::~StationSVGPlanDlg() void StationSVGPlanDlg::setStation(db_id stId) { - stationId = stId; + stationId = stId; m_station->stationId = stationId; } @@ -142,12 +146,12 @@ void StationSVGPlanDlg::reloadSVG(QIODevice *dev) { m_plan->clear(); - //TODO: load station data from DB + // TODO: load station data from DB ssplib::StreamParser parser(m_plan, dev); parser.parse(); - //Sort items + // Sort items std::sort(m_plan->labels.begin(), m_plan->labels.end()); std::sort(m_plan->platforms.begin(), m_plan->platforms.end()); std::sort(m_plan->trackConnections.begin(), m_plan->trackConnections.end()); @@ -165,15 +169,15 @@ void StationSVGPlanDlg::reloadDBData() { clearDBData(); - //Reload from database - if(!StationSVGHelper::loadStationFromDB(mDb, stationId, m_plan, true)) + // Reload from database + if (!StationSVGHelper::loadStationFromDB(mDb, stationId, m_plan, true)) { QMessageBox::warning(this, tr("Error Loading Station"), tr("Cannot load station from database")); return; } - if(m_showJobs) + if (m_showJobs) reloadJobs(); setWindowTitle(tr("%1 Station Plan").arg(m_plan->stationName)); @@ -181,34 +185,34 @@ void StationSVGPlanDlg::reloadDBData() void StationSVGPlanDlg::clearDBData() { - //Clear previous data obtained from Database - for(ssplib::LabelItem& item : m_plan->labels) + // Clear previous data obtained from Database + for (ssplib::LabelItem &item : m_plan->labels) { item.visible = false; - item.itemId = 0; + item.itemId = 0; item.labelText.clear(); } - for(ssplib::TrackItem& item : m_plan->platforms) + for (ssplib::TrackItem &item : m_plan->platforms) { item.visible = false; - item.itemId = 0; + item.itemId = 0; - item.color = ssplib::whiteRGB; + item.color = ssplib::whiteRGB; item.tooltip.clear(); item.trackName.clear(); } - for(ssplib::TrackConnectionItem& item : m_plan->trackConnections) + for (ssplib::TrackConnectionItem &item : m_plan->trackConnections) { item.visible = false; - item.itemId = 0; + item.itemId = 0; - item.color = ssplib::whiteRGB; + item.color = ssplib::whiteRGB; item.tooltip.clear(); - item.info.gateId = 0; + item.info.gateId = 0; item.info.trackId = 0; } } @@ -223,7 +227,7 @@ void StationSVGPlanDlg::reloadJobs() { clearJobs_internal(); - if(m_showJobs) + if (m_showJobs) { StationSVGHelper::loadStationJobsFromDB(mDb, m_station); StationSVGHelper::applyStationJobsToPlan(m_station, m_plan); @@ -234,7 +238,7 @@ void StationSVGPlanDlg::reloadJobs() void StationSVGPlanDlg::showJobs(bool val) { - if(m_showJobs == val) + if (m_showJobs == val) return; m_showJobs = val; @@ -243,7 +247,7 @@ void StationSVGPlanDlg::showJobs(bool val) act_prevTime->setVisible(m_showJobs); act_nextTime->setVisible(m_showJobs); - if(m_station->time.isNull()) + if (m_station->time.isNull()) m_station->time = QTime(0, 0); reloadJobs(); @@ -253,15 +257,15 @@ void StationSVGPlanDlg::setJobTime(const QTime &t) { stopJobTimer(); - //Remove seconds part, round to minutes + // Remove seconds part, round to minutes QTime rounded = QTime(t.hour(), t.minute()); - if(m_station->time == rounded) + if (m_station->time == rounded) return; m_station->time = rounded; - //Avoid starting timer + // Avoid starting timer mTimeEdit->blockSignals(true); mTimeEdit->setTime(rounded); mTimeEdit->blockSignals(false); @@ -279,14 +283,13 @@ void StationSVGPlanDlg::reloadPlan() std::unique_ptr dev; dev.reset(StationSVGHelper::loadImage(mDb, stationId)); - if(!dev) + if (!dev) { - QMessageBox::warning(this, tr("Error Loading SVG"), - tr("Cannot find SVG data")); + QMessageBox::warning(this, tr("Error Loading SVG"), tr("Cannot find SVG data")); return; } - if(!dev->open(QIODevice::ReadOnly)) + if (!dev->open(QIODevice::ReadOnly)) { QMessageBox::warning(this, tr("Error Loading SVG"), tr("Cannot read data: %1").arg(dev->errorString())); @@ -301,14 +304,14 @@ void StationSVGPlanDlg::setZoom(int val, bool force) { val = qBound(10, val, 500); - if(val == m_zoom && !force) + if (val == m_zoom && !force) return; m_zoom = val; emit zoomChanged(m_zoom); QSize s = scrollArea->widget()->sizeHint(); - s = s * m_zoom / 100; + s = s * m_zoom / 100; scrollArea->widget()->resize(s); } @@ -320,12 +323,12 @@ void StationSVGPlanDlg::setZoom_slot(int val) void StationSVGPlanDlg::zoomToFit() { const QSize available = scrollArea->size(); - const QSize contents = scrollArea->widget()->sizeHint(); + const QSize contents = scrollArea->widget()->sizeHint(); - const int zoomH = 100 * available.width() / contents.width(); - const int zoomV = 100 * available.height() / contents.height(); + const int zoomH = 100 * available.width() / contents.width(); + const int zoomV = 100 * available.height() / contents.height(); - const int val = qMin(zoomH, zoomV); + const int val = qMin(zoomH, zoomV); setZoom(val, true); } @@ -333,23 +336,23 @@ void StationSVGPlanDlg::onLabelClicked(qint64 gateId, QChar letter, const QStrin { RailwaySegmentHelper helper(mDb); utils::RailwaySegmentInfo info; - if(!helper.getSegmentInfoFromGate(gateId, info)) + if (!helper.getSegmentInfoFromGate(gateId, info)) { QMessageBox::warning(this, tr("Database Error"), tr("Cannot retrive details for gate %1 (%2)").arg(letter).arg(text)); return; } - if(info.to.stationId == stationId) + if (info.to.stationId == stationId) { - //Reverse segment + // Reverse segment qSwap(info.from, info.to); } - else if(info.from.stationId != stationId) + else if (info.from.stationId != stationId) { - //Segment not of this station - qWarning() << "StationSVGPlanDlg::onLabelClicked segment" << info.segmentId << info.segmentName - << "NOT OF THIS STATION" << stationId; + // Segment not of this station + qWarning() << "StationSVGPlanDlg::onLabelClicked segment" << info.segmentId + << info.segmentName << "NOT OF THIS STATION" << stationId; } OwningQPointer msgBox = new QMessageBox(this); @@ -357,24 +360,21 @@ void StationSVGPlanDlg::onLabelClicked(qint64 gateId, QChar letter, const QStrin msgBox->setWindowTitle(tr("Gate %1").arg(letter)); const QString translatedText = - tr( - "

Railway Segment Details

" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
Segment:%1
From:%2 (Gate: %3)
To:%4 (Gate: %5)
Distance:%6 Km
Max. Speed:%7 km/h
") - .arg(info.segmentName, - info.from.stationName, info.from.gateLetter, - info.to.stationName, info.to.gateLetter, - utils::kmNumToText(info.distanceMeters)) - .arg(info.maxSpeedKmH); + tr("

Railway Segment Details

" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
Segment:%1
From:%2 (Gate: %3)
To:%4 (Gate: %5)
Distance:%6 Km
Max. Speed:%7 km/h
") + .arg(info.segmentName, info.from.stationName, info.from.gateLetter, info.to.stationName, + info.to.gateLetter, utils::kmNumToText(info.distanceMeters)) + .arg(info.maxSpeedKmH); msgBox->setTextFormat(Qt::RichText); msgBox->setText(translatedText); @@ -384,28 +384,29 @@ void StationSVGPlanDlg::onLabelClicked(qint64 gateId, QChar letter, const QStrin msgBox->setDefaultButton(QMessageBox::Ok); msgBox->exec(); - if(!msgBox) + if (!msgBox) return; - if(msgBox->clickedButton() == showSVGBut) + if (msgBox->clickedButton() == showSVGBut) { Session->getViewManager()->requestStSVGPlan(info.to.stationId); } } -void showTrackMsgBox(const StationSVGJobStops::Stop& stop, ssplib::StationPlan *plan, +void showTrackMsgBox(const StationSVGJobStops::Stop &stop, ssplib::StationPlan *plan, db_id stationId, QWidget *parent) { const QString jobName = JobCategoryName::jobName(stop.job.jobId, stop.job.category); OwningQPointer msgBox = new QMessageBox(parent); msgBox->setIcon(QMessageBox::Information); - msgBox->setWindowTitle(StationSVGPlanDlg::tr("Job %1", "Message box title on double click").arg(jobName)); + msgBox->setWindowTitle( + StationSVGPlanDlg::tr("Job %1", "Message box title on double click").arg(jobName)); QString platformName; - for(const ssplib::TrackItem& track : qAsConst(plan->platforms)) + for (const ssplib::TrackItem &track : qAsConst(plan->platforms)) { - if(track.itemId == stop.in_gate.trackId || track.itemId == stop.out_gate.trackId) + if (track.itemId == stop.in_gate.trackId || track.itemId == stop.out_gate.trackId) { platformName = track.trackName; break; @@ -413,48 +414,48 @@ void showTrackMsgBox(const StationSVGJobStops::Stop& stop, ssplib::StationPlan * } const QString translatedText = - StationSVGPlanDlg::tr( - "

%1

" - "" - "" - "" - "" - "" - "" - "" - "" - "
Job:%2
From:%3
To:%4
Platform:%5
") - .arg(plan->stationName, jobName, - stop.arrival.toString("HH:mm"), stop.departure.toString("HH:mm"), - platformName); + StationSVGPlanDlg::tr("

%1

" + "" + "" + "" + "" + "" + "" + "" + "" + "
Job:%2
From:%3
To:%4
Platform:%5
") + .arg(plan->stationName, jobName, stop.arrival.toString("HH:mm"), + stop.departure.toString("HH:mm"), platformName); msgBox->setTextFormat(Qt::RichText); msgBox->setText(translatedText); - QPushButton *showJobEditor = msgBox->addButton(StationSVGPlanDlg::tr("Show in Job Editor"), QMessageBox::YesRole); - QPushButton *showStJobs = msgBox->addButton(StationSVGPlanDlg::tr("Show Station Jobs"), QMessageBox::YesRole); + QPushButton *showJobEditor = + msgBox->addButton(StationSVGPlanDlg::tr("Show in Job Editor"), QMessageBox::YesRole); + QPushButton *showStJobs = + msgBox->addButton(StationSVGPlanDlg::tr("Show Station Jobs"), QMessageBox::YesRole); msgBox->addButton(QMessageBox::Ok); msgBox->setDefaultButton(QMessageBox::Ok); msgBox->exec(); - if(!msgBox) + if (!msgBox) return; - if(msgBox->clickedButton() == showJobEditor) + if (msgBox->clickedButton() == showJobEditor) { Session->getViewManager()->requestJobEditor(stop.job.jobId, stop.job.stopId); } - else if(msgBox->clickedButton() == showStJobs) + else if (msgBox->clickedButton() == showStJobs) { Session->getViewManager()->requestStJobViewer(stationId); } } -void StationSVGPlanDlg::onTrackClicked(qint64 trackId, const QString &/*name*/) +void StationSVGPlanDlg::onTrackClicked(qint64 trackId, const QString & /*name*/) { - for(const StationSVGJobStops::Stop& stop : qAsConst(m_station->stops)) + for (const StationSVGJobStops::Stop &stop : qAsConst(m_station->stops)) { - if(stop.in_gate.trackId == trackId || stop.out_gate.trackId == trackId) + if (stop.in_gate.trackId == trackId || stop.out_gate.trackId == trackId) { showTrackMsgBox(stop, m_plan, stationId, this); break; @@ -465,9 +466,9 @@ void StationSVGPlanDlg::onTrackClicked(qint64 trackId, const QString &/*name*/) void StationSVGPlanDlg::onTrackConnClicked(qint64 connId, qint64 /*trackId*/, qint64 /*gateId*/, int /*gateTrackPos*/, int /*trackSide*/) { - for(const StationSVGJobStops::Stop& stop : qAsConst(m_station->stops)) + for (const StationSVGJobStops::Stop &stop : qAsConst(m_station->stops)) { - if(stop.in_gate.connId == connId || stop.out_gate.connId == connId) + if (stop.in_gate.connId == connId || stop.out_gate.connId == connId) { showTrackMsgBox(stop, m_plan, stationId, this); break; @@ -483,7 +484,7 @@ void StationSVGPlanDlg::startJobTimer() void StationSVGPlanDlg::stopJobTimer() { - if(mJobTimer) + if (mJobTimer) { killTimer(mJobTimer); mJobTimer = 0; @@ -498,12 +499,12 @@ void StationSVGPlanDlg::applyJobTime() void StationSVGPlanDlg::goToPrevStop() { QTime time = m_station->time; - if(!StationSVGHelper::getPrevNextStop(mDb, stationId, false, time)) + if (!StationSVGHelper::getPrevNextStop(mDb, stationId, false, time)) { QMessageBox::warning(this, tr("No Stop Found"), tr("No Jobs found to arrive or depart from station %1" " before %2") - .arg(m_plan->stationName, m_station->time.toString("HH:mm"))); + .arg(m_plan->stationName, m_station->time.toString("HH:mm"))); return; } @@ -513,12 +514,12 @@ void StationSVGPlanDlg::goToPrevStop() void StationSVGPlanDlg::goToNextStop() { QTime time = m_station->time; - if(!StationSVGHelper::getPrevNextStop(mDb, stationId, true, time)) + if (!StationSVGHelper::getPrevNextStop(mDb, stationId, true, time)) { QMessageBox::warning(this, tr("No Stop Found"), tr("No Jobs found to arrive or depart from station %1" " after %2") - .arg(m_plan->stationName, m_station->time.toString("HH:mm"))); + .arg(m_plan->stationName, m_station->time.toString("HH:mm"))); return; } @@ -527,16 +528,16 @@ void StationSVGPlanDlg::goToNextStop() void StationSVGPlanDlg::showEvent(QShowEvent *) { - //NOTE: when dialog is created it is hidden so it cannot zoom - //We load the station and then show the dialog - //Since dialog is hidden at first it cannot calculate zoom - //So when the dialog is first shown we trigger zoom again. + // NOTE: when dialog is created it is hidden so it cannot zoom + // We load the station and then show the dialog + // Since dialog is hidden at first it cannot calculate zoom + // So when the dialog is first shown we trigger zoom again. zoomToFit(); } void StationSVGPlanDlg::timerEvent(QTimerEvent *e) { - if(e->timerId() == mJobTimer) + if (e->timerId() == mJobTimer) { applyJobTime(); return; @@ -547,19 +548,19 @@ void StationSVGPlanDlg::timerEvent(QTimerEvent *e) void StationSVGPlanDlg::clearJobs_internal() { - for(ssplib::TrackItem& item : m_plan->platforms) + for (ssplib::TrackItem &item : m_plan->platforms) { item.visible = false; - item.color = ssplib::whiteRGB; + item.color = ssplib::whiteRGB; item.tooltip.clear(); } - for(ssplib::TrackConnectionItem& item : m_plan->trackConnections) + for (ssplib::TrackConnectionItem &item : m_plan->trackConnections) { item.visible = false; - item.color = ssplib::whiteRGB; + item.color = ssplib::whiteRGB; item.tooltip.clear(); } } diff --git a/src/stations/manager/stations/dialogs/stationsvgplandlg.h b/src/stations/manager/stations/dialogs/stationsvgplandlg.h index 2c68d34..6172be7 100644 --- a/src/stations/manager/stations/dialogs/stationsvgplandlg.h +++ b/src/stations/manager/stations/dialogs/stationsvgplandlg.h @@ -31,7 +31,6 @@ class QToolBar; class QScrollArea; class QTimeEdit; - namespace sqlite3pp { class database; } @@ -39,7 +38,7 @@ class database; namespace ssplib { class StationPlan; class SSPViewer; -} +} // namespace ssplib struct StationSVGJobStops; @@ -66,16 +65,16 @@ signals: public slots: void reloadPlan(); void showJobs(bool val); - void setJobTime(const QTime& t); + void setJobTime(const QTime &t); private slots: void setZoom(int val, bool force = false); void setZoom_slot(int val); void zoomToFit(); - void onLabelClicked(qint64 gateId, QChar letter, const QString& text); - void onTrackClicked(qint64 trackId, const QString& name); - void onTrackConnClicked(qint64 connId, qint64 trackId, qint64 gateId, - int gateTrackPos, int trackSide); + void onLabelClicked(qint64 gateId, QChar letter, const QString &text); + void onTrackClicked(qint64 trackId, const QString &name); + void onTrackConnClicked(qint64 connId, qint64 trackId, qint64 gateId, int gateTrackPos, + int trackSide); void startJobTimer(); void stopJobTimer(); @@ -96,10 +95,10 @@ private: db_id stationId; QToolBar *toolBar; - QAction *act_showJobs; - QAction *act_timeEdit; - QAction *act_prevTime; - QAction *act_nextTime; + QAction *act_showJobs; + QAction *act_timeEdit; + QAction *act_prevTime; + QAction *act_nextTime; QTimeEdit *mTimeEdit; QScrollArea *scrollArea; diff --git a/src/stations/manager/stations/model/stationgatesmodel.cpp b/src/stations/manager/stations/model/stationgatesmodel.cpp index 82dbbec..a366df6 100644 --- a/src/stations/manager/stations/model/stationgatesmodel.cpp +++ b/src/stations/manager/stations/model/stationgatesmodel.cpp @@ -28,25 +28,21 @@ using namespace sqlite3pp; #include -//Error messages -static constexpr char - errorNameNotLetterText[] = QT_TRANSLATE_NOOP("StationGatesModel", - "Gate name must be a letter."); +// Error messages +static constexpr char errorNameNotLetterText[] = + QT_TRANSLATE_NOOP("StationGatesModel", "Gate name must be a letter."); -static constexpr char - errorNameAlreadyUsedText[] = QT_TRANSLATE_NOOP("StationGatesModel", - "This gate letter %1 is already used by another gate of this station."); +static constexpr char errorNameAlreadyUsedText[] = + QT_TRANSLATE_NOOP("StationGatesModel", + "This gate letter %1 is already used by another gate of this station."); -static constexpr char - errorGateInUseText[] = QT_TRANSLATE_NOOP("StationGatesModel", - "This gate is still referenced.\n" - "Please remove all references before deleting it."); - -static constexpr char - errorGateEntranceOrExitText[] = QT_TRANSLATE_NOOP("StationGatesModel", - "The gate must be at least Entrance or Exit.\n" - "It can also be both (Bidirectional) but cannot be neither."); +static constexpr char errorGateInUseText[] = + QT_TRANSLATE_NOOP("StationGatesModel", "This gate is still referenced.\n" + "Please remove all references before deleting it."); +static constexpr char errorGateEntranceOrExitText[] = QT_TRANSLATE_NOOP( + "StationGatesModel", "The gate must be at least Entrance or Exit.\n" + "It can also be both (Bidirectional) but cannot be neither."); StationGatesModel::StationGatesModel(sqlite3pp::database &db, QObject *parent) : BaseClass(BatchSize, db, parent), @@ -58,7 +54,7 @@ StationGatesModel::StationGatesModel(sqlite3pp::database &db, QObject *parent) : QVariant StationGatesModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -98,7 +94,7 @@ QVariant StationGatesModel::headerData(int section, Qt::Orientation orientation, } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -112,16 +108,16 @@ QVariant StationGatesModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const GateItem& item = cache.at(row - cacheFirstRow); + const GateItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -185,16 +181,17 @@ QVariant StationGatesModel::data(const QModelIndex &idx, int role) const bool StationGatesModel::setData(const QModelIndex &idx, const QVariant &value, int role) { - if(!editable) + if (!editable) return false; const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - GateItem &item = cache[row - cacheFirstRow]; + GateItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -205,7 +202,7 @@ bool StationGatesModel::setData(const QModelIndex &idx, const QVariant &value, i case LetterCol: { QString str = value.toString().simplified(); - if(str.isEmpty() || !setName(item, str.at(0))) + if (str.isEmpty() || !setName(item, str.at(0))) return false; break; } @@ -213,7 +210,7 @@ bool StationGatesModel::setData(const QModelIndex &idx, const QVariant &value, i { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setSide(item, val)) + if (!ok || !setSide(item, val)) return false; break; } @@ -221,7 +218,7 @@ bool StationGatesModel::setData(const QModelIndex &idx, const QVariant &value, i { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setOutTrackCount(item, val)) + if (!ok || !setOutTrackCount(item, val)) return false; break; } @@ -234,21 +231,21 @@ bool StationGatesModel::setData(const QModelIndex &idx, const QVariant &value, i { case IsEntranceCol: { - Qt::CheckState cs = value.value(); + Qt::CheckState cs = value.value(); QFlags type = item.type; type.setFlag(utils::GateType::Entrance, cs == Qt::Checked); - if(!setType(item, type)) + if (!setType(item, type)) return false; break; } case IsExitCol: { - Qt::CheckState cs = value.value(); + Qt::CheckState cs = value.value(); QFlags type = item.type; type.setFlag(utils::GateType::Exit, cs == Qt::Checked); - if(!setType(item, type)) + if (!setType(item, type)) return false; break; } @@ -268,12 +265,12 @@ Qt::ItemFlags StationGatesModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == IsEntranceCol || idx.column() == IsExitCol) + if (idx.column() == IsEntranceCol || idx.column() == IsExitCol) f.setFlag(Qt::ItemIsUserCheckable); - else if(editable) + else if (editable) f.setFlag(Qt::ItemIsEditable); return f; @@ -281,25 +278,25 @@ Qt::ItemFlags StationGatesModel::flags(const QModelIndex &idx) const void StationGatesModel::setSortingColumn(int col) { - if(sortColumn == col || (col != LetterCol && col != SideCol)) + if (sortColumn == col || (col != LetterCol && col != SideCol)) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } bool StationGatesModel::getFieldData(int row, int col, db_id &idOut, QString &nameOut) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size() || col != DefaultInPlatfCol) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size() || col != DefaultInPlatfCol) return false; - const GateItem& item = cache[row - cacheFirstRow]; - idOut = item.defaultInPlatfId; - nameOut = item.defPlatfName; + const GateItem &item = cache[row - cacheFirstRow]; + idOut = item.defaultInPlatfId; + nameOut = item.defPlatfName; return true; } @@ -315,11 +312,11 @@ bool StationGatesModel::validateData(int row, int col, db_id id, const QString & bool StationGatesModel::setFieldData(int row, int col, db_id id, const QString &name) { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size() || col != DefaultInPlatfCol) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size() || col != DefaultInPlatfCol) return false; - GateItem& item = cache[row - cacheFirstRow]; - if(setDefaultPlatf(item, id, name)) + GateItem &item = cache[row - cacheFirstRow]; + if (setDefaultPlatf(item, id, name)) { QModelIndex idx = index(row, DefaultInPlatfCol); emit dataChanged(idx, idx); @@ -338,13 +335,13 @@ bool StationGatesModel::setStation(db_id stationId) bool StationGatesModel::addGate(const QChar &name, db_id *outGateId) { char ch = name.toUpper().toLatin1(); - if(ch < 'A' || ch > 'Z') + if (ch < 'A' || ch > 'Z') { emit modelError(tr(errorNameNotLetterText)); return false; } - char tmp[2] = { ch, '\0'}; + char tmp[2] = {ch, '\0'}; const utils::GateType type = utils::GateType::Bidirectional; command q_newGate(mDb, "INSERT INTO station_gates" @@ -356,18 +353,18 @@ bool StationGatesModel::addGate(const QChar &name, db_id *outGateId) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - int ret = q_newGate.execute(); + int ret = q_newGate.execute(); db_id gateId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newGate.reset(); - if((ret != SQLITE_OK && ret != SQLITE_DONE) || gateId == 0) + if ((ret != SQLITE_OK && ret != SQLITE_DONE) || gateId == 0) { - //Error - if(outGateId) + // Error + if (outGateId) *outGateId = 0; - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(ch)); } @@ -378,12 +375,12 @@ bool StationGatesModel::addGate(const QChar &name, db_id *outGateId) return false; } - if(outGateId) + if (outGateId) *outGateId = gateId; - refreshData(); //Recalc row count + refreshData(); // Recalc row count setSortingColumn(LetterCol); - switchToPage(0); //Reset to first page and so it is shown as first row + switchToPage(0); // Reset to first page and so it is shown as first row return true; } @@ -396,11 +393,11 @@ bool StationGatesModel::removeGate(db_id gateId) int ret = q.execute(); q.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_TRIGGER) { - //TODO: show more information to the user, like where it's still referenced + // TODO: show more information to the user, like where it's still referenced emit modelError(tr(errorGateInUseText)); } else @@ -411,7 +408,7 @@ bool StationGatesModel::removeGate(db_id gateId) return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count emit gateRemoved(gateId); @@ -422,46 +419,47 @@ QString StationGatesModel::getStationName() const { query q(mDb, "SELECT name FROM stations WHERE id=?"); q.bind(1, m_stationId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return QString(); return q.getRows().get(0); } -bool StationGatesModel::getStationInfo(QString& name, QString &shortName, - utils::StationType &type, qint64 &phoneNumber, - bool &hasImage) const +bool StationGatesModel::getStationInfo(QString &name, QString &shortName, utils::StationType &type, + qint64 &phoneNumber, bool &hasImage) const { - query q(mDb, "SELECT name,short_name,type,phone_number,svg_data IS NULL FROM stations WHERE id=?"); + query q(mDb, + "SELECT name,short_name,type,phone_number,svg_data IS NULL FROM stations WHERE id=?"); q.bind(1, m_stationId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - auto r = q.getRows(); - name = r.get(0); + auto r = q.getRows(); + name = r.get(0); shortName = r.get(1); - type = utils::StationType(r.get(2)); + type = utils::StationType(r.get(2)); - if(r.column_type(3) == SQLITE_NULL) + if (r.column_type(3) == SQLITE_NULL) phoneNumber = -1; else phoneNumber = r.get(3); - //svg_data IS NULL == 0 --> station has SVG image + // svg_data IS NULL == 0 --> station has SVG image hasImage = r.get(4) == 0; return true; } -bool StationGatesModel::setStationInfo(const QString &name, const QString &shortName, utils::StationType type, qint64 phoneNumber) +bool StationGatesModel::setStationInfo(const QString &name, const QString &shortName, + utils::StationType type, qint64 phoneNumber) { command q(mDb, "UPDATE stations SET name=?,short_name=?,type=?,phone_number=? WHERE id=?"); q.bind(1, name); - if(shortName.isEmpty()) - q.bind(2); //Bind NULL + if (shortName.isEmpty()) + q.bind(2); // Bind NULL else q.bind(2, shortName); q.bind(3, int(type)); - if(phoneNumber == -1) - q.bind(4); //Bind NULL + if (phoneNumber == -1) + q.bind(4); // Bind NULL else q.bind(4, phoneNumber); q.bind(5, m_stationId); @@ -470,7 +468,7 @@ bool StationGatesModel::setStationInfo(const QString &name, const QString &short qint64 StationGatesModel::recalcTotalItemCount() { - //TODO: consider filters + // TODO: consider filters query q(mDb, "SELECT COUNT(1) FROM station_gates WHERE station_id=?"); q.bind(1, m_stationId); q.step(); @@ -482,26 +480,28 @@ void StationGatesModel::internalFetch(int first, int sortCol, int valRow, const { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT g.id,g.out_track_count,g.type,g.def_in_platf_id,g.name,g.side,t.name FROM station_gates g" + QByteArray sql = "SELECT g.id,g.out_track_count,g.type,g.def_in_platf_id,g.name,g.side,t.name " + "FROM station_gates g" " LEFT JOIN station_tracks t ON t.id=g.def_in_platf_id"; switch (sortCol) { case LetterCol: { - whereCol = "g.name"; //Order by 1 column, no where clause + whereCol = "g.name"; // Order by 1 column, no where clause break; } case SideCol: @@ -511,30 +511,30 @@ void StationGatesModel::internalFetch(int first, int sortCol, int valRow, const } } -// if(val.isValid()) -// { -// sql += " WHERE "; -// sql += whereCol; -// if(reverse) -// sql += "?3"; -// } + // if(val.isValid()) + // { + // sql += " WHERE "; + // sql += whereCol; + // if(reverse) + // sql += "?3"; + // } sql += " WHERE g.station_id=?4"; sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); q.bind(4, m_stationId); @@ -553,31 +553,31 @@ void StationGatesModel::internalFetch(int first, int sortCol, int valRow, const QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = reverse ? BatchSize - 1 : 0; + int i = reverse ? BatchSize - 1 : 0; const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - GateItem &item = vec[i]; - item.gateId = r.get(0); - item.outTrackCount = r.get(1); - item.type = utils::GateType(r.get(2)); + auto r = *it; + GateItem &item = vec[i]; + item.gateId = r.get(0); + item.outTrackCount = r.get(1); + item.type = utils::GateType(r.get(2)); item.defaultInPlatfId = r.get(3); - item.letter = r.get(4)[0]; - item.side = utils::Side(r.get(5)); - if(r.column_type(6) != SQLITE_NULL) + item.letter = r.get(4)[0]; + item.side = utils::Side(r.get(5)); + if (r.column_type(6) != SQLITE_NULL) item.defPlatfName = r.get(6); i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); @@ -586,24 +586,24 @@ void StationGatesModel::internalFetch(int first, int sortCol, int valRow, const bool StationGatesModel::setName(StationGatesModel::GateItem &item, const QChar &val) { char ch = val.toUpper().toLatin1(); - if(ch < 'A' || ch > 'Z') + if (ch < 'A' || ch > 'Z') { emit modelError(tr(errorNameNotLetterText)); return false; } - if(item.letter == ch) + if (item.letter == ch) return false; - char tmp[2] = { ch, '\0'}; + char tmp[2] = {ch, '\0'}; command q(mDb, "UPDATE station_gates SET name=? WHERE id=?"); q.bind(1, tmp, sqlite3pp::copy_semantic::nocopy); q.bind(2, item.gateId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(ch)); } @@ -617,9 +617,9 @@ bool StationGatesModel::setName(StationGatesModel::GateItem &item, const QChar & item.letter = ch; emit gateNameChanged(item.gateId, item.letter); - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -629,14 +629,14 @@ bool StationGatesModel::setName(StationGatesModel::GateItem &item, const QChar & bool StationGatesModel::setSide(StationGatesModel::GateItem &item, int val) { utils::Side side = utils::Side(val); - if(item.side == side) + if (item.side == side) return false; command q(mDb, "UPDATE station_gates SET side=? WHERE id=?"); q.bind(1, val); q.bind(2, item.gateId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -644,11 +644,11 @@ bool StationGatesModel::setSide(StationGatesModel::GateItem &item, int val) item.side = side; - if(sortColumn == SideCol) + if (sortColumn == SideCol) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } @@ -658,13 +658,13 @@ bool StationGatesModel::setSide(StationGatesModel::GateItem &item, int val) bool StationGatesModel::setType(StationGatesModel::GateItem &item, QFlags type) { - if(item.type == type) + if (item.type == type) return false; - if((type & utils::GateType::Bidirectional) == 0) + if ((type & utils::GateType::Bidirectional) == 0) { - //Gate is neither Entrance nor Exit - //This is also checked by SQL CHECK() but this error message is better + // Gate is neither Entrance nor Exit + // This is also checked by SQL CHECK() but this error message is better emit modelError(tr(errorGateEntranceOrExitText)); return false; } @@ -673,7 +673,7 @@ bool StationGatesModel::setType(StationGatesModel::GateItem &item, QFlags Error - //Message box offering to delete track connection or leave old track count + // FIXME: check if there are railway_connections referencing track higher than count - 1. + // Like connecting a double track line and then setting track count to 1 -> Error + // Message box offering to delete track connection or leave old track count command q(mDb, "UPDATE station_gates SET out_track_count=? WHERE id=?"); q.bind(1, count); q.bind(2, item.gateId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -708,28 +708,30 @@ bool StationGatesModel::setOutTrackCount(StationGatesModel::GateItem &item, int return true; } -bool StationGatesModel::setDefaultPlatf(StationGatesModel::GateItem &item, db_id trackId, const QString& trackName) +bool StationGatesModel::setDefaultPlatf(StationGatesModel::GateItem &item, db_id trackId, + const QString &trackName) { - if(item.defaultInPlatfId == trackId) + if (item.defaultInPlatfId == trackId) return false; - //FIXME: restrict popup suggestions to tracks connected to this gate and not all station's tracks + // FIXME: restrict popup suggestions to tracks connected to this gate and not all station's + // tracks command q(mDb, "UPDATE station_gates SET def_in_platf_id=? WHERE id=?"); - if(trackId) + if (trackId) q.bind(1, trackId); else - q.bind(1); //Bind NULL + q.bind(1); // Bind NULL q.bind(2, item.gateId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; } item.defaultInPlatfId = trackId; - item.defPlatfName = trackName; + item.defPlatfName = trackName; return true; } diff --git a/src/stations/manager/stations/model/stationgatesmodel.h b/src/stations/manager/stations/model/stationgatesmodel.h index 87f9a24..720a49b 100644 --- a/src/stations/manager/stations/model/stationgatesmodel.h +++ b/src/stations/manager/stations/model/stationgatesmodel.h @@ -42,10 +42,13 @@ class StationGatesModel : public IPagedItemModelImpl 0; } QString getStationName() const; - bool getStationInfo(QString &name, QString& shortName, - utils::StationType& type, qint64& phoneNumber, - bool &hasImage) const; - bool setStationInfo(const QString &name, const QString& shortName, utils::StationType type, qint64 phoneNumber); + bool getStationInfo(QString &name, QString &shortName, utils::StationType &type, + qint64 &phoneNumber, bool &hasImage) const; + bool setStationInfo(const QString &name, const QString &shortName, utils::StationType type, + qint64 phoneNumber); // Convinience inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const GateItem& item = cache.at(row - cacheFirstRow); + const GateItem &item = cache.at(row - cacheFirstRow); return item.gateId; } inline QChar getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QChar(); //Invalid + return QChar(); // Invalid - const GateItem& item = cache.at(row - cacheFirstRow); + const GateItem &item = cache.at(row - cacheFirstRow); return item.letter; } signals: - void gateNameChanged(db_id gateId, const QString& name); + void gateNameChanged(db_id gateId, const QString &name); void gateRemoved(db_id gateId); protected: @@ -141,7 +153,8 @@ private: bool setSide(GateItem &item, int val); bool setType(GateItem &item, QFlags type); bool setOutTrackCount(GateItem &item, int count); - bool setDefaultPlatf(StationGatesModel::GateItem &item, db_id trackId, const QString &trackName); + bool setDefaultPlatf(StationGatesModel::GateItem &item, db_id trackId, + const QString &trackName); private: db_id m_stationId; diff --git a/src/stations/manager/stations/model/stationsmodel.cpp b/src/stations/manager/stations/model/stationsmodel.cpp index 55da457..862c459 100644 --- a/src/stations/manager/stations/model/stationsmodel.cpp +++ b/src/stations/manager/stations/model/stationsmodel.cpp @@ -30,28 +30,23 @@ using namespace sqlite3pp; #include -//Error messages -static constexpr char - errorNameAlreadyUsedText[] = QT_TRANSLATE_NOOP("StationsModel", - "The name %1 is already used by another station.
" - "Please choose a different name for each station."); -static constexpr char - errorShortNameAlreadyUsedText[] = QT_TRANSLATE_NOOP("StationsModel", - "The name %1 is already used as short name for station %2.
" - "Please choose a different name for each station."); -static constexpr char - errorNameSameShortNameText[] = QT_TRANSLATE_NOOP("StationsModel", - "Name and short name cannot be equal (%1)."); +// Error messages +static constexpr char errorNameAlreadyUsedText[] = + QT_TRANSLATE_NOOP("StationsModel", "The name %1 is already used by another station.
" + "Please choose a different name for each station."); +static constexpr char errorShortNameAlreadyUsedText[] = QT_TRANSLATE_NOOP( + "StationsModel", "The name %1 is already used as short name for station %2.
" + "Please choose a different name for each station."); +static constexpr char errorNameSameShortNameText[] = + QT_TRANSLATE_NOOP("StationsModel", "Name and short name cannot be equal (%1)."); -static constexpr char - errorPhoneSameNumberText[] = QT_TRANSLATE_NOOP("StationsModel", - "The phone number %1 is already used by another station.
" - "Please choose a different phone number for each station."); +static constexpr char errorPhoneSameNumberText[] = QT_TRANSLATE_NOOP( + "StationsModel", "The phone number %1 is already used by another station.
" + "Please choose a different phone number for each station."); -static constexpr char - errorStationInUseText[] = QT_TRANSLATE_NOOP("StationsModel", - "Cannot delete %1 station because it is still referenced.
" - "Please delete all jobs stopping here and remove the station from any line."); +static constexpr char errorStationInUseText[] = QT_TRANSLATE_NOOP( + "StationsModel", "Cannot delete %1 station because it is still referenced.
" + "Please delete all jobs stopping here and remove the station from any line."); StationsModel::StationsModel(sqlite3pp::database &db, QObject *parent) : BaseClass(500, db, parent) @@ -61,7 +56,7 @@ StationsModel::StationsModel(sqlite3pp::database &db, QObject *parent) : QVariant StationsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -91,7 +86,7 @@ QVariant StationsModel::headerData(int section, Qt::Orientation orientation, int } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -105,16 +100,16 @@ QVariant StationsModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -130,8 +125,8 @@ QVariant StationsModel::data(const QModelIndex &idx, int role) const return utils::StationUtils::name(item.type); case PhoneCol: { - if(item.phone_number == -1) - return QVariant(); //Null + if (item.phone_number == -1) + return QVariant(); // Null return item.phone_number; } } @@ -160,24 +155,25 @@ QVariant StationsModel::data(const QModelIndex &idx, int role) const bool StationsModel::setData(const QModelIndex &idx, const QVariant &value, int role) { const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size() || role != Qt::EditRole) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size() || role != Qt::EditRole) + return false; // Not fetched yet or invalid StationItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (idx.column()) { case NameCol: { - if(!setName(item, value.toString())) + if (!setName(item, value.toString())) return false; break; } case ShortNameCol: { - if(!setShortName(item, value.toString())) + if (!setShortName(item, value.toString())) return false; break; } @@ -185,17 +181,17 @@ bool StationsModel::setData(const QModelIndex &idx, const QVariant &value, int r { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setType(item, val)) + if (!ok || !setType(item, val)) return false; break; } case PhoneCol: { - bool ok = false; + bool ok = false; qint64 val = value.toLongLong(&ok); - if(!ok) + if (!ok) val = -1; - if(!setPhoneNumber(item, val)) + if (!setPhoneNumber(item, val)) return false; break; } @@ -212,8 +208,8 @@ Qt::ItemFlags StationsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet f.setFlag(Qt::ItemIsEditable); @@ -233,41 +229,41 @@ qint64 StationsModel::recalcTotalItemCount() void StationsModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, bool fullData) { QByteArray sql; - if(fullData) + if (fullData) sql = "SELECT id,name,short_name,type,phone_number FROM stations"; else sql = "SELECT COUNT(1) FROM stations"; - bool whereClauseAdded = false; + bool whereClauseAdded = false; bool phoneFilterIsNull = m_phoneFilter.startsWith(nullFilterStr, Qt::CaseInsensitive); - if(!m_phoneFilter.isEmpty()) + if (!m_phoneFilter.isEmpty()) { - if(phoneFilterIsNull) + if (phoneFilterIsNull) sql.append(" WHERE phone_number IS NULL"); else sql.append(" WHERE phone_number LIKE ?3"); whereClauseAdded = true; } - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { - if(whereClauseAdded) + if (whereClauseAdded) sql.append(" AND "); else sql.append(" WHERE "); sql.append("(name LIKE ?4 OR short_name LIKE ?4)"); } - if(fullData) + if (fullData) { - //Apply sorting + // Apply sorting const char *sortColExpr = nullptr; switch (sortCol) { case NameCol: { - sortColExpr = "name"; //Order by 1 column, no where clause + sortColExpr = "name"; // Order by 1 column, no where clause break; } case TypeCol: @@ -281,23 +277,23 @@ void StationsModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, boo sql += sortColExpr; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; } q.prepare(sql); - if(fullData) + if (fullData) { - //Apply offset and batch size + // Apply offset and batch size q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); } - //Apply filters + // Apply filters QByteArray phoneFilter; - if(!m_phoneFilter.isEmpty() && !phoneFilterIsNull) + if (!m_phoneFilter.isEmpty() && !phoneFilterIsNull) { phoneFilter.reserve(m_phoneFilter.size() + 2); phoneFilter.append('%'); @@ -307,7 +303,7 @@ void StationsModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, boo } QByteArray nameFilter; - if(!m_nameFilter.isEmpty()) + if (!m_nameFilter.isEmpty()) { nameFilter.reserve(m_nameFilter.size() + 2); nameFilter.append('%'); @@ -319,14 +315,14 @@ void StationsModel::buildQuery(sqlite3pp::query &q, int sortCol, int offset, boo void StationsModel::setSortingColumn(int col) { - if(sortColumn == col || (col != NameCol && col != TypeCol)) + if (sortColumn == col || (col != NameCol && col != TypeCol)) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } @@ -351,8 +347,8 @@ bool StationsModel::setFilterAtCol(int col, const QString &str) { case NameCol: { - if(isNull) - return false; //Cannot have NULL Name + if (isNull) + return false; // Cannot have NULL Name m_nameFilter = str; break; } @@ -371,7 +367,7 @@ bool StationsModel::setFilterAtCol(int col, const QString &str) bool StationsModel::addStation(const QString &name, db_id *outStationId) { - if(name.isEmpty()) + if (name.isEmpty()) return false; command q_newStation(mDb, "INSERT INTO stations(id,name,short_name,type,phone_number,svg_data)" @@ -380,18 +376,18 @@ bool StationsModel::addStation(const QString &name, db_id *outStationId) sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - int ret = q_newStation.execute(); + int ret = q_newStation.execute(); db_id stationId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newStation.reset(); - if((ret != SQLITE_OK && ret != SQLITE_DONE) || stationId == 0) + if ((ret != SQLITE_OK && ret != SQLITE_DONE) || stationId == 0) { - //Error - if(outStationId) + // Error + if (outStationId) *outStationId = 0; - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(name)); } @@ -402,19 +398,19 @@ bool StationsModel::addStation(const QString &name, db_id *outStationId) return false; } - if(outStationId) + if (outStationId) *outStationId = stationId; - //Clear filters + // Clear filters m_nameFilter.clear(); m_nameFilter.squeeze(); m_phoneFilter.clear(); m_phoneFilter.squeeze(); emit filterChanged(); - refreshData(); //Recalc row count + refreshData(); // Recalc row count setSortingColumn(NameCol); - switchToPage(0); //Reset to first page and so it is shown as first row + switchToPage(0); // Reset to first page and so it is shown as first row return true; } @@ -427,14 +423,14 @@ bool StationsModel::removeStation(db_id stationId) int ret = q_removeStation.execute(); q_removeStation.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { - //TODO: show more information to the user, like where it's still referenced + // TODO: show more information to the user, like where it's still referenced query q(mDb, "SELECT name FROM stations WHERE id=?"); q.bind(1, stationId); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { const QString name = q.getRows().get(0); emit modelError(tr(errorStationInUseText).arg(name)); @@ -450,12 +446,12 @@ bool StationsModel::removeStation(db_id stationId) emit Session->stationRemoved(stationId); - refreshData(); //Recalc row count + refreshData(); // Recalc row count return true; } -void StationsModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant &/*val*/) +void StationsModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVariant & /*val*/) { query q(mDb); @@ -467,19 +463,19 @@ void StationsModel::internalFetch(int first, int sortCol, int /*valRow*/, const QVector vec(BatchSize); - auto it = q.begin(); + auto it = q.begin(); const auto end = q.end(); - int i = 0; - for(; it != end; ++it) + int i = 0; + for (; it != end; ++it) { - auto r = *it; + auto r = *it; StationItem &item = vec[i]; - item.stationId = r.get(0); - item.name = r.get(1); - item.shortName = r.get(2); - item.type = utils::StationType(r.get(3)); - if(r.column_type(4) == SQLITE_NULL) + item.stationId = r.get(0); + item.name = r.get(1); + item.shortName = r.get(2); + item.type = utils::StationType(r.get(3)); + if (r.column_type(4) == SQLITE_NULL) item.phone_number = -1; else item.phone_number = r.get(4); @@ -487,7 +483,7 @@ void StationsModel::internalFetch(int first, int sortCol, int /*valRow*/, const i += 1; } - if(i < BatchSize) + if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); @@ -496,17 +492,17 @@ void StationsModel::internalFetch(int first, int sortCol, int /*valRow*/, const bool StationsModel::setName(StationsModel::StationItem &item, const QString &val) { const QString name = val.simplified(); - if(name.isEmpty() || item.name == name) + if (name.isEmpty() || item.name == name) return false; - //TODO: check non allowed characters + // TODO: check non allowed characters query q(mDb, "SELECT id,name FROM stations WHERE short_name=?"); q.bind(1, name); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { db_id stId = q.getRows().get(0); - if(stId == item.stationId) + if (stId == item.stationId) { emit modelError(tr(errorNameSameShortNameText).arg(name)); } @@ -522,9 +518,9 @@ bool StationsModel::setName(StationsModel::StationItem &item, const QString &val q.bind(1, name); q.bind(2, item.stationId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(name)); } @@ -539,9 +535,9 @@ bool StationsModel::setName(StationsModel::StationItem &item, const QString &val emit Session->stationNameChanged(item.stationId); - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -551,17 +547,17 @@ bool StationsModel::setName(StationsModel::StationItem &item, const QString &val bool StationsModel::setShortName(StationsModel::StationItem &item, const QString &val) { const QString shortName = val.simplified(); - if(item.shortName == shortName) + if (item.shortName == shortName) return false; - //TODO: check non allowed characters + // TODO: check non allowed characters query q(mDb, "SELECT id,name FROM stations WHERE name=?"); q.bind(1, shortName); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { db_id stId = q.getRows().get(0); - if(stId == item.stationId) + if (stId == item.stationId) { emit modelError(tr(errorNameSameShortNameText).arg(shortName)); } @@ -574,15 +570,15 @@ bool StationsModel::setShortName(StationsModel::StationItem &item, const QString } q.prepare("UPDATE stations SET short_name=? WHERE id=?"); - if(shortName.isEmpty()) - q.bind(1); //Bind NULL + if (shortName.isEmpty()) + q.bind(1); // Bind NULL else q.bind(1, shortName); q.bind(2, item.stationId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorShortNameAlreadyUsedText).arg(shortName, QString())); } @@ -602,14 +598,14 @@ bool StationsModel::setShortName(StationsModel::StationItem &item, const QString bool StationsModel::setType(StationsModel::StationItem &item, int val) { utils::StationType type = utils::StationType(val); - if(val < 0 || type >= utils::StationType::NTypes || item.type == type) + if (val < 0 || type >= utils::StationType::NTypes || item.type == type) return false; query q(mDb, "UPDATE stations SET type=? WHERE id=?"); q.bind(1, val); q.bind(2, item.stationId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -617,11 +613,11 @@ bool StationsModel::setType(StationsModel::StationItem &item, int val) item.type = type; - if(sortColumn == TypeCol) + if (sortColumn == TypeCol) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } @@ -631,24 +627,24 @@ bool StationsModel::setType(StationsModel::StationItem &item, int val) bool StationsModel::setPhoneNumber(StationsModel::StationItem &item, qint64 val) { - if(item.phone_number == val) + if (item.phone_number == val) return false; - //TODO: better handling of NULL (= remove phone number) - //TODO: maybe is better TEXT type for phone number - if(val < 0) + // TODO: better handling of NULL (= remove phone number) + // TODO: maybe is better TEXT type for phone number + if (val < 0) val = -1; query q(mDb, "UPDATE stations SET phone_number=? WHERE id=?"); - if(val == -1) - q.bind(1); //Bind NULL + if (val == -1) + q.bind(1); // Bind NULL else q.bind(1, val); q.bind(2, item.stationId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorPhoneSameNumberText).arg(val)); } diff --git a/src/stations/manager/stations/model/stationsmodel.h b/src/stations/manager/stations/model/stationsmodel.h index 2e507a4..075c8e8 100644 --- a/src/stations/manager/stations/model/stationsmodel.h +++ b/src/stations/manager/stations/model/stationsmodel.h @@ -43,10 +43,13 @@ class StationsModel : public IPagedItemModelImpl getFilterAtCol(int col) override; - bool setFilterAtCol(int col, const QString& str) override; + bool setFilterAtCol(int col, const QString &str) override; // StationsModel - bool addStation(const QString& name, db_id *outStationId = nullptr); + bool addStation(const QString &name, db_id *outStationId = nullptr); bool removeStation(db_id stationId); // Convinience inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); return item.stationId; } inline QString getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QString(); //Invalid + return QString(); // Invalid - const StationItem& item = cache.at(row - cacheFirstRow); + const StationItem &item = cache.at(row - cacheFirstRow); return item.name; } diff --git a/src/stations/manager/stations/model/stationsvghelper.cpp b/src/stations/manager/stations/model/stationsvghelper.cpp index 09492c8..ff147bb 100644 --- a/src/stations/manager/stations/model/stationsvghelper.cpp +++ b/src/stations/manager/stations/model/stationsvghelper.cpp @@ -37,7 +37,7 @@ #include -const char stationTable[] = "stations"; +const char stationTable[] = "stations"; const char stationSVGCol[] = "svg_data"; static ImageMetaData::ImageBlobDevice *loadImage_internal(sqlite3pp::database &db, db_id stationId) @@ -52,32 +52,33 @@ bool StationSVGHelper::stationHasSVG(sqlite3pp::database &db, db_id stationId, Q sqlite3pp::query q(db); q.prepare("SELECT name, (svg_data IS NULL) FROM stations WHERE id=?"); q.bind(1, stationId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; - if(stNameOut) + if (stNameOut) *stNameOut = q.getRows().get(0); - //svg_data IS NULL == 0 --> station has SVG image + // svg_data IS NULL == 0 --> station has SVG image return q.getRows().get(1) == 0; } -bool StationSVGHelper::addImage(sqlite3pp::database &db, db_id stationId, QIODevice *source, QString *errOut) +bool StationSVGHelper::addImage(sqlite3pp::database &db, db_id stationId, QIODevice *source, + QString *errOut) { std::unique_ptr dest; dest.reset(loadImage_internal(db, stationId)); - if(!source || !dest) + if (!source || !dest) { - if(errOut) + if (errOut) *errOut = tr("Null device"); return false; } - //Make room for storing data and open device - if(!dest->reserveSizeAndReset(source->size())) + // Make room for storing data and open device + if (!dest->reserveSizeAndReset(source->size())) { - if(errOut) + if (errOut) *errOut = dest->errorString(); return false; } @@ -100,36 +101,37 @@ bool StationSVGHelper::removeImage(sqlite3pp::database &db, db_id stationId, QSt sqlite3pp::command cmd(db, "UPDATE stations SET svg_data = NULL WHERE id=?"); cmd.bind(1, stationId); int ret = cmd.execute(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(errOut) + if (errOut) *errOut = tr("Cannot remove SVG: %1").arg(db.error_msg()); return false; } return true; } -bool StationSVGHelper::saveImage(sqlite3pp::database &db, db_id stationId, QIODevice *dest, QString *errOut) +bool StationSVGHelper::saveImage(sqlite3pp::database &db, db_id stationId, QIODevice *dest, + QString *errOut) { std::unique_ptr source; source.reset(loadImage_internal(db, stationId)); - if(!source || !dest) + if (!source || !dest) { - if(errOut) + if (errOut) *errOut = tr("Null device"); return false; } - if(!source->open(QIODevice::ReadOnly)) + if (!source->open(QIODevice::ReadOnly)) { - if(errOut) + if (errOut) *errOut = tr("Cannot open source: %1").arg(source->errorString()); return false; } - //Optimization for files, resize to avoid reallocations - if(QFileDevice *dev = qobject_cast(dest)) + // Optimization for files, resize to avoid reallocations + if (QFileDevice *dev = qobject_cast(dest)) dev->resize(source->size()); constexpr int bufSize = 4096; @@ -150,51 +152,52 @@ QIODevice *StationSVGHelper::loadImage(sqlite3pp::database &db, db_id stationId) return loadImage_internal(db, stationId); } -bool loadStationLabels(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, bool onlyAlreadyPresent) +bool loadStationLabels(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, + bool onlyAlreadyPresent) { sqlite3pp::query q(db); - //Load Gate labels + // Load Gate labels q.prepare("SELECT g.id,g.out_track_count,g.name,g.side FROM station_gates g" " WHERE g.station_id=?" " ORDER BY g.name" " LIMIT 1000"); q.bind(1, stationId); - //const QString labelFmt = QStringLiteral("%1 (%2)"); + // const QString labelFmt = QStringLiteral("%1 (%2)"); - for(auto r : q) + for (auto r : q) { - db_id gateId = r.get(0); - int outTrackCount = r.get(1); - QChar gateLetter = r.get(2)[0]; + db_id gateId = r.get(0); + int outTrackCount = r.get(1); + QChar gateLetter = r.get(2)[0]; ssplib::Side gateSide = ssplib::Side(r.get(3)); - int i = 0; - for(; i < plan->labels.size(); i++) + int i = 0; + for (; i < plan->labels.size(); i++) { - if(plan->labels.at(i).gateLetter == gateLetter) - break; //Label already exists, fill data + if (plan->labels.at(i).gateLetter == gateLetter) + break; // Label already exists, fill data } - if(i >= plan->labels.size()) + if (i >= plan->labels.size()) { - if(onlyAlreadyPresent) + if (onlyAlreadyPresent) { - //Skip gate because it was not registered in SVG + // Skip gate because it was not registered in SVG continue; } - //Create new gate + // Create new gate ssplib::LabelItem gate; gate.gateLetter = gateLetter; plan->labels.append(gate); i = plan->labels.size() - 1; } - ssplib::LabelItem& item = plan->labels[i]; - item.itemId = gateId; - item.gateOutTrkCount = outTrackCount; - item.gateSide = gateSide; + ssplib::LabelItem &item = plan->labels[i]; + item.itemId = gateId; + item.gateOutTrkCount = outTrackCount; + item.gateSide = gateSide; sqlite3pp::query sub(db); sub.prepare("SELECT s.id, s.name, s.max_speed_kmh, s.type, s.distance_meters," @@ -207,19 +210,19 @@ bool loadStationLabels(sqlite3pp::database &db, db_id stationId, ssplib::Station " JOIN stations st2 ON st2.id=g2.station_id" " WHERE s.in_gate_id=?1 OR s.out_gate_id=?1"); sub.bind(1, gateId); - for(auto s : sub) + for (auto s : sub) { - db_id segId = s.get(0); - QString segName = s.get(1); - int maxSpeedKmH = s.get(2); + db_id segId = s.get(0); + QString segName = s.get(1); + int maxSpeedKmH = s.get(2); utils::RailwaySegmentType segType = utils::RailwaySegmentType(s.get(3)); - int distanceMeters = s.get(4); + int distanceMeters = s.get(4); - db_id fromStationId = s.get(5); - db_id toStationId = s.get(6); + db_id fromStationId = s.get(5); + db_id toStationId = s.get(6); - QString fromStationName = s.get(7); - QString toStationName = s.get(8); + QString fromStationName = s.get(7); + QString toStationName = s.get(8); Q_UNUSED(segId) Q_UNUSED(maxSpeedKmH) @@ -227,31 +230,30 @@ bool loadStationLabels(sqlite3pp::database &db, db_id stationId, ssplib::Station Q_UNUSED(distanceMeters) bool reversed = false; - if(toStationId == stationId) + if (toStationId == stationId) { qSwap(fromStationId, toStationId); qSwap(fromStationName, toStationName); reversed = true; } - else if(fromStationId != stationId) + else if (fromStationId != stationId) { - //Error: station is neither 'from' nor 'to' - //Skip segment + // Error: station is neither 'from' nor 'to' + // Skip segment continue; } Q_UNUSED(reversed) - //TODO: set segment name as tooltip because otherwise label is too long - //item.labelText = labelFmt.arg(toStationName, segName); + // TODO: set segment name as tooltip because otherwise label is too long + // item.labelText = labelFmt.arg(toStationName, segName); Q_UNUSED(segName) item.labelText = toStationName; - - //Mark label as visible + // Mark label as visible item.visible = true; - //Found the segment, break + // Found the segment, break break; } } @@ -259,54 +261,56 @@ bool loadStationLabels(sqlite3pp::database &db, db_id stationId, ssplib::Station return true; } -bool loadStationTracks(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, bool onlyAlreadyPresent) +bool loadStationTracks(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, + bool onlyAlreadyPresent) { sqlite3pp::query q(db); - //Load Station Tracks + // Load Station Tracks q.prepare("SELECT id, pos, name FROM station_tracks WHERE station_id=?"); q.bind(1, stationId); - for(auto r : q) + for (auto r : q) { - db_id trackId = r.get(0); - int trackPos = r.get(1); + db_id trackId = r.get(0); + int trackPos = r.get(1); QString trackName = r.get(2); - int i = 0; - for(; i < plan->platforms.size(); i++) + int i = 0; + for (; i < plan->platforms.size(); i++) { - if(plan->platforms.at(i).trackPos == trackPos) - break; //Track already exists, fill data + if (plan->platforms.at(i).trackPos == trackPos) + break; // Track already exists, fill data } - if(i >= plan->platforms.size()) + if (i >= plan->platforms.size()) { - if(onlyAlreadyPresent) + if (onlyAlreadyPresent) { - //Skip track because it was not registered in SVG + // Skip track because it was not registered in SVG continue; } - //Create new track + // Create new track ssplib::TrackItem track; track.trackPos = trackPos; plan->platforms.append(track); i = plan->platforms.size() - 1; } - ssplib::TrackItem& item = plan->platforms[i]; - item.itemId = trackId; - item.trackName = trackName; + ssplib::TrackItem &item = plan->platforms[i]; + item.itemId = trackId; + item.trackName = trackName; } return true; } -bool loadStationTrackConnections(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, bool onlyAlreadyPresent) +bool loadStationTrackConnections(sqlite3pp::database &db, db_id stationId, + ssplib::StationPlan *plan, bool onlyAlreadyPresent) { sqlite3pp::query q(db); - //Load Station Tracks + // Load Station Tracks q.prepare("SELECT c.id, c.track_id, c.track_side, t.pos," "c.gate_id, g.name, c.gate_track FROM station_gate_connections c" " JOIN station_tracks t ON t.id=c.track_id" @@ -315,44 +319,44 @@ bool loadStationTrackConnections(sqlite3pp::database &db, db_id stationId, sspli " LIMIT 500"); q.bind(1, stationId); - auto& trackConnections = plan->trackConnections; + auto &trackConnections = plan->trackConnections; - for(auto r : q) + for (auto r : q) { ssplib::TrackConnectionInfo info; - db_id connId = r.get(0); - info.trackId = r.get(1); - info.trackSide = ssplib::Side(r.get(2)); + db_id connId = r.get(0); + info.trackId = r.get(1); + info.trackSide = ssplib::Side(r.get(2)); info.stationTrackPos = r.get(3); - info.gateId = r.get(4); - info.gateLetter = r.get(5)[0]; - info.gateTrackPos = r.get(6); + info.gateId = r.get(4); + info.gateLetter = r.get(5)[0]; + info.gateTrackPos = r.get(6); - int i = 0; - for(; i < trackConnections.size(); i++) + int i = 0; + for (; i < trackConnections.size(); i++) { - const ssplib::TrackConnectionItem& item = trackConnections.at(i); - if(item.info.matchNames(info)) - break; //Track connection already exists, fill data + const ssplib::TrackConnectionItem &item = trackConnections.at(i); + if (item.info.matchNames(info)) + break; // Track connection already exists, fill data } - if(i >= trackConnections.size()) + if (i >= trackConnections.size()) { - if(onlyAlreadyPresent) + if (onlyAlreadyPresent) { - //Skip connection because it was not registered in SVG + // Skip connection because it was not registered in SVG continue; } - //Create new gate + // Create new gate plan->trackConnections.append(ssplib::TrackConnectionItem()); i = plan->trackConnections.size() - 1; } - ssplib::TrackConnectionItem& item = trackConnections[i]; - item.itemId = connId; + ssplib::TrackConnectionItem &item = trackConnections[i]; + item.itemId = connId; - //NOTE: when TrackConnectionInfo matches to another, it checks only some fields - //So replace it with new data + // NOTE: when TrackConnectionInfo matches to another, it checks only some fields + // So replace it with new data item.info = info; } @@ -365,29 +369,29 @@ bool StationSVGHelper::loadStationFromDB(sqlite3pp::database &db, db_id stationI sqlite3pp::query q(db); q.prepare("SELECT name FROM stations WHERE id=?"); q.bind(1, stationId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return false; plan->stationName = q.getRows().get(0); - if(!loadStationLabels(db, stationId, plan, onlyAlreadyPresent)) + if (!loadStationLabels(db, stationId, plan, onlyAlreadyPresent)) return false; - if(!loadStationTracks(db, stationId, plan, onlyAlreadyPresent)) + if (!loadStationTracks(db, stationId, plan, onlyAlreadyPresent)) return false; - if(!loadStationTrackConnections(db, stationId, plan, onlyAlreadyPresent)) + if (!loadStationTrackConnections(db, stationId, plan, onlyAlreadyPresent)) return false; return true; } -bool StationSVGHelper::getPrevNextStop(sqlite3pp::database &db, db_id stationId, - bool next, QTime &time) +bool StationSVGHelper::getPrevNextStop(sqlite3pp::database &db, db_id stationId, bool next, + QTime &time) { const QTime origTime = time; sqlite3pp::query q(db); - if(next) + if (next) q.prepare("SELECT MIN(arrival) FROM stops WHERE station_id=? AND arrival>?"); else q.prepare("SELECT MAX(departure) FROM stops WHERE station_id=? AND departure(0); - //Try with swapped arrival and departure - if(next) + // Try with swapped arrival and departure + if (next) q.prepare("SELECT MIN(departure) FROM stops WHERE station_id=? AND departure>?"); else q.prepare("SELECT MAX(arrival) FROM stops WHERE station_id=? AND arrival(0); - //NOTE: If previous query didn't find any stop take this - //Otherwise compare with previous query result - //If next, keep earlier one, if previous keep latest one - if(!found || (next && otherTime < time) || (!next && otherTime > time)) + // NOTE: If previous query didn't find any stop take this + // Otherwise compare with previous query result + // If next, keep earlier one, if previous keep latest one + if (!found || (next && otherTime < time) || (!next && otherTime > time)) time = otherTime; found = true; } @@ -439,29 +443,29 @@ bool StationSVGHelper::loadStationJobsFromDB(sqlite3pp::database &db, StationSVG station->stops.clear(); - for(auto stop : q) + for (auto stop : q) { StationSVGJobStops::Stop s; - s.job.stopId = stop.get(0); - s.job.jobId = stop.get(1); - s.job.category = JobCategory(stop.get(2)); - s.arrival = stop.get(3); - s.departure = stop.get(4); + s.job.stopId = stop.get(0); + s.job.jobId = stop.get(1); + s.job.category = JobCategory(stop.get(2)); + s.arrival = stop.get(3); + s.departure = stop.get(4); - s.in_gate.connId = stop.get(5); - s.in_gate.trackId = stop.get(6); - s.in_gate.trackSide = utils::Side(stop.get(7)); - s.in_gate.gateId = stop.get(8); - s.in_gate.gateTrackNum = stop.get(9); + s.in_gate.connId = stop.get(5); + s.in_gate.trackId = stop.get(6); + s.in_gate.trackSide = utils::Side(stop.get(7)); + s.in_gate.gateId = stop.get(8); + s.in_gate.gateTrackNum = stop.get(9); - s.out_gate.connId = stop.get(10); - s.out_gate.trackId = stop.get(11); - s.out_gate.trackSide = utils::Side(stop.get(12)); - s.out_gate.gateId = stop.get(13); + s.out_gate.connId = stop.get(10); + s.out_gate.trackId = stop.get(11); + s.out_gate.trackSide = utils::Side(stop.get(12)); + s.out_gate.gateId = stop.get(13); s.out_gate.gateTrackNum = stop.get(14); - s.next_seg_conn = stop.get(15); - s.type = StopType(stop.get(16)); + s.next_seg_conn = stop.get(15); + s.type = StopType(stop.get(16)); station->stops.append(s); } @@ -469,52 +473,53 @@ bool StationSVGHelper::loadStationJobsFromDB(sqlite3pp::database &db, StationSVG return true; } -bool StationSVGHelper::applyStationJobsToPlan(const StationSVGJobStops *station, ssplib::StationPlan *plan) +bool StationSVGHelper::applyStationJobsToPlan(const StationSVGJobStops *station, + ssplib::StationPlan *plan) { - const QString fmt = tr("%1 from %2 to %3
" - "Platform: %4
" - "%5"); - const QString statusArr = tr("Arriving"); - const QString statusDep = tr("Departing"); - const QString statusStop = tr("Stop"); + const QString fmt = tr("%1 from %2 to %3
" + "Platform: %4
" + "%5"); + const QString statusArr = tr("Arriving"); + const QString statusDep = tr("Departing"); + const QString statusStop = tr("Stop"); const QString statusTransit = tr("Transit"); - for(const StationSVGJobStops::Stop& stop : station->stops) + for (const StationSVGJobStops::Stop &stop : station->stops) { db_id trackId = stop.in_gate.trackId; - if(!trackId) + if (!trackId) trackId = stop.out_gate.trackId; - QString tooltip = fmt.arg(JobCategoryName::jobName(stop.job.jobId, stop.job.category), - stop.arrival.toString("HH:mm"), stop.departure.toString("HH:mm")); + QString tooltip = fmt.arg(JobCategoryName::jobName(stop.job.jobId, stop.job.category), + stop.arrival.toString("HH:mm"), stop.departure.toString("HH:mm")); - QRgb color = Session->colorForCat(stop.job.category).rgb(); + QRgb color = Session->colorForCat(stop.job.category).rgb(); bool foundPlatform = false; - for(ssplib::TrackItem &platf : plan->platforms) + for (ssplib::TrackItem &platf : plan->platforms) { - if(platf.itemId != trackId) + if (platf.itemId != trackId) continue; - foundPlatform = true; - tooltip = tooltip.arg(platf.trackName); + foundPlatform = true; + tooltip = tooltip.arg(platf.trackName); QString status = statusStop; - if(stop.type == StopType::Transit) + if (stop.type == StopType::Transit) status = statusTransit; - else if(stop.departure == station->time && stop.next_seg_conn) + else if (stop.departure == station->time && stop.next_seg_conn) status = statusDep; platf.visible = true; platf.tooltip = tooltip.arg(status); - platf.color = color; + platf.color = color; break; } - if(!foundPlatform) + if (!foundPlatform) tooltip = tooltip.arg(tr("Not found", "Station platform was not found in SVG")); - if(stop.arrival == station->time && stop.in_gate.connId) + if (stop.arrival == station->time && stop.in_gate.connId) { ssplib::TrackConnectionInfo inConn; inConn.gateId = stop.in_gate.gateId; @@ -522,22 +527,22 @@ bool StationSVGHelper::applyStationJobsToPlan(const StationSVGJobStops *station, inConn.trackId = stop.in_gate.trackId; inConn.trackSide = ssplib::Side(stop.in_gate.trackSide); - //Train is arriving at requested time, show path - for(ssplib::TrackConnectionItem &conn : plan->trackConnections) + // Train is arriving at requested time, show path + for (ssplib::TrackConnectionItem &conn : plan->trackConnections) { - if(conn.itemId != stop.in_gate.connId && !conn.info.matchIDs(inConn)) + if (conn.itemId != stop.in_gate.connId && !conn.info.matchIDs(inConn)) continue; conn.visible = true; conn.tooltip = tooltip.arg(statusArr); - conn.color = color; + conn.color = color; break; } } - //Check also next_seg_conn because sometimes gate out connection - //is used to store track in stop but doesn't mean job will depart. - if(stop.departure == station->time && stop.next_seg_conn) + // Check also next_seg_conn because sometimes gate out connection + // is used to store track in stop but doesn't mean job will depart. + if (stop.departure == station->time && stop.next_seg_conn) { ssplib::TrackConnectionInfo outConn; outConn.gateId = stop.out_gate.gateId; @@ -545,15 +550,15 @@ bool StationSVGHelper::applyStationJobsToPlan(const StationSVGJobStops *station, outConn.trackId = stop.out_gate.trackId; outConn.trackSide = ssplib::Side(stop.out_gate.trackSide); - //Train is departing at requested time, show path - for(ssplib::TrackConnectionItem &conn : plan->trackConnections) + // Train is departing at requested time, show path + for (ssplib::TrackConnectionItem &conn : plan->trackConnections) { - if(conn.itemId != stop.out_gate.connId && !conn.info.matchIDs(outConn)) + if (conn.itemId != stop.out_gate.connId && !conn.info.matchIDs(outConn)) continue; conn.visible = true; conn.tooltip = tooltip.arg(statusDep); - conn.color = color; + conn.color = color; break; } } @@ -568,41 +573,45 @@ bool StationSVGHelper::writeStationXml(QIODevice *dev, ssplib::StationPlan *plan return writer.write(plan); } -bool StationSVGHelper::writeStationXmlFromDB(sqlite3pp::database &db, db_id stationId, QIODevice *dev) +bool StationSVGHelper::writeStationXmlFromDB(sqlite3pp::database &db, db_id stationId, + QIODevice *dev) { ssplib::StationPlan plan; - if(!loadStationFromDB(db, stationId, &plan, false)) + if (!loadStationFromDB(db, stationId, &plan, false)) return false; return writeStationXml(dev, &plan); } -bool StationSVGHelper::importTrackConnFromSVG(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan) +bool StationSVGHelper::importTrackConnFromSVG(sqlite3pp::database &db, db_id stationId, + ssplib::StationPlan *plan) { query q_getTrack(db, "SELECT id FROM station_tracks WHERE station_id=? AND pos=?"); - query q_getGate(db, "SELECT id, out_track_count FROM station_gates WHERE station_id=? AND name=?"); + query q_getGate(db, + "SELECT id, out_track_count FROM station_gates WHERE station_id=? AND name=?"); - command q_newTrackConn(db, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" - " VALUES(NULL,?,?,?,?)"); + command q_newTrackConn( + db, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" + " VALUES(NULL,?,?,?,?)"); QVector existing; for (const auto &conn : qAsConst(plan->trackConnections)) { bool alreadyAdded = false; - for(const auto& info : qAsConst(existing)) + for (const auto &info : qAsConst(existing)) { - if(info.matchNames(conn.info)) + if (info.matchNames(conn.info)) { alreadyAdded = true; break; } } - if(alreadyAdded) - continue; //Skip + if (alreadyAdded) + continue; // Skip - db_id trackId = 0; - db_id gateId = 0; + db_id trackId = 0; + db_id gateId = 0; int gateTrkCnt = 0; q_getTrack.bind(1, stationId); @@ -611,31 +620,32 @@ bool StationSVGHelper::importTrackConnFromSVG(sqlite3pp::database &db, db_id sta trackId = q_getTrack.getRows().get(0); q_getTrack.reset(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - qWarning() << "Error importing connection from SVG, station" - << stationId << "has no track at pos" << conn.info.stationTrackPos; + qWarning() << "Error importing connection from SVG, station" << stationId + << "has no track at pos" << conn.info.stationTrackPos; continue; } q_getGate.bind(1, stationId); q_getGate.bind(2, conn.info.gateLetter); - ret = q_getGate.step(); - gateId = q_getGate.getRows().get(0); + ret = q_getGate.step(); + gateId = q_getGate.getRows().get(0); gateTrkCnt = q_getGate.getRows().get(1); q_getGate.reset(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - qWarning() << "Error importing connection from SVG, station" - << stationId << "has no gate" << conn.info.gateLetter; + qWarning() << "Error importing connection from SVG, station" << stationId + << "has no gate" << conn.info.gateLetter; continue; } - if(conn.info.gateTrackPos >= gateTrkCnt) + if (conn.info.gateTrackPos >= gateTrkCnt) { qWarning() << "Error importing connection from SVG, station" << stationId << "\n" - << "gate" << conn.info.gateLetter << gateId << "has only" << gateTrkCnt << "tracks\n" + << "gate" << conn.info.gateLetter << gateId << "has only" << gateTrkCnt + << "tracks\n" << "Track" << conn.info.stationTrackPos << "requested."; continue; } @@ -647,9 +657,9 @@ bool StationSVGHelper::importTrackConnFromSVG(sqlite3pp::database &db, db_id sta ret = q_newTrackConn.execute(); q_newTrackConn.reset(); - if(ret != SQLITE_OK && ret != SQLITE_CONSTRAINT_UNIQUE) + if (ret != SQLITE_OK && ret != SQLITE_CONSTRAINT_UNIQUE) { - //Failed not because already existing + // Failed not because already existing qWarning() << "Error importing connection from SVG, station" << stationId << "\n" << db.error_msg() << db.extended_error_code(); } @@ -660,11 +670,12 @@ bool StationSVGHelper::importTrackConnFromSVG(sqlite3pp::database &db, db_id sta return true; } -bool StationSVGHelper::importTrackConnFromSVGDev(sqlite3pp::database &db, db_id stationId, QIODevice *dev) +bool StationSVGHelper::importTrackConnFromSVGDev(sqlite3pp::database &db, db_id stationId, + QIODevice *dev) { ssplib::StationPlan plan; ssplib::StreamParser parser(&plan, dev); - if(!parser.parse()) + if (!parser.parse()) return false; return importTrackConnFromSVG(db, stationId, &plan); diff --git a/src/stations/manager/stations/model/stationsvghelper.h b/src/stations/manager/stations/model/stationsvghelper.h index d52aa9c..e7cd22e 100644 --- a/src/stations/manager/stations/model/stationsvghelper.h +++ b/src/stations/manager/stations/model/stationsvghelper.h @@ -43,10 +43,10 @@ struct StationSVGJobStops { struct Gate { - db_id connId = 0; - db_id gateId = 0; - db_id gateTrackNum = 0; - db_id trackId = 0; + db_id connId = 0; + db_id gateId = 0; + db_id gateTrackNum = 0; + db_id trackId = 0; utils::Side trackSide = utils::Side::NSides; }; @@ -64,7 +64,7 @@ struct StationSVGJobStops QTime time; }; -//FIXME: compress SVG on saving and uncompress on loading? +// FIXME: compress SVG on saving and uncompress on loading? class StationSVGHelper { Q_DECLARE_TR_FUNCTIONS(Odt) @@ -73,28 +73,28 @@ public: static bool addImage(sqlite3pp::database &db, db_id stationId, QIODevice *source, QString *errOut = nullptr); - static bool removeImage(sqlite3pp::database &db, db_id stationId, - QString *errOut = nullptr); + static bool removeImage(sqlite3pp::database &db, db_id stationId, QString *errOut = nullptr); static bool saveImage(sqlite3pp::database &db, db_id stationId, QIODevice *dest, QString *errOut = nullptr); - static QIODevice* loadImage(sqlite3pp::database &db, db_id stationId); + static QIODevice *loadImage(sqlite3pp::database &db, db_id stationId); static bool loadStationFromDB(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan, bool onlyAlreadyPresent); - static bool getPrevNextStop(sqlite3pp::database &db, db_id stationId, - bool next, QTime &time); + static bool getPrevNextStop(sqlite3pp::database &db, db_id stationId, bool next, QTime &time); static bool loadStationJobsFromDB(sqlite3pp::database &db, StationSVGJobStops *station); - static bool applyStationJobsToPlan(const StationSVGJobStops *station, ssplib::StationPlan *plan); + static bool applyStationJobsToPlan(const StationSVGJobStops *station, + ssplib::StationPlan *plan); static bool writeStationXml(QIODevice *dev, ssplib::StationPlan *plan); static bool writeStationXmlFromDB(sqlite3pp::database &db, db_id stationId, QIODevice *dev); - static bool importTrackConnFromSVG(sqlite3pp::database &db, db_id stationId, ssplib::StationPlan *plan); + static bool importTrackConnFromSVG(sqlite3pp::database &db, db_id stationId, + ssplib::StationPlan *plan); static bool importTrackConnFromSVGDev(sqlite3pp::database &db, db_id stationId, QIODevice *dev); }; diff --git a/src/stations/manager/stations/model/stationtrackconnectionsmodel.cpp b/src/stations/manager/stations/model/stationtrackconnectionsmodel.cpp index 0feff94..670c0b7 100644 --- a/src/stations/manager/stations/model/stationtrackconnectionsmodel.cpp +++ b/src/stations/manager/stations/model/stationtrackconnectionsmodel.cpp @@ -28,31 +28,29 @@ using namespace sqlite3pp; #include -//Error messages +// Error messages -static constexpr char - errorTrackConnInUseText[] = QT_TRANSLATE_NOOP("StationTrackConnectionsModel", - "This track connection is still referenced.\n" - "Please change remove or change path to all Jobs travelling on this connection."); +static constexpr char errorTrackConnInUseText[] = QT_TRANSLATE_NOOP( + "StationTrackConnectionsModel", + "This track connection is still referenced.\n" + "Please change remove or change path to all Jobs travelling on this connection."); -static constexpr char - errorConnAlreadyExistsText[] = QT_TRANSLATE_NOOP("StationTrackConnectionsModel", - "This track is already connected to this gade track by this side."); +static constexpr char errorConnAlreadyExistsText[] = + QT_TRANSLATE_NOOP("StationTrackConnectionsModel", + "This track is already connected to this gade track by this side."); -static constexpr char - errorInvalidGateId[] = QT_TRANSLATE_NOOP("StationTrackConnectionsModel", - "Please select a valid Gate."); +static constexpr char errorInvalidGateId[] = + QT_TRANSLATE_NOOP("StationTrackConnectionsModel", "Please select a valid Gate."); -static constexpr char - errorGateOnDifferentStation[] = QT_TRANSLATE_NOOP("StationTrackConnectionsModel", - "The selected Gate belongs to a different station."); +static constexpr char errorGateOnDifferentStation[] = QT_TRANSLATE_NOOP( + "StationTrackConnectionsModel", "The selected Gate belongs to a different station."); -static constexpr char - errorGateTrackOutOfBound[] = QT_TRANSLATE_NOOP("StationTrackConnectionsModel", - "Gate track is out of bound.
" - "The selected Gate has only %1 tracks."); +static constexpr char errorGateTrackOutOfBound[] = + QT_TRANSLATE_NOOP("StationTrackConnectionsModel", "Gate track is out of bound.
" + "The selected Gate has only %1 tracks."); -StationTrackConnectionsModel::StationTrackConnectionsModel(sqlite3pp::database &db, QObject *parent) : +StationTrackConnectionsModel::StationTrackConnectionsModel(sqlite3pp::database &db, + QObject *parent) : BaseClass(500, db, parent), m_stationId(0), editable(false) @@ -60,9 +58,10 @@ StationTrackConnectionsModel::StationTrackConnectionsModel(sqlite3pp::database & sortColumn = TrackCol; } -QVariant StationTrackConnectionsModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant StationTrackConnectionsModel::headerData(int section, Qt::Orientation orientation, + int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -83,7 +82,7 @@ QVariant StationTrackConnectionsModel::headerData(int section, Qt::Orientation o } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -97,16 +96,16 @@ QVariant StationTrackConnectionsModel::data(const QModelIndex &idx, int role) co if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const TrackConnItem& item = cache.at(row - cacheFirstRow); + const TrackConnItem &item = cache.at(row - cacheFirstRow); switch (role) { @@ -155,16 +154,17 @@ QVariant StationTrackConnectionsModel::data(const QModelIndex &idx, int role) co bool StationTrackConnectionsModel::setData(const QModelIndex &idx, const QVariant &value, int role) { - if(!editable) + if (!editable) return false; const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid TrackConnItem &item = cache[row - cacheFirstRow]; - QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex first = idx; + QModelIndex last = idx; switch (role) { @@ -176,7 +176,7 @@ bool StationTrackConnectionsModel::setData(const QModelIndex &idx, const QVarian { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setTrackSide(item, val)) + if (!ok || !setTrackSide(item, val)) return false; break; } @@ -184,7 +184,7 @@ bool StationTrackConnectionsModel::setData(const QModelIndex &idx, const QVarian { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setGateTrack(item, val)) + if (!ok || !setGateTrack(item, val)) return false; break; } @@ -204,8 +204,8 @@ Qt::ItemFlags StationTrackConnectionsModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(!editable || idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (!editable || idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet f.setFlag(Qt::ItemIsEditable); return f; @@ -213,35 +213,36 @@ Qt::ItemFlags StationTrackConnectionsModel::flags(const QModelIndex &idx) const void StationTrackConnectionsModel::setSortingColumn(int col) { - if(sortColumn == col || col >= NCols) + if (sortColumn == col || col >= NCols) return; clearCache(); - sortColumn = col; + sortColumn = col; QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, NCols - 1); + QModelIndex last = index(curItemCount - 1, NCols - 1); emit dataChanged(first, last); } -bool StationTrackConnectionsModel::getFieldData(int row, int col, db_id &idOut, QString &nameOut) const +bool StationTrackConnectionsModel::getFieldData(int row, int col, db_id &idOut, + QString &nameOut) const { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - const TrackConnItem& item = cache[row - cacheFirstRow]; + const TrackConnItem &item = cache[row - cacheFirstRow]; switch (col) { case TrackCol: { - idOut = item.trackId; + idOut = item.trackId; nameOut = item.trackName; break; } case GateCol: { - idOut = item.gateId; + idOut = item.gateId; nameOut = item.gateName; break; } @@ -263,11 +264,11 @@ bool StationTrackConnectionsModel::validateData(int row, int col, db_id id, cons bool StationTrackConnectionsModel::setFieldData(int row, int col, db_id id, const QString &name) { - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) return false; - TrackConnItem& item = cache[row - cacheFirstRow]; - bool ret = false; + TrackConnItem &item = cache[row - cacheFirstRow]; + bool ret = false; switch (col) { case TrackCol: @@ -282,7 +283,7 @@ bool StationTrackConnectionsModel::setFieldData(int row, int col, db_id id, cons } } - if(ret) + if (ret) { QModelIndex idx = index(row, col); emit dataChanged(idx, idx); @@ -298,13 +299,15 @@ bool StationTrackConnectionsModel::setStation(db_id stationId) return true; } -bool StationTrackConnectionsModel::addTrackConnection(db_id trackId, utils::Side trackSide, db_id gateId, int gateTrack) +bool StationTrackConnectionsModel::addTrackConnection(db_id trackId, utils::Side trackSide, + db_id gateId, int gateTrack) { - if(!trackId || !gateId || gateTrack < 0) + if (!trackId || !gateId || gateTrack < 0) return false; - command q_newTrackConn(mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" - " VALUES(NULL,?,?,?,?)"); + command q_newTrackConn( + mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" + " VALUES(NULL,?,?,?,?)"); q_newTrackConn.bind(1, trackId); q_newTrackConn.bind(2, int(trackSide)); q_newTrackConn.bind(3, gateId); @@ -312,16 +315,16 @@ bool StationTrackConnectionsModel::addTrackConnection(db_id trackId, utils::Side sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - int ret = q_newTrackConn.execute(); + int ret = q_newTrackConn.execute(); db_id connId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newTrackConn.reset(); - if((ret != SQLITE_OK && ret != SQLITE_DONE) || connId == 0) + if ((ret != SQLITE_OK && ret != SQLITE_DONE) || connId == 0) { - //Error + // Error - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorConnAlreadyExistsText)); } @@ -332,8 +335,8 @@ bool StationTrackConnectionsModel::addTrackConnection(db_id trackId, utils::Side return false; } - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row return true; } @@ -346,11 +349,11 @@ bool StationTrackConnectionsModel::removeTrackConnection(db_id connId) int ret = q.execute(); q.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_FOREIGNKEY || ret == SQLITE_CONSTRAINT_TRIGGER) { - //TODO: show more information to the user, like where it's still referenced + // TODO: show more information to the user, like where it's still referenced emit modelError(tr(errorTrackConnInUseText)); } else @@ -361,42 +364,45 @@ bool StationTrackConnectionsModel::removeTrackConnection(db_id connId) return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count emit trackConnRemoved(connId, 0, 0); return true; } -bool StationTrackConnectionsModel::addTrackToAllGatesOnSide(db_id trackId, utils::Side side, int preferredGateTrack) +bool StationTrackConnectionsModel::addTrackToAllGatesOnSide(db_id trackId, utils::Side side, + int preferredGateTrack) { - if(!trackId) + if (!trackId) return false; - if(preferredGateTrack < 0) + if (preferredGateTrack < 0) preferredGateTrack = 0; - command q_newTrackConn(mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" - " VALUES(NULL,?,?,?,?)"); + command q_newTrackConn( + mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" + " VALUES(NULL,?,?,?,?)"); - //Select all gates on requested side - query q_selectGates(mDb, "SELECT id,out_track_count FROM station_gates WHERE station_id=? AND side=?"); + // Select all gates on requested side + query q_selectGates( + mDb, "SELECT id,out_track_count FROM station_gates WHERE station_id=? AND side=?"); q_selectGates.bind(1, m_stationId); q_selectGates.bind(2, int(side)); - for(auto gate : q_selectGates) + for (auto gate : q_selectGates) { - db_id gateId = gate.get(0); + db_id gateId = gate.get(0); int outTrackCount = gate.get(1); - //If gate track is out of bound chose the highest + // If gate track is out of bound chose the highest int gateTrack = preferredGateTrack; - if(gateTrack >= outTrackCount) + if (gateTrack >= outTrackCount) gateTrack = outTrackCount - 1; - //Ignore return codes - //Some connections may already exist - //Skip them by ignoring failed inserts + // Ignore return codes + // Some connections may already exist + // Skip them by ignoring failed inserts q_newTrackConn.bind(1, trackId); q_newTrackConn.bind(2, int(side)); q_newTrackConn.bind(3, gateId); @@ -405,63 +411,64 @@ bool StationTrackConnectionsModel::addTrackToAllGatesOnSide(db_id trackId, utils q_newTrackConn.reset(); } - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row return true; } bool StationTrackConnectionsModel::addGateToAllTracks(db_id gateId, int gateTrack) { - if(!gateId) + if (!gateId) return false; - if(gateTrack < 0) + if (gateTrack < 0) gateTrack = 0; - command q_newTrackConn(mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" - " VALUES(NULL,?,?,?,?)"); + command q_newTrackConn( + mDb, "INSERT INTO station_gate_connections(id, track_id, track_side, gate_id, gate_track)" + " VALUES(NULL,?,?,?,?)"); - //Select gate side and track count + // Select gate side and track count query q(mDb, "SELECT station_id,out_track_count,side FROM station_gates WHERE id=?"); q.bind(1, gateId); int ret = q.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - //Invalid Id + // Invalid Id emit modelError(tr(errorInvalidGateId)); return false; } db_id gateStationId = q.getRows().get(0); - if(gateStationId != m_stationId) + if (gateStationId != m_stationId) { - //Gate belongs to a different station. + // Gate belongs to a different station. emit modelError(tr(errorGateOnDifferentStation)); return false; } - int outTrackCount = q.getRows().get(1); + int outTrackCount = q.getRows().get(1); utils::Side trackSide = utils::Side(q.getRows().get(2)); - if(gateTrack >= outTrackCount) + if (gateTrack >= outTrackCount) { - //Gate track out of bound + // Gate track out of bound emit modelError(tr(errorGateTrackOutOfBound).arg(outTrackCount)); return false; } - //Select all tracks + // Select all tracks q.prepare("SELECT id FROM station_tracks WHERE station_id=?"); q.bind(1, m_stationId); - for(auto track : q) + for (auto track : q) { db_id trackId = track.get(0); - //Ignore return codes - //Some connections may already exist - //Skip them by ignoring failed inserts + // Ignore return codes + // Some connections may already exist + // Skip them by ignoring failed inserts q_newTrackConn.bind(1, trackId); q_newTrackConn.bind(2, int(trackSide)); q_newTrackConn.bind(3, gateId); @@ -470,15 +477,15 @@ bool StationTrackConnectionsModel::addGateToAllTracks(db_id gateId, int gateTrac q_newTrackConn.reset(); } - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row return true; } qint64 StationTrackConnectionsModel::recalcTotalItemCount() { - //TODO: consider filters + // TODO: consider filters query q(mDb, "SELECT COUNT(1) FROM station_gate_connections c" " JOIN station_gates g ON g.id=c.gate_id WHERE g.station_id=?"); q.bind(1, m_stationId); @@ -487,27 +494,29 @@ qint64 StationTrackConnectionsModel::recalcTotalItemCount() return count; } -void StationTrackConnectionsModel::internalFetch(int first, int sortCol, int valRow, const QVariant &val) +void StationTrackConnectionsModel::internalFetch(int first, int sortCol, int valRow, + const QVariant &val) { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT c.id, c.track_id, c.track_side, t.name," - "c.gate_id, g.name, c.gate_track FROM station_gate_connections c" - " JOIN station_tracks t ON t.id=c.track_id" - " JOIN station_gates g ON g.id=c.gate_id"; + QByteArray sql = "SELECT c.id, c.track_id, c.track_side, t.name," + "c.gate_id, g.name, c.gate_track FROM station_gate_connections c" + " JOIN station_tracks t ON t.id=c.track_id" + " JOIN station_gates g ON g.id=c.gate_id"; switch (sortCol) { case TrackCol: @@ -538,16 +547,16 @@ void StationTrackConnectionsModel::internalFetch(int first, int sortCol, int val sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); q.bind(4, m_stationId); @@ -566,46 +575,47 @@ void StationTrackConnectionsModel::internalFetch(int first, int sortCol, int val QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); - int i = reverse ? BatchSize - 1 : 0; + int i = reverse ? BatchSize - 1 : 0; const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; + auto r = *it; TrackConnItem &item = vec[i]; - item.connId = r.get(0); - item.trackId = r.get(1); - item.trackSide = utils::Side(r.get(2)); - item.trackName = r.get(3); - item.gateId = r.get(4); - item.gateName = r.get(5); - item.gateTrack = r.get(6); + item.connId = r.get(0); + item.trackId = r.get(1); + item.trackSide = utils::Side(r.get(2)); + item.trackName = r.get(3); + item.gateId = r.get(4); + item.gateName = r.get(5); + item.gateTrack = r.get(6); i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); } -bool StationTrackConnectionsModel::setTrackSide(StationTrackConnectionsModel::TrackConnItem &item, int val) +bool StationTrackConnectionsModel::setTrackSide(StationTrackConnectionsModel::TrackConnItem &item, + int val) { utils::Side side = utils::Side(val); - if(item.trackSide == side) + if (item.trackSide == side) return false; command q(mDb, "UPDATE station_gate_connections SET track_side=? WHERE id=?"); q.bind(1, val); q.bind(2, item.connId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -613,25 +623,26 @@ bool StationTrackConnectionsModel::setTrackSide(StationTrackConnectionsModel::Tr item.trackSide = side; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; return true; } -bool StationTrackConnectionsModel::setGateTrack(StationTrackConnectionsModel::TrackConnItem &item, int track) +bool StationTrackConnectionsModel::setGateTrack(StationTrackConnectionsModel::TrackConnItem &item, + int track) { - if(item.gateTrack == track) + if (item.gateTrack == track) return false; command q(mDb, "UPDATE station_gate_connections SET gate_track=? WHERE id=?"); q.bind(1, track); q.bind(2, item.connId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -639,9 +650,9 @@ bool StationTrackConnectionsModel::setGateTrack(StationTrackConnectionsModel::Tr item.gateTrack = track; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; @@ -649,66 +660,67 @@ bool StationTrackConnectionsModel::setGateTrack(StationTrackConnectionsModel::Tr } bool StationTrackConnectionsModel::setTrack(StationTrackConnectionsModel::TrackConnItem &item, - db_id trackId, const QString& trackName) + db_id trackId, const QString &trackName) { - if(item.trackId == trackId) + if (item.trackId == trackId) return false; command q(mDb, "UPDATE station_gate_connections SET track_id=? WHERE id=?"); - if(trackId) + if (trackId) q.bind(1, trackId); else - q.bind(1); //Bind NULL + q.bind(1); // Bind NULL q.bind(2, item.connId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; } - //Old track is no more connected by this connection + // Old track is no more connected by this connection emit trackConnRemoved(item.connId, item.trackId, item.gateId); - item.trackId = trackId; + item.trackId = trackId; item.trackName = trackName; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; return true; } -bool StationTrackConnectionsModel::setGate(StationTrackConnectionsModel::TrackConnItem &item, db_id gateId, const QString &gateName) +bool StationTrackConnectionsModel::setGate(StationTrackConnectionsModel::TrackConnItem &item, + db_id gateId, const QString &gateName) { - if(item.gateId == gateId) + if (item.gateId == gateId) return false; command q(mDb, "UPDATE station_gate_connections SET gate_id=? WHERE id=?"); - if(gateId) + if (gateId) q.bind(1, gateId); else - q.bind(1); //Bind NULL + q.bind(1); // Bind NULL q.bind(2, item.connId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; } - //Old gate is no more connected by this connection + // Old gate is no more connected by this connection emit trackConnRemoved(item.connId, item.trackId, item.gateId); - item.gateId = gateId; + item.gateId = gateId; item.gateName = gateName; - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; diff --git a/src/stations/manager/stations/model/stationtrackconnectionsmodel.h b/src/stations/manager/stations/model/stationtrackconnectionsmodel.h index ec417fd..3a88b28 100644 --- a/src/stations/manager/stations/model/stationtrackconnectionsmodel.h +++ b/src/stations/manager/stations/model/stationtrackconnectionsmodel.h @@ -36,16 +36,20 @@ struct StationTrackConnectionsModelItem utils::Side trackSide; }; -class StationTrackConnectionsModel : public IPagedItemModelImpl, - public IFKField +class StationTrackConnectionsModel + : public IPagedItemModelImpl, + public IFKField { Q_OBJECT public: + enum + { + BatchSize = 100 + }; - enum { BatchSize = 100 }; - - enum Columns{ + enum Columns + { TrackCol = 0, TrackSideCol, GateCol, @@ -54,21 +58,22 @@ public: }; typedef StationTrackConnectionsModelItem TrackConnItem; - typedef IPagedItemModelImpl BaseClass; + typedef IPagedItemModelImpl + BaseClass; StationTrackConnectionsModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // Editable: - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &idx, const QVariant &value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; // IPagedItemModel @@ -77,17 +82,19 @@ public: // IFKField - virtual bool getFieldData(int row, int col, db_id &idOut, QString& nameOut) const override; - virtual bool validateData(int row, int col, db_id id, const QString& name) override; - virtual bool setFieldData(int row, int col, db_id id, const QString& name) override; + virtual bool getFieldData(int row, int col, db_id &idOut, QString &nameOut) const override; + virtual bool validateData(int row, int col, db_id id, const QString &name) override; + virtual bool setFieldData(int row, int col, db_id id, const QString &name) override; // StationTrackConnectionsModel bool setStation(db_id stationId); - inline db_id getStation() const { return m_stationId; } + inline db_id getStation() const + { + return m_stationId; + } - bool addTrackConnection(db_id trackId, utils::Side trackSide, - db_id gateId, int gateTrack); + bool addTrackConnection(db_id trackId, utils::Side trackSide, db_id gateId, int gateTrack); bool removeTrackConnection(db_id connId); bool addTrackToAllGatesOnSide(db_id trackId, utils::Side side, int preferredGateTrack); @@ -97,14 +104,20 @@ public: inline db_id getIdAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const TrackConnItem& item = cache.at(row - cacheFirstRow); + const TrackConnItem &item = cache.at(row - cacheFirstRow); return item.connId; } - inline bool isEditable() const { return editable; } - inline void setEditable(bool val) { editable = val; } + inline bool isEditable() const + { + return editable; + } + inline void setEditable(bool val) + { + editable = val; + } signals: void trackConnRemoved(db_id connId, db_id trackId, db_id gateId); diff --git a/src/stations/manager/stations/model/stationtracksmodel.cpp b/src/stations/manager/stations/model/stationtracksmodel.cpp index 8ba5233..e595f1c 100644 --- a/src/stations/manager/stations/model/stationtracksmodel.cpp +++ b/src/stations/manager/stations/model/stationtracksmodel.cpp @@ -28,21 +28,19 @@ using namespace sqlite3pp; #include -//Error messages +// Error messages -static constexpr char - errorNameAlreadyUsedText[] = QT_TRANSLATE_NOOP("StationTracksModel", - "The track name %1 is already used by another track of this station."); +static constexpr char errorNameAlreadyUsedText[] = + QT_TRANSLATE_NOOP("StationTracksModel", + "The track name %1 is already used by another track of this station."); -static constexpr char - errorLengthGreaterThanTrackText[] = QT_TRANSLATE_NOOP("StationTracksModel", - "Passenger and Freight train length must be less than or equal to track length."); - -static constexpr char - errorTrackInUseText[] = QT_TRANSLATE_NOOP("StationTracksModel", - "This track is still referenced.\n" - "Please remove all references before deleting it."); +static constexpr char errorLengthGreaterThanTrackText[] = QT_TRANSLATE_NOOP( + "StationTracksModel", + "Passenger and Freight train length must be less than or equal to track length."); +static constexpr char errorTrackInUseText[] = + QT_TRANSLATE_NOOP("StationTracksModel", "This track is still referenced.\n" + "Please remove all references before deleting it."); StationTracksModel::StationTracksModel(sqlite3pp::database &db, QObject *parent) : BaseClass(BatchSize, db, parent), @@ -54,7 +52,7 @@ StationTracksModel::StationTracksModel(sqlite3pp::database &db, QObject *parent) QVariant StationTracksModel::headerData(int section, Qt::Orientation orientation, int role) const { - if(orientation == Qt::Horizontal) + if (orientation == Qt::Horizontal) { switch (role) { @@ -105,7 +103,7 @@ QVariant StationTracksModel::headerData(int section, Qt::Orientation orientation } } } - else if(role == Qt::DisplayRole) + else if (role == Qt::DisplayRole) { return section + curPage * ItemsPerPage + 1; } @@ -119,16 +117,16 @@ QVariant StationTracksModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols) return QVariant(); - if(row < cacheFirstRow || row >= cacheFirstRow + cache.size()) + if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) { - //Fetch above or below current cache + // Fetch above or below current cache const_cast(this)->fetchRow(row); - //Temporarily return null + // Temporarily return null return role == Qt::DisplayRole ? QVariant("...") : QVariant(); } - const TrackItem& item = cache.at(row - cacheFirstRow); + const TrackItem &item = cache.at(row - cacheFirstRow); const QString fmt(QStringLiteral("%1 cm")); @@ -186,9 +184,11 @@ QVariant StationTracksModel::data(const QModelIndex &idx, int role) const switch (idx.column()) { case IsElectrifiedCol: - return item.type.testFlag(utils::StationTrackType::Electrified) ? Qt::Checked : Qt::Unchecked; + return item.type.testFlag(utils::StationTrackType::Electrified) ? Qt::Checked + : Qt::Unchecked; case IsThroughCol: - return item.type.testFlag(utils::StationTrackType::Through) ? Qt::Checked : Qt::Unchecked; + return item.type.testFlag(utils::StationTrackType::Through) ? Qt::Checked + : Qt::Unchecked; case PassengerLegthCol: return item.platfLength ? Qt::Checked : Qt::Unchecked; case FreightLengthCol: @@ -198,7 +198,7 @@ QVariant StationTracksModel::data(const QModelIndex &idx, int role) const } case COLOR_ROLE: { - if(idx.column() == ColorCol) + if (idx.column() == ColorCol) return item.color; break; } @@ -209,16 +209,17 @@ QVariant StationTracksModel::data(const QModelIndex &idx, int role) const bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, int role) { - if(!editable) + if (!editable) return false; const int row = idx.row(); - if(!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return false; //Not fetched yet or invalid + if (!idx.isValid() || row >= curItemCount || idx.column() >= NCols || row < cacheFirstRow + || row >= cacheFirstRow + cache.size()) + return false; // Not fetched yet or invalid - TrackItem &item = cache[row - cacheFirstRow]; + TrackItem &item = cache[row - cacheFirstRow]; QModelIndex first = idx; - QModelIndex last = idx; + QModelIndex last = idx; switch (role) { @@ -229,7 +230,7 @@ bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, case NameCol: { QString str = value.toString().simplified(); - if(str.isEmpty() || !setName(item, str)) + if (str.isEmpty() || !setName(item, str)) return false; break; } @@ -237,7 +238,7 @@ bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, { bool ok = false; int val = value.toInt(&ok); - if(!ok || !setLength(item, val, Columns(idx.column()))) + if (!ok || !setLength(item, val, Columns(idx.column()))) return false; break; } @@ -250,32 +251,32 @@ bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, { case IsElectrifiedCol: { - Qt::CheckState cs = value.value(); + Qt::CheckState cs = value.value(); QFlags type = item.type; type.setFlag(utils::StationTrackType::Electrified, cs == Qt::Checked); - if(!setType(item, type)) + if (!setType(item, type)) return false; break; } case IsThroughCol: { - Qt::CheckState cs = value.value(); + Qt::CheckState cs = value.value(); QFlags type = item.type; type.setFlag(utils::StationTrackType::Through, cs == Qt::Checked); - if(!setType(item, type)) + if (!setType(item, type)) return false; break; } case PassengerLegthCol: { Qt::CheckState cs = value.value(); - if(cs == Qt::Unchecked && item.platfLength != 0) + if (cs == Qt::Unchecked && item.platfLength != 0) { return setLength(item, 0, PassengerLegthCol); } - else if(cs == Qt::Checked && item.platfLength == 0) + else if (cs == Qt::Checked && item.platfLength == 0) { return setLength(item, item.trackLegth, PassengerLegthCol); } @@ -284,11 +285,11 @@ bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, case FreightLengthCol: { Qt::CheckState cs = value.value(); - if(cs == Qt::Unchecked && item.freightLength != 0) + if (cs == Qt::Unchecked && item.freightLength != 0) { return setLength(item, 0, FreightLengthCol); } - else if(cs == Qt::Checked && item.freightLength == 0) + else if (cs == Qt::Checked && item.freightLength == 0) { return setLength(item, item.trackLegth, FreightLengthCol); } @@ -299,12 +300,12 @@ bool StationTracksModel::setData(const QModelIndex &idx, const QVariant &value, } case COLOR_ROLE: { - if(idx.column() != ColorCol) + if (idx.column() != ColorCol) return false; - bool ok = false; + bool ok = false; QRgb val = value.toInt(&ok); - if(!ok || !setColor(item, val)) - break; + if (!ok || !setColor(item, val)) + break; } } @@ -319,25 +320,25 @@ Qt::ItemFlags StationTracksModel::flags(const QModelIndex &idx) const return Qt::NoItemFlags; Qt::ItemFlags f = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemNeverHasChildren; - if(idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) - return f; //Not fetched yet + if (idx.row() < cacheFirstRow || idx.row() >= cacheFirstRow + cache.size()) + return f; // Not fetched yet - if(idx.column() == PassengerLegthCol || idx.column() == FreightLengthCol) + if (idx.column() == PassengerLegthCol || idx.column() == FreightLengthCol) { f.setFlag(Qt::ItemIsUserCheckable); } - if(idx.column() == IsElectrifiedCol || idx.column() == IsThroughCol) + if (idx.column() == IsElectrifiedCol || idx.column() == IsThroughCol) { f.setFlag(Qt::ItemIsUserCheckable); } - else if(editable) + else if (editable) { const TrackItem &item = cache[idx.row() - cacheFirstRow]; - if(idx.column() == PassengerLegthCol && item.platfLength == 0) - return f; //Not editable until ticking the checkbox - if(idx.column() == FreightLengthCol && item.freightLength == 0) - return f; //Not editable until ticking the checkbox + if (idx.column() == PassengerLegthCol && item.platfLength == 0) + return f; // Not editable until ticking the checkbox + if (idx.column() == FreightLengthCol && item.freightLength == 0) + return f; // Not editable until ticking the checkbox f.setFlag(Qt::ItemIsEditable); } @@ -348,7 +349,7 @@ Qt::ItemFlags StationTracksModel::flags(const QModelIndex &idx) const void StationTracksModel::setSortingColumn(int col) { Q_UNUSED(col); - return; //TODO: should enable sorting??? + return; // TODO: should enable sorting??? } bool StationTracksModel::setStation(db_id stationId) @@ -362,20 +363,21 @@ bool StationTracksModel::addTrack(int pos, const QString &name, db_id *outTrackI { constexpr const int defaultTrackLength_cm = 150; - if(name.isEmpty()) + if (name.isEmpty()) return false; query q_getMaxPos(mDb, "SELECT MAX(pos) FROM station_tracks WHERE station_id=?"); q_getMaxPos.bind(1, m_stationId); q_getMaxPos.step(); int maxPos = 0; - if(q_getMaxPos.getRows().column_type(0) != SQLITE_NULL) + if (q_getMaxPos.getRows().column_type(0) != SQLITE_NULL) maxPos = q_getMaxPos.getRows().get(0) + 1; q_getMaxPos.finish(); command q_newTrack(mDb, "INSERT INTO station_tracks" - "(id, station_id, pos, type, track_length_cm, platf_length_cm, freight_length_cm, max_axes, color_rgb, name)" - " VALUES (NULL, ?, ?, 0, ?, 0, 0, 2, NULL, ?)"); + "(id, station_id, pos, type, track_length_cm, platf_length_cm, " + "freight_length_cm, max_axes, color_rgb, name)" + " VALUES (NULL, ?, ?, 0, ?, 0, 0, 2, NULL, ?)"); q_newTrack.bind(1, m_stationId); q_newTrack.bind(2, maxPos); q_newTrack.bind(3, defaultTrackLength_cm); @@ -383,18 +385,18 @@ bool StationTracksModel::addTrack(int pos, const QString &name, db_id *outTrackI sqlite3_mutex *mutex = sqlite3_db_mutex(mDb.db()); sqlite3_mutex_enter(mutex); - int ret = q_newTrack.execute(); + int ret = q_newTrack.execute(); db_id trackId = mDb.last_insert_rowid(); sqlite3_mutex_leave(mutex); q_newTrack.reset(); - if((ret != SQLITE_OK && ret != SQLITE_DONE) || trackId == 0) + if ((ret != SQLITE_OK && ret != SQLITE_DONE) || trackId == 0) { - //Error - if(outTrackId) + // Error + if (outTrackId) *outTrackId = 0; - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(name)); } @@ -405,14 +407,14 @@ bool StationTracksModel::addTrack(int pos, const QString &name, db_id *outTrackI return false; } - if(outTrackId) + if (outTrackId) *outTrackId = trackId; - if(pos >= 0) + if (pos >= 0) moveTrack(trackId, pos); - refreshData(); //Recalc row count - switchToPage(0); //Reset to first page and so it is shown as first row + refreshData(); // Recalc row count + switchToPage(0); // Reset to first page and so it is shown as first row return true; } @@ -425,11 +427,11 @@ bool StationTracksModel::removeTrack(db_id trackId) int ret = q.execute(); q.reset(); - if(ret != SQLITE_OK) + if (ret != SQLITE_OK) { - if(ret == SQLITE_CONSTRAINT_TRIGGER) + if (ret == SQLITE_CONSTRAINT_TRIGGER) { - //TODO: show more information to the user, like where it's still referenced + // TODO: show more information to the user, like where it's still referenced emit modelError(tr(errorTrackInUseText)); } else @@ -440,7 +442,7 @@ bool StationTracksModel::removeTrack(db_id trackId) return false; } - refreshData(); //Recalc row count + refreshData(); // Recalc row count emit trackRemoved(trackId); @@ -450,24 +452,28 @@ bool StationTracksModel::removeTrack(db_id trackId) bool StationTracksModel::moveTrackUpDown(db_id trackId, bool up, bool topOrBottom) { query q(mDb); - if(topOrBottom) + if (topOrBottom) { - if(up) + if (up) { q.prepare("SELECT MIN(pos) FROM station_tracks WHERE station_id=?"); - }else{ + } + else + { q.prepare("SELECT MAX(pos) FROM station_tracks WHERE station_id=?"); } } else { - //Move by one - if(up) + // Move by one + if (up) { q.prepare("SELECT MAX(t1.pos) FROM station_tracks t1" " JOIN station_tracks t ON t.id=?2" " WHERE t1.station_id=?1 AND t.pos>t1.pos"); - }else{ + } + else + { q.prepare("SELECT MIN(t1.pos) FROM station_tracks t1" " JOIN station_tracks t ON t.id=?2" " WHERE t1.station_id=?1 AND t.pos(0); q.finish(); moveTrack(trackId, pos); - //Refresh model + // Refresh model clearCache(); emit dataChanged(index(0, 0), index(curItemCount - 1, NCols - 1)); @@ -494,7 +500,7 @@ bool StationTracksModel::moveTrackUpDown(db_id trackId, bool up, bool topOrBotto qint64 StationTracksModel::recalcTotalItemCount() { - //TODO: consider filters + // TODO: consider filters query q(mDb, "SELECT COUNT(1) FROM station_tracks WHERE station_id=?"); q.bind(1, m_stationId); q.step(); @@ -506,27 +512,28 @@ void StationTracksModel::internalFetch(int first, int sortCol, int valRow, const { query q(mDb); - int offset = first - valRow + curPage * ItemsPerPage; + int offset = first - valRow + curPage * ItemsPerPage; bool reverse = false; - if(valRow > first) + if (valRow > first) { - offset = 0; + offset = 0; reverse = true; } - qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset << "Reverse:" << reverse; + qDebug() << "Fetching:" << first << "ValRow:" << valRow << val << "Offset:" << offset + << "Reverse:" << reverse; const char *whereCol = nullptr; - QByteArray sql = "SELECT id, type, track_length_cm, platf_length_cm, freight_length_cm," - "max_axes, color_rgb, name FROM station_tracks"; + QByteArray sql = "SELECT id, type, track_length_cm, platf_length_cm, freight_length_cm," + "max_axes, color_rgb, name FROM station_tracks"; switch (sortCol) { case PosCol: default: { - whereCol = "pos"; //Order by 1 column, no where clause + whereCol = "pos"; // Order by 1 column, no where clause break; } } @@ -545,16 +552,16 @@ void StationTracksModel::internalFetch(int first, int sortCol, int valRow, const sql += " ORDER BY "; sql += whereCol; - if(reverse) + if (reverse) sql += " DESC"; sql += " LIMIT ?1"; - if(offset) + if (offset) sql += " OFFSET ?2"; q.prepare(sql); q.bind(1, BatchSize); - if(offset) + if (offset) q.bind(2, offset); q.bind(4, m_stationId); @@ -573,25 +580,25 @@ void StationTracksModel::internalFetch(int first, int sortCol, int valRow, const QVector vec(BatchSize); - auto it = q.begin(); - const auto end = q.end(); + auto it = q.begin(); + const auto end = q.end(); const QRgb whiteColor = qRgb(255, 255, 255); - int i = reverse ? BatchSize - 1 : 0; - const int increment = reverse ? -1 : 1; + int i = reverse ? BatchSize - 1 : 0; + const int increment = reverse ? -1 : 1; - for(; it != end; ++it) + for (; it != end; ++it) { - auto r = *it; - TrackItem &item = vec[i]; - item.trackId = r.get(0); - item.type = utils::StationTrackType(r.get(1)); - item.trackLegth = r.get(2); - item.platfLength = r.get(3); + auto r = *it; + TrackItem &item = vec[i]; + item.trackId = r.get(0); + item.type = utils::StationTrackType(r.get(1)); + item.trackLegth = r.get(2); + item.platfLength = r.get(3); item.freightLength = r.get(4); - item.maxAxesCount = r.get(5); - if(r.column_type(6) == SQLITE_NULL) + item.maxAxesCount = r.get(5); + if (r.column_type(6) == SQLITE_NULL) item.color = whiteColor; else item.color = QRgb(r.get(6)); @@ -600,9 +607,9 @@ void StationTracksModel::internalFetch(int first, int sortCol, int valRow, const i += increment; } - if(reverse && i > -1) + if (reverse && i > -1) vec.remove(0, i + 1); - else if(i < BatchSize) + else if (i < BatchSize) vec.remove(i, BatchSize - i); postResult(vec, first); @@ -610,15 +617,15 @@ void StationTracksModel::internalFetch(int first, int sortCol, int valRow, const bool StationTracksModel::setName(StationTracksModel::TrackItem &item, const QString &name) { - //TODO: check non valid characters + // TODO: check non valid characters command q(mDb, "UPDATE station_tracks SET name=? WHERE id=?"); q.bind(1, name); q.bind(2, item.trackId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { - if(ret == SQLITE_CONSTRAINT_UNIQUE) + if (ret == SQLITE_CONSTRAINT_UNIQUE) { emit modelError(tr(errorNameAlreadyUsedText).arg(name)); } @@ -632,11 +639,11 @@ bool StationTracksModel::setName(StationTracksModel::TrackItem &item, const QStr item.name = name; emit trackNameChanged(item.trackId, item.name); - if(sortColumn != PosCol) + if (sortColumn != PosCol) { - //This row has now changed position so we need to invalidate cache - //HACK: we emit dataChanged for this index (that doesn't exist anymore) - //but the view will trigger fetching at same scroll position so it is enough + // This row has now changed position so we need to invalidate cache + // HACK: we emit dataChanged for this index (that doesn't exist anymore) + // but the view will trigger fetching at same scroll position so it is enough cache.clear(); cacheFirstRow = 0; } @@ -644,18 +651,19 @@ bool StationTracksModel::setName(StationTracksModel::TrackItem &item, const QStr return true; } -bool StationTracksModel::setType(StationTracksModel::TrackItem &item, QFlags type) +bool StationTracksModel::setType(StationTracksModel::TrackItem &item, + QFlags type) { - if(item.type == type) + if (item.type == type) return false; - //TODO: check through tracks must be default in at least 1 gate per side + // TODO: check through tracks must be default in at least 1 gate per side command q(mDb, "UPDATE station_tracks SET type=? WHERE id=?"); q.bind(1, type); q.bind(2, item.trackId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -666,35 +674,36 @@ bool StationTracksModel::setType(StationTracksModel::TrackItem &item, QFlags item.trackLegth && column != TrackLengthCol && column != MaxAxesCol) + if (val > item.trackLegth && column != TrackLengthCol && column != MaxAxesCol) { emit modelError(errorLengthGreaterThanTrackText); return false; @@ -720,7 +729,7 @@ bool StationTracksModel::setLength(StationTracksModel::TrackItem &item, int val, q.bind(1, val); q.bind(2, item.trackId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -733,19 +742,19 @@ bool StationTracksModel::setLength(StationTracksModel::TrackItem &item, int val, bool StationTracksModel::setColor(StationTracksModel::TrackItem &item, QRgb color) { - if(item.color == color) + if (item.color == color) return false; const QRgb whiteColor = qRgb(255, 255, 255); command q(mDb, "UPDATE station_tracks SET color_rgb=? WHERE id=?"); - if(color == whiteColor) - q.bind(1); //Bind NULL + if (color == whiteColor) + q.bind(1); // Bind NULL else q.bind(1, int(color)); q.bind(2, item.trackId); int ret = q.step(); - if(ret != SQLITE_OK && ret != SQLITE_DONE) + if (ret != SQLITE_OK && ret != SQLITE_DONE) { emit modelError(tr("Error: %1").arg(mDb.error_msg())); return false; @@ -761,36 +770,37 @@ void StationTracksModel::moveTrack(db_id trackId, int pos) command q_setPos(mDb, "UPDATE station_tracks SET pos=? WHERE id=?"); query q(mDb); - //Get max pos + // Get max pos q.prepare("SELECT MAX(pos) FROM station_tracks WHERE station_id=?"); q.bind(1, m_stationId); q.step(); const int max = q.getRows().get(0); - //Save old pos + // Save old pos q.prepare("SELECT pos FROM station_tracks WHERE id=?"); q.bind(1, trackId); q.step(); const int oldPos = q.getRows().get(0); - //Move our track to max+1 + // Move our track to max+1 q_setPos.bind(1, max + 1); q_setPos.bind(2, trackId); q_setPos.execute(); q_setPos.reset(); - if(pos > oldPos) + if (pos > oldPos) { - //Moving down (towards higher pos number) + // Moving down (towards higher pos number) int otherPos = oldPos; - //Shift tracks by one (caution: there is UNIQUE constraint on pos) - q.prepare("SELECT id FROM station_tracks WHERE station_id=? AND pos BETWEEN ? AND ? ORDER BY pos ASC"); + // Shift tracks by one (caution: there is UNIQUE constraint on pos) + q.prepare("SELECT id FROM station_tracks WHERE station_id=? AND pos BETWEEN ? AND ? ORDER " + "BY pos ASC"); q.bind(1, m_stationId); q.bind(2, oldPos); q.bind(3, pos); - for(auto track : q) + for (auto track : q) { db_id otherId = track.get(0); q_setPos.bind(1, otherPos); @@ -800,18 +810,19 @@ void StationTracksModel::moveTrack(db_id trackId, int pos) otherPos++; } } - else if(oldPos > pos) + else if (oldPos > pos) { - //Moving up (towards lower pos number) + // Moving up (towards lower pos number) int otherPos = oldPos; - //Shift tracks by one (caution: there is UNIQUE constraint on pos) - q.prepare("SELECT id FROM station_tracks WHERE station_id=? AND pos BETWEEN ? AND ? ORDER BY pos DESC"); + // Shift tracks by one (caution: there is UNIQUE constraint on pos) + q.prepare("SELECT id FROM station_tracks WHERE station_id=? AND pos BETWEEN ? AND ? ORDER " + "BY pos DESC"); q.bind(1, m_stationId); q.bind(2, pos); q.bind(3, oldPos); - for(auto track : q) + for (auto track : q) { db_id otherId = track.get(0); q_setPos.bind(1, otherPos); @@ -822,7 +833,7 @@ void StationTracksModel::moveTrack(db_id trackId, int pos) } } - //Move our track to pos + // Move our track to pos q_setPos.bind(1, pos); q_setPos.bind(2, trackId); q_setPos.execute(); diff --git a/src/stations/manager/stations/model/stationtracksmodel.h b/src/stations/manager/stations/model/stationtracksmodel.h index 6f59c9e..0a43a3c 100644 --- a/src/stations/manager/stations/model/stationtracksmodel.h +++ b/src/stations/manager/stations/model/stationtracksmodel.h @@ -45,10 +45,14 @@ class StationTracksModel : public IPagedItemModelImpl= cacheFirstRow + cache.size()) - return 0; //Invalid + return 0; // Invalid - const TrackItem& item = cache.at(row - cacheFirstRow); + const TrackItem &item = cache.at(row - cacheFirstRow); return item.trackId; } inline QString getNameAtRow(int row) const { if (row < cacheFirstRow || row >= cacheFirstRow + cache.size()) - return QChar(); //Invalid + return QChar(); // Invalid - const TrackItem& item = cache.at(row - cacheFirstRow); + const TrackItem &item = cache.at(row - cacheFirstRow); return item.name; } - inline bool isEditable() const { return editable; } - inline void setEditable(bool val) { editable = val; } + inline bool isEditable() const + { + return editable; + } + inline void setEditable(bool val) + { + editable = val; + } inline bool hasAtLeastOneTrack() { - refreshData(); //Recalc count + refreshData(); // Recalc count return getTotalItemsCount() > 0; } signals: - void trackNameChanged(db_id trackId, const QString& name); + void trackNameChanged(db_id trackId, const QString &name); void trackRemoved(db_id trackId); protected: diff --git a/src/stations/manager/stationsmanager.cpp b/src/stations/manager/stationsmanager.cpp index 06a876d..877522c 100644 --- a/src/stations/manager/stationsmanager.cpp +++ b/src/stations/manager/stationsmanager.cpp @@ -86,9 +86,9 @@ StationsManager::~StationsManager() { delete ui; - for(int i = 0; i < NTabs; i++) + for (int i = 0; i < NTabs; i++) { - if(clearModelTimers[i] > 0) + if (clearModelTimers[i] > 0) { killTimer(clearModelTimers[i]); clearModelTimers[i] = 0; @@ -99,7 +99,7 @@ StationsManager::~StationsManager() void StationsManager::setup_StationPage() { QVBoxLayout *vboxLayout = new QVBoxLayout(ui->stationsTab); - stationToolBar = new QToolBar(ui->stationsTab); + stationToolBar = new QToolBar(ui->stationsTab); vboxLayout->addWidget(stationToolBar); stationView = new QTableView(ui->stationsTab); @@ -116,22 +116,24 @@ void StationsManager::setup_StationPage() vboxLayout->addWidget(ps); ps->setModel(stationsModel); - //Station Type Delegate + // Station Type Delegate QStringList types; types.reserve(int(utils::StationType::NTypes)); - for(int i = 0; i < int(utils::StationType::NTypes); i++) + for (int i = 0; i < int(utils::StationType::NTypes); i++) types.append(utils::StationUtils::name(utils::StationType(i))); - stationView->setItemDelegateForColumn(StationsModel::TypeCol, new ComboDelegate(types, Qt::EditRole, this)); + stationView->setItemDelegateForColumn(StationsModel::TypeCol, + new ComboDelegate(types, Qt::EditRole, this)); - act_addSt = stationToolBar->addAction(tr("Add"), this, &StationsManager::onNewStation); - act_remSt = stationToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveStation); + act_addSt = stationToolBar->addAction(tr("Add"), this, &StationsManager::onNewStation); + act_remSt = stationToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveStation); act_editSt = stationToolBar->addAction(tr("Edit"), this, &StationsManager::onEditStation); stationToolBar->addSeparator(); act_stJobs = stationToolBar->addAction(tr("Jobs"), this, &StationsManager::showStJobViewer); - act_stSVG = stationToolBar->addAction(tr("SVG Plan"), this, &StationsManager::showStSVGPlan); + act_stSVG = stationToolBar->addAction(tr("SVG Plan"), this, &StationsManager::showStSVGPlan); act_freeRs = stationToolBar->addAction(tr("Free RS"), this, &StationsManager::onShowFreeRS); stationToolBar->addSeparator(); - QAction *act_ImportSt = stationToolBar->addAction(tr("Import"), this, &StationsManager::onImportStations); + QAction *act_ImportSt = + stationToolBar->addAction(tr("Import"), this, &StationsManager::onImportStations); act_addSt->setToolTip(tr("Create new Station")); act_remSt->setToolTip(tr("Remove selected Station")); @@ -141,16 +143,16 @@ void StationsManager::setup_StationPage() act_freeRs->setToolTip(tr("Show free Rollingstock items in selected Station")); act_ImportSt->setToolTip(tr("Import Stations")); - connect(stationView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &StationsManager::onStationSelectionChanged); - connect(stationsModel, &QAbstractItemModel::modelReset, - this, &StationsManager::onStationSelectionChanged); + connect(stationView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &StationsManager::onStationSelectionChanged); + connect(stationsModel, &QAbstractItemModel::modelReset, this, + &StationsManager::onStationSelectionChanged); } void StationsManager::setup_SegmentPage() { QVBoxLayout *vboxLayout = new QVBoxLayout(ui->segmentsTab); - segmentsToolBar = new QToolBar; + segmentsToolBar = new QToolBar; vboxLayout->addWidget(segmentsToolBar); segmentsView = new QTableView; @@ -167,27 +169,29 @@ void StationsManager::setup_SegmentPage() vboxLayout->addWidget(ps); ps->setModel(segmentsModel); - QAction *act_addSeg = segmentsToolBar->addAction(tr("Add"), this, &StationsManager::onNewSegment); - act_remSeg = segmentsToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveSegment); + QAction *act_addSeg = + segmentsToolBar->addAction(tr("Add"), this, &StationsManager::onNewSegment); + act_remSeg = segmentsToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveSegment); act_editSeg = segmentsToolBar->addAction(tr("Edit"), this, &StationsManager::onEditSegment); segmentsToolBar->addSeparator(); - QAction *act_splitSeg = segmentsToolBar->addAction(tr("Split"), this, &StationsManager::onSplitSegment); + QAction *act_splitSeg = + segmentsToolBar->addAction(tr("Split"), this, &StationsManager::onSplitSegment); act_addSeg->setToolTip(tr("Create new Railway Segment")); act_remSeg->setToolTip(tr("Delete selected Railway Segment")); act_editSeg->setToolTip(tr("Edit selected Railway Segment")); act_splitSeg->setToolTip(tr("Split Railway Segment in 2 parts")); - connect(segmentsView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &StationsManager::onSegmentSelectionChanged); - connect(segmentsModel, &QAbstractItemModel::modelReset, - this, &StationsManager::onSegmentSelectionChanged); + connect(segmentsView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &StationsManager::onSegmentSelectionChanged); + connect(segmentsModel, &QAbstractItemModel::modelReset, this, + &StationsManager::onSegmentSelectionChanged); } void StationsManager::setup_LinePage() { QVBoxLayout *vboxLayout = new QVBoxLayout(ui->linesTab); - linesToolBar = new QToolBar(ui->linesTab); + linesToolBar = new QToolBar(ui->linesTab); vboxLayout->addWidget(linesToolBar); linesView = new QTableView(ui->linesTab); @@ -205,25 +209,25 @@ void StationsManager::setup_LinePage() ps->setModel(linesModel); QAction *act_addLine = linesToolBar->addAction(tr("Add"), this, &StationsManager::onNewLine); - act_remLine = linesToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveLine); + act_remLine = linesToolBar->addAction(tr("Remove"), this, &StationsManager::onRemoveLine); act_editLine = linesToolBar->addAction(tr("Edit"), this, &StationsManager::onEditLine); act_addLine->setToolTip(tr("Create new Railway Line")); act_remLine->setToolTip(tr("Delete selected Railway Line")); act_editLine->setToolTip(tr("Edit selected Railway Line")); - connect(linesView->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &StationsManager::onLineSelectionChanged); - connect(linesModel, &QAbstractItemModel::modelReset, - this, &StationsManager::onLineSelectionChanged); + connect(linesView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &StationsManager::onLineSelectionChanged); + connect(linesModel, &QAbstractItemModel::modelReset, this, + &StationsManager::onLineSelectionChanged); } void StationsManager::showEvent(QShowEvent *e) { - if(!windowConnected) + if (!windowConnected) { QWindow *w = windowHandle(); - if(w) + if (w) { windowConnected = true; connect(w, &QWindow::visibilityChanged, this, &StationsManager::visibilityChanged); @@ -235,21 +239,21 @@ void StationsManager::showEvent(QShowEvent *e) void StationsManager::timerEvent(QTimerEvent *e) { - if(e->timerId() == clearModelTimers[StationsTab]) + if (e->timerId() == clearModelTimers[StationsTab]) { stationsModel->clearCache(); killTimer(e->timerId()); clearModelTimers[StationsTab] = ModelCleared; return; } - else if(e->timerId() == clearModelTimers[RailwaySegmentsTab]) + else if (e->timerId() == clearModelTimers[RailwaySegmentsTab]) { segmentsModel->clearCache(); killTimer(e->timerId()); clearModelTimers[RailwaySegmentsTab] = ModelCleared; return; } - else if(e->timerId() == clearModelTimers[LinesTab]) + else if (e->timerId() == clearModelTimers[LinesTab]) { linesModel->clearCache(); killTimer(e->timerId()); @@ -262,15 +266,17 @@ void StationsManager::timerEvent(QTimerEvent *e) void StationsManager::visibilityChanged(int v) { - if(v == QWindow::Minimized || v == QWindow::Hidden) + if (v == QWindow::Minimized || v == QWindow::Hidden) { - //If the window is minimized start timer to clear model cache of current tab - //The other tabs already have been cleared or are waiting with their timers - if(clearModelTimers[oldCurrentTab] == ModelLoaded) + // If the window is minimized start timer to clear model cache of current tab + // The other tabs already have been cleared or are waiting with their timers + if (clearModelTimers[oldCurrentTab] == ModelLoaded) { clearModelTimers[oldCurrentTab] = startTimer(ClearModelTimeout, Qt::VeryCoarseTimer); } - }else{ + } + else + { updateModels(); } } @@ -279,14 +285,14 @@ void StationsManager::updateModels() { int curTab = ui->tabWidget->currentIndex(); - if(clearModelTimers[curTab] > 0) + if (clearModelTimers[curTab] > 0) { - //This page was already cached, stop it from clearing + // This page was already cached, stop it from clearing killTimer(clearModelTimers[curTab]); } - else if(clearModelTimers[curTab] == ModelCleared) + else if (clearModelTimers[curTab] == ModelCleared) { - //This page wasn't already cached + // This page wasn't already cached switch (curTab) { case StationsTab: @@ -308,8 +314,9 @@ void StationsManager::updateModels() } clearModelTimers[curTab] = ModelLoaded; - //Now start timer to clear old current page if not already done - if(oldCurrentTab != curTab && clearModelTimers[oldCurrentTab] == ModelLoaded) //Wait 10 seconds and then clear cache + // Now start timer to clear old current page if not already done + if (oldCurrentTab != curTab + && clearModelTimers[oldCurrentTab] == ModelLoaded) // Wait 10 seconds and then clear cache { clearModelTimers[oldCurrentTab] = startTimer(ClearModelTimeout, Qt::VeryCoarseTimer); } @@ -321,20 +328,20 @@ void StationsManager::onRemoveStation() { DEBUG_ENTRY; - if(!stationView->selectionModel()->hasSelection()) + if (!stationView->selectionModel()->hasSelection()) return; QModelIndex idx = stationView->currentIndex(); - //Ask confirmation + // Ask confirmation int ret = QMessageBox::question(this, tr("Remove Station?"), tr("Are you sure you want to remove station %1?") - .arg(stationsModel->getNameAtRow(idx.row()))); - if(ret != QMessageBox::Yes) + .arg(stationsModel->getNameAtRow(idx.row()))); + if (ret != QMessageBox::Yes) return; db_id stId = stationsModel->getIdAtRow(idx.row()); - if(!stId) + if (!stId) return; stationsModel->removeStation(stId); @@ -349,35 +356,35 @@ void StationsManager::onNewStation() dlg->setLabelText(tr("Please choose a name for the new station.")); dlg->setTextValue(QString()); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Station name cannot be empty.")); - continue; //Second chance + continue; // Second chance } - if(stationsModel->addStation(name)) + if (stationsModel->addStation(name)) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); - //TODO - // QModelIndex idx = stationsModel->index(row, 0); - // stationView->setCurrentIndex(idx); - // stationView->scrollTo(idx); - // stationView->edit(idx); + // TODO + // QModelIndex idx = stationsModel->index(row, 0); + // stationView->setCurrentIndex(idx); + // stationView->scrollTo(idx); + // stationView->edit(idx); } -void StationsManager::onModelError(const QString& msg) +void StationsManager::onModelError(const QString &msg) { QMessageBox::warning(this, tr("Station Error"), msg); } @@ -385,12 +392,12 @@ void StationsManager::onModelError(const QString& msg) void StationsManager::onEditStation() { DEBUG_ENTRY; - if(!stationView->selectionModel()->hasSelection()) + if (!stationView->selectionModel()->hasSelection()) return; QModelIndex idx = stationView->currentIndex(); - db_id stId = stationsModel->getIdAtRow(idx.row()); - if(!stId) + db_id stId = stationsModel->getIdAtRow(idx.row()); + if (!stId) return; OwningQPointer dlg(new StationEditDialog(Session->m_Db, this)); @@ -398,27 +405,27 @@ void StationsManager::onEditStation() dlg->setStationExternalEditingEnabled(true); dlg->setStation(stId); int ret = dlg->exec(); - if(!dlg || ret != QDialog::Accepted) + if (!dlg || ret != QDialog::Accepted) return; - //Refresh stations model + // Refresh stations model stationsModel->refreshData(true); - //FIXME: check if actually changed + // FIXME: check if actually changed emit Session->stationNameChanged(stId); emit Session->stationTrackPlanChanged({stId}); emit Session->stationJobsPlanChanged({stId}); - //Refresh segments + // Refresh segments int &segmentsTimer = clearModelTimers[RailwaySegmentsTab]; - if(segmentsTimer != ModelCleared) + if (segmentsTimer != ModelCleared) { - //If model was loaded clear cache and refresh row count + // If model was loaded clear cache and refresh row count segmentsModel->refreshData(true); - if(segmentsTimer != ModelLoaded) + if (segmentsTimer != ModelLoaded) { - //Mark as cleared + // Mark as cleared killTimer(segmentsTimer); segmentsTimer = ModelCleared; } @@ -428,12 +435,12 @@ void StationsManager::onEditStation() void StationsManager::showStJobViewer() { DEBUG_ENTRY; - if(!stationView->selectionModel()->hasSelection()) + if (!stationView->selectionModel()->hasSelection()) return; QModelIndex idx = stationView->currentIndex(); - db_id stId = stationsModel->getIdAtRow(idx.row()); - if(!stId) + db_id stId = stationsModel->getIdAtRow(idx.row()); + if (!stId) return; Session->getViewManager()->requestStJobViewer(stId); } @@ -441,12 +448,12 @@ void StationsManager::showStJobViewer() void StationsManager::showStSVGPlan() { DEBUG_ENTRY; - if(!stationView->selectionModel()->hasSelection()) + if (!stationView->selectionModel()->hasSelection()) return; QModelIndex idx = stationView->currentIndex(); - db_id stId = stationsModel->getIdAtRow(idx.row()); - if(!stId) + db_id stId = stationsModel->getIdAtRow(idx.row()); + if (!stId) return; Session->getViewManager()->requestStSVGPlan(stId); } @@ -454,97 +461,99 @@ void StationsManager::showStSVGPlan() void StationsManager::onShowFreeRS() { DEBUG_COLOR_ENTRY(SHELL_BLUE); - if(!stationView->selectionModel()->hasSelection()) + if (!stationView->selectionModel()->hasSelection()) return; QModelIndex idx = stationView->currentIndex(); - db_id stId = stationsModel->getIdAtRow(idx.row()); - if(!stId) + db_id stId = stationsModel->getIdAtRow(idx.row()); + if (!stId) return; Session->getViewManager()->requestStFreeRSViewer(stId); } void StationsManager::onRemoveSegment() { - if(!segmentsView->selectionModel()->hasSelection()) + if (!segmentsView->selectionModel()->hasSelection()) return; QModelIndex idx = segmentsView->currentIndex(); - //Ask confirmation + // Ask confirmation int ret = QMessageBox::question(this, tr("Remove Segment?"), tr("Are you sure you want to remove segment %1?") - .arg(segmentsModel->getNameAtRow(idx.row()))); - if(ret != QMessageBox::Yes) + .arg(segmentsModel->getNameAtRow(idx.row()))); + if (ret != QMessageBox::Yes) return; db_id segmentId = segmentsModel->getIdAtRow(idx.row()); - if(!segmentId) + if (!segmentId) return; QString errMsg; RailwaySegmentHelper helper(Session->m_Db); - if(!helper.removeSegment(segmentId, &errMsg)) + if (!helper.removeSegment(segmentId, &errMsg)) { onModelError(errMsg); return; } - //Re-calc row count + // Re-calc row count segmentsModel->refreshData(); } void StationsManager::onNewSegment() { - OwningQPointer dlg = new EditRailwaySegmentDlg(Session->m_Db, nullptr, this); + OwningQPointer dlg = + new EditRailwaySegmentDlg(Session->m_Db, nullptr, this); dlg->setSegment(0, EditRailwaySegmentDlg::DoNotLock, EditRailwaySegmentDlg::DoNotLock); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - //Re-calc row count + // Re-calc row count segmentsModel->refreshData(); } void StationsManager::onEditSegment() { - if(!segmentsView->selectionModel()->hasSelection()) + if (!segmentsView->selectionModel()->hasSelection()) return; QModelIndex idx = segmentsView->currentIndex(); db_id segmentId = segmentsModel->getIdAtRow(idx.row()); - if(!segmentId) + if (!segmentId) return; - OwningQPointer dlg = new EditRailwaySegmentDlg(Session->m_Db, nullptr, this); + OwningQPointer dlg = + new EditRailwaySegmentDlg(Session->m_Db, nullptr, this); dlg->setSegment(segmentId, EditRailwaySegmentDlg::DoNotLock, EditRailwaySegmentDlg::DoNotLock); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - //FIXME: check if actually changed + // FIXME: check if actually changed emit Session->segmentNameChanged(segmentId); emit Session->segmentStationsChanged(segmentId); - //Refresh fields + // Refresh fields segmentsModel->refreshData(true); } void StationsManager::onSplitSegment() { OwningQPointer dlg = new SplitRailwaySegmentDlg(Session->m_Db, this); - int ret = dlg->exec(); + int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - //FIXME: get segments ID - //emit Session->segmentNameChanged(segmentId); - //emit Session->segmentStationsChanged(segmentId); + // FIXME: get segments ID + // emit Session->segmentNameChanged(segmentId); + // emit Session->segmentStationsChanged(segmentId); - //Refresh fields + // Refresh fields segmentsModel->refreshData(true); } @@ -557,51 +566,51 @@ void StationsManager::onNewLine() dlg->setLabelText(tr("Please choose a name for the new railway line.")); dlg->setTextValue(QString()); - do{ + do + { int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) { - break; //User canceled + break; // User canceled } const QString name = dlg->textValue().simplified(); - if(name.isEmpty()) + if (name.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("Line name cannot be empty.")); - continue; //Second chance + continue; // Second chance } - if(linesModel->addLine(name)) + if (linesModel->addLine(name)) { - break; //Done! + break; // Done! } - } - while (true); + } while (true); - //TODO - // QModelIndex idx = linesModel->index(row, 0); - // linesView->setCurrentIndex(idx); - // linesView->scrollTo(idx); - // linesView->edit(idx); + // TODO + // QModelIndex idx = linesModel->index(row, 0); + // linesView->setCurrentIndex(idx); + // linesView->scrollTo(idx); + // linesView->edit(idx); } void StationsManager::onRemoveLine() { DEBUG_ENTRY; - if(!linesView->selectionModel()->hasSelection()) + if (!linesView->selectionModel()->hasSelection()) return; QModelIndex idx = linesView->currentIndex(); - //Ask confirmation + // Ask confirmation int ret = QMessageBox::question(this, tr("Remove Line?"), tr("Are you sure you want to remove line %1?") - .arg(linesModel->getNameAtRow(idx.row()))); - if(ret != QMessageBox::Yes) + .arg(linesModel->getNameAtRow(idx.row()))); + if (ret != QMessageBox::Yes) return; db_id lineId = linesModel->getIdAtRow(idx.row()); - if(!lineId) + if (!lineId) return; linesModel->removeLine(lineId); @@ -610,26 +619,26 @@ void StationsManager::onRemoveLine() void StationsManager::onEditLine() { DEBUG_ENTRY; - if(!linesView->selectionModel()->hasSelection()) + if (!linesView->selectionModel()->hasSelection()) return; - int row = linesView->currentIndex().row(); + int row = linesView->currentIndex().row(); db_id lineId = linesModel->getIdAtRow(row); - if(!lineId) + if (!lineId) return; OwningQPointer dlg(new EditLineDlg(Session->m_Db, this)); dlg->setLineId(lineId); int ret = dlg->exec(); - if(ret != QDialog::Accepted || !dlg) + if (ret != QDialog::Accepted || !dlg) return; - //FIXME: check if actually changed + // FIXME: check if actually changed emit Session->lineNameChanged(lineId); emit Session->lineSegmentsChanged(lineId); - //Refresh fields + // Refresh fields linesModel->refreshData(true); } @@ -667,7 +676,7 @@ void StationsManager::onImportStations() void StationsManager::setReadOnly(bool readOnly) { - if(m_readOnly == readOnly) + if (m_readOnly == readOnly) return; m_readOnly = readOnly; @@ -679,7 +688,7 @@ void StationsManager::setReadOnly(bool readOnly) act_remSt->setDisabled(m_readOnly); act_editSt->setDisabled(m_readOnly); - if(m_readOnly) + if (m_readOnly) { stationView->setEditTriggers(QTableView::NoEditTriggers); segmentsView->setEditTriggers(QTableView::NoEditTriggers); diff --git a/src/stations/manager/stationsmanager.h b/src/stations/manager/stationsmanager.h index 0fe5ff3..30c6490 100644 --- a/src/stations/manager/stationsmanager.h +++ b/src/stations/manager/stationsmanager.h @@ -25,7 +25,6 @@ #include "utils/types.h" - class QToolBar; class QToolButton; class QTableView; @@ -43,7 +42,6 @@ class StationsManager : public QWidget Q_OBJECT public: - enum Tabs { StationsTab = 0, @@ -55,10 +53,13 @@ public: enum ModelState { ModelCleared = 0, - ModelLoaded = -1 + ModelLoaded = -1 }; - enum { ClearModelTimeout = 5000 }; // 5 seconds + enum + { + ClearModelTimeout = 5000 + }; // 5 seconds explicit StationsManager(QWidget *parent = nullptr); ~StationsManager() override; diff --git a/src/stations/match_models/linesmatchmodel.cpp b/src/stations/match_models/linesmatchmodel.cpp index 967c68b..35b0bcd 100644 --- a/src/stations/match_models/linesmatchmodel.cpp +++ b/src/stations/match_models/linesmatchmodel.cpp @@ -31,7 +31,7 @@ LinesMatchModel::LinesMatchModel(database &db, bool useTimer, QObject *parent) : LinesMatchModel::~LinesMatchModel() { - if(timerId > 0) + if (timerId > 0) { killTimer(timerId); timerId = 0; @@ -47,11 +47,11 @@ QVariant LinesMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -60,7 +60,7 @@ QVariant LinesMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -74,7 +74,7 @@ QVariant LinesMatchModel::data(const QModelIndex &idx, int role) const void LinesMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.reserve(text.size() + 2); mQuery.append('%'); @@ -87,40 +87,41 @@ void LinesMatchModel::autoSuggest(const QString &text) void LinesMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; - if(!q_getMatches.stmt()) - q_getMatches.prepare("SELECT id,name FROM lines WHERE name LIKE ?1 LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); + if (!q_getMatches.stmt()) + q_getMatches.prepare( + "SELECT id,name FROM lines WHERE name LIKE ?1 LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { items[i].lineId = (*it).get(0); - items[i].name = (*it).get(1); + items[i].name = (*it).get(1); ++it; } size = i; - if(hasEmptyRow) - size++; //Items + Empty, add 1 row + if (hasEmptyRow) + size++; // Items + Empty, add 1 row - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -128,9 +129,9 @@ void LinesMatchModel::refreshData() emit resultsReady(false); - if(timerId < 0) - return; //Do not use timer - if(timerId == 0) + if (timerId < 0) + return; // Do not use timer + if (timerId == 0) timerId = startTimer(3000); timer.start(); } @@ -144,12 +145,12 @@ void LinesMatchModel::clearCache() QString LinesMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM lines WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } @@ -166,10 +167,10 @@ QString LinesMatchModel::getNameAtRow(int row) const void LinesMatchModel::timerEvent(QTimerEvent *e) { - if(timerId > 0 && e->timerId() == timerId) + if (timerId > 0 && e->timerId() == timerId) { - if(timer.isValid() && timer.elapsed() < 3000) - return; //Do another round + if (timer.isValid() && timer.elapsed() < 3000) + return; // Do another round killTimer(timerId); timerId = 0; diff --git a/src/stations/match_models/linesmatchmodel.h b/src/stations/match_models/linesmatchmodel.h index d880c9a..59f3107 100644 --- a/src/stations/match_models/linesmatchmodel.h +++ b/src/stations/match_models/linesmatchmodel.h @@ -40,7 +40,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; void clearCache() override; diff --git a/src/stations/match_models/railwaysegmentmatchmodel.cpp b/src/stations/match_models/railwaysegmentmatchmodel.cpp index 72e53d3..4aa944e 100644 --- a/src/stations/match_models/railwaysegmentmatchmodel.cpp +++ b/src/stations/match_models/railwaysegmentmatchmodel.cpp @@ -31,7 +31,6 @@ RailwaySegmentMatchModel::RailwaySegmentMatchModel(sqlite3pp::database &db, QObj m_toStationId(0), m_excludeSegmentId(0) { - } QVariant RailwaySegmentMatchModel::data(const QModelIndex &idx, int role) const @@ -43,11 +42,11 @@ QVariant RailwaySegmentMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -56,9 +55,9 @@ QVariant RailwaySegmentMatchModel::data(const QModelIndex &idx, int role) const } case Qt::DecorationRole: { - //Draw a small blue square for electified segments - if(!isEmptyRow(idx.row()) && isEllipsesRow(idx.row()) && - items[idx.row()].type.testFlag(utils::RailwaySegmentType::Electrified)) + // Draw a small blue square for electified segments + if (!isEmptyRow(idx.row()) && isEllipsesRow(idx.row()) + && items[idx.row()].type.testFlag(utils::RailwaySegmentType::Electrified)) { return QColor(Qt::blue); } @@ -66,36 +65,37 @@ QVariant RailwaySegmentMatchModel::data(const QModelIndex &idx, int role) const } case Qt::ToolTipRole: { - if(!isEmptyRow(idx.row()) && !isEllipsesRow(idx.row())) + if (!isEmptyRow(idx.row()) && !isEllipsesRow(idx.row())) { QStringList tips; - //Electrification - if(items[idx.row()].type.testFlag(utils::RailwaySegmentType::Electrified)) + // Electrification + if (items[idx.row()].type.testFlag(utils::RailwaySegmentType::Electrified)) tips.append(tr("Electrified")); else tips.append(tr("Non electrified")); - //Direction - if(items[idx.row()].reversed) + // Direction + if (items[idx.row()].reversed) tips.append(tr("Segment is reversed.")); - return tr("Segment %1
%2").arg(items[idx.row()].segmentName, tips.join("
")); + return tr("Segment %1
%2") + .arg(items[idx.row()].segmentName, tips.join("
")); } break; } case Qt::BackgroundRole: { - if(!isEmptyRow(idx.row()) && !isEllipsesRow(idx.row()) && items[idx.row()].reversed) + if (!isEmptyRow(idx.row()) && !isEllipsesRow(idx.row()) && items[idx.row()].reversed) { - //Light cyan background for reversed segments - return QBrush(qRgb(158, 226, 255)); //#9EE2FF + // Light cyan background for reversed segments + return QBrush(qRgb(158, 226, 255)); // #9EE2FF } break; } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -109,7 +109,7 @@ QVariant RailwaySegmentMatchModel::data(const QModelIndex &idx, int role) const void RailwaySegmentMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -123,60 +123,62 @@ void RailwaySegmentMatchModel::autoSuggest(const QString &text) void RailwaySegmentMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); - if(m_fromStationId) + if (m_fromStationId) { q_getMatches.bind(2, m_fromStationId); - if(m_toStationId) + if (m_toStationId) q_getMatches.bind(3, m_toStationId); } - if(m_excludeSegmentId) + if (m_excludeSegmentId) { q_getMatches.bind(4, m_excludeSegmentId); } auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { - auto seg = *it; - items[i].segmentId = seg.get(0); + auto seg = *it; + items[i].segmentId = seg.get(0); items[i].segmentName = seg.get(1); - items[i].type = utils::RailwaySegmentType(seg.get(2)); + items[i].type = utils::RailwaySegmentType(seg.get(2)); - db_id inStationId = seg.get(3); - db_id outStationId = seg.get(4); + db_id inStationId = seg.get(3); + db_id outStationId = seg.get(4); - if(!m_fromStationId || inStationId == m_fromStationId) + if (!m_fromStationId || inStationId == m_fromStationId) { items[i].toStationId = outStationId; - items[i].reversed = false; - }else{ + items[i].reversed = false; + } + else + { items[i].toStationId = inStationId; - items[i].reversed = true; + items[i].reversed = true; } ++it; } - size = i + 1; //Items + Empty + size = i + 1; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -187,12 +189,12 @@ void RailwaySegmentMatchModel::refreshData() QString RailwaySegmentMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM railway_segments WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } @@ -207,31 +209,32 @@ QString RailwaySegmentMatchModel::getNameAtRow(int row) const return items[row].segmentName; } -void RailwaySegmentMatchModel::setFilter(db_id fromStationId, db_id toStationId, db_id excludeSegmentId) +void RailwaySegmentMatchModel::setFilter(db_id fromStationId, db_id toStationId, + db_id excludeSegmentId) { m_fromStationId = fromStationId; - m_toStationId = toStationId; - if(!m_fromStationId) - m_toStationId = 0; //NOTE: don't filter by destination only + m_toStationId = toStationId; + if (!m_fromStationId) + m_toStationId = 0; // NOTE: don't filter by destination only m_excludeSegmentId = excludeSegmentId; - QByteArray sql = "SELECT seg.id, seg.name, seg.type, g1.station_id, g2.station_id" - " FROM railway_segments seg" - " JOIN station_gates g1 ON g1.id=seg.in_gate_id" - " JOIN station_gates g2 ON g2.id=seg.out_gate_id" - " WHERE "; + QByteArray sql = "SELECT seg.id, seg.name, seg.type, g1.station_id, g2.station_id" + " FROM railway_segments seg" + " JOIN station_gates g1 ON g1.id=seg.in_gate_id" + " JOIN station_gates g2 ON g2.id=seg.out_gate_id" + " WHERE "; - if(m_fromStationId) + if (m_fromStationId) { sql += "((g1.station_id=?2"; - if(m_toStationId) + if (m_toStationId) sql += " AND g2.station_id=?3"; sql += ") OR (g2.station_id=?2"; - if(m_toStationId) + if (m_toStationId) sql += " AND g1.station_id=?3"; sql += ")) AND "; } - if(m_excludeSegmentId) + if (m_excludeSegmentId) { sql += "seg.id<>?4 AND "; } @@ -243,9 +246,9 @@ void RailwaySegmentMatchModel::setFilter(db_id fromStationId, db_id toStationId, bool RailwaySegmentMatchModel::isReversed(db_id segId) const { - for(const SegmentItem& item : items) + for (const SegmentItem &item : items) { - if(item.segmentId == segId) + if (item.segmentId == segId) return item.reversed; } return false; diff --git a/src/stations/match_models/railwaysegmentmatchmodel.h b/src/stations/match_models/railwaysegmentmatchmodel.h index 36b8bc6..a1719d3 100644 --- a/src/stations/match_models/railwaysegmentmatchmodel.h +++ b/src/stations/match_models/railwaysegmentmatchmodel.h @@ -34,14 +34,13 @@ class RailwaySegmentMatchModel : public ISqlFKMatchModel Q_OBJECT public: - explicit RailwaySegmentMatchModel(sqlite3pp::database &db, - QObject *parent = nullptr); + explicit RailwaySegmentMatchModel(sqlite3pp::database &db, QObject *parent = nullptr); // Basic functionality: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; diff --git a/src/stations/match_models/stationgatesmatchmodel.cpp b/src/stations/match_models/stationgatesmatchmodel.cpp index 48a2e87..e071dc2 100644 --- a/src/stations/match_models/stationgatesmatchmodel.cpp +++ b/src/stations/match_models/stationgatesmatchmodel.cpp @@ -41,19 +41,19 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= size) return QVariant(); - const bool emptyRow = hasEmptyRow && - (idx.row() == ItemCount || (size < ItemCount + 2 && idx.row() == size - 1)); + const bool emptyRow = + hasEmptyRow && (idx.row() == ItemCount || (size < ItemCount + 2 && idx.row() == size - 1)); const bool ellipsesRow = idx.row() == (ItemCount - 1 - (hasEmptyRow ? 0 : 1)); switch (role) { case Qt::DisplayRole: { - if(emptyRow) + if (emptyRow) { return ISqlFKMatchModel::tr("Empty"); } - else if(ellipsesRow) + else if (ellipsesRow) { return ellipsesString; } @@ -62,19 +62,19 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const } case Qt::ToolTipRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) { - QString tip = tr("Gate %1 is %2") - .arg(items[idx.row()].gateLetter, - utils::StationUtils::name(items[idx.row()].side)); - if(m_markConnectedGates) + QString tip = + tr("Gate %1 is %2") + .arg(items[idx.row()].gateLetter, utils::StationUtils::name(items[idx.row()].side)); + if (m_markConnectedGates) { QString state; db_id segId = items[idx.row()].segmentId; - if(segId) + if (segId) { state = tr("Segment: %1").arg(items[idx.row()].segmentName); - if(segId == m_excludeSegmentId) + if (segId == m_excludeSegmentId) state.append(tr("
Current")); } else @@ -82,7 +82,7 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const state = tr("Not connected"); } - //New line, then append + // New line, then append tip.append("
"); tip.append(state); } @@ -92,7 +92,7 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(emptyRow) + if (emptyRow) { return boldFont(); } @@ -100,18 +100,18 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const } case Qt::TextAlignmentRole: { - if(!emptyRow && !ellipsesRow && !m_showOnlySegments) - return Qt::AlignRight + Qt::AlignVCenter; //Segments will be Left aligned + if (!emptyRow && !ellipsesRow && !m_showOnlySegments) + return Qt::AlignRight + Qt::AlignVCenter; // Segments will be Left aligned break; } case Qt::BackgroundRole: { - if(!emptyRow && !ellipsesRow && m_markConnectedGates) + if (!emptyRow && !ellipsesRow && m_markConnectedGates) { db_id segId = items[idx.row()].segmentId; - if(segId && segId != m_excludeSegmentId) + if (segId && segId != m_excludeSegmentId) { - //Cyan if gate is connected to a segment + // Cyan if gate is connected to a segment return QBrush(Qt::cyan); } } @@ -119,16 +119,16 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const } case Qt::DecorationRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) { QColor color; - if(items[idx.row()].type.testFlag(utils::GateType::Bidirectional)) - break; //Default color + if (items[idx.row()].type.testFlag(utils::GateType::Bidirectional)) + break; // Default color - if(items[idx.row()].type.testFlag(utils::GateType::Entrance)) - color = Qt::green; //Entrance only - else if(items[idx.row()].type.testFlag(utils::GateType::Exit)) - color = Qt::red; //Exit only + if (items[idx.row()].type.testFlag(utils::GateType::Entrance)) + color = Qt::green; // Entrance only + else if (items[idx.row()].type.testFlag(utils::GateType::Exit)) + color = Qt::red; // Exit only return color; } break; @@ -141,7 +141,7 @@ QVariant StationGatesMatchModel::data(const QModelIndex &idx, int role) const void StationGatesMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -155,14 +155,14 @@ void StationGatesMatchModel::autoSuggest(const QString &text) void StationGatesMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); @@ -170,30 +170,30 @@ void StationGatesMatchModel::refreshData() q_getMatches.bind(2, m_stationId); auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < ItemCount && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < ItemCount && it != end; i++) { - auto track = *it; - items[i].gateId = track.get(0); + auto track = *it; + items[i].gateId = track.get(0); items[i].outTrackCount = track.get(1); - items[i].type = utils::GateType(track.get(2)); - items[i].gateLetter = sqlite3_column_text(q_getMatches.stmt(), 3)[0]; - items[i].side = utils::Side(track.get(4)); + items[i].type = utils::GateType(track.get(2)); + items[i].gateLetter = sqlite3_column_text(q_getMatches.stmt(), 3)[0]; + items[i].side = utils::Side(track.get(4)); - if(m_markConnectedGates) + if (m_markConnectedGates) { items[i].segmentId = track.get(5); - if(m_showOnlySegments && !items[i].segmentId) + if (m_showOnlySegments && !items[i].segmentId) { - //Skip this gate because it is not connected to a segment - i--; //Overwrite with new item - ++it; //Step query to next record + // Skip this gate because it is not connected to a segment + i--; // Overwrite with new item + ++it; // Step query to next record continue; } - items[i].segmentName = track.get(6); - const db_id inGateId = track.get(7); + items[i].segmentName = track.get(6); + const db_id inGateId = track.get(7); items[i].segmentReversed = (inGateId != items[i].gateId); } else @@ -207,13 +207,13 @@ void StationGatesMatchModel::refreshData() } size = i; - if(hasEmptyRow) - size++; //Items + Empty + if (hasEmptyRow) + size++; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -224,20 +224,20 @@ void StationGatesMatchModel::refreshData() QString StationGatesMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM station_gates WHERE id=?"); q.bind(1, id); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return QString(); QString str = q.getRows().get(0); - if(m_showOnlySegments) + if (m_showOnlySegments) { q.prepare("SELECT name FROM railway_segments WHERE in_gate_id=?1 OR out_gate_id=?1"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) { str.append(QLatin1String(": ")); str.append(q.getRows().get(0)); @@ -254,7 +254,7 @@ db_id StationGatesMatchModel::getIdAtRow(int row) const QString StationGatesMatchModel::getNameAtRow(int row) const { QString str = items[row].gateLetter; - if(m_showOnlySegments) + if (m_showOnlySegments) { str.reserve(3 + items[row].segmentName.size()); str.append(QLatin1String(": ")); @@ -263,20 +263,21 @@ QString StationGatesMatchModel::getNameAtRow(int row) const return str; } -void StationGatesMatchModel::setFilter(db_id stationId, bool markConnectedGates, db_id excludeSegmentId, bool showOnlySegments) +void StationGatesMatchModel::setFilter(db_id stationId, bool markConnectedGates, + db_id excludeSegmentId, bool showOnlySegments) { - m_stationId = stationId; + m_stationId = stationId; m_markConnectedGates = markConnectedGates; - m_excludeSegmentId = m_markConnectedGates ? excludeSegmentId : 0; - m_showOnlySegments = showOnlySegments; + m_excludeSegmentId = m_markConnectedGates ? excludeSegmentId : 0; + m_showOnlySegments = showOnlySegments; - QByteArray sql = "SELECT g.id,g.out_track_count,g.type,g.name,g.side"; - if(m_markConnectedGates) + QByteArray sql = "SELECT g.id,g.out_track_count,g.type,g.name,g.side"; + if (m_markConnectedGates) { sql += ",s.id,s.name,s.in_gate_id"; } sql += " FROM station_gates g"; - if(m_markConnectedGates) + if (m_markConnectedGates) { sql += " LEFT JOIN railway_segments s ON s.in_gate_id=g.id OR s.out_gate_id=g.id"; } @@ -292,9 +293,9 @@ void StationGatesMatchModel::setFilter(db_id stationId, bool markConnectedGates, int StationGatesMatchModel::getOutTrackCount(db_id gateId) const { - for(const GateItem& item : items) + for (const GateItem &item : items) { - if(item.gateId == gateId) + if (item.gateId == gateId) return item.outTrackCount; } return 0; @@ -302,9 +303,9 @@ int StationGatesMatchModel::getOutTrackCount(db_id gateId) const utils::Side StationGatesMatchModel::getGateSide(db_id gateId) const { - for(const GateItem& item : items) + for (const GateItem &item : items) { - if(item.gateId == gateId) + if (item.gateId == gateId) return item.side; } return utils::Side::West; @@ -312,26 +313,26 @@ utils::Side StationGatesMatchModel::getGateSide(db_id gateId) const db_id StationGatesMatchModel::getSegmentIdAtRow(int row) const { - if(row < 0 || row >= size) + if (row < 0 || row >= size) return 0; return items[row].segmentId; } db_id StationGatesMatchModel::isSegmentReversedAtRow(int row) const { - if(row < 0 || row >= size) + if (row < 0 || row >= size) return 0; return items[row].segmentReversed; } int StationGatesMatchModel::getGateTrackCount(db_id gateId) const { - if(!mDb.db()) + if (!mDb.db()) return 0; query q(mDb, "SELECT out_track_count FROM station_gates WHERE id=?"); q.bind(1, gateId); - if(q.step() != SQLITE_ROW) + if (q.step() != SQLITE_ROW) return 0; return q.getRows().get(0); } @@ -343,7 +344,6 @@ StationGatesMatchFactory::StationGatesMatchFactory(database &db, QObject *parent markConnectedGates(false), mDb(db) { - } ISqlFKMatchModel *StationGatesMatchFactory::createModel() diff --git a/src/stations/match_models/stationgatesmatchmodel.h b/src/stations/match_models/stationgatesmatchmodel.h index 3714e6f..dbb6dfc 100644 --- a/src/stations/match_models/stationgatesmatchmodel.h +++ b/src/stations/match_models/stationgatesmatchmodel.h @@ -41,7 +41,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; @@ -49,7 +49,8 @@ public: QString getNameAtRow(int row) const override; // StationsMatchModel: - void setFilter(db_id stationId, bool markConnectedGates, db_id excludeSegmentId, bool showOnlySegments = false); + void setFilter(db_id stationId, bool markConnectedGates, db_id excludeSegmentId, + bool showOnlySegments = false); int getOutTrackCount(db_id gateId) const; utils::Side getGateSide(db_id gateId) const; @@ -91,7 +92,10 @@ public: virtual ISqlFKMatchModel *createModel() override; - inline void setStationId(db_id stationId) { m_stationId = stationId; } + inline void setStationId(db_id stationId) + { + m_stationId = stationId; + } inline void setMarkConnectedGates(bool val, db_id excludeSegId) { markConnectedGates = val; diff --git a/src/stations/match_models/stationsmatchmodel.cpp b/src/stations/match_models/stationsmatchmodel.cpp index b193661..1aa714e 100644 --- a/src/stations/match_models/stationsmatchmodel.cpp +++ b/src/stations/match_models/stationsmatchmodel.cpp @@ -25,7 +25,6 @@ StationsMatchModel::StationsMatchModel(database &db, QObject *parent) : q_getMatches(mDb), m_exceptStId(0) { - } QVariant StationsMatchModel::data(const QModelIndex &idx, int role) const @@ -37,11 +36,11 @@ QVariant StationsMatchModel::data(const QModelIndex &idx, int role) const { case Qt::DisplayRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return ISqlFKMatchModel::tr("Empty"); } - else if(isEllipsesRow(idx.row())) + else if (isEllipsesRow(idx.row())) { return ellipsesString; } @@ -50,7 +49,7 @@ QVariant StationsMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(isEmptyRow(idx.row())) + if (isEmptyRow(idx.row())) { return boldFont(); } @@ -64,7 +63,7 @@ QVariant StationsMatchModel::data(const QModelIndex &idx, int role) const void StationsMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -78,37 +77,37 @@ void StationsMatchModel::autoSuggest(const QString &text) void StationsMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); - if(m_exceptStId) + if (m_exceptStId) q_getMatches.bind(2, m_exceptStId); auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < MaxMatchItems && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < MaxMatchItems && it != end; i++) { items[i].stationId = (*it).get(0); - items[i].name = (*it).get(1); + items[i].name = (*it).get(1); ++it; } - size = i + 1; //Items + Empty + size = i + 1; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -119,12 +118,12 @@ void StationsMatchModel::refreshData() QString StationsMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM stations WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } @@ -141,13 +140,14 @@ QString StationsMatchModel::getNameAtRow(int row) const void StationsMatchModel::setFilter(db_id exceptStId) { - m_exceptStId = exceptStId; + m_exceptStId = exceptStId; QByteArray sql = "SELECT stations.id,stations.name FROM stations WHERE "; - if(m_exceptStId) + if (m_exceptStId) sql.append("stations.id<>?2 AND "); - sql.append("(stations.name LIKE ?1 OR stations.short_name LIKE ?1) LIMIT " QT_STRINGIFY(MaxMatchItems + 1)); + sql.append("(stations.name LIKE ?1 OR stations.short_name LIKE ?1) LIMIT " QT_STRINGIFY( + MaxMatchItems + 1)); q_getMatches.prepare(sql.constData()); } @@ -157,7 +157,6 @@ StationMatchFactory::StationMatchFactory(database &db, QObject *parent) : exceptStId(0), mDb(db) { - } ISqlFKMatchModel *StationMatchFactory::createModel() diff --git a/src/stations/match_models/stationsmatchmodel.h b/src/stations/match_models/stationsmatchmodel.h index 02f8aa6..60b22fb 100644 --- a/src/stations/match_models/stationsmatchmodel.h +++ b/src/stations/match_models/stationsmatchmodel.h @@ -38,7 +38,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; @@ -71,7 +71,10 @@ class StationMatchFactory : public IMatchModelFactory ISqlFKMatchModel *createModel() override; - inline void setExceptStation(db_id stationId) { exceptStId = stationId; } + inline void setExceptStation(db_id stationId) + { + exceptStId = stationId; + } private: db_id exceptStId; diff --git a/src/stations/match_models/stationtracksmatchmodel.cpp b/src/stations/match_models/stationtracksmatchmodel.cpp index 096d5af..ae35dde 100644 --- a/src/stations/match_models/stationtracksmatchmodel.cpp +++ b/src/stations/match_models/stationtracksmatchmodel.cpp @@ -31,7 +31,6 @@ StationTracksMatchModel::StationTracksMatchModel(sqlite3pp::database &db, QObjec " ORDER BY pos"), m_stationId(0) { - } QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const @@ -39,19 +38,19 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= size) return QVariant(); - const bool emptyRow = hasEmptyRow && - (idx.row() == ItemCount || (size < ItemCount + 2 && idx.row() == size - 1)); + const bool emptyRow = + hasEmptyRow && (idx.row() == ItemCount || (size < ItemCount + 2 && idx.row() == size - 1)); const bool ellipsesRow = idx.row() == (ItemCount - 1 - (hasEmptyRow ? 0 : 1)); switch (role) { case Qt::DisplayRole: { - if(emptyRow) + if (emptyRow) { return ISqlFKMatchModel::tr("Empty"); } - else if(ellipsesRow) + else if (ellipsesRow) { return ellipsesString; } @@ -60,14 +59,14 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const } case Qt::ToolTipRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) { QString typeStr; - if(items[idx.row()].passenger && items[idx.row()].freight) + if (items[idx.row()].passenger && items[idx.row()].freight) typeStr = tr("All"); - else if(items[idx.row()].passenger) + else if (items[idx.row()].passenger) typeStr = tr("Passenger"); - else if(items[idx.row()].freight) + else if (items[idx.row()].freight) typeStr = tr("Freight"); return tr("Track %1 for %2 traffic.").arg(items[idx.row()].name, typeStr); } @@ -75,11 +74,11 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const } case Qt::FontRole: { - if(emptyRow) + if (emptyRow) { return boldFont(); } - if(!ellipsesRow && items[idx.row()].type.testFlag(utils::StationTrackType::Through)) + if (!ellipsesRow && items[idx.row()].type.testFlag(utils::StationTrackType::Through)) { return boldFont(); } @@ -87,20 +86,20 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const } case Qt::TextAlignmentRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) return Qt::AlignRight + Qt::AlignVCenter; break; } case Qt::BackgroundRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) { QColor color; - if(items[idx.row()].passenger && items[idx.row()].freight) + if (items[idx.row()].passenger && items[idx.row()].freight) color = Qt::red; - else if(items[idx.row()].passenger) + else if (items[idx.row()].passenger) color = Qt::yellow; - else if(items[idx.row()].freight) + else if (items[idx.row()].freight) color = Qt::green; color.setAlpha(70); return QBrush(color); @@ -109,9 +108,9 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const } case Qt::DecorationRole: { - if(!emptyRow && !ellipsesRow) + if (!emptyRow && !ellipsesRow) { - if(items[idx.row()].type.testFlag(utils::StationTrackType::Electrified)) + if (items[idx.row()].type.testFlag(utils::StationTrackType::Electrified)) return QColor(Qt::blue); } break; @@ -124,7 +123,7 @@ QVariant StationTracksMatchModel::data(const QModelIndex &idx, int role) const void StationTracksMatchModel::autoSuggest(const QString &text) { mQuery.clear(); - if(!text.isEmpty()) + if (!text.isEmpty()) { mQuery.clear(); mQuery.reserve(text.size() + 2); @@ -138,14 +137,14 @@ void StationTracksMatchModel::autoSuggest(const QString &text) void StationTracksMatchModel::refreshData() { - if(!mDb.db()) + if (!mDb.db()) return; beginResetModel(); char emptyQuery = '%'; - if(mQuery.isEmpty()) + if (mQuery.isEmpty()) sqlite3_bind_text(q_getMatches.stmt(), 1, &emptyQuery, 1, SQLITE_STATIC); else sqlite3_bind_text(q_getMatches.stmt(), 1, mQuery, mQuery.size(), SQLITE_STATIC); @@ -153,27 +152,27 @@ void StationTracksMatchModel::refreshData() q_getMatches.bind(2, m_stationId); auto end = q_getMatches.end(); - auto it = q_getMatches.begin(); - int i = 0; - for(; i < ItemCount && it != end; i++) + auto it = q_getMatches.begin(); + int i = 0; + for (; i < ItemCount && it != end; i++) { - auto track = *it; - items[i].trackId = track.get(0); - items[i].type = utils::StationTrackType(track.get(1)); + auto track = *it; + items[i].trackId = track.get(0); + items[i].type = utils::StationTrackType(track.get(1)); items[i].passenger = track.get(2) != 0; - items[i].freight = track.get(3) != 0; - items[i].name = track.get(4); + items[i].freight = track.get(3) != 0; + items[i].name = track.get(4); ++it; } size = i; - if(hasEmptyRow) - size++; //Items + Empty + if (hasEmptyRow) + size++; // Items + Empty - if(it != end) + if (it != end) { - //There would be still rows, show Ellipses - size++; //Items + Empty + Ellispses + // There would be still rows, show Ellipses + size++; // Items + Empty + Ellispses } q_getMatches.reset(); @@ -184,12 +183,12 @@ void StationTracksMatchModel::refreshData() QString StationTracksMatchModel::getName(db_id id) const { - if(!mDb.db()) + if (!mDb.db()) return QString(); query q(mDb, "SELECT name FROM station_tracks WHERE id=?"); q.bind(1, id); - if(q.step() == SQLITE_ROW) + if (q.step() == SQLITE_ROW) return q.getRows().get(0); return QString(); } @@ -215,7 +214,6 @@ StationTracksMatchFactory::StationTracksMatchFactory(database &db, QObject *pare m_stationId(0), mDb(db) { - } ISqlFKMatchModel *StationTracksMatchFactory::createModel() diff --git a/src/stations/match_models/stationtracksmatchmodel.h b/src/stations/match_models/stationtracksmatchmodel.h index 557e8d9..6c3ecc2 100644 --- a/src/stations/match_models/stationtracksmatchmodel.h +++ b/src/stations/match_models/stationtracksmatchmodel.h @@ -41,7 +41,7 @@ public: QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; // ISqlFKMatchModel: - void autoSuggest(const QString& text) override; + void autoSuggest(const QString &text) override; virtual void refreshData() override; QString getName(db_id id) const override; @@ -77,7 +77,10 @@ public: virtual ISqlFKMatchModel *createModel() override; - inline void setStationId(db_id stationId) { m_stationId = stationId; } + inline void setStationId(db_id stationId) + { + m_stationId = stationId; + } private: db_id m_stationId; diff --git a/src/stations/station_name_utils.h b/src/stations/station_name_utils.h index 7bfd431..55203e9 100644 --- a/src/stations/station_name_utils.h +++ b/src/stations/station_name_utils.h @@ -26,11 +26,9 @@ namespace utils { -static const char* StationTypeNamesTable[] = { - QT_TRANSLATE_NOOP("StationUtils", "Normal"), - QT_TRANSLATE_NOOP("StationUtils", "Simple Stop"), - QT_TRANSLATE_NOOP("StationUtils", "Junction") -}; +static const char *StationTypeNamesTable[] = {QT_TRANSLATE_NOOP("StationUtils", "Normal"), + QT_TRANSLATE_NOOP("StationUtils", "Simple Stop"), + QT_TRANSLATE_NOOP("StationUtils", "Junction")}; class StationUtils { @@ -39,7 +37,7 @@ class StationUtils public: static inline QString name(StationType t) { - if(t >= StationType::NTypes) + if (t >= StationType::NTypes) return QString(); return tr(StationTypeNamesTable[int(t)]); } diff --git a/src/stations/station_utils.h b/src/stations/station_utils.h index 894b2fb..a8742da 100644 --- a/src/stations/station_utils.h +++ b/src/stations/station_utils.h @@ -25,28 +25,27 @@ #include -namespace utils -{ +namespace utils { enum class StationType : qint8 { - Normal = 0, //Normal station - SimpleStop = 1, //Trains can stop but cannot be origin or destination - Junction = 2, //This is not a real station but instead a junction between 2 lines + Normal = 0, // Normal station + SimpleStop = 1, // Trains can stop but cannot be origin or destination + Junction = 2, // This is not a real station but instead a junction between 2 lines NTypes }; -//TODO: is this useful??? +// TODO: is this useful??? enum class GateType : qint8 { - Unknown = 0, - Entrance = 1 << 0, //NOTE: at least Entrance or Exit - Exit = 1 << 1, - Bidirectional = (Entrance | Exit), + Unknown = 0, + Entrance = 1 << 0, // NOTE: at least Entrance or Exit + Exit = 1 << 1, + Bidirectional = (Entrance | Exit), - LeftHandTraffic = 1 << 2, + LeftHandTraffic = 1 << 2, RightHandTraffic = 1 << 3, - MultipleTraffic = (LeftHandTraffic | RightHandTraffic) + MultipleTraffic = (LeftHandTraffic | RightHandTraffic) }; enum class Side : qint8 @@ -56,26 +55,26 @@ enum class Side : qint8 NSides }; -//NOTE: a track can be for passenger and freight traffic at the same time or none of them -// just set platf_length_cm TO non-zero, same for freight_length_cm +// NOTE: a track can be for passenger and freight traffic at the same time or none of them +// just set platf_length_cm TO non-zero, same for freight_length_cm enum class StationTrackType : qint8 { - Electrified = 1 << 0, //Electric engines are allowed - Through = 1 << 1 //For non-stopping trains + Electrified = 1 << 0, // Electric engines are allowed + Through = 1 << 1 // For non-stopping trains }; enum class RailwaySegmentType : qint8 { - Electrified = 1 << 0, //Electric engines are allowed + Electrified = 1 << 0, // Electric engines are allowed - LeftHandTraffic = 1 << 2, + LeftHandTraffic = 1 << 2, RightHandTraffic = 1 << 3, - MultipleTraffic = (LeftHandTraffic | RightHandTraffic) + MultipleTraffic = (LeftHandTraffic | RightHandTraffic) }; struct RailwaySegmentGateInfo { - db_id gateId = 0; + db_id gateId = 0; db_id stationId = 0; QString stationName; QChar gateLetter; @@ -85,8 +84,8 @@ struct RailwaySegmentInfo { db_id segmentId = 0; QString segmentName; - int distanceMeters = 10000; //10 Km - int maxSpeedKmH = 120; + int distanceMeters = 10000; // 10 Km + int maxSpeedKmH = 120; RailwaySegmentType type; RailwaySegmentGateInfo from; diff --git a/src/utils/delegates/color/colordelegate.cpp b/src/utils/delegates/color/colordelegate.cpp index 92aeb0d..cd2bbd8 100644 --- a/src/utils/delegates/color/colordelegate.cpp +++ b/src/utils/delegates/color/colordelegate.cpp @@ -28,22 +28,24 @@ ColorDelegate::ColorDelegate(QObject *parent) : QStyledItemDelegate(parent) { - } -void ColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +void ColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const { QRgb rgb = index.data(COLOR_ROLE).toUInt(); QColor col(rgb); painter->fillRect(option.rect, col); } -QSize ColorDelegate::sizeHint(const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const +QSize ColorDelegate::sizeHint(const QStyleOptionViewItem & /*option*/, + const QModelIndex & /*index*/) const { return QSize(); } -QWidget *ColorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const +QWidget *ColorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex & /*index*/) const { QColorDialog *dlg = new QColorDialog(parent); connect(dlg, &QColorDialog::colorSelected, this, &ColorDelegate::commitAndCloseEditor); @@ -56,7 +58,8 @@ void ColorDelegate::setEditorData(QWidget *editor, const QModelIndex &index) con ed->setCurrentColor(index.data(COLOR_ROLE).toUInt()); } -void ColorDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void ColorDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const { QColorDialog *ed = static_cast(editor); model->setData(index, ed->currentColor().rgb(), COLOR_ROLE); diff --git a/src/utils/delegates/color/colordelegate.h b/src/utils/delegates/color/colordelegate.h index 2e9b4a3..b5358db 100644 --- a/src/utils/delegates/color/colordelegate.h +++ b/src/utils/delegates/color/colordelegate.h @@ -30,8 +30,7 @@ public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; diff --git a/src/utils/delegates/color/colorview.cpp b/src/utils/delegates/color/colorview.cpp index b829e6e..e61908e 100644 --- a/src/utils/delegates/color/colorview.cpp +++ b/src/utils/delegates/color/colorview.cpp @@ -31,12 +31,12 @@ ColorView::ColorView(QWidget *parent) : void ColorView::setColor(const QColor &color, bool user) { - if(mColor == color) + if (mColor == color) return; mColor = color; - if(user) + if (user) { emit colorChanged(mColor); } @@ -44,9 +44,7 @@ void ColorView::setColor(const QColor &color, bool user) void ColorView::openColorDialog() { - QColor col = QColorDialog::getColor(mColor, - this, - tr("Choose a color")); + QColor col = QColorDialog::getColor(mColor, this, tr("Choose a color")); setColor(col, true); emit editingFinished(); diff --git a/src/utils/delegates/color/colorview.h b/src/utils/delegates/color/colorview.h index f116b56..5ee8b5b 100644 --- a/src/utils/delegates/color/colorview.h +++ b/src/utils/delegates/color/colorview.h @@ -38,7 +38,7 @@ public: void openColorDialog(); signals: - void colorChanged(const QColor&); + void colorChanged(const QColor &); void editingFinished(); protected: diff --git a/src/utils/delegates/combobox/combodelegate.cpp b/src/utils/delegates/combobox/combodelegate.cpp index a9cbf28..d1cf6eb 100644 --- a/src/utils/delegates/combobox/combodelegate.cpp +++ b/src/utils/delegates/combobox/combodelegate.cpp @@ -27,57 +27,61 @@ ComboDelegate::ComboDelegate(const QStringList &list, int role, QObject *parent) mList(list), mRole(role) { - //DEBUG_ENTRY; + // DEBUG_ENTRY; qDebug() << mList; } -QWidget *ComboDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const +QWidget *ComboDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex & /*index*/) const { - //DEBUG_ENTRY; + // DEBUG_ENTRY; QComboBox *combo = new QComboBox(parent); - connect(combo, static_cast(&QComboBox::activated), this, &ComboDelegate::onItemClicked); + connect(combo, static_cast(&QComboBox::activated), this, + &ComboDelegate::onItemClicked); combo->addItems(mList); return combo; } void ComboDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { - //DEBUG_ENTRY; - QComboBox *combo = static_cast(editor); - QVariant v = index.model()->data(index, mRole); - if(v.isValid()) + // DEBUG_ENTRY; + QComboBox *combo = static_cast(editor); + QVariant v = index.model()->data(index, mRole); + if (v.isValid()) { int val = v.toInt(); combo->setCurrentIndex(val); } else { - combo->setCurrentIndex(0); //TODO??? -1 --> 0 ? + combo->setCurrentIndex(0); // TODO??? -1 --> 0 ? } combo->showPopup(); } -void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void ComboDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const { - //DEBUG_ENTRY; - QComboBox *combo = static_cast(editor); - int val = combo->currentIndex(); + // DEBUG_ENTRY; + QComboBox *combo = static_cast(editor); + int val = combo->currentIndex(); model->setData(index, val, mRole); - //QString text = combo->currentText(); - //model->setData(index, text, Qt::DisplayRole); + // QString text = combo->currentText(); + // model->setData(index, text, Qt::DisplayRole); } void ComboDelegate::onItemClicked() { QComboBox *combo = qobject_cast(sender()); - if(combo) + if (combo) { emit commitData(combo); emit closeEditor(combo); } } -void ComboDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const +void ComboDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex & /*index*/) const { editor->setGeometry(option.rect); } diff --git a/src/utils/delegates/combobox/combodelegate.h b/src/utils/delegates/combobox/combodelegate.h index dc7ebc5..076a009 100644 --- a/src/utils/delegates/combobox/combodelegate.h +++ b/src/utils/delegates/combobox/combodelegate.h @@ -27,7 +27,7 @@ class ComboDelegate : public QStyledItemDelegate { Q_OBJECT public: - ComboDelegate(const QStringList& list, int role, QObject *parent = nullptr); + ComboDelegate(const QStringList &list, int role, QObject *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; @@ -36,8 +36,8 @@ public: void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; private slots: void onItemClicked(); diff --git a/src/utils/delegates/imageviewer/imageviewer.cpp b/src/utils/delegates/imageviewer/imageviewer.cpp index bee4bed..bad334e 100644 --- a/src/utils/delegates/imageviewer/imageviewer.cpp +++ b/src/utils/delegates/imageviewer/imageviewer.cpp @@ -29,7 +29,7 @@ ImageViewer::ImageViewer(QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - infoLabel = new QLabel; + infoLabel = new QLabel; lay->addWidget(infoLabel); slider = new QSlider(Qt::Horizontal); @@ -53,15 +53,14 @@ ImageViewer::ImageViewer(QWidget *parent) : void ImageViewer::setImage(const QImage &img) { - originalImg = img; + originalImg = img; + const int widthPx = img.width(); + const int heightPx = img.height(); + const int dotsX = img.dotsPerMeterX(); + const int dotsY = img.dotsPerMeterY(); - const int widthPx = img.width(); - const int heightPx = img.height(); - const int dotsX = img.dotsPerMeterX(); - const int dotsY = img.dotsPerMeterY(); - - const double widthCm = 100.0 * double(widthPx) / double(dotsX); + const double widthCm = 100.0 * double(widthPx) / double(dotsX); const double heightCm = 100.0 * double(heightPx) / double(dotsY); QString info; @@ -70,7 +69,7 @@ void ImageViewer::setImage(const QImage &img) info.append(QStringLiteral("Height: %1 cm\n").arg(heightCm, 0, 'f', 2)); QStringList keys = img.textKeys(); - for(const QString& key : keys) + for (const QString &key : keys) { info.append("'"); info.append(key); @@ -82,7 +81,7 @@ void ImageViewer::setImage(const QImage &img) setScale(100); - if(originalImg.isNull()) + if (originalImg.isNull()) { imageLabel->setPixmap(QPixmap()); imageLabel->setText(tr("No image")); @@ -92,7 +91,7 @@ void ImageViewer::setImage(const QImage &img) void ImageViewer::setScale(int val) { - if(originalImg.isNull()) + if (originalImg.isNull()) return; slider->setValue(val); @@ -100,11 +99,14 @@ void ImageViewer::setScale(int val) imageLabel->setToolTip(tip); slider->setToolTip(tip); - if(val == 100) + if (val == 100) { scaledImg = originalImg; - }else{ - scaledImg = originalImg.scaledToWidth(originalImg.width() * val / 100, Qt::SmoothTransformation); + } + else + { + scaledImg = + originalImg.scaledToWidth(originalImg.width() * val / 100, Qt::SmoothTransformation); } imageLabel->setPixmap(QPixmap::fromImage(scaledImg)); diff --git a/src/utils/delegates/imageviewer/imageviewer.h b/src/utils/delegates/imageviewer/imageviewer.h index 5fe23da..2f25c68 100644 --- a/src/utils/delegates/imageviewer/imageviewer.h +++ b/src/utils/delegates/imageviewer/imageviewer.h @@ -32,9 +32,11 @@ class ImageViewer : public QDialog Q_OBJECT public: ImageViewer(QWidget *parent = nullptr); - virtual ~ImageViewer() {} + virtual ~ImageViewer() + { + } - void setImage(const QImage& img); + void setImage(const QImage &img); public slots: void setScale(int val); diff --git a/src/utils/delegates/kmspinbox/kmdelegate.cpp b/src/utils/delegates/kmspinbox/kmdelegate.cpp index b004043..4026f5b 100644 --- a/src/utils/delegates/kmspinbox/kmdelegate.cpp +++ b/src/utils/delegates/kmspinbox/kmdelegate.cpp @@ -24,10 +24,10 @@ KmDelegate::KmDelegate(QObject *parent) : QStyledItemDelegate(parent), minimum(0) { - } -QWidget *KmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const +QWidget *KmDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex & /*index*/) const { KmSpinBox *spin = new KmSpinBox(parent); spin->setMinimum(minimum); @@ -41,13 +41,15 @@ void KmDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const spin->setValue(index.data(Qt::EditRole).toInt()); } -void KmDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void KmDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const { KmSpinBox *spin = static_cast(editor); model->setData(index, spin->value(), Qt::EditRole); } -void KmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const +void KmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex & /*index*/) const { editor->setGeometry(option.rect); } @@ -55,5 +57,5 @@ void KmDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewIte void KmDelegate::setMinAndPrefix(int min, const QString &pref) { minimum = min; - prefix = pref; + prefix = pref; } diff --git a/src/utils/delegates/kmspinbox/kmdelegate.h b/src/utils/delegates/kmspinbox/kmdelegate.h index aad983e..44c95b5 100644 --- a/src/utils/delegates/kmspinbox/kmdelegate.h +++ b/src/utils/delegates/kmspinbox/kmdelegate.h @@ -35,10 +35,10 @@ public: void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &index) const override; - void setMinAndPrefix(int min, const QString& pref); + void setMinAndPrefix(int min, const QString &pref); private: int minimum; diff --git a/src/utils/delegates/kmspinbox/kmspinbox.cpp b/src/utils/delegates/kmspinbox/kmspinbox.cpp index bab1a53..3bd3c2a 100644 --- a/src/utils/delegates/kmspinbox/kmspinbox.cpp +++ b/src/utils/delegates/kmspinbox/kmspinbox.cpp @@ -30,7 +30,7 @@ KmSpinBox::KmSpinBox(QWidget *parent) : QSpinBox(parent), currentSection(KmSection) { - setRange(0, 9999 * 1000 + 999); //9999 km + 999 meters + setRange(0, 9999 * 1000 + 999); // 9999 km + 999 meters setAlignment(Qt::AlignRight | Qt::AlignVCenter); connect(lineEdit(), &QLineEdit::cursorPositionChanged, this, &KmSpinBox::cursorPosChanged); } @@ -44,18 +44,18 @@ void KmSpinBox::focusInEvent(QFocusEvent *e) void KmSpinBox::keyPressEvent(QKeyEvent *e) { bool plusPressed = false; - if(e->key() == Qt::Key_Plus || e->text().contains('+')) + if (e->key() == Qt::Key_Plus || e->text().contains('+')) plusPressed = true; QSpinBox::keyPressEvent(e); - if(plusPressed && currentSection == KmSection) + if (plusPressed && currentSection == KmSection) setCurrentSection(MetersSection); } bool KmSpinBox::focusNextPrevChild(bool next) { - if((currentSection == MetersSection) == next) + if ((currentSection == MetersSection) == next) { - //Before KmSection or after MetersSection is out of the widget + // Before KmSection or after MetersSection is out of the widget return QSpinBox::focusNextPrevChild(next); } setCurrentSection(currentSection == KmSection ? MetersSection : KmSection); @@ -64,58 +64,58 @@ bool KmSpinBox::focusNextPrevChild(bool next) QValidator::State KmSpinBox::validate(QString &input, int &pos) const { - int plusPos = -1; - int val = 0; + int plusPos = -1; + int val = 0; int firstNonBlank = 0; - int i = 0; - bool empty = true; + int i = 0; + bool empty = true; - QString copy = stripped(input, &pos); + QString copy = stripped(input, &pos); - for(; i < copy.size(); i++) + for (; i < copy.size(); i++) { QChar ch = copy.at(i); - if(ch.isSpace()) + if (ch.isSpace()) { - if(!empty) + if (!empty) break; firstNonBlank++; continue; } - if(ch.isDigit()) + if (ch.isDigit()) { val *= 10; val += ch.digitValue(); empty = false; continue; } - if(ch != '+' || plusPos != -1) //Not '+' or digit or multiple '+' + if (ch != '+' || plusPos != -1) // Not '+' or digit or multiple '+' return QValidator::Invalid; plusPos = i; } - if(empty || val > maximum() || plusPos == -1) + if (empty || val > maximum() || plusPos == -1) return QValidator::Invalid; - if(plusPos != i - 4) + if (plusPos != i - 4) return QValidator::Intermediate; //+ is not 3 chars from last - if(firstNonBlank > 0 && copy.at(firstNonBlank) == '+') + if (firstNonBlank > 0 && copy.at(firstNonBlank) == '+') firstNonBlank--; pos -= copy.size() - i - firstNonBlank; copy = copy.mid(firstNonBlank, i - firstNonBlank); - if(copy.at(0) == '+') + if (copy.at(0) == '+') { - copy.prepend('0'); //Add leading zero + copy.prepend('0'); // Add leading zero } - else if(copy.size() > 1 && copy.at(1) == '+' && !copy.at(0).isDigit()) + else if (copy.size() > 1 && copy.at(1) == '+' && !copy.at(0).isDigit()) { - copy[0] = '0'; //Replace first char with leading zero + copy[0] = '0'; // Replace first char with leading zero } - //FIXME: prefix creates problems parsing + // FIXME: prefix creates problems parsing input = prefix() + copy + suffix(); return QValidator::Acceptable; @@ -133,28 +133,28 @@ QString KmSpinBox::textFromValue(int val) const void KmSpinBox::fixup(QString &str) const { - if(str.isEmpty() || str.at(0) == '+') + if (str.isEmpty() || str.at(0) == '+') str.prepend('0'); int plusPos = str.indexOf('+'); - if(plusPos < 0) + if (plusPos < 0) { str.append('+'); plusPos = str.size() - 1; } - else if(str.indexOf('+', plusPos + 1) >= 0) + else if (str.indexOf('+', plusPos + 1) >= 0) { - return; //Do not fix if there are multiple '+' + return; // Do not fix if there are multiple '+' } int nDigitsAfterPlus = str.size() - plusPos - 1; - if(nDigitsAfterPlus < 3) + if (nDigitsAfterPlus < 3) { - for(int i = nDigitsAfterPlus; i < 3; i++) + for (int i = nDigitsAfterPlus; i < 3; i++) { str.append('0'); } } - else if(nDigitsAfterPlus > 3) + else if (nDigitsAfterPlus > 3) { str.chop(nDigitsAfterPlus - 3); } @@ -163,20 +163,20 @@ void KmSpinBox::fixup(QString &str) const void KmSpinBox::stepBy(int steps) { int val = value(); - if(currentSection == KmSection) + if (currentSection == KmSection) { - //If steps are negative apply only if result km part is >= 0 + // If steps are negative apply only if result km part is >= 0 val += steps * 1000; - if(val >= 0) + if (val >= 0) { setValue(val); } } else { - //Keep 0 <= meters <= 999 otherwhise we change also km part + // Keep 0 <= meters <= 999 otherwhise we change also km part int meters = val % 1000 + steps; - if(meters >= 0 && meters <= 999) + if (meters >= 0 && meters <= 999) setValue(val + steps); } setCurrentSection(currentSection); @@ -185,8 +185,8 @@ void KmSpinBox::stepBy(int steps) void KmSpinBox::cursorPosChanged(int /*oldPos*/, int newPos) { QString text = lineEdit()->text(); - int plusPos = text.indexOf('+'); - if(plusPos < 0) + int plusPos = text.indexOf('+'); + if (plusPos < 0) { currentSection = KmSection; return; @@ -196,27 +196,27 @@ void KmSpinBox::cursorPosChanged(int /*oldPos*/, int newPos) void KmSpinBox::setCurrentSection(int section) { - QLineEdit *edit = lineEdit(); - QString text = edit->text(); - const int plusPos = text.indexOf('+'); + QLineEdit *edit = lineEdit(); + QString text = edit->text(); + const int plusPos = text.indexOf('+'); const int prefixSize = prefix().size(); const int suffixSize = suffix().size(); - if(plusPos < 0) + if (plusPos < 0) { currentSection = KmSection; return; } edit->deselect(); currentSection = section; - if(currentSection == KmSection) + if (currentSection == KmSection) { - //Select after prefix, before '+' + // Select after prefix, before '+' const int length = plusPos - prefixSize; edit->setSelection(prefixSize, length); } else { - //Select after '+', before suffix + // Select after '+', before suffix const int length = text.size() - suffixSize - plusPos - 1; edit->setSelection(plusPos + 1, length); } @@ -227,17 +227,17 @@ QString KmSpinBox::stripped(const QString &t, int *pos) const QStringRef text(&t); if (specialValueText().size() == 0 || text != specialValueText()) { - int from = 0; - int size = text.size(); + int from = 0; + int size = text.size(); bool changed = false; - if(prefix().size() && text.startsWith(prefix())) + if (prefix().size() && text.startsWith(prefix())) { from += prefix().size(); size -= from; changed = true; } - if(suffix().size() && text.endsWith(suffix())) + if (suffix().size() && text.endsWith(suffix())) { size -= suffix().size(); changed = true; @@ -246,7 +246,7 @@ QString KmSpinBox::stripped(const QString &t, int *pos) const text = text.mid(from, size); } const int s = text.size(); - text = text.trimmed(); + text = text.trimmed(); if (pos) (*pos) -= (s - text.size()); return text.toString(); diff --git a/src/utils/delegates/kmspinbox/kmutils.cpp b/src/utils/delegates/kmspinbox/kmutils.cpp index b5f8bc6..ef38844 100644 --- a/src/utils/delegates/kmspinbox/kmutils.cpp +++ b/src/utils/delegates/kmspinbox/kmutils.cpp @@ -23,20 +23,20 @@ QString utils::kmNumToText(int kmInMeters) { - //Add last digit and '+', at least 5 char (X+XXX) + // Add last digit and '+', at least 5 char (X+XXX) int numberLen = qMax(5, int(floor(log10(kmInMeters))) + 2); QString str(numberLen, QChar('0')); - for(int i = 0; i < numberLen; i++) + for (int i = 0; i < numberLen; i++) { - if(i == 3) + if (i == 3) { str[str.size() - 4] = '+'; continue; } - int rem = kmInMeters % 10; + int rem = kmInMeters % 10; str[str.size() - i - 1] = QChar('0' + rem); - kmInMeters = (kmInMeters - rem) / 10; + kmInMeters = (kmInMeters - rem) / 10; } return str; } @@ -44,10 +44,10 @@ QString utils::kmNumToText(int kmInMeters) int utils::kmNumFromTextInMeters(const QString &str) { int kmInMeters = 0; - for(int i = 0; i < str.size(); i++) + for (int i = 0; i < str.size(); i++) { QChar ch = str.at(i); - if(ch.isDigit()) + if (ch.isDigit()) { kmInMeters *= 10; kmInMeters += ch.digitValue(); diff --git a/src/utils/delegates/kmspinbox/kmutils.h b/src/utils/delegates/kmspinbox/kmutils.h index b983411..171f5f8 100644 --- a/src/utils/delegates/kmspinbox/kmutils.h +++ b/src/utils/delegates/kmspinbox/kmutils.h @@ -33,8 +33,8 @@ namespace utils { * Example: 15.75 km -> KM 15+750 */ QString kmNumToText(int kmInMeters); -int kmNumFromTextInMeters(const QString& str); +int kmNumFromTextInMeters(const QString &str); -} //namespace utils +} // namespace utils #endif // KMUTILS_H diff --git a/src/utils/delegates/kmspinbox/spinboxeditorfactory.cpp b/src/utils/delegates/kmspinbox/spinboxeditorfactory.cpp index 7f93456..45016a6 100644 --- a/src/utils/delegates/kmspinbox/spinboxeditorfactory.cpp +++ b/src/utils/delegates/kmspinbox/spinboxeditorfactory.cpp @@ -24,7 +24,6 @@ SpinBoxEditorFactory::SpinBoxEditorFactory() : m_minVal(0), m_maxVal(99) { - } QWidget *SpinBoxEditorFactory::createEditor(int /*userType*/, QWidget *parent) const diff --git a/src/utils/delegates/sql/IFKField.cpp b/src/utils/delegates/sql/IFKField.cpp index 23530f2..d25dd5f 100644 --- a/src/utils/delegates/sql/IFKField.cpp +++ b/src/utils/delegates/sql/IFKField.cpp @@ -21,5 +21,4 @@ IFKField::~IFKField() { - } diff --git a/src/utils/delegates/sql/IFKField.h b/src/utils/delegates/sql/IFKField.h index c66cc8e..82f07b9 100644 --- a/src/utils/delegates/sql/IFKField.h +++ b/src/utils/delegates/sql/IFKField.h @@ -26,16 +26,16 @@ /* IOwnerField * Generic interface for RSOwnersSQLDelegate so it can be used by multiple models * Used for set a Foreign Key field: user types the name and the model gets the corresponding id -*/ + */ class IFKField { public: virtual ~IFKField(); - virtual bool getFieldData(int row, int col, db_id &idOut, QString& nameOut) const = 0; - virtual bool validateData(int row, int col, db_id id, const QString& name) = 0; - virtual bool setFieldData(int row, int col, db_id id, const QString& name) = 0; + virtual bool getFieldData(int row, int col, db_id &idOut, QString &nameOut) const = 0; + virtual bool validateData(int row, int col, db_id id, const QString &name) = 0; + virtual bool setFieldData(int row, int col, db_id id, const QString &name) = 0; }; #endif // IFKFIELD_H diff --git a/src/utils/delegates/sql/chooseitemdlg.cpp b/src/utils/delegates/sql/chooseitemdlg.cpp index 81a1d64..90e3435 100644 --- a/src/utils/delegates/sql/chooseitemdlg.cpp +++ b/src/utils/delegates/sql/chooseitemdlg.cpp @@ -33,7 +33,7 @@ ChooseItemDlg::ChooseItemDlg(ISqlFKMatchModel *matchModel, QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - label = new QLabel; + label = new QLabel; lay->addWidget(label); lineEdit = new CustomCompletionLineEdit(matchModel); @@ -64,10 +64,10 @@ void ChooseItemDlg::setPlaceholder(const QString &text) void ChooseItemDlg::done(int res) { - if(res == QDialog::Accepted) + if (res == QDialog::Accepted) { QString errMsg; - if(m_callback && !m_callback(itemId, errMsg)) + if (m_callback && !m_callback(itemId, errMsg)) { QMessageBox::warning(this, tr("Error"), errMsg); return; @@ -79,13 +79,15 @@ void ChooseItemDlg::done(int res) void ChooseItemDlg::itemChosen(db_id id) { - itemId = id; + itemId = id; QPushButton *okBut = buttonBox->button(QDialogButtonBox::Ok); - if(itemId) + if (itemId) { okBut->setToolTip(QString()); okBut->setEnabled(true); - }else{ + } + else + { okBut->setToolTip(tr("In order to proceed you must select a valid item.")); okBut->setEnabled(false); } diff --git a/src/utils/delegates/sql/chooseitemdlg.h b/src/utils/delegates/sql/chooseitemdlg.h index 6186e0f..173e2a8 100644 --- a/src/utils/delegates/sql/chooseitemdlg.h +++ b/src/utils/delegates/sql/chooseitemdlg.h @@ -35,16 +35,19 @@ class ChooseItemDlg : public QDialog { Q_OBJECT public: - typedef std::function Callback; + typedef std::function Callback; ChooseItemDlg(ISqlFKMatchModel *matchModel, QWidget *parent); - void setDescription(const QString& text); - void setPlaceholder(const QString& text); + void setDescription(const QString &text); + void setPlaceholder(const QString &text); void setCallback(const Callback &callback); - inline db_id getItemId() const { return itemId; } + inline db_id getItemId() const + { + return itemId; + } public slots: void done(int res) override; diff --git a/src/utils/delegates/sql/customcompletionlineedit.cpp b/src/utils/delegates/sql/customcompletionlineedit.cpp index 64b6a89..9c875ba 100644 --- a/src/utils/delegates/sql/customcompletionlineedit.cpp +++ b/src/utils/delegates/sql/customcompletionlineedit.cpp @@ -70,20 +70,20 @@ CustomCompletionLineEdit::~CustomCompletionLineEdit() void CustomCompletionLineEdit::showPopup() { - if(isReadOnly() || popup->isVisible()) + if (isReadOnly() || popup->isVisible()) return; popup->move(mapToGlobal(QPoint(0, height()))); popup->resize(width(), height() * 4); popup->setFocus(); popup->show(); - if(model) + if (model) model->refreshData(); } -bool CustomCompletionLineEdit::getData(db_id &idOut, QString& nameOut) const +bool CustomCompletionLineEdit::getData(db_id &idOut, QString &nameOut) const { - idOut = dataId; + idOut = dataId; nameOut = text(); return dataId != 0; @@ -91,12 +91,12 @@ bool CustomCompletionLineEdit::getData(db_id &idOut, QString& nameOut) const void CustomCompletionLineEdit::setData(db_id id, const QString &name) { - if(model && id && name.isEmpty()) + if (model && id && name.isEmpty()) setText(model->getName(id)); else setText(name); - if(id == dataId) + if (id == dataId) return; dataId = id; @@ -105,20 +105,22 @@ void CustomCompletionLineEdit::setData(db_id id, const QString &name) void CustomCompletionLineEdit::setModel(ISqlFKMatchModel *m) { - if(model) - disconnect(model, &ISqlFKMatchModel::resultsReady, this, &CustomCompletionLineEdit::resultsReady); + if (model) + disconnect(model, &ISqlFKMatchModel::resultsReady, this, + &CustomCompletionLineEdit::resultsReady); model = m; popup->setModel(model); - if(model) + if (model) { - connect(model, &ISqlFKMatchModel::resultsReady, this, &CustomCompletionLineEdit::resultsReady); + connect(model, &ISqlFKMatchModel::resultsReady, this, + &CustomCompletionLineEdit::resultsReady); - //Force reloading of current entry + // Force reloading of current entry setData(dataId, QString()); - if(popup->isVisible()) + if (popup->isVisible()) { model->autoSuggest(text()); model->refreshData(); @@ -128,11 +130,11 @@ void CustomCompletionLineEdit::setModel(ISqlFKMatchModel *m) void CustomCompletionLineEdit::timerEvent(QTimerEvent *e) { - if(suggestionsTimerId && e->timerId() == suggestionsTimerId) + if (suggestionsTimerId && e->timerId() == suggestionsTimerId) { stopSuggestionsTimer(); - if(model) + if (model) { model->autoSuggest(text()); showPopup(); @@ -158,7 +160,7 @@ bool CustomCompletionLineEdit::eventFilter(QObject *obj, QEvent *ev) if (ev->type() == QEvent::MouseButtonPress) { popup->hide(); - if(model) + if (model) model->clearCache(); setFocus(); return true; @@ -167,7 +169,7 @@ bool CustomCompletionLineEdit::eventFilter(QObject *obj, QEvent *ev) if (ev->type() == QEvent::KeyPress) { bool consumed = false; - int key = static_cast(ev)->key(); + int key = static_cast(ev)->key(); switch (key) { case Qt::Key_Enter: @@ -179,7 +181,7 @@ bool CustomCompletionLineEdit::eventFilter(QObject *obj, QEvent *ev) case Qt::Key_Escape: setFocus(); popup->hide(); - if(model) + if (model) model->clearCache(); consumed = true; break; @@ -196,7 +198,7 @@ bool CustomCompletionLineEdit::eventFilter(QObject *obj, QEvent *ev) setFocus(); event(ev); popup->hide(); - if(model) + if (model) model->clearCache(); break; } @@ -207,13 +209,13 @@ bool CustomCompletionLineEdit::eventFilter(QObject *obj, QEvent *ev) return false; } -void CustomCompletionLineEdit::doneCompletion(const QModelIndex& idx) +void CustomCompletionLineEdit::doneCompletion(const QModelIndex &idx) { stopSuggestionsTimer(); - if(model) + if (model) { - if(idx.row() >= 0 && !model->isEmptyRow(idx.row()) && !model->isEllipsesRow(idx.row())) + if (idx.row() >= 0 && !model->isEmptyRow(idx.row()) && !model->isEllipsesRow(idx.row())) { setData(model->getIdAtRow(idx.row()), model->getNameAtRow(idx.row())); emit indexSelected(idx); @@ -240,7 +242,7 @@ void CustomCompletionLineEdit::startSuggestionsTimer() void CustomCompletionLineEdit::stopSuggestionsTimer() { - if(suggestionsTimerId) + if (suggestionsTimerId) { killTimer(suggestionsTimerId); suggestionsTimerId = 0; @@ -255,19 +257,19 @@ void CustomCompletionLineEdit::resultsReady(bool forceFirst) void CustomCompletionLineEdit::resizeColumnToContents() { - if(!model) + if (!model) return; const int colCount = model->columnCount(); - for(int i = 0; i < colCount; i++) + for (int i = 0; i < colCount; i++) popup->resizeColumnToContents(i); } void CustomCompletionLineEdit::selectFirstIndexOrNone(bool forceFirst) { - QModelIndex idx; //Invalid index (no item chosen, empty text) - if(model && (dataId || forceFirst)) - idx = model->index(0, 0); //Select the chosen item + QModelIndex idx; // Invalid index (no item chosen, empty text) + if (model && (dataId || forceFirst)) + idx = model->index(0, 0); // Select the chosen item popup->setCurrentIndex(idx); } diff --git a/src/utils/delegates/sql/customcompletionlineedit.h b/src/utils/delegates/sql/customcompletionlineedit.h index cc0863e..951b0ee 100644 --- a/src/utils/delegates/sql/customcompletionlineedit.h +++ b/src/utils/delegates/sql/customcompletionlineedit.h @@ -39,7 +39,7 @@ public: bool getData(db_id &idOut, QString &nameOut) const; - void setData(db_id id, const QString& name = QString()); + void setData(db_id id, const QString &name = QString()); void setModel(ISqlFKMatchModel *m); @@ -49,7 +49,7 @@ public: signals: void completionDone(CustomCompletionLineEdit *self); void dataIdChanged(db_id id); - void indexSelected(const QModelIndex& idx); + void indexSelected(const QModelIndex &idx); public slots: void setData_slot(db_id id); diff --git a/src/utils/delegates/sql/filterheaderlineedit.cpp b/src/utils/delegates/sql/filterheaderlineedit.cpp index bf1744e..e76c5cc 100644 --- a/src/utils/delegates/sql/filterheaderlineedit.cpp +++ b/src/utils/delegates/sql/filterheaderlineedit.cpp @@ -34,10 +34,10 @@ FilterHeaderLineEdit::FilterHeaderLineEdit(int col, QWidget *parent) : setPlaceholderText(tr("Filter")); setClearButtonEnabled(true); - //Delay text changed until user stops typing + // Delay text changed until user stops typing connect(this, &QLineEdit::textEdited, this, &FilterHeaderLineEdit::startTextTimer); - //Bypass timer when losing focus or pressing Enter + // Bypass timer when losing focus or pressing Enter connect(this, &QLineEdit::editingFinished, this, &FilterHeaderLineEdit::delayedTimerFinished); actionFilterNull = new QAction(tr("Filter #NULL"), this); @@ -71,7 +71,7 @@ void FilterHeaderLineEdit::startTextTimer() void FilterHeaderLineEdit::stopTextTimer() { - if(m_textTimerId) + if (m_textTimerId) { killTimer(m_textTimerId); m_textTimerId = 0; @@ -81,7 +81,7 @@ void FilterHeaderLineEdit::stopTextTimer() void FilterHeaderLineEdit::delayedTimerFinished() { stopTextTimer(); - if(lastValue != text()) + if (lastValue != text()) { lastValue = text(); emit delayedTextChanged(this, lastValue); @@ -90,17 +90,17 @@ void FilterHeaderLineEdit::delayedTimerFinished() void FilterHeaderLineEdit::setNULLFilter() { - if(!m_allowNull) + if (!m_allowNull) return; setText(IPagedItemModel::nullFilterStr); - delayedTimerFinished(); //Skip timer, emit now + delayedTimerFinished(); // Skip timer, emit now } bool FilterHeaderLineEdit::event(QEvent *e) { - if(e->type() == QEvent::ToolTip) + if (e->type() == QEvent::ToolTip) { - //Send tooltip request to FilterHeaderView + // Send tooltip request to FilterHeaderView QHelpEvent *ev = static_cast(e); emit tooltipRequested(this, ev->globalPos()); return true; @@ -111,7 +111,7 @@ bool FilterHeaderLineEdit::event(QEvent *e) void FilterHeaderLineEdit::timerEvent(QTimerEvent *e) { - if(e->timerId() == m_textTimerId) + if (e->timerId() == m_textTimerId) { delayedTimerFinished(); return; @@ -127,7 +127,7 @@ void FilterHeaderLineEdit::contextMenuEvent(QContextMenuEvent *e) QAction *firstAction = menu->actions().value(0, nullptr); menu->insertAction(firstAction, actionFilterNull); - if(firstAction) + if (firstAction) menu->insertSeparator(firstAction); menu->popup(e->globalPos()); } diff --git a/src/utils/delegates/sql/filterheaderlineedit.h b/src/utils/delegates/sql/filterheaderlineedit.h index e23082d..440e0f7 100644 --- a/src/utils/delegates/sql/filterheaderlineedit.h +++ b/src/utils/delegates/sql/filterheaderlineedit.h @@ -36,16 +36,22 @@ public: FilterHeaderLineEdit(int col, QWidget *parent = nullptr); ~FilterHeaderLineEdit(); - void updateTextWithoutEmitting(const QString& str); + void updateTextWithoutEmitting(const QString &str); - inline int getColumn() const { return m_column; } + inline int getColumn() const + { + return m_column; + } - inline int allowNull() const { return m_allowNull; } + inline int allowNull() const + { + return m_allowNull; + } void setAllowNull(bool val); signals: - void delayedTextChanged(FilterHeaderLineEdit *self, const QString& str); - void tooltipRequested(FilterHeaderLineEdit *self, const QPoint& globalPos); + void delayedTextChanged(FilterHeaderLineEdit *self, const QString &str); + void tooltipRequested(FilterHeaderLineEdit *self, const QPoint &globalPos); private slots: void startTextTimer(); diff --git a/src/utils/delegates/sql/filterheaderview.cpp b/src/utils/delegates/sql/filterheaderview.cpp index a66f47c..9276576 100644 --- a/src/utils/delegates/sql/filterheaderview.cpp +++ b/src/utils/delegates/sql/filterheaderview.cpp @@ -41,7 +41,8 @@ FilterHeaderView::FilterHeaderView(QWidget *parent) : // Highlight column headers of selected cells to emulate spreadsheet behaviour setHighlightSections(true); - // Do some connects: Basically just resize and reposition the input widgets whenever anything changes + // Do some connects: Basically just resize and reposition the input widgets whenever anything + // changes connect(this, &FilterHeaderView::sectionResized, this, &FilterHeaderView::adjustPositions); connect(this, &FilterHeaderView::sectionClicked, this, &FilterHeaderView::updateSoring); @@ -54,25 +55,25 @@ void FilterHeaderView::generateFilters() { bool needsUpdateGeo = false; - IPagedItemModel *m = qobject_cast(model()); - if(m) + IPagedItemModel *m = qobject_cast(model()); + if (m) { - int i = 0; + int i = 0; const int columnCount = m->columnCount(); - for(int col = 0; col < columnCount; col++) + for (int col = 0; col < columnCount; col++) { auto filter = m->getFilterAtCol(col); - if(!filter.second.testFlag(IPagedItemModel::FilterFlag::BasicFiltering)) + if (!filter.second.testFlag(IPagedItemModel::FilterFlag::BasicFiltering)) { - //No filtering for this column - for(; i < filterWidgets.size(); i++) + // No filtering for this column + for (; i < filterWidgets.size(); i++) { - if(filterWidgets.at(i)->getColumn() > col) - break; //We went past + if (filterWidgets.at(i)->getColumn() > col) + break; // We went past - if(filterWidgets.at(i)->getColumn() == col) + if (filterWidgets.at(i)->getColumn() == col) { - //Remove old filter + // Remove old filter delete filterWidgets.takeAt(i); i--; } @@ -80,24 +81,26 @@ void FilterHeaderView::generateFilters() continue; } - FilterHeaderLineEdit* filterEdit = nullptr; - for(; i < filterWidgets.size(); i++) + FilterHeaderLineEdit *filterEdit = nullptr; + for (; i < filterWidgets.size(); i++) { - if(filterWidgets.at(i)->getColumn() > col) - break; //We went past + if (filterWidgets.at(i)->getColumn() > col) + break; // We went past - if(filterWidgets.at(i)->getColumn() == col) + if (filterWidgets.at(i)->getColumn() == col) { filterEdit = filterWidgets.at(i); break; } } - if(!filterEdit) + if (!filterEdit) { filterEdit = new FilterHeaderLineEdit(col, this); - connect(filterEdit, &FilterHeaderLineEdit::delayedTextChanged, this, &FilterHeaderView::inputChanged); - connect(filterEdit, &FilterHeaderLineEdit::tooltipRequested, this, &FilterHeaderView::showColumnTooltip); + connect(filterEdit, &FilterHeaderLineEdit::delayedTextChanged, this, + &FilterHeaderView::inputChanged); + connect(filterEdit, &FilterHeaderLineEdit::tooltipRequested, this, + &FilterHeaderView::showColumnTooltip); filterWidgets.insert(i, filterEdit); needsUpdateGeo = true; } @@ -106,7 +109,7 @@ void FilterHeaderView::generateFilters() filterEdit->setAllowNull(filter.second.testFlag(IPagedItemModel::ExplicitNULL)); } - //Update sorting + // Update sorting setSortIndicator(m->getSortingColumn(), Qt::AscendingOrder); } else @@ -115,7 +118,7 @@ void FilterHeaderView::generateFilters() filterWidgets.clear(); } - if(needsUpdateGeo || filterWidgets.isEmpty()) + if (needsUpdateGeo || filterWidgets.isEmpty()) { // Position them correctly updateGeometries(); @@ -124,17 +127,20 @@ void FilterHeaderView::generateFilters() QSize FilterHeaderView::sizeHint() const { - // For the size hint just take the value of the standard implementation and add the height of a input widget to it if necessary + // For the size hint just take the value of the standard implementation and add the height of a + // input widget to it if necessary QSize s = QHeaderView::sizeHint(); - if(filterWidgets.size()) - s.setHeight(s.height() + filterWidgets.at(0)->sizeHint().height() + 4); // The 4 adds just adds some extra space + if (filterWidgets.size()) + s.setHeight(s.height() + filterWidgets.at(0)->sizeHint().height() + + 4); // The 4 adds just adds some extra space return s; } void FilterHeaderView::updateGeometries() { - // If there are any input widgets add a viewport margin to the header to generate some empty space for them which is not affected by scrolling - if(filterWidgets.size()) + // If there are any input widgets add a viewport margin to the header to generate some empty + // space for them which is not affected by scrolling + if (filterWidgets.size()) setViewportMargins(0, 0, 0, filterWidgets.at(0)->sizeHint().height()); else setViewportMargins(0, 0, 0, 0); @@ -148,19 +154,19 @@ void FilterHeaderView::adjustPositions() { int y = QHeaderView::sizeHint().height(); - //Sometimes it's 0 when recursion happen, skip moving widgets to avoid flickering - if(y == 0) + // Sometimes it's 0 when recursion happen, skip moving widgets to avoid flickering + if (y == 0) return; // The two adds some extra space between the header label and the input widget y += 2; // Loop through all widgets - for(int i = 0; i < filterWidgets.size(); ++i) + for (int i = 0; i < filterWidgets.size(); ++i) { // Get the current widget, move it and resize it - FilterHeaderLineEdit* w = filterWidgets.at(i); - const int col = w->getColumn(); + FilterHeaderLineEdit *w = filterWidgets.at(i); + const int col = w->getColumn(); if (QApplication::layoutDirection() == Qt::RightToLeft) w->move(width() - (sectionPosition(col) + sectionSize(col) - offset()), y); else @@ -169,13 +175,14 @@ void FilterHeaderView::adjustPositions() } } -void FilterHeaderView::inputChanged(FilterHeaderLineEdit *w, const QString& new_value) +void FilterHeaderView::inputChanged(FilterHeaderLineEdit *w, const QString &new_value) { - // Just get the column number and the new value and send them to anybody interested in filter changes + // Just get the column number and the new value and send them to anybody interested in filter + // changes emit filterChanged(w->getColumn(), new_value); IPagedItemModel *m = qobject_cast(model()); - if(!m) + if (!m) return; m->setFilterAtCol(w->getColumn(), new_value); @@ -186,22 +193,22 @@ void FilterHeaderView::showColumnTooltip(FilterHeaderLineEdit *w, const QPoint & { int col = w->getColumn(); QString str; - if(w->allowNull()) + if (w->allowNull()) str = tr("Type #NULL to filter empty cells."); QString modelTooltip; - if(model()) //Get model header tooltip at requested column + if (model()) // Get model header tooltip at requested column modelTooltip = model()->headerData(col, Qt::Horizontal, Qt::ToolTipRole).toString(); - if(!modelTooltip.isEmpty()) + if (!modelTooltip.isEmpty()) { - if(!str.isEmpty()) - str.append(QLatin1String("

")); //Separate with a line between - modelTooltip.replace('\n', QLatin1String("
")); //Use HTML line break + if (!str.isEmpty()) + str.append(QLatin1String("

")); // Separate with a line between + modelTooltip.replace('\n', QLatin1String("
")); // Use HTML line break str.append(modelTooltip); } - if(str.isEmpty()) + if (str.isEmpty()) QToolTip::hideText(); else QToolTip::showText(globalPos, str, w); @@ -209,16 +216,16 @@ void FilterHeaderView::showColumnTooltip(FilterHeaderLineEdit *w, const QPoint & void FilterHeaderView::clearFilters() { - for(FilterHeaderLineEdit* filterLineEdit : qAsConst(filterWidgets)) + for (FilterHeaderLineEdit *filterLineEdit : qAsConst(filterWidgets)) filterLineEdit->clear(); } -void FilterHeaderView::setFilter(int column, const QString& value) +void FilterHeaderView::setFilter(int column, const QString &value) { Q_UNUSED(value) - for(FilterHeaderLineEdit* filterLineEdit : qAsConst(filterWidgets)) + for (FilterHeaderLineEdit *filterLineEdit : qAsConst(filterWidgets)) { - if(filterLineEdit->getColumn() == column) + if (filterLineEdit->getColumn() == column) { filterLineEdit->clear(); break; @@ -229,7 +236,7 @@ void FilterHeaderView::setFilter(int column, const QString& value) void FilterHeaderView::updateSoring(int col) { IPagedItemModel *m = qobject_cast(model()); - if(!m) + if (!m) return; m->setSortingColumn(col); @@ -238,9 +245,9 @@ void FilterHeaderView::updateSoring(int col) QString FilterHeaderView::filterValue(int column) const { - for(FilterHeaderLineEdit* filterLineEdit : qAsConst(filterWidgets)) + for (FilterHeaderLineEdit *filterLineEdit : qAsConst(filterWidgets)) { - if(filterLineEdit->getColumn() == column) + if (filterLineEdit->getColumn() == column) { return filterLineEdit->text(); } @@ -253,32 +260,36 @@ void FilterHeaderView::installOnTable(QTableView *view) { view->setHorizontalHeader(this); - connect(view->horizontalScrollBar(), &QScrollBar::valueChanged, this, &FilterHeaderView::adjustPositions); - connect(view->verticalScrollBar(), &QScrollBar::valueChanged, this, &FilterHeaderView::adjustPositions); + connect(view->horizontalScrollBar(), &QScrollBar::valueChanged, this, + &FilterHeaderView::adjustPositions); + connect(view->verticalScrollBar(), &QScrollBar::valueChanged, this, + &FilterHeaderView::adjustPositions); // Disconnect clicking in header to select column, since we will use it for sorting. // Note that, in order to work, this cannot be converted to the standard C++11 format. disconnect(this, SIGNAL(sectionPressed(int)), view, SLOT(selectColumn(int))); disconnect(this, SIGNAL(sectionEntered(int)), view, SLOT(_q_selectColumn(int))); - //Must be enabled again because QTableView disables it if sorting not enabled in QTableView + // Must be enabled again because QTableView disables it if sorting not enabled in QTableView setSortIndicatorShown(true); } void FilterHeaderView::setModel(QAbstractItemModel *m) { IPagedItemModel *pagedModel = qobject_cast(model()); - if(pagedModel) + if (pagedModel) { - disconnect(pagedModel, &IPagedItemModel::filterChanged, this, &FilterHeaderView::generateFilters); + disconnect(pagedModel, &IPagedItemModel::filterChanged, this, + &FilterHeaderView::generateFilters); } QHeaderView::setModel(m); pagedModel = qobject_cast(model()); - if(pagedModel) + if (pagedModel) { - connect(pagedModel, &IPagedItemModel::filterChanged, this, &FilterHeaderView::generateFilters); + connect(pagedModel, &IPagedItemModel::filterChanged, this, + &FilterHeaderView::generateFilters); } generateFilters(); diff --git a/src/utils/delegates/sql/filterheaderview.h b/src/utils/delegates/sql/filterheaderview.h index 7c0dab6..e5769fd 100644 --- a/src/utils/delegates/sql/filterheaderview.h +++ b/src/utils/delegates/sql/filterheaderview.h @@ -38,12 +38,15 @@ class FilterHeaderView : public QHeaderView { Q_OBJECT public: - explicit FilterHeaderView(QWidget* parent = nullptr); + explicit FilterHeaderView(QWidget *parent = nullptr); QSize sizeHint() const override; void setModel(QAbstractItemModel *m) override; - bool hasFilters() const { return (filterWidgets.size() > 0); } + bool hasFilters() const + { + return (filterWidgets.size() > 0); + } QString filterValue(int column) const; void installOnTable(QTableView *view); @@ -52,18 +55,18 @@ public slots: void generateFilters(); void adjustPositions(); void clearFilters(); - void setFilter(int column, const QString& value); + void setFilter(int column, const QString &value); void updateSoring(int col); signals: - void filterChanged(int column, const QString& value); + void filterChanged(int column, const QString &value); protected: void updateGeometries() override; private slots: - void inputChanged(FilterHeaderLineEdit *w, const QString& new_value); - void showColumnTooltip(FilterHeaderLineEdit *w, const QPoint& globalPos); + void inputChanged(FilterHeaderLineEdit *w, const QString &new_value); + void showColumnTooltip(FilterHeaderLineEdit *w, const QPoint &globalPos); private: QVector filterWidgets; diff --git a/src/utils/delegates/sql/imatchmodelfactory.cpp b/src/utils/delegates/sql/imatchmodelfactory.cpp index ca66736..77cb69e 100644 --- a/src/utils/delegates/sql/imatchmodelfactory.cpp +++ b/src/utils/delegates/sql/imatchmodelfactory.cpp @@ -22,5 +22,4 @@ IMatchModelFactory::IMatchModelFactory(QObject *parent) : QObject(parent) { - } diff --git a/src/utils/delegates/sql/isqlfkmatchmodel.cpp b/src/utils/delegates/sql/isqlfkmatchmodel.cpp index 22efeda..06d994b 100644 --- a/src/utils/delegates/sql/isqlfkmatchmodel.cpp +++ b/src/utils/delegates/sql/isqlfkmatchmodel.cpp @@ -28,7 +28,6 @@ ISqlFKMatchModel::ISqlFKMatchModel(QObject *parent) : hasEmptyRow(true), size(0) { - } int ISqlFKMatchModel::rowCount(const QModelIndex &parent) const @@ -43,12 +42,10 @@ int ISqlFKMatchModel::columnCount(const QModelIndex &parent) const void ISqlFKMatchModel::refreshData() { - } void ISqlFKMatchModel::clearCache() { - } QString ISqlFKMatchModel::getName(db_id /*id*/) const @@ -64,7 +61,7 @@ QFont initBoldFont() return f; } -//static +// static QVariant ISqlFKMatchModel::boldFont() { static QFont emptyRowF = initBoldFont(); diff --git a/src/utils/delegates/sql/isqlfkmatchmodel.h b/src/utils/delegates/sql/isqlfkmatchmodel.h index 569e8a7..810652d 100644 --- a/src/utils/delegates/sql/isqlfkmatchmodel.h +++ b/src/utils/delegates/sql/isqlfkmatchmodel.h @@ -23,7 +23,7 @@ #include #include "utils/types.h" -#define MaxMatchItems 10 //TODO: use constexpr +#define MaxMatchItems 10 // TODO: use constexpr class ISqlFKMatchModel : public QAbstractTableModel { @@ -34,7 +34,7 @@ public: int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; - virtual void autoSuggest(const QString& text) = 0; + virtual void autoSuggest(const QString &text) = 0; virtual void refreshData(); virtual void clearCache(); @@ -42,17 +42,18 @@ public: inline bool isEmptyRow(int row) const { - //If it's last row and there isn't '...' or if it's just before '...' - return hasEmptyRow && (row == EllipsesRow - 1 || (size < MaxMatchItems + 2 && row == size - 1)); + // If it's last row and there isn't '...' or if it's just before '...' + return hasEmptyRow + && (row == EllipsesRow - 1 || (size < MaxMatchItems + 2 && row == size - 1)); } inline bool isEllipsesRow(int row) const { - //If there isn't 'Empty' row, ellipses come 1 row before EllipsesRow + // If there isn't 'Empty' row, ellipses come 1 row before EllipsesRow return row == (EllipsesRow - (hasEmptyRow ? 0 : 1)); } - virtual db_id getIdAtRow(int row) const = 0; + virtual db_id getIdAtRow(int row) const = 0; virtual QString getNameAtRow(int row) const = 0; void setHasEmptyRow(bool value); @@ -68,11 +69,12 @@ protected: bool hasEmptyRow; public: - enum { + enum + { EllipsesRow = MaxMatchItems + 1 //(10 items + Empty + ...) - //Items: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - //Empty: 10 - //Ellipses: 11 + // Items: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + // Empty: 10 + // Ellipses: 11 }; int size; }; diff --git a/src/utils/delegates/sql/modelpageswitcher.cpp b/src/utils/delegates/sql/modelpageswitcher.cpp index 4c61b78..202f21d 100644 --- a/src/utils/delegates/sql/modelpageswitcher.cpp +++ b/src/utils/delegates/sql/modelpageswitcher.cpp @@ -36,35 +36,40 @@ ModelPageSwitcher::ModelPageSwitcher(bool autoHide, QWidget *parent) : { QHBoxLayout *lay = new QHBoxLayout(this); - prevBut = new QPushButton(autoHideMode ? QChar('<') : tr("Prev")); - nextBut = new QPushButton(autoHideMode ? QChar('>') : tr("Next")); + prevBut = new QPushButton(autoHideMode ? QChar('<') : tr("Prev")); + nextBut = new QPushButton(autoHideMode ? QChar('>') : tr("Next")); - //NOTE: use released() instead of clicked() and QueuedConnection because prevBut and nextBut might get disabled - // after switching the page and there is an artifact if it is disabled while being clicked so defer disabling - connect(prevBut, &QPushButton::released, this, &ModelPageSwitcher::prevPage, Qt::QueuedConnection); - connect(nextBut, &QPushButton::released, this, &ModelPageSwitcher::nextPage, Qt::QueuedConnection); + // NOTE: use released() instead of clicked() and QueuedConnection because prevBut and nextBut + // might get disabled + // after switching the page and there is an artifact if it is disabled while being clicked + // so defer disabling + connect(prevBut, &QPushButton::released, this, &ModelPageSwitcher::prevPage, + Qt::QueuedConnection); + connect(nextBut, &QPushButton::released, this, &ModelPageSwitcher::nextPage, + Qt::QueuedConnection); pageSpin = new QSpinBox; pageSpin->setMinimum(1); pageSpin->setKeyboardTracking(false); - if(autoHideMode) + if (autoHideMode) { - connect(pageSpin, static_cast(&QSpinBox::valueChanged), this, &ModelPageSwitcher::goToPage); + connect(pageSpin, static_cast(&QSpinBox::valueChanged), this, + &ModelPageSwitcher::goToPage); } else { statusLabel = new QLabel; statusLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - goToPageBut = new QPushButton(tr("Go")); + goToPageBut = new QPushButton(tr("Go")); refreshModelBut = new QPushButton(tr("Refresh")); connect(goToPageBut, &QPushButton::clicked, this, &ModelPageSwitcher::goToPage); connect(refreshModelBut, &QPushButton::clicked, this, &ModelPageSwitcher::refreshModel); } - //Layout - if(autoHideMode) + // Layout + if (autoHideMode) { lay->addWidget(prevBut); lay->addWidget(pageSpin); @@ -84,21 +89,27 @@ ModelPageSwitcher::ModelPageSwitcher(bool autoHide, QWidget *parent) : void ModelPageSwitcher::setModel(IPagedItemModel *m) { - if(model) + if (model) { - disconnect(model, &IPagedItemModel::totalItemsCountChanged, this, &ModelPageSwitcher::totalItemCountChanged); - disconnect(model, &IPagedItemModel::pageCountChanged, this, &ModelPageSwitcher::pageCountChanged); - disconnect(model, &IPagedItemModel::currentPageChanged, this, &ModelPageSwitcher::currentPageChanged); + disconnect(model, &IPagedItemModel::totalItemsCountChanged, this, + &ModelPageSwitcher::totalItemCountChanged); + disconnect(model, &IPagedItemModel::pageCountChanged, this, + &ModelPageSwitcher::pageCountChanged); + disconnect(model, &IPagedItemModel::currentPageChanged, this, + &ModelPageSwitcher::currentPageChanged); disconnect(model, &IPagedItemModel::destroyed, this, &ModelPageSwitcher::onModelDestroyed); } model = m; - if(model) + if (model) { - connect(model, &IPagedItemModel::totalItemsCountChanged, this, &ModelPageSwitcher::totalItemCountChanged); - connect(model, &IPagedItemModel::pageCountChanged, this, &ModelPageSwitcher::pageCountChanged); - connect(model, &IPagedItemModel::currentPageChanged, this, &ModelPageSwitcher::currentPageChanged); + connect(model, &IPagedItemModel::totalItemsCountChanged, this, + &ModelPageSwitcher::totalItemCountChanged); + connect(model, &IPagedItemModel::pageCountChanged, this, + &ModelPageSwitcher::pageCountChanged); + connect(model, &IPagedItemModel::currentPageChanged, this, + &ModelPageSwitcher::currentPageChanged); connect(model, &IPagedItemModel::destroyed, this, &ModelPageSwitcher::onModelDestroyed); recalcPages(); @@ -127,35 +138,35 @@ void ModelPageSwitcher::currentPageChanged() void ModelPageSwitcher::recalcText() { - if(!statusLabel) + if (!statusLabel) return; statusLabel->setText(tr("Page %1/%2 (%3 items)") - .arg(model->currentPage() + 1) - .arg(model->getPageCount()) - .arg(model->getTotalItemsCount())); + .arg(model->currentPage() + 1) + .arg(model->getPageCount()) + .arg(model->getTotalItemsCount())); } void ModelPageSwitcher::recalcPages() { int curPage = model->currentPage(); - int count = model->getPageCount(); - if(count == 0) + int count = model->getPageCount(); + if (count == 0) count = 1; pageSpin->setMaximum(count); prevBut->setEnabled(curPage > 0); nextBut->setEnabled(curPage < count - 1); - //NOTE: redraw to avoid artifact like disabled but still highlighted + // NOTE: redraw to avoid artifact like disabled but still highlighted prevBut->update(); nextBut->update(); - if(autoHideMode) + if (autoHideMode) { pageSpin->setValue(curPage + 1); - if(count == 1) + if (count == 1) hide(); else show(); @@ -166,25 +177,25 @@ void ModelPageSwitcher::recalcPages() void ModelPageSwitcher::prevPage() { - if(model) + if (model) model->switchToPage(model->currentPage() - 1); } void ModelPageSwitcher::nextPage() { - if(model) + if (model) model->switchToPage(model->currentPage() + 1); } void ModelPageSwitcher::goToPage() { - if(model) + if (model) model->switchToPage(pageSpin->value() - 1); } void ModelPageSwitcher::refreshModel() { - if(model) + if (model) { model->refreshData(true); } diff --git a/src/utils/delegates/sql/pageditemmodel.cpp b/src/utils/delegates/sql/pageditemmodel.cpp index 57b39b0..c2c0cdb 100644 --- a/src/utils/delegates/sql/pageditemmodel.cpp +++ b/src/utils/delegates/sql/pageditemmodel.cpp @@ -31,18 +31,17 @@ IPagedItemModel::IPagedItemModel(const int itemsPerPage, sqlite3pp::database &db sortColumn(0), ItemsPerPage(itemsPerPage) { - } void IPagedItemModel::refreshData(bool forceUpdate) { - if(!mDb.db()) + if (!mDb.db()) return; - emit itemsReady(-1, -1); //Notify we are about to refresh + emit itemsReady(-1, -1); // Notify we are about to refresh qint64 count = recalcTotalItemCount(); - if(count != totalItemsCount || forceUpdate) + if (count != totalItemsCount || forceUpdate) { beginResetModel(); @@ -50,12 +49,12 @@ void IPagedItemModel::refreshData(bool forceUpdate) totalItemsCount = count; emit totalItemsCountChanged(totalItemsCount); - //Round up division + // Round up division const int rem = count % ItemsPerPage; - pageCount = count / ItemsPerPage + (rem != 0); + pageCount = count / ItemsPerPage + (rem != 0); emit pageCountChanged(pageCount); - if(curPage >= pageCount) + if (curPage >= pageCount) { switchToPage(pageCount - 1); } @@ -68,7 +67,7 @@ void IPagedItemModel::refreshData(bool forceUpdate) void IPagedItemModel::setSortingColumn(int col) { - //Do nothing, it must be reimplemented + // Do nothing, it must be reimplemented Q_UNUSED(col) } @@ -94,15 +93,15 @@ int IPagedItemModel::currentPage() void IPagedItemModel::switchToPage(int page) { - if(curPage == page || page < 0 || page >= pageCount) + if (curPage == page || page < 0 || page >= pageCount) return; clearCache(); - curPage = page; + curPage = page; - const int rem = totalItemsCount % ItemsPerPage; + const int rem = totalItemsCount % ItemsPerPage; const int items = (curPage == pageCount - 1 && rem) ? rem : ItemsPerPage; - if(items != curItemCount) + if (items != curItemCount) { beginResetModel(); curItemCount = items; @@ -112,7 +111,7 @@ void IPagedItemModel::switchToPage(int page) emit currentPageChanged(curPage); QModelIndex first = index(0, 0); - QModelIndex last = index(curItemCount - 1, columnCount() - 1); + QModelIndex last = index(curItemCount - 1, columnCount() - 1); emit dataChanged(first, last); } @@ -133,12 +132,12 @@ void IPagedItemModel::clearCache_slot() { clearCache(); QModelIndex start = index(0, 0); - QModelIndex end = index(rowCount() - 1, columnCount() - 1); + QModelIndex end = index(rowCount() - 1, columnCount() - 1); emit dataChanged(start, end); } qint64 IPagedItemModel::recalcTotalItemCount() { - //NOTE: either override this or refreshData() - return 0; //Default implementation + // NOTE: either override this or refreshData() + return 0; // Default implementation } diff --git a/src/utils/delegates/sql/pageditemmodel.h b/src/utils/delegates/sql/pageditemmodel.h index 715608a..640adec 100644 --- a/src/utils/delegates/sql/pageditemmodel.h +++ b/src/utils/delegates/sql/pageditemmodel.h @@ -39,7 +39,10 @@ class IPagedItemModel : public QAbstractTableModel public: IPagedItemModel(const int itemsPerPage, sqlite3pp::database &db, QObject *parent = nullptr); - inline sqlite3pp::database &getDb() const { return mDb; } + inline sqlite3pp::database &getDb() const + { + return mDb; + } // Cached rows management virtual void clearCache() = 0; @@ -57,7 +60,7 @@ public: int currentPage(); void switchToPage(int page); - //Filter + // Filter /*! * \brief nullFilterStr @@ -76,9 +79,10 @@ public: */ enum FilterFlag { - NoFiltering = 0, /*!< This column doesn't support filtering, do not show filter */ + NoFiltering = 0, /*!< This column doesn't support filtering, do not show filter */ BasicFiltering = 1, /*!< This column supports filtering, show filter */ - ExplicitNULL = (1<<1) /*!< This column can be filtered with "\#NULL" string \sa nullFilterStr */ + ExplicitNULL = + (1 << 1) /*!< This column can be filtered with "\#NULL" string \sa nullFilterStr */ }; typedef QFlags FilterFlags; @@ -109,14 +113,14 @@ public: * \sa refreshData() * \sa FilterHeaderView */ - virtual bool setFilterAtCol(int col, const QString& str); + virtual bool setFilterAtCol(int col, const QString &str); signals: - void modelError(const QString& msg); + void modelError(const QString &msg); // Items signals void totalItemsCountChanged(qint64 count); - void itemsReady(int startRow, int endRow); //In local indices + void itemsReady(int startRow, int endRow); // In local indices // Page signals void pageCountChanged(int count); @@ -141,5 +145,4 @@ protected: const int ItemsPerPage; }; - #endif // PAGEDITEMMODEL_H diff --git a/src/utils/delegates/sql/pageditemmodelhelper.h b/src/utils/delegates/sql/pageditemmodelhelper.h index 6ec7f26..e07391f 100644 --- a/src/utils/delegates/sql/pageditemmodelhelper.h +++ b/src/utils/delegates/sql/pageditemmodelhelper.h @@ -36,8 +36,8 @@ template class IPagedItemModelImpl : public IPagedItemModel { protected: - //Get some definition from SuperType so we don't have to pass them as templates - static constexpr int NCols_ = SuperType::NCols; + // Get some definition from SuperType so we don't have to pass them as templates + static constexpr int NCols_ = SuperType::NCols; static constexpr int BatchSize_ = SuperType::BatchSize; public: @@ -65,7 +65,10 @@ protected: { public: static constexpr Type _Type = Type(QEvent::User + 1); - inline ResultEvent() : QEvent(_Type) {} + inline ResultEvent() : + QEvent(_Type) + { + } Cache items; int firstRow; diff --git a/src/utils/delegates/sql/pageditemmodelhelper_impl.h b/src/utils/delegates/sql/pageditemmodelhelper_impl.h index 410788e..41cf998 100644 --- a/src/utils/delegates/sql/pageditemmodelhelper_impl.h +++ b/src/utils/delegates/sql/pageditemmodelhelper_impl.h @@ -27,12 +27,13 @@ #include template -IPagedItemModelImpl::IPagedItemModelImpl(const int itemsPerPage, sqlite3pp::database &db, QObject *parent) - : IPagedItemModel(itemsPerPage, db, parent), +IPagedItemModelImpl::IPagedItemModelImpl(const int itemsPerPage, + sqlite3pp::database &db, + QObject *parent) : + IPagedItemModel(itemsPerPage, db, parent), cacheFirstRow(0), firstPendingRow(-BatchSize_) { - } template @@ -58,7 +59,7 @@ void IPagedItemModelImpl::clearCache() template bool IPagedItemModelImpl::event(QEvent *e) { - if(e->type() == ResultEvent::_Type) + if (e->type() == ResultEvent::_Type) { ResultEvent *ev = static_cast(e); ev->setAccepted(true); @@ -74,39 +75,38 @@ bool IPagedItemModelImpl::event(QEvent *e) template void IPagedItemModelImpl::fetchRow(int row) { - if(firstPendingRow != -BatchSize_) - return; //Currently fetching another batch, wait for it to finish first + if (firstPendingRow != -BatchSize_) + return; // Currently fetching another batch, wait for it to finish first - if(row >= firstPendingRow && row < firstPendingRow + BatchSize_) - return; //Already fetching this batch + if (row >= firstPendingRow && row < firstPendingRow + BatchSize_) + return; // Already fetching this batch - if(row >= cacheFirstRow && row < cacheFirstRow + cache.size()) - return; //Already cached + if (row >= cacheFirstRow && row < cacheFirstRow + cache.size()) + return; // Already cached - //TODO: abort previous fetching here + // TODO: abort previous fetching here const int remainder = row % BatchSize_; - firstPendingRow = row - remainder; + firstPendingRow = row - remainder; qDebug() << "Requested:" << row << "From:" << firstPendingRow; QVariant val; int valRow = 0; - - //TODO: use a custom QRunnable - // QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection, - // Q_ARG(int, firstPendingRow), Q_ARG(int, sortCol), - // Q_ARG(int, valRow), Q_ARG(QVariant, val)); + // TODO: use a custom QRunnable + // QMetaObject::invokeMethod(this, "internalFetch", Qt::QueuedConnection, + // Q_ARG(int, firstPendingRow), Q_ARG(int, sortCol), + // Q_ARG(int, valRow), Q_ARG(QVariant, val)); SuperType *self = static_cast(this); self->internalFetch(firstPendingRow, sortColumn, val.isNull() ? 0 : valRow, val); } -template +template void IPagedItemModelImpl::postResult(const Cache &items, int firstRow) { ResultEvent *ev = new ResultEvent; - ev->items = items; - ev->firstRow = firstRow; + ev->items = items; + ev->firstRow = firstRow; qApp->postEvent(this, ev); } @@ -116,39 +116,42 @@ void IPagedItemModelImpl::handleResult(const Cache &it { Cache itemsCopy = items; - int lastRow = firstRow + itemsCopy.count(); //Last row + 1 extra to re-trigger possible next batch - if(lastRow >= curItemCount) + int lastRow = + firstRow + itemsCopy.count(); // Last row + 1 extra to re-trigger possible next batch + if (lastRow >= curItemCount) { - //Ok, there is no extra row so notify just our batch - lastRow = curItemCount -1; + // Ok, there is no extra row so notify just our batch + lastRow = curItemCount - 1; } - else if(itemsCopy.count() < BatchSize_) + else if (itemsCopy.count() < BatchSize_) { - //Error: fetching returned less rows than expected + // Error: fetching returned less rows than expected - //NOTE: when not on last batch of last page, it should always be of BatchSize_ - // last batch of last page can have less rows + // NOTE: when not on last batch of last page, it should always be of BatchSize_ + // last batch of last page can have less rows emit modelError(IPagedItemModel::tr("Fetching returned less rows than expected.\n" - "%1 instead of %2").arg(itemsCopy.count()).arg(BatchSize_)); + "%1 instead of %2") + .arg(itemsCopy.count()) + .arg(BatchSize_)); - //Insert fake items to prevent triggering re-fetching which leads to infinite loop + // Insert fake items to prevent triggering re-fetching which leads to infinite loop const int expectedCount = qMin(BatchSize_, curItemCount - firstRow); - const int realCount = itemsCopy.count(); + const int realCount = itemsCopy.count(); itemsCopy.insert(realCount, expectedCount - realCount, ModelItemType{}); lastRow = firstRow + itemsCopy.count() - 1; } - if(firstRow == cacheFirstRow + cache.size()) + if (firstRow == cacheFirstRow + cache.size()) { qDebug() << "RES: appending First:" << cacheFirstRow; cache.append(itemsCopy); - if(cache.size() > IPagedItemModel::ItemsPerPage) + if (cache.size() > IPagedItemModel::ItemsPerPage) { - const int extra = cache.size() - IPagedItemModel::ItemsPerPage; //Round up to BatchSize + const int extra = cache.size() - IPagedItemModel::ItemsPerPage; // Round up to BatchSize const int remainder = extra % BatchSize_; - const int n = remainder ? extra + BatchSize_ - remainder : extra; + const int n = remainder ? extra + BatchSize_ - remainder : extra; qDebug() << "RES: removing last" << n; cache.remove(0, n); cacheFirstRow += n; @@ -156,13 +159,13 @@ void IPagedItemModelImpl::handleResult(const Cache &it } else { - if(firstRow + itemsCopy.size() == cacheFirstRow) + if (firstRow + itemsCopy.size() == cacheFirstRow) { qDebug() << "RES: prepending First:" << cacheFirstRow; Cache tmp = itemsCopy; tmp.append(cache); cache = tmp; - if(cache.size() > IPagedItemModel::ItemsPerPage) + if (cache.size() > IPagedItemModel::ItemsPerPage) { const int n = cache.size() - IPagedItemModel::ItemsPerPage; cache.remove(IPagedItemModel::ItemsPerPage, n); @@ -178,12 +181,13 @@ void IPagedItemModelImpl::handleResult(const Cache &it qDebug() << "NEW First:" << cacheFirstRow; } - firstPendingRow = -BatchSize_; //Tell model we ended fetching + firstPendingRow = -BatchSize_; // Tell model we ended fetching - if(firstRow > 0) - firstRow--; //Try notify also the row before because there might be another batch waiting so re-trigger it + if (firstRow > 0) + firstRow--; // Try notify also the row before because there might be another batch waiting + // so re-trigger it QModelIndex firstIdx = index(firstRow, 0); - QModelIndex lastIdx = index(lastRow, NCols_ - 1); + QModelIndex lastIdx = index(lastRow, NCols_ - 1); emit dataChanged(firstIdx, lastIdx); emit itemsReady(firstRow, lastRow); @@ -191,5 +195,3 @@ void IPagedItemModelImpl::handleResult(const Cache &it } #endif // IPAGEDITEMMODELHELPER_IMPL_H - - diff --git a/src/utils/delegates/sql/sqlfkfielddelegate.cpp b/src/utils/delegates/sql/sqlfkfielddelegate.cpp index bdf0eb5..d7f658a 100644 --- a/src/utils/delegates/sql/sqlfkfielddelegate.cpp +++ b/src/utils/delegates/sql/sqlfkfielddelegate.cpp @@ -25,38 +25,41 @@ #include "isqlfkmatchmodel.h" #include "IFKField.h" -SqlFKFieldDelegate::SqlFKFieldDelegate(IMatchModelFactory *factory, IFKField *iface, QObject *parent) : +SqlFKFieldDelegate::SqlFKFieldDelegate(IMatchModelFactory *factory, IFKField *iface, + QObject *parent) : QStyledItemDelegate(parent), mIface(iface), mFactory(factory) { - } -QWidget *SqlFKFieldDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) const +QWidget *SqlFKFieldDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /*option*/, + const QModelIndex & /*index*/) const { - ISqlFKMatchModel *model = mFactory->createModel(); + ISqlFKMatchModel *model = mFactory->createModel(); CustomCompletionLineEdit *editor = new CustomCompletionLineEdit(model, parent); model->setParent(editor); - connect(editor, &CustomCompletionLineEdit::completionDone, this, &SqlFKFieldDelegate::handleCompletionDone); + connect(editor, &CustomCompletionLineEdit::completionDone, this, + &SqlFKFieldDelegate::handleCompletionDone); return editor; } void SqlFKFieldDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { CustomCompletionLineEdit *ed = static_cast(editor); - db_id dataId = 0; + db_id dataId = 0; QString name; - if(mIface->getFieldData(index.row(), index.column(), dataId, name)) + if (mIface->getFieldData(index.row(), index.column(), dataId, name)) { ed->setData(dataId, name); } } -void SqlFKFieldDelegate::setModelData(QWidget *editor, QAbstractItemModel */*model*/, const QModelIndex &index) const +void SqlFKFieldDelegate::setModelData(QWidget *editor, QAbstractItemModel * /*model*/, + const QModelIndex &index) const { CustomCompletionLineEdit *ed = static_cast(editor); - //FIXME: use also validateData() ? + // FIXME: use also validateData() ? db_id dataId = 0; QString name; ed->getData(dataId, name); diff --git a/src/utils/files/file_format_names.h b/src/utils/files/file_format_names.h index 57848a4..e791c4f 100644 --- a/src/utils/files/file_format_names.h +++ b/src/utils/files/file_format_names.h @@ -27,16 +27,22 @@ class FileFormats Q_DECLARE_TR_FUNCTIONS(FileFormats) public: - //BIG TODO: maybe use mimetypes so we automatically get the name from system - //TODO: add custom extension that in future will be registered with an Icon (*.ttt) + // BIG TODO: maybe use mimetypes so we automatically get the name from system + // TODO: add custom extension that in future will be registered with an Icon (*.ttt) static constexpr const char *allFiles = QT_TRANSLATE_NOOP("FileFormats", "All Files (*.*)"); - static constexpr const char *odsFormat = QT_TRANSLATE_NOOP("FileFormats", "OpenDocument Sheet (*.ods)"); - static constexpr const char *odtFormat = QT_TRANSLATE_NOOP("FileFormats", "OpenDocument Text (*.odt)"); - static constexpr const char *tttFormat = QT_TRANSLATE_NOOP("FileFormats", "MRTPlanner Session (*.ttt)"); - static constexpr const char *sqliteFormat = QT_TRANSLATE_NOOP("FileFormats", "SQLite 3 Database (*.db *.sqlite *.sqlite3 *.db3)"); - static constexpr const char *svgFile = QT_TRANSLATE_NOOP("FileFormats", "SVG vectorial image (*.svg)"); + static constexpr const char *odsFormat = + QT_TRANSLATE_NOOP("FileFormats", "OpenDocument Sheet (*.ods)"); + static constexpr const char *odtFormat = + QT_TRANSLATE_NOOP("FileFormats", "OpenDocument Text (*.odt)"); + static constexpr const char *tttFormat = + QT_TRANSLATE_NOOP("FileFormats", "MRTPlanner Session (*.ttt)"); + static constexpr const char *sqliteFormat = + QT_TRANSLATE_NOOP("FileFormats", "SQLite 3 Database (*.db *.sqlite *.sqlite3 *.db3)"); + static constexpr const char *svgFile = + QT_TRANSLATE_NOOP("FileFormats", "SVG vectorial image (*.svg)"); static constexpr const char *xmlFile = QT_TRANSLATE_NOOP("FileFormats", "XML (*.xml)"); - static constexpr const char *pdfFile = QT_TRANSLATE_NOOP("FileFormats", "Portable Document Format (*.pdf)"); + static constexpr const char *pdfFile = + QT_TRANSLATE_NOOP("FileFormats", "Portable Document Format (*.pdf)"); }; #endif // FILE_FORMAT_NAMES_H diff --git a/src/utils/files/openfileinfolder.cpp b/src/utils/files/openfileinfolder.cpp index 10f2bbc..8cb9262 100644 --- a/src/utils/files/openfileinfolder.cpp +++ b/src/utils/files/openfileinfolder.cpp @@ -37,23 +37,24 @@ namespace utils { -static bool openDefAppOrShowFolder(const QFileInfo& info, bool folder) +static bool openDefAppOrShowFolder(const QFileInfo &info, bool folder) { - if(info.isDir()) + if (info.isDir()) folder = true; QString path = folder ? info.absolutePath() : info.absoluteFilePath(); -#if defined(Q_OS_WIN) && !defined (Q_OS_WINRT) - if(folder && !info.isDir()) +#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) + if (folder && !info.isDir()) { - //NOTE: on Windows desktop we can also select a file inside a folder - //So prefer it instead of default QDesktopServices - QString args = QStringLiteral("/select,%1").arg(QDir::toNativeSeparators(info.absoluteFilePath())); + // NOTE: on Windows desktop we can also select a file inside a folder + // So prefer it instead of default QDesktopServices + QString args = + QStringLiteral("/select,%1").arg(QDir::toNativeSeparators(info.absoluteFilePath())); QProcess explorer; explorer.setProgram(QLatin1String("explorer.exe")); - explorer.setNativeArguments(args); //This must not be quoted - if(explorer.startDetached()) + explorer.setNativeArguments(args); // This must not be quoted + if (explorer.startDetached()) return true; } #endif @@ -66,7 +67,7 @@ OpenFileInFolderDlg::OpenFileInFolderDlg(QWidget *parent) : { QGridLayout *lay = new QGridLayout(this); - mIconLabel = new QLabel; + mIconLabel = new QLabel; mIconLabel->setAlignment(Qt::AlignCenter); mIconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); lay->addWidget(mIconLabel, 0, 0, Qt::AlignCenter); @@ -78,15 +79,15 @@ OpenFileInFolderDlg::OpenFileInFolderDlg(QWidget *parent) : QDialogButtonBox *box = new QDialogButtonBox(Qt::Horizontal); lay->addWidget(box, 1, 0, 1, 2); - openFileBut = box->addButton(tr("Open In App"), QDialogButtonBox::AcceptRole); - openFolderBut = box->addButton(tr("Show Folder"), QDialogButtonBox::AcceptRole); + openFileBut = box->addButton(tr("Open In App"), QDialogButtonBox::AcceptRole); + openFolderBut = box->addButton(tr("Show Folder"), QDialogButtonBox::AcceptRole); QPushButton *okBut = box->addButton(QDialogButtonBox::Ok); - //Open Folder by default + // Open Folder by default openFolderBut->setDefault(true); openFolderBut->setFocus(); - //Only close dialog with Ok button, ignore others + // Only close dialog with Ok button, ignore others connect(okBut, &QPushButton::clicked, this, &QDialog::accept); connect(openFileBut, &QPushButton::clicked, this, &OpenFileInFolderDlg::onOpenFile); connect(openFolderBut, &QPushButton::clicked, this, &OpenFileInFolderDlg::onOpenFolder); @@ -98,18 +99,18 @@ void OpenFileInFolderDlg::setFilePath(const QString &newFilePath) openFileBut->setVisible(info.isFile()); QFileIconProvider provider; - QIcon fileIcon = provider.icon(info); + QIcon fileIcon = provider.icon(info); - QStyle *s = style(); + QStyle *s = style(); const int iconSize = s->pixelMetric(QStyle::PM_MessageBoxIconSize, 0, this); - if(fileIcon.isNull()) + if (fileIcon.isNull()) fileIcon = s->standardIcon(QStyle::SP_MessageBoxInformation, 0, this); QPixmap pix; - if(!fileIcon.isNull()) + if (!fileIcon.isNull()) { QWindow *window = nativeParentWidget() ? nativeParentWidget()->windowHandle() : nullptr; - pix = fileIcon.pixmap(window, QSize(iconSize, iconSize)); + pix = fileIcon.pixmap(window, QSize(iconSize, iconSize)); } mIconLabel->setPixmap(pix); @@ -127,7 +128,7 @@ void OpenFileInFolderDlg::askUser(const QString &title, const QString &filePath, dlg->setWindowTitle(title); dlg->setFilePath(filePath); dlg->setLabelText(OpenFileInFolderDlg::tr("Do you want to open file?
%1") - .arg(dlg->getInfo().canonicalFilePath())); + .arg(dlg->getInfo().canonicalFilePath())); dlg->exec(); } @@ -141,4 +142,4 @@ void OpenFileInFolderDlg::onOpenFolder() openDefAppOrShowFolder(info, true); } -} //namespace utils +} // namespace utils diff --git a/src/utils/files/openfileinfolder.h b/src/utils/files/openfileinfolder.h index 1213aea..9c69d56 100644 --- a/src/utils/files/openfileinfolder.h +++ b/src/utils/files/openfileinfolder.h @@ -50,7 +50,10 @@ public: void setFilePath(const QString &newFilePath); void setLabelText(const QString &text); - inline QFileInfo getInfo() const { return info; } + inline QFileInfo getInfo() const + { + return info; + } /*! * \brief askUser @@ -60,7 +63,7 @@ public: * * This convinience function opens standard dialog with default text */ - static void askUser(const QString& title, const QString& filePath, QWidget *parent); + static void askUser(const QString &title, const QString &filePath, QWidget *parent); private slots: void onOpenFile(); @@ -75,6 +78,6 @@ private: QFileInfo info; }; -} +} // namespace utils #endif // OPENFILEINFOLDER_H diff --git a/src/utils/files/recentdirstore.cpp b/src/utils/files/recentdirstore.cpp index a417f90..7b9d424 100644 --- a/src/utils/files/recentdirstore.cpp +++ b/src/utils/files/recentdirstore.cpp @@ -47,11 +47,11 @@ inline QStandardPaths::StandardLocation convertFlag(RecentDirStore::DefaultDir k QString RecentDirStore::getDir(const QString &key, DefaultDir kind) { auto it = recent_dirs()->m_dirs.find(key); - if(it == recent_dirs()->m_dirs.end()) + if (it == recent_dirs()->m_dirs.end()) { - //Insert new dir + // Insert new dir QString path = QStandardPaths::writableLocation(convertFlag(kind)); - it = recent_dirs->m_dirs.insert(key, path); + it = recent_dirs->m_dirs.insert(key, path); } return it.value(); @@ -60,17 +60,17 @@ QString RecentDirStore::getDir(const QString &key, DefaultDir kind) void RecentDirStore::setPath(const QString &key, const QString &path) { auto it = recent_dirs()->m_dirs.find(key); - if(it == recent_dirs()->m_dirs.end()) + if (it == recent_dirs()->m_dirs.end()) return; QFileInfo info(path); - if(info.isDir()) + if (info.isDir()) it.value() = info.absoluteFilePath(); else { QString path2 = info.absolutePath(); info.setFile(path2); - if(info.isDir()) + if (info.isDir()) it.value() = path2; } } diff --git a/src/utils/files/recentdirstore.h b/src/utils/files/recentdirstore.h index ad51ce7..0a64b88 100644 --- a/src/utils/files/recentdirstore.h +++ b/src/utils/files/recentdirstore.h @@ -31,8 +31,8 @@ public: Images }; - static QString getDir(const QString& key, DefaultDir kind); - static void setPath(const QString& key, const QString& path); + static QString getDir(const QString &key, DefaultDir kind); + static void setPath(const QString &key, const QString &path); }; #endif // RECENTDIRSTORE_H diff --git a/src/utils/jobcategorystrings.h b/src/utils/jobcategorystrings.h index 3be1893..1a76b28 100644 --- a/src/utils/jobcategorystrings.h +++ b/src/utils/jobcategorystrings.h @@ -23,7 +23,8 @@ #include #include "types.h" -static const char* JobCategoryFullNameTable[int(JobCategory::NCategories)] = { //NOTE: keep in sync wiht JobCategory +static const char *JobCategoryFullNameTable[int(JobCategory::NCategories)] = + { // NOTE: keep in sync wiht JobCategory QT_TRANSLATE_NOOP("JobCategoryName", "FREIGHT"), QT_TRANSLATE_NOOP("JobCategoryName", "LIS"), QT_TRANSLATE_NOOP("JobCategoryName", "POSTAL"), @@ -34,28 +35,22 @@ static const char* JobCategoryFullNameTable[int(JobCategory::NCategories)] = { / QT_TRANSLATE_NOOP("JobCategoryName", "INTERCITY"), QT_TRANSLATE_NOOP("JobCategoryName", "EXPRESS"), QT_TRANSLATE_NOOP("JobCategoryName", "DIRECT"), - QT_TRANSLATE_NOOP("JobCategoryName", "HIGH SPEED") -}; + QT_TRANSLATE_NOOP("JobCategoryName", "HIGH SPEED")}; -static const char* JobCategoryAbbrNameTable[int(JobCategory::NCategories)] = { //NOTE: keep in sync wiht JobCategory - QT_TRANSLATE_NOOP("JobCategoryName", "FRG"), - QT_TRANSLATE_NOOP("JobCategoryName", "LIS"), +static const char *JobCategoryAbbrNameTable[int(JobCategory::NCategories)] = + { // NOTE: keep in sync wiht JobCategory + QT_TRANSLATE_NOOP("JobCategoryName", "FRG"), QT_TRANSLATE_NOOP("JobCategoryName", "LIS"), QT_TRANSLATE_NOOP("JobCategoryName", "P"), - QT_TRANSLATE_NOOP("JobCategoryName", "R"), - QT_TRANSLATE_NOOP("JobCategoryName", "RF"), - QT_TRANSLATE_NOOP("JobCategoryName", "LOC"), - QT_TRANSLATE_NOOP("JobCategoryName", "IC"), - QT_TRANSLATE_NOOP("JobCategoryName", "EXP"), - QT_TRANSLATE_NOOP("JobCategoryName", "DIR"), - QT_TRANSLATE_NOOP("JobCategoryName", "HSP") -}; + QT_TRANSLATE_NOOP("JobCategoryName", "R"), QT_TRANSLATE_NOOP("JobCategoryName", "RF"), + QT_TRANSLATE_NOOP("JobCategoryName", "LOC"), QT_TRANSLATE_NOOP("JobCategoryName", "IC"), + QT_TRANSLATE_NOOP("JobCategoryName", "EXP"), QT_TRANSLATE_NOOP("JobCategoryName", "DIR"), + QT_TRANSLATE_NOOP("JobCategoryName", "HSP")}; namespace JobCategoryName__ { constexpr char unknownCatName[] = "Unknown"; } - class JobCategoryName { Q_DECLARE_TR_FUNCTIONS(JobCategoryName) @@ -63,26 +58,26 @@ class JobCategoryName public: static inline QString fullName(JobCategory cat) { - if(cat >= JobCategory::NCategories) + if (cat >= JobCategory::NCategories) return JobCategoryName__::unknownCatName; return tr(JobCategoryFullNameTable[int(cat)]); } static inline QString shortName(JobCategory cat) { - if(cat >= JobCategory::NCategories) + if (cat >= JobCategory::NCategories) return JobCategoryName__::unknownCatName; return tr(JobCategoryAbbrNameTable[int(cat)]); } static inline QString jobName(db_id jobId, JobCategory cat) { - return shortName(cat) + QString::number(jobId); //Example: LIS1234 + return shortName(cat) + QString::number(jobId); // Example: LIS1234 } static inline QString jobNameSpaced(db_id jobId, JobCategory cat) { - return shortName(cat) + QChar(' ') + QString::number(jobId); //Example: LIS1234 + return shortName(cat) + QChar(' ') + QString::number(jobId); // Example: LIS1234 } }; diff --git a/src/utils/localization/languageutils.cpp b/src/utils/localization/languageutils.cpp index f00729e..115b5e0 100644 --- a/src/utils/localization/languageutils.cpp +++ b/src/utils/localization/languageutils.cpp @@ -30,15 +30,17 @@ #include -constexpr const char *mrtpTranslationName = "mrtp"; +constexpr const char *mrtpTranslationName = "mrtp"; static const QLatin1String translationsFolder = QLatin1String("/translations"); -static inline QTranslator *loadTranslatorInternal(const QLocale &loc, const QString& path, const QString& prefix) +static inline QTranslator *loadTranslatorInternal(const QLocale &loc, const QString &path, + const QString &prefix) { QTranslator *translator = new QTranslator(qApp); - if(!translator->load(loc, prefix, QStringLiteral("_"), path)) + if (!translator->load(loc, prefix, QStringLiteral("_"), path)) { - qDebug() << "Cannot load translations for:" << prefix.toUpper() << loc.name() << loc.uiLanguages(); + qDebug() << "Cannot load translations for:" << prefix.toUpper() << loc.name() + << loc.uiLanguages(); delete translator; return nullptr; } @@ -55,21 +57,22 @@ bool utils::language::loadTranslationsFromSettings() { const QString localPath = qApp->applicationDirPath() + translationsFolder; const QString qtLibPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); - QLocale loc = Session->getAppLanguage(); + QLocale loc = Session->getAppLanguage(); - //NOTE: If locale is English with default country we do not need translations - //because they are already embedded in the executable strings so skip it - if(loc == MeetingSession::embeddedLocale) + // NOTE: If locale is English with default country we do not need translations + // because they are already embedded in the executable strings so skip it + if (loc == MeetingSession::embeddedLocale) return true; QTranslator *qtTransl = ::loadTranslatorInternal(loc, qtLibPath, QLatin1String("qt")); - if(qtTransl) + if (qtTransl) { QCoreApplication::installTranslator(qtTransl); } - QTranslator *mrtpTransl = ::loadTranslatorInternal(loc, localPath, QString::fromLatin1(mrtpTranslationName)); - if(mrtpTransl) + QTranslator *mrtpTransl = + ::loadTranslatorInternal(loc, localPath, QString::fromLatin1(mrtpTranslationName)); + if (mrtpTransl) { QCoreApplication::installTranslator(mrtpTransl); return true; @@ -82,28 +85,28 @@ QVector utils::language::getAvailableTranslations() { QVector vec; - //NOTE: First add default laguage embedded in executable strings + // NOTE: First add default laguage embedded in executable strings vec.append(MeetingSession::embeddedLocale); - const QString path = qApp->applicationDirPath() + translationsFolder; + const QString path = qApp->applicationDirPath() + translationsFolder; const QString filter = mrtpTranslationName + QStringLiteral("_*.qm"); - const int startIdx = qstrlen(mrtpTranslationName) + 1; //Add the '_' + const int startIdx = qstrlen(mrtpTranslationName) + 1; // Add the '_' - //Get all installed translation files + // Get all installed translation files QDirIterator iter(path, {filter}, QDir::Files); while (iter.hasNext()) { iter.next(); const QString fullName = iter.fileName(); - int lastIdx = fullName.indexOf('.'); - if(lastIdx < 0) - continue; //Skip invalid name + int lastIdx = fullName.indexOf('.'); + if (lastIdx < 0) + continue; // Skip invalid name - //Extract language from file name + // Extract language from file name QString language = fullName.mid(startIdx, lastIdx - startIdx); QLocale loc(language); - if(loc == QLocale::c()) - continue; //This means it didn't parse locale + if (loc == QLocale::c()) + continue; // This means it didn't parse locale vec.append(loc); } diff --git a/src/utils/localization/languageutils.h b/src/utils/localization/languageutils.h index b77dcc3..8a78639 100644 --- a/src/utils/localization/languageutils.h +++ b/src/utils/localization/languageutils.h @@ -23,14 +23,13 @@ class QTranslator; class QLocale; -template -class QVector; +template class QVector; namespace utils { namespace language { -QTranslator *loadAppTranslator(const QLocale& loc); +QTranslator *loadAppTranslator(const QLocale &loc); bool loadTranslationsFromSettings(); diff --git a/src/utils/model_mode.h b/src/utils/model_mode.h index 2e718c3..f5776ef 100644 --- a/src/utils/model_mode.h +++ b/src/utils/model_mode.h @@ -26,7 +26,7 @@ enum Mode Owners, Models, Rollingstock -}; //FIXME: maybe remove -} +}; // FIXME: maybe remove +} // namespace ModelModes #endif // MODEL_MODE_H diff --git a/src/utils/model_roles.h b/src/utils/model_roles.h index bb1ca1e..4c9b6e4 100644 --- a/src/utils/model_roles.h +++ b/src/utils/model_roles.h @@ -22,19 +22,16 @@ #include -//Useful constants to set/retrive data from models +// Useful constants to set/retrive data from models +#define JOB_ID_ROLE (Qt::UserRole + 10) +#define RS_MODEL_ID (Qt::UserRole + 40) +#define RS_TYPE_ROLE (Qt::UserRole + 41) +#define RS_SUB_TYPE_ROLE (Qt::UserRole + 42) +#define RS_NUMBER (Qt::UserRole + 44) +#define RS_IS_ENGINE (Qt::UserRole + 45) - -#define JOB_ID_ROLE (Qt::UserRole + 10) - -#define RS_MODEL_ID (Qt::UserRole + 40) -#define RS_TYPE_ROLE (Qt::UserRole + 41) -#define RS_SUB_TYPE_ROLE (Qt::UserRole + 42) -#define RS_NUMBER (Qt::UserRole + 44) -#define RS_IS_ENGINE (Qt::UserRole + 45) - -#define COLOR_ROLE (Qt::UserRole + 46) +#define COLOR_ROLE (Qt::UserRole + 46) #endif // MODEL_ROLES_H diff --git a/src/utils/owningqpointer.h b/src/utils/owningqpointer.h index 0c5ecda..188cf6d 100644 --- a/src/utils/owningqpointer.h +++ b/src/utils/owningqpointer.h @@ -28,18 +28,19 @@ * OwningQPointer adds ownership of tracked object by deleting it if still valid * when the pointer goes out of scope */ -template -class OwningQPointer : public QPointer +template class OwningQPointer : public QPointer { public: - inline OwningQPointer(T *p) : QPointer(p) { } + inline OwningQPointer(T *p) : + QPointer(p) + { + } ~OwningQPointer(); }; -template -OwningQPointer::~OwningQPointer() +template OwningQPointer::~OwningQPointer() { - if(this->data()) + if (this->data()) delete this->data(); } diff --git a/src/utils/rs_types_names.h b/src/utils/rs_types_names.h index ac5463d..bdc7b0c 100644 --- a/src/utils/rs_types_names.h +++ b/src/utils/rs_types_names.h @@ -23,19 +23,13 @@ #include #include "types.h" -static const char* RsTypeNamesTable[] = { - QT_TRANSLATE_NOOP("RsTypeNames", "Engine"), - QT_TRANSLATE_NOOP("RsTypeNames", "Freight Wagon"), - QT_TRANSLATE_NOOP("RsTypeNames", "Coach") -}; - -static const char* RsSubTypeNamesTable[] = { - QT_TRANSLATE_NOOP("RsTypeNames", "Not set!"), - QT_TRANSLATE_NOOP("RsTypeNames", "Electric"), - QT_TRANSLATE_NOOP("RsTypeNames", "Diesel"), - QT_TRANSLATE_NOOP("RsTypeNames", "Steam") -}; +static const char *RsTypeNamesTable[] = {QT_TRANSLATE_NOOP("RsTypeNames", "Engine"), + QT_TRANSLATE_NOOP("RsTypeNames", "Freight Wagon"), + QT_TRANSLATE_NOOP("RsTypeNames", "Coach")}; +static const char *RsSubTypeNamesTable[] = { + QT_TRANSLATE_NOOP("RsTypeNames", "Not set!"), QT_TRANSLATE_NOOP("RsTypeNames", "Electric"), + QT_TRANSLATE_NOOP("RsTypeNames", "Diesel"), QT_TRANSLATE_NOOP("RsTypeNames", "Steam")}; class RsTypeNames { @@ -44,14 +38,14 @@ class RsTypeNames public: static inline QString name(RsType t) { - if(t >= RsType::NTypes) + if (t >= RsType::NTypes) return QString(); return tr(RsTypeNamesTable[int(t)]); } static inline QString name(RsEngineSubType t) { - if(t >= RsEngineSubType::NTypes) + if (t >= RsEngineSubType::NTypes) return QString(); return tr(RsSubTypeNamesTable[int(t)]); } diff --git a/src/utils/rs_utils.cpp b/src/utils/rs_utils.cpp index ab7255f..2c8bd95 100644 --- a/src/utils/rs_utils.cpp +++ b/src/utils/rs_utils.cpp @@ -23,13 +23,13 @@ QString rs_utils::formatNum(RsType type, int number) { - if(type == RsType::Engine) + if (type == RsType::Engine) { return QString::number(number).rightJustified(3, '0'); } else { - //Freight wagons and coaches + // Freight wagons and coaches QString str = QStringLiteral("%1").arg(number, 4, 10, QChar('0')); str.insert(3, '-'); // 'XXX-X' return str; @@ -39,55 +39,56 @@ QString rs_utils::formatNum(RsType type, int number) QString rs_utils::formatName(const QString &model, int number, const QString &suffix, RsType type) { QString name = model; - name.reserve(model.size() + suffix.size() + 10); //1 char separator (' ', '.') + 9 digit max - + name.reserve(model.size() + suffix.size() + 10); // 1 char separator (' ', '.') + 9 digit max int numberLen = int(floor(log10(number))) + 1; - if(type == RsType::Engine) + if (type == RsType::Engine) { name.append('.'); //'[Name].XXX[Suffix] const int count = qMax(5, numberLen); - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) name.append('0'); - for(int i = 0; i < numberLen; i++) + for (int i = 0; i < numberLen; i++) { - int rem = number % 10; + int rem = number % 10; name[name.size() - i - 1] = QChar('0' + rem); - number = (number - rem) / 10; + number = (number - rem) / 10; } } else { name.append(' '); - //Freight wagons and coaches '[Name] XXX-X[Suffix]' + // Freight wagons and coaches '[Name] XXX-X[Suffix]' numberLen++; const int count = qMax(5, numberLen); - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) name.append('0'); - for(int i = 0; i < numberLen; i++) + for (int i = 0; i < numberLen; i++) { - if(i == 1) + if (i == 1) { name[name.size() - 2] = '-'; continue; } - int rem = number % 10; + int rem = number % 10; name[name.size() - i - 1] = QChar('0' + rem); - number = (number - rem) / 10; + number = (number - rem) / 10; } } - if(type == RsType::Engine) + if (type == RsType::Engine) { name.append('.'); name.append(QString::number(number)); - }else{ + } + else + { name.append(' '); - //Freight wagons and coaches + // Freight wagons and coaches QString str = QStringLiteral("%1").arg(number, 4, 10, QChar('0')); str.insert(3, '-'); // 'XXX-X' name.append(str); @@ -96,43 +97,44 @@ QString rs_utils::formatName(const QString &model, int number, const QString &su return name; } -QString rs_utils::formatNameRef(const char *model, int modelSize, int number, const char *suffix, int suffixSize, RsType type) +QString rs_utils::formatNameRef(const char *model, int modelSize, int number, const char *suffix, + int suffixSize, RsType type) { QByteArray name; - name.reserve(modelSize + suffixSize + 10); //1 char separator (' ', '.') + 9 digit max + name.reserve(modelSize + suffixSize + 10); // 1 char separator (' ', '.') + 9 digit max name.append(model, modelSize); int numberLen = int(floor(log10(number))) + 1; - if(type == RsType::Engine) + if (type == RsType::Engine) { name.append('.'); //'[Name].XXX[Suffix] name.append(qMax(3, numberLen), '0'); - for(int i = 0; i < numberLen; i++) + for (int i = 0; i < numberLen; i++) { - int rem = number % 10; + int rem = number % 10; name[name.size() - i - 1] = char('0' + rem); - number = (number - rem) / 10; + number = (number - rem) / 10; } } else { name.append(' '); - //Freight wagons and coaches '[Name] XXX-X[Suffix]' + // Freight wagons and coaches '[Name] XXX-X[Suffix]' numberLen++; name.append(qMax(5, numberLen), '0'); - for(int i = 0; i < numberLen; i++) + for (int i = 0; i < numberLen; i++) { - if(i == 1) + if (i == 1) { name[name.size() - 2] = '-'; continue; } - int rem = number % 10; + int rem = number % 10; name[name.size() - i - 1] = char('0' + rem); - number = (number - rem) / 10; + number = (number - rem) / 10; } } name.append(suffix, suffixSize); diff --git a/src/utils/rs_utils.h b/src/utils/rs_utils.h index 2222ef8..d98627c 100644 --- a/src/utils/rs_utils.h +++ b/src/utils/rs_utils.h @@ -24,14 +24,14 @@ #include "types.h" -namespace rs_utils -{ -//Format RS number according to its type +namespace rs_utils { +// Format RS number according to its type QString formatNum(RsType type, int number); -QString formatName(const QString& model, int number, const QString& suffix, RsType type); -QString formatNameRef(const char *model, int modelSize, int number, const char *suffix, int suffixSize, RsType type); +QString formatName(const QString &model, int number, const QString &suffix, RsType type); +QString formatNameRef(const char *model, int modelSize, int number, const char *suffix, + int suffixSize, RsType type); -} +} // namespace rs_utils #endif // RS_UTILS_H diff --git a/src/utils/scene/basicgraphheader.cpp b/src/utils/scene/basicgraphheader.cpp index 121978c..bf8491b 100644 --- a/src/utils/scene/basicgraphheader.cpp +++ b/src/utils/scene/basicgraphheader.cpp @@ -31,7 +31,6 @@ BasicGraphHeader::BasicGraphHeader(Qt::Orientation orient, QWidget *parent) : mZoom(100), m_orientation(orient) { - } void BasicGraphHeader::setScene(IGraphScene *scene) @@ -57,21 +56,21 @@ void BasicGraphHeader::paintEvent(QPaintEvent *e) QColor c(255, 255, 255, 220); painter.fillRect(rect(), c); - if(!m_scene) - return; //Nothing to draw + if (!m_scene) + return; // Nothing to draw - //FIXME: consider QPaintEvent rect? + // FIXME: consider QPaintEvent rect? Q_UNUSED(e) const double scaleFactor = mZoom / 100.0; - //Map to scene + // Map to scene const double sceneScroll = m_scroll / scaleFactor; - QRectF sceneRect = rect(); + QRectF sceneRect = rect(); sceneRect.setSize(sceneRect.size() / scaleFactor); - //Apply scrolling - if(m_orientation == Qt::Horizontal) + // Apply scrolling + if (m_orientation == Qt::Horizontal) sceneRect.moveLeft(sceneScroll); else sceneRect.moveTop(sceneScroll); diff --git a/src/utils/scene/basicgraphview.cpp b/src/utils/scene/basicgraphview.cpp index 58dec75..59c3e66 100644 --- a/src/utils/scene/basicgraphview.cpp +++ b/src/utils/scene/basicgraphview.cpp @@ -41,11 +41,13 @@ BasicGraphView::BasicGraphView(QWidget *parent) : horizontalScrollBar()->setSingleStep(20); verticalScrollBar()->setSingleStep(20); - m_verticalHeader = new BasicGraphHeader(Qt::Vertical, this); + m_verticalHeader = new BasicGraphHeader(Qt::Vertical, this); m_horizontalHeader = new BasicGraphHeader(Qt::Horizontal, this); - connect(verticalScrollBar(), &QScrollBar::valueChanged, m_verticalHeader, &BasicGraphHeader::setScroll); - connect(horizontalScrollBar(), &QScrollBar::valueChanged, m_horizontalHeader, &BasicGraphHeader::setScroll); + connect(verticalScrollBar(), &QScrollBar::valueChanged, m_verticalHeader, + &BasicGraphHeader::setScroll); + connect(horizontalScrollBar(), &QScrollBar::valueChanged, m_horizontalHeader, + &BasicGraphHeader::setScroll); resizeHeaders(); } @@ -60,15 +62,16 @@ void BasicGraphView::setScene(IGraphScene *newScene) m_verticalHeader->setScene(newScene); m_horizontalHeader->setScene(newScene); - if(m_scene) + if (m_scene) { disconnect(m_scene, &IGraphScene::redrawGraph, this, &BasicGraphView::redrawGraph); disconnect(m_scene, &IGraphScene::headersSizeChanged, this, &BasicGraphView::resizeHeaders); - disconnect(m_scene, &IGraphScene::requestShowRect, this, &BasicGraphView::ensureRectVisible); + disconnect(m_scene, &IGraphScene::requestShowRect, this, + &BasicGraphView::ensureRectVisible); disconnect(m_scene, &QObject::destroyed, this, &BasicGraphView::onSceneDestroyed); } m_scene = newScene; - if(m_scene) + if (m_scene) { connect(m_scene, &IGraphScene::redrawGraph, this, &BasicGraphView::redrawGraph); connect(m_scene, &IGraphScene::headersSizeChanged, this, &BasicGraphView::resizeHeaders); @@ -82,23 +85,23 @@ void BasicGraphView::setScene(IGraphScene *newScene) void BasicGraphView::ensureVisible(double x, double y, double xmargin, double ymargin) { - if(!m_scene) + if (!m_scene) return; - auto hbar = horizontalScrollBar(); - auto vbar = verticalScrollBar(); - auto vp = viewport(); + auto hbar = horizontalScrollBar(); + auto vbar = verticalScrollBar(); + auto vp = viewport(); const double scaleFactor = mZoom / 100.0; - //Prevent going under headers + // Prevent going under headers QSizeF headerSize = m_scene->getHeaderSize().toSize(); - //Apply scaling + // Apply scaling headerSize *= scaleFactor; - //const double horizOffset = (hourPanel->width() + 5) * scaleFactor; - //const double vertOffset = (stationHeader->height() + 5) * scaleFactor; + // const double horizOffset = (hourPanel->width() + 5) * scaleFactor; + // const double vertOffset = (stationHeader->height() + 5) * scaleFactor; x *= scaleFactor; y *= scaleFactor; @@ -107,7 +110,7 @@ void BasicGraphView::ensureVisible(double x, double y, double xmargin, double ym int logicalX = x; - double val = hbar->value(); + double val = hbar->value(); if (logicalX - xmargin < hbar->value() + headerSize.width()) { val = qMax(0.0, logicalX - xmargin - headerSize.width()); @@ -137,10 +140,10 @@ QPointF BasicGraphView::mapToScene(const QPointF &pos) const const QPoint origin(-horizontalScrollBar()->value(), -verticalScrollBar()->value()); const QRect vp = viewport()->rect(); - //Map to viewport + // Map to viewport scenePos -= vp.topLeft(); - //Map to scene + // Map to scene scenePos -= origin; scenePos /= mZoom / 100.0; @@ -157,28 +160,28 @@ void BasicGraphView::redrawGraph() void BasicGraphView::ensureRectVisible(const QRectF &r) { - //FIXME: better implementation - QRect r2 = r.toRect(); + // FIXME: better implementation + QRect r2 = r.toRect(); const QPoint c = r2.center(); ensureVisible(c.x(), c.y(), r2.width() / 2, r2.height() / 2); } void BasicGraphView::setZoomLevel(int zoom) { - if(mZoom == zoom) + if (mZoom == zoom) return; - auto hbar = horizontalScrollBar(); - auto vbar = verticalScrollBar(); + auto hbar = horizontalScrollBar(); + auto vbar = verticalScrollBar(); double horizScroll = hbar->value(); - double vertScroll = vbar->value(); + double vertScroll = vbar->value(); - //Bound values + // Bound values zoom = qBound(25, zoom, 400); - //Reposition scrollbars - horizScroll *= zoom/double(mZoom); - vertScroll *= zoom/double(mZoom); + // Reposition scrollbars + horizScroll *= zoom / double(mZoom); + vertScroll *= zoom / double(mZoom); mZoom = zoom; m_verticalHeader->setZoom(mZoom); @@ -189,12 +192,12 @@ void BasicGraphView::setZoomLevel(int zoom) updateScrollBars(); resizeHeaders(); - //Try set values + // Try set values hbar->setValue(horizScroll); vbar->setValue(vertScroll); - //Headers get already updated by setting zoom - //Now update maint contents + // Headers get already updated by setting zoom + // Now update maint contents viewport()->update(); } @@ -211,28 +214,28 @@ bool BasicGraphView::event(QEvent *e) void BasicGraphView::paintEvent(QPaintEvent *e) { - if(!m_scene) - return; //Nothing to draw + if (!m_scene) + return; // Nothing to draw const double scaleFactor = mZoom / 100.0; const QPoint origin(-horizontalScrollBar()->value(), -verticalScrollBar()->value()); QRectF exposedRect = e->rect(); - const QRect vp = viewport()->rect(); + const QRect vp = viewport()->rect(); - //Map to viewport + // Map to viewport exposedRect.moveTopLeft(exposedRect.topLeft() - vp.topLeft()); exposedRect = exposedRect.intersected(vp); - //Map to scene + // Map to scene exposedRect.moveTopLeft(exposedRect.topLeft() - origin); - //Set zoom + // Set zoom const QRectF sceneRect(exposedRect.topLeft() / scaleFactor, exposedRect.size() / scaleFactor); QPainter painter(viewport()); - //Scroll contents + // Scroll contents painter.translate(origin); painter.scale(scaleFactor, scaleFactor); @@ -247,7 +250,7 @@ void BasicGraphView::resizeEvent(QResizeEvent *) void BasicGraphView::focusInEvent(QFocusEvent *e) { - if(m_scene) + if (m_scene) m_scene->activateScene(); QAbstractScrollArea::focusInEvent(e); @@ -264,10 +267,10 @@ void BasicGraphView::onSceneDestroyed() void BasicGraphView::resizeHeaders() { QSizeF headerSize; - if(m_scene) + if (m_scene) headerSize = m_scene->getHeaderSize().toSize(); - //Apply scaling + // Apply scaling headerSize *= mZoom / 100.0; const QRect vg = viewport()->geometry(); @@ -283,23 +286,23 @@ void BasicGraphView::resizeHeaders() void BasicGraphView::updateScrollBars() { - if(!m_scene) + if (!m_scene) return; QSizeF contentsSize = m_scene->getContentsSize(); - if(contentsSize.isEmpty()) + if (contentsSize.isEmpty()) return; - //Scale contents + // Scale contents contentsSize *= mZoom / 100.0; QSize roundedContentsSize = contentsSize.toSize(); - QSize p = viewport()->size(); - QSize m = maximumViewportSize(); + QSize p = viewport()->size(); + QSize m = maximumViewportSize(); - if(m.expandedTo(roundedContentsSize) == m) - p = m; //No scrollbars needed + if (m.expandedTo(roundedContentsSize) == m) + p = m; // No scrollbars needed auto hbar = horizontalScrollBar(); hbar->setRange(0, roundedContentsSize.width() - p.width()); diff --git a/src/utils/scene/basicgraphview.h b/src/utils/scene/basicgraphview.h index d60113e..d311f41 100644 --- a/src/utils/scene/basicgraphview.h +++ b/src/utils/scene/basicgraphview.h @@ -50,10 +50,9 @@ public: * the nearest valid position. The default value for both margins is 50 pixels. * * Vertical and horizontal headers are excluded from the visible zone - */ + */ void ensureVisible(double x, double y, double xmargin, double ymargin); - /*! * \brief getZoomLevel * \return view zoom level @@ -63,7 +62,10 @@ public: * \sa setZoomLevel() * \sa zoomLevelChanged() */ - inline int getZoomLevel() const { return mZoom; } + inline int getZoomLevel() const + { + return mZoom; + } /*! * \brief mapToScene @@ -72,7 +74,7 @@ public: * * Applies scrolling and scaling */ - QPointF mapToScene(const QPointF& pos) const; + QPointF mapToScene(const QPointF &pos) const; signals: void zoomLevelChanged(int zoom); @@ -90,7 +92,7 @@ public slots: * * \sa ensureVisible() */ - void ensureRectVisible(const QRectF& r); + void ensureRectVisible(const QRectF &r); /*! * \brief setZoomLevel diff --git a/src/utils/scene/igraphscene.cpp b/src/utils/scene/igraphscene.cpp index 8da1c52..aca4761 100644 --- a/src/utils/scene/igraphscene.cpp +++ b/src/utils/scene/igraphscene.cpp @@ -22,5 +22,4 @@ IGraphScene::IGraphScene(QObject *parent) : QObject(parent) { - } diff --git a/src/utils/scene/igraphscene.h b/src/utils/scene/igraphscene.h index ef0a573..4c735fb 100644 --- a/src/utils/scene/igraphscene.h +++ b/src/utils/scene/igraphscene.h @@ -81,7 +81,10 @@ public: * * \sa sceneActivated() */ - inline void activateScene() { emit sceneActivated(this); } + inline void activateScene() + { + emit sceneActivated(this); + } /*! * \brief renderContents @@ -90,7 +93,7 @@ public: * * Renders requested portion of scene contents */ - virtual void renderContents(QPainter *painter, const QRectF& sceneRect) = 0; + virtual void renderContents(QPainter *painter, const QRectF &sceneRect) = 0; /*! * \brief render header in scene coordinates @@ -103,8 +106,8 @@ public: * * \sa renderHeaderScroll() */ - virtual void renderHeader(QPainter *painter, const QRectF& sceneRect, - Qt::Orientation orient, double scroll) = 0; + virtual void renderHeader(QPainter *painter, const QRectF &sceneRect, Qt::Orientation orient, + double scroll) = 0; signals: /*! @@ -129,7 +132,7 @@ signals: * * The view will ensure this rect is visible if possible */ - void requestShowRect(const QRectF& rect); + void requestShowRect(const QRectF &rect); /*! * \brief Signal for activation diff --git a/src/utils/singledepthtreemodelhelper.h b/src/utils/singledepthtreemodelhelper.h index 87abd48..a8ce782 100644 --- a/src/utils/singledepthtreemodelhelper.h +++ b/src/utils/singledepthtreemodelhelper.h @@ -42,26 +42,28 @@ template class SingleDepthTreeModelHelper : public QAbstractItemModel { public: - SingleDepthTreeModelHelper(QObject *p = nullptr) : QAbstractItemModel(p) {} + SingleDepthTreeModelHelper(QObject *p = nullptr) : + QAbstractItemModel(p) + { + } // Basic functionality: - QModelIndex index(int row, int column, - const QModelIndex &p = QModelIndex()) const override + QModelIndex index(int row, int column, const QModelIndex &p = QModelIndex()) const override { - if(p.isValid()) + if (p.isValid()) { - if(p.row() >= m_data.topLevelCount() || p.internalPointer()) - return QModelIndex(); //Out of bound or child-most + if (p.row() >= m_data.topLevelCount() || p.internalPointer()) + return QModelIndex(); // Out of bound or child-most auto topLevel = m_data.getTopLevelAtRow(p.row()); - if(row >= topLevel->childCount()) + if (row >= topLevel->childCount()) return QModelIndex(); void *ptr = const_cast(static_cast(topLevel->ptrForRow(row))); return createIndex(row, column, ptr); } - if(row >= m_data.topLevelCount()) + if (row >= m_data.topLevelCount()) return QModelIndex(); return createIndex(row, column, nullptr); @@ -69,25 +71,25 @@ public: QModelIndex parent(const QModelIndex &idx) const override { - if(!idx.isValid()) + if (!idx.isValid()) return QModelIndex(); - RowData *item = static_cast(idx.internalPointer()); - if(!item) //Caption, it's toplevel so no parent + RowData *item = static_cast(idx.internalPointer()); + if (!item) // Caption, it's toplevel so no parent return QModelIndex(); int topLevelRow = m_data.getParentRow(item); - if(topLevelRow < 0) + if (topLevelRow < 0) return QModelIndex(); return index(topLevelRow, 0); } int rowCount(const QModelIndex &p) const override { - if(p.isValid()) + if (p.isValid()) { - if(p.internalPointer()) - return 0; //Child most, no childs below so 0 rows + if (p.internalPointer()) + return 0; // Child most, no childs below so 0 rows auto topLevel = m_data.getTopLevelAtRow(p.row()); return topLevel->childCount(); @@ -103,12 +105,12 @@ public: bool hasChildren(const QModelIndex &p) const override { - if(p.isValid()) + if (p.isValid()) { - if(p.internalPointer() || p.row() >= m_data.topLevelCount()) + if (p.internalPointer() || p.row() >= m_data.topLevelCount()) return false; - //Every tree has always childrens otherwhise gets removed + // Every tree has always childrens otherwhise gets removed return true; } @@ -117,36 +119,39 @@ public: QModelIndex sibling(int row, int column, const QModelIndex &idx) const override { - if(!idx.isValid()) + if (!idx.isValid()) return QModelIndex(); - if(idx.internalPointer()) + if (idx.internalPointer()) { - //It's a row inside a toplevel tree - if(column >= Super::NCols) + // It's a row inside a toplevel tree + if (column >= Super::NCols) return QModelIndex(); void *ptr = idx.internalPointer(); - if(row != idx.row()) + if (row != idx.row()) { - //Calculate new ptr for row - RowData *item = static_cast(idx.internalPointer()); + // Calculate new ptr for row + RowData *item = static_cast(idx.internalPointer()); auto topLevel = m_data.getParent(item); - if(!topLevel || row >= topLevel->childCount()) - return QModelIndex(); //Out of bound child row + if (!topLevel || row >= topLevel->childCount()) + return QModelIndex(); // Out of bound child row ptr = const_cast(static_cast(topLevel->ptrForRow(row))); } return createIndex(row, column, ptr); } - if(column > 0 || row >= m_data.topLevelCount()) - return QModelIndex(); //Parents (RS Items) have only column zero + if (column > 0 || row >= m_data.topLevelCount()) + return QModelIndex(); // Parents (RS Items) have only column zero return createIndex(row, 0, nullptr); } - inline const RowData *getItem(const QModelIndex& idx) const { return static_cast(idx.internalPointer()); } + inline const RowData *getItem(const QModelIndex &idx) const + { + return static_cast(idx.internalPointer()); + } protected: ModelData m_data; diff --git a/src/utils/thread/iquittabletask.cpp b/src/utils/thread/iquittabletask.cpp index 892bfb3..0a27e58 100644 --- a/src/utils/thread/iquittabletask.cpp +++ b/src/utils/thread/iquittabletask.cpp @@ -27,7 +27,7 @@ IQuittableTask::IQuittableTask(QObject *receiver) : mPointerGuard(false), mQuit(false) { - //NOTE: we disable Qt auto deletion flafg and handle it ourselves + // NOTE: we disable Qt auto deletion flafg and handle it ourselves setAutoDelete(false); } @@ -44,16 +44,16 @@ void IQuittableTask::cleanup() { lockTask(); - if(mReceiver) + if (mReceiver) { - //This means task has not finished yet. - //Clear receiver to tell task to delete itself when done inside sendEvent() + // This means task has not finished yet. + // Clear receiver to tell task to delete itself when done inside sendEvent() mReceiver = nullptr; unlockTask(); } else { - //The task was already finished, delete it + // The task was already finished, delete it delete this; } } @@ -62,20 +62,20 @@ void IQuittableTask::sendEvent(QEvent *e, bool finish) { lockTask(); - if(mReceiver) + if (mReceiver) { - //Post the event to receiver object + // Post the event to receiver object qApp->postEvent(mReceiver, e); - if(finish) - mReceiver = nullptr; //Clear receiver to tell cleanup() to delete task + if (finish) + mReceiver = nullptr; // Clear receiver to tell cleanup() to delete task unlockTask(); } else { - //Delete event because it cannot be posted + // Delete event because it cannot be posted delete e; - if(finish) - delete this; //cleanup() was called, we are responsible for deleting ourselves + if (finish) + delete this; // cleanup() was called, we are responsible for deleting ourselves else unlockTask(); } diff --git a/src/utils/thread/iquittabletask.h b/src/utils/thread/iquittabletask.h index 1eb67f5..472ba05 100644 --- a/src/utils/thread/iquittabletask.h +++ b/src/utils/thread/iquittabletask.h @@ -92,9 +92,13 @@ public: * NOTE: this must be called when task in not running (before starting or after finished) * * This is useful if you want to re-use the task. - * To do so, set again the receiver before re-starting, because it got cleared when task finished. + * To do so, set again the receiver before re-starting, because it got cleared when task + * finished. */ - inline void setReceiver(QObject *obj) { mReceiver = obj; } + inline void setReceiver(QObject *obj) + { + mReceiver = obj; + } /*! * \brief lock task to prevent it from being deleted @@ -107,7 +111,7 @@ public: { while (!mPointerGuard.testAndSetOrdered(false, true)) { - //Busy wait + // Busy wait } } diff --git a/src/utils/thread/taskprogressevent.cpp b/src/utils/thread/taskprogressevent.cpp index 3d6c02d..f76b5ef 100644 --- a/src/utils/thread/taskprogressevent.cpp +++ b/src/utils/thread/taskprogressevent.cpp @@ -23,7 +23,6 @@ GenericTaskEvent::GenericTaskEvent(Type type_, IQuittableTask *self) : QEvent(type_), task(self) { - } TaskProgressEvent::TaskProgressEvent(IQuittableTask *self, int pr, int max, const QString &descr) : @@ -32,5 +31,4 @@ TaskProgressEvent::TaskProgressEvent(IQuittableTask *self, int pr, int max, cons progressMax(max), description(descr) { - } diff --git a/src/utils/thread/taskprogressevent.h b/src/utils/thread/taskprogressevent.h index 0aaba28..6b1391f 100644 --- a/src/utils/thread/taskprogressevent.h +++ b/src/utils/thread/taskprogressevent.h @@ -39,16 +39,16 @@ class TaskProgressEvent : public GenericTaskEvent public: enum { - ProgressError = -1, + ProgressError = -1, ProgressAbortedByUser = -2, - ProgressFinished = -3 + ProgressFinished = -3 }; static constexpr Type _Type = Type(CustomEvents::TaskProgress); - TaskProgressEvent(IQuittableTask *self, int pr, int max, const QString& descr = QString()); + TaskProgressEvent(IQuittableTask *self, int pr, int max, const QString &descr = QString()); - int progress = 0; + int progress = 0; int progressMax = 0; QString description; }; diff --git a/src/utils/types.h b/src/utils/types.h index 1db0a0b..62c74c6 100644 --- a/src/utils/types.h +++ b/src/utils/types.h @@ -22,14 +22,14 @@ #include -//64 bit signed integer used for SQL Primary Key ID +// 64 bit signed integer used for SQL Primary Key ID typedef qint64 db_id; enum class RsType : qint8 { Engine = 0, FreightWagon, - Coach , + Coach, NTypes }; @@ -42,15 +42,17 @@ enum class RsEngineSubType : qint8 NTypes }; -enum class StopType { - ToggleType = -1, //Used as flag in StopModel::setStopTypeRange() - Normal = 0, +enum class StopType +{ + ToggleType = -1, // Used as flag in StopModel::setStopTypeRange() + Normal = 0, Transit, First, Last }; -enum class RsOp { +enum class RsOp +{ Uncoupled = 0, Coupled = 1 }; @@ -58,11 +60,11 @@ enum class RsOp { enum class JobCategory : qint8 { FREIGHT = 0, - LIS, //Locomotiva In Spostamento (Rimando) + LIS, // Locomotiva In Spostamento (Rimando) POSTAL, - REGIONAL, //Passenger - FAST_REGIONAL, //RV - Regionale veloce + REGIONAL, // Passenger + FAST_REGIONAL, // RV - Regionale veloce LOCAL, INTERCITY, EXPRESS, @@ -72,19 +74,19 @@ enum class JobCategory : qint8 NCategories }; -constexpr JobCategory LastFreightCategory = JobCategory::POSTAL; +constexpr JobCategory LastFreightCategory = JobCategory::POSTAL; constexpr JobCategory FirstPassengerCategory = JobCategory::REGIONAL; struct JobEntry { - db_id jobId = 0; + db_id jobId = 0; JobCategory category = JobCategory::NCategories; }; struct JobStopEntry { - db_id stopId = 0; - db_id jobId = 0; + db_id stopId = 0; + db_id jobId = 0; JobCategory category = JobCategory::NCategories; }; diff --git a/src/utils/wizard/choosefilepage.cpp b/src/utils/wizard/choosefilepage.cpp index ba1ef36..6d93d47 100644 --- a/src/utils/wizard/choosefilepage.cpp +++ b/src/utils/wizard/choosefilepage.cpp @@ -36,7 +36,7 @@ ChooseFilePage::ChooseFilePage(QWidget *parent) : { QHBoxLayout *lay = new QHBoxLayout(this); - pathEdit = new QLineEdit; + pathEdit = new QLineEdit; pathEdit->setPlaceholderText(tr("Insert path here or click 'Choose' button")); connect(pathEdit, &QLineEdit::textChanged, this, &QWizardPage::completeChanged); lay->addWidget(pathEdit); @@ -48,8 +48,8 @@ ChooseFilePage::ChooseFilePage(QWidget *parent) : setTitle(tr("Choose file")); setSubTitle(tr("Choose a file to import in selected format")); - //Prevent user from going back to this page and change file. - //If user wants to change file he has to Cancel the wizard and start it again + // Prevent user from going back to this page and change file. + // If user wants to change file he has to Cancel the wizard and start it again setCommitPage(true); } @@ -60,13 +60,13 @@ bool ChooseFilePage::isComplete() const void ChooseFilePage::initializePage() { - //HACK: I don't like the 'Commit' button. This hack makes it similar to 'Next' button + // HACK: I don't like the 'Commit' button. This hack makes it similar to 'Next' button setButtonText(QWizard::CommitButton, wizard()->buttonText(QWizard::NextButton)); } void ChooseFilePage::setFileDlgOptions(const QString &dlgTitle, const QStringList &fileFormats) { - fileDlgTitle = dlgTitle; + fileDlgTitle = dlgTitle; fileDlgFormats = fileFormats; } @@ -75,7 +75,7 @@ bool ChooseFilePage::validatePage() QString fileName = pathEdit->text(); QFileInfo f(fileName); - if(f.exists() && f.isFile()) + if (f.exists() && f.isFile()) { emit fileChosen(fileName); return true; @@ -93,7 +93,7 @@ void ChooseFilePage::onChoose() dlg->setAcceptMode(QFileDialog::AcceptOpen); dlg->setNameFilters(fileDlgFormats); - if(dlg->exec() != QDialog::Accepted || !dlg) + if (dlg->exec() != QDialog::Accepted || !dlg) return; QString fileName = dlg->selectedUrls().value(0).toLocalFile(); diff --git a/src/utils/wizard/choosefilepage.h b/src/utils/wizard/choosefilepage.h index 08af419..dc5716f 100644 --- a/src/utils/wizard/choosefilepage.h +++ b/src/utils/wizard/choosefilepage.h @@ -35,10 +35,10 @@ public: bool validatePage() override; void initializePage() override; - void setFileDlgOptions(const QString& dlgTitle, const QStringList& fileFormats); + void setFileDlgOptions(const QString &dlgTitle, const QStringList &fileFormats); signals: - void fileChosen(const QString& fileName); + void fileChosen(const QString &fileName); private slots: void onChoose(); diff --git a/src/utils/worker_event_types.h b/src/utils/worker_event_types.h index 32af251..6e2c8ff 100644 --- a/src/utils/worker_event_types.h +++ b/src/utils/worker_event_types.h @@ -22,17 +22,17 @@ #include -//Here we define custom QEvent types in a central place to avoid conflicts +// Here we define custom QEvent types in a central place to avoid conflicts enum class CustomEvents { - //IQuittableTask + // IQuittableTask TaskProgress = QEvent::User + 1, - //Searchbox + // Searchbox SearchBoxResults, - //RS error checker + // RS error checker RsErrWorkerResult, // RS Import @@ -43,16 +43,16 @@ enum class CustomEvents RsImportedOwnersResult, RsImportCheckDuplicates, - //RS main models + // RS main models RollingstockModelResult, RsModelsModelResult, RsOwnersModelResult, RsOnDemandListModelResult, - //Shift + // Shift ShiftWorkerResult, - //Stations + // Stations StationsModelResult, LinesModelResult, LineSegmentsModelResult, @@ -62,16 +62,16 @@ enum class CustomEvents StationTracksListResult, StationTrackConnListResult, - //Jobs + // Jobs JobsModelResult, - //Jobs Checker + // Jobs Checker JobsCrossingCheckResult, - //Printing + // Printing PrintProgress, - //Line Graph Manager + // Line Graph Manager LineGraphManagerUpdate }; diff --git a/src/viewmanager/rsjobviewer.cpp b/src/viewmanager/rsjobviewer.cpp index 71c3c98..965265e 100644 --- a/src/viewmanager/rsjobviewer.cpp +++ b/src/viewmanager/rsjobviewer.cpp @@ -44,10 +44,10 @@ RSJobViewer::RSJobViewer(QWidget *parent) : { QVBoxLayout *lay = new QVBoxLayout(this); - infoLabel = new QLabel(this); + infoLabel = new QLabel(this); lay->addWidget(infoLabel); - view = new QTableView(this); + view = new QTableView(this); model = new RsPlanModel(Session->m_Db, this); view->setModel(model); @@ -65,7 +65,6 @@ RSJobViewer::RSJobViewer(QWidget *parent) : RSJobViewer::~RSJobViewer() { - } void RSJobViewer::setRS(db_id id) @@ -75,7 +74,7 @@ void RSJobViewer::setRS(db_id id) void RSJobViewer::updatePlan() { - //TODO: clear data 5 seconds after window is hidden + // TODO: clear data 5 seconds after window is hidden model->loadPlan(m_rsId); view->resizeColumnsToContents(); } @@ -83,19 +82,19 @@ void RSJobViewer::updatePlan() void RSJobViewer::showContextMenu(const QPoint &pos) { QModelIndex idx = view->indexAt(pos); - if(!idx.isValid()) + if (!idx.isValid()) return; - RsPlanItem item = model->getItem(idx.row()); + RsPlanItem item = model->getItem(idx.row()); OwningQPointer menu = new QMenu(this); - QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); + QAction *showInJobEditor = new QAction(tr("Show in Job Editor"), menu); menu->addAction(showInJobEditor); QAction *act = menu->exec(view->viewport()->mapToGlobal(pos)); - if(act == showInJobEditor) + if (act == showInJobEditor) { Session->getViewManager()->requestJobEditor(item.jobId, item.stopId); } @@ -103,40 +102,41 @@ void RSJobViewer::showContextMenu(const QPoint &pos) void RSJobViewer::updateRsInfo() { - query q_getRSInfo(Session->m_Db, "SELECT rs_list.number,rs_models.name,rs_models.suffix,rs_models.type,rs_owners.name" - " FROM rs_list" - " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" - " LEFT JOIN rs_owners ON rs_owners.id=rs_list.owner_id" - " WHERE rs_list.id=?"); + query q_getRSInfo( + Session->m_Db, + "SELECT rs_list.number,rs_models.name,rs_models.suffix,rs_models.type,rs_owners.name" + " FROM rs_list" + " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" + " LEFT JOIN rs_owners ON rs_owners.id=rs_list.owner_id" + " WHERE rs_list.id=?"); q_getRSInfo.bind(1, m_rsId); int ret = q_getRSInfo.step(); - if(ret != SQLITE_ROW) + if (ret != SQLITE_ROW) { - //Error: RS does not exist! + // Error: RS does not exist! close(); return; } - auto rs = q_getRSInfo.getRows(); - sqlite3_stmt *stmt = q_getRSInfo.stmt(); - int number = rs.get(0); - int modelNameLen = sqlite3_column_bytes(stmt, 1); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 1)); + auto rs = q_getRSInfo.getRows(); + sqlite3_stmt *stmt = q_getRSInfo.stmt(); + int number = rs.get(0); + int modelNameLen = sqlite3_column_bytes(stmt, 1); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 1)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 2); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 2)); - RsType type = RsType(rs.get(3)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 2); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 2)); + RsType type = RsType(rs.get(3)); - QString owner = rs.get(4); + QString owner = rs.get(4); - const QString name = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + const QString name = + rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, modelSuffixLen, type); setWindowTitle(name); const QString info = tr("Type: %1
" - "Owner: %2").arg(RsTypeNames::name(type)); + "Owner: %2") + .arg(RsTypeNames::name(type)); infoLabel->setText(owner.isEmpty() ? info.arg(tr("Not set!")) : info.arg(owner)); } diff --git a/src/viewmanager/rsplanmodel.cpp b/src/viewmanager/rsplanmodel.cpp index 273d7ec..dbb6bc5 100644 --- a/src/viewmanager/rsplanmodel.cpp +++ b/src/viewmanager/rsplanmodel.cpp @@ -26,17 +26,15 @@ using namespace sqlite3pp; #include -RsPlanModel::RsPlanModel(sqlite3pp::database &db, - QObject *parent) : +RsPlanModel::RsPlanModel(sqlite3pp::database &db, QObject *parent) : QAbstractTableModel(parent), mDb(db) { - } QVariant RsPlanModel::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) { @@ -72,9 +70,9 @@ QVariant RsPlanModel::data(const QModelIndex &idx, int role) const if (!idx.isValid() || idx.row() >= m_data.size() || idx.column() >= NCols) return QVariant(); - const RsPlanItem& item = m_data.at(idx.row()); + const RsPlanItem &item = m_data.at(idx.row()); const RsPlanItem *prevItem = nullptr; - if(idx.row() > 0) + if (idx.row() > 0) prevItem = &m_data.at(idx.row() - 1); switch (role) @@ -92,28 +90,27 @@ QVariant RsPlanModel::data(const QModelIndex &idx, int role) const case Departure: return item.departure; case Operation: - return item.op == RsOp::Coupled ? - tr("Coupled") : tr("Uncoupled"); + return item.op == RsOp::Coupled ? tr("Coupled") : tr("Uncoupled"); } break; } case Qt::BackgroundRole: { - //Mark cells with errors + // Mark cells with errors switch (idx.column()) { case Station: { - //Coupled in a different station than previous, this means it gets teleported - if(item.op == RsOp::Coupled && prevItem && prevItem->stationId != item.stationId) - return QBrush(QColor(255, 0, 183)); //Magenta + // Coupled in a different station than previous, this means it gets teleported + if (item.op == RsOp::Coupled && prevItem && prevItem->stationId != item.stationId) + return QBrush(QColor(255, 0, 183)); // Magenta break; } case Operation: { - //Coupled while already coupled or uncoupled while not coupled - if(prevItem && item.op == prevItem->op) - return QBrush(QColor(255, 110, 110)); //Light red + // Coupled while already coupled or uncoupled while not coupled + if (prevItem && item.op == prevItem->op) + return QBrush(QColor(255, 110, 110)); // Light red break; } } @@ -130,33 +127,32 @@ void RsPlanModel::loadPlan(db_id rsId) m_data.clear(); - //TODO: load in thread with same query prepared form many models - query q_selectOps(mDb, - "SELECT stops.id," - "stops.job_id," - "jobs.category," - "stops.station_id," - "stops.arrival," - "stops.departure," - "coupling.operation," - "stations.name" - " FROM stops" - " JOIN coupling ON coupling.stop_id=stops.id AND coupling.rs_id=?" - " JOIN jobs ON jobs.id=stops.job_id" - " JOIN stations ON stations.id=stops.station_id" - " ORDER BY stops.arrival"); + // TODO: load in thread with same query prepared form many models + query q_selectOps(mDb, "SELECT stops.id," + "stops.job_id," + "jobs.category," + "stops.station_id," + "stops.arrival," + "stops.departure," + "coupling.operation," + "stations.name" + " FROM stops" + " JOIN coupling ON coupling.stop_id=stops.id AND coupling.rs_id=?" + " JOIN jobs ON jobs.id=stops.job_id" + " JOIN stations ON stations.id=stops.station_id" + " ORDER BY stops.arrival"); q_selectOps.bind(1, rsId); - for(auto r : q_selectOps) + for (auto r : q_selectOps) { RsPlanItem item; - item.stopId = r.get(0); - item.jobId = r.get(1); - item.jobCat = JobCategory(r.get(2)); - item.stationId = r.get(3); - item.arrival = r.get(4); - item.departure = r.get(5); - item.op = RsOp(r.get(6)); + item.stopId = r.get(0); + item.jobId = r.get(1); + item.jobCat = JobCategory(r.get(2)); + item.stationId = r.get(3); + item.arrival = r.get(4); + item.departure = r.get(5); + item.op = RsOp(r.get(6)); item.stationName = r.get(7); m_data.append(item); diff --git a/src/viewmanager/rsplanmodel.h b/src/viewmanager/rsplanmodel.h index 919b743..ab5998a 100644 --- a/src/viewmanager/rsplanmodel.h +++ b/src/viewmanager/rsplanmodel.h @@ -59,11 +59,11 @@ public: NCols }; - RsPlanModel(sqlite3pp::database& db, - QObject *parent = nullptr); + RsPlanModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -77,7 +77,7 @@ public: RsPlanItem getItem(int row); private: - sqlite3pp::database& mDb; + sqlite3pp::database &mDb; QVector m_data; }; diff --git a/src/viewmanager/sessionstartendmodel.cpp b/src/viewmanager/sessionstartendmodel.cpp index 530e270..93b5f3c 100644 --- a/src/viewmanager/sessionstartendmodel.cpp +++ b/src/viewmanager/sessionstartendmodel.cpp @@ -37,12 +37,11 @@ SessionStartEndModel::SessionStartEndModel(sqlite3pp::database &db, QObject *par m_mode(SessionRSMode::StartOfSession), m_order(SessionRSOrder::ByStation) { - } QVariant SessionStartEndModel::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) { @@ -55,7 +54,8 @@ QVariant SessionStartEndModel::headerData(int section, Qt::Orientation orientati case DepartureCol: return m_mode == SessionRSMode::StartOfSession ? tr("Departure") : tr("Arrival"); case StationOrOwnerCol: - return m_order == SessionRSOrder::ByStation ? tr("Owner") : tr("Station"); //Opposite of order + return m_order == SessionRSOrder::ByStation ? tr("Owner") + : tr("Station"); // Opposite of order default: break; } @@ -65,21 +65,22 @@ QVariant SessionStartEndModel::headerData(int section, Qt::Orientation orientati QModelIndex SessionStartEndModel::index(int row, int column, const QModelIndex &p) const { - if(p.isValid()) + if (p.isValid()) { - if(p.internalId() != PARENT) + if (p.internalId() != PARENT) return QModelIndex(); - //It's a rs + // It's a rs int parentRow = p.row(); - if(parentRow < 0 || parentRow >= parents.size()) + if (parentRow < 0 || parentRow >= parents.size()) return QModelIndex(); - if(row < 0 || (row + parents[parentRow].firstIdx) >= rsData.size() || column < 0 || column >= NCols) + if (row < 0 || (row + parents[parentRow].firstIdx) >= rsData.size() || column < 0 + || column >= NCols) return QModelIndex(); QModelIndex par = parent(createIndex(row, column, parentRow)); - if(par != p) + if (par != p) { qWarning() << "IDX ERROR" << p << par; par = parent(createIndex(row, column, parentRow)); @@ -88,8 +89,8 @@ QModelIndex SessionStartEndModel::index(int row, int column, const QModelIndex & return createIndex(row, column, parentRow); } - //Station or RS owner - if(row < 0 || row >= parents.size() || column != 0) + // Station or RS owner + if (row < 0 || row >= parents.size() || column != 0) return QModelIndex(); Q_ASSERT(parent(createIndex(row, column, PARENT)) == p); @@ -99,7 +100,7 @@ QModelIndex SessionStartEndModel::index(int row, int column, const QModelIndex & QModelIndex SessionStartEndModel::parent(const QModelIndex &idx) const { - if(!idx.isValid() || idx.internalId() == PARENT) + if (!idx.isValid() || idx.internalId() == PARENT) return QModelIndex(); int parentRow = int(idx.internalId()); @@ -109,20 +110,20 @@ QModelIndex SessionStartEndModel::parent(const QModelIndex &idx) const int SessionStartEndModel::rowCount(const QModelIndex &p) const { - if(p.isValid()) + if (p.isValid()) { - if(p.internalId() != PARENT) - return 0; //RS + if (p.internalId() != PARENT) + return 0; // RS - //Station or Owner + // Station or Owner int firstIdx = parents.at(p.row()).firstIdx; - int lastIdx = rsData.size(); //Until end - if(p.row() + 1 < parents.size()) - lastIdx = parents.at(p.row() + 1).firstIdx; //Until next station/owner first index + int lastIdx = rsData.size(); // Until end + if (p.row() + 1 < parents.size()) + lastIdx = parents.at(p.row() + 1).firstIdx; // Until next station/owner first index return lastIdx - firstIdx; } - //Root + // Root return parents.size(); } @@ -133,12 +134,12 @@ int SessionStartEndModel::columnCount(const QModelIndex &parent) const QVariant SessionStartEndModel::data(const QModelIndex &idx, int role) const { - if(!idx.isValid()) + if (!idx.isValid()) return QVariant(); - if(idx.internalId() == PARENT) + if (idx.internalId() == PARENT) { - //Station or Owner + // Station or Owner switch (role) { case Qt::DisplayRole: @@ -155,9 +156,9 @@ QVariant SessionStartEndModel::data(const QModelIndex &idx, int role) const } else { - //RS - int realIdx = parents.at(int(idx.internalId())).firstIdx + idx.row(); - const RSItem& item = rsData.at(realIdx); + // RS + int realIdx = parents.at(int(idx.internalId())).firstIdx + idx.row(); + const RSItem &item = rsData.at(realIdx); switch (role) { case Qt::DisplayRole: @@ -167,7 +168,7 @@ QVariant SessionStartEndModel::data(const QModelIndex &idx, int role) const case RsNameCol: return item.rsName; case JobCol: - //return item.jobId; + // return item.jobId; return JobCategoryName::jobName(item.jobId, item.jobCategory); case PlatfCol: return item.platform; @@ -187,9 +188,9 @@ QVariant SessionStartEndModel::data(const QModelIndex &idx, int role) const bool SessionStartEndModel::hasChildren(const QModelIndex &parent) const { - if(parent.isValid()) + if (parent.isValid()) { - if(parent.internalId() == PARENT) + if (parent.internalId() == PARENT) return true; return false; } @@ -199,24 +200,24 @@ bool SessionStartEndModel::hasChildren(const QModelIndex &parent) const QModelIndex SessionStartEndModel::sibling(int row, int column, const QModelIndex &idx) const { - if(!idx.isValid()) + if (!idx.isValid()) return QModelIndex(); - if(idx.internalId() == PARENT) + if (idx.internalId() == PARENT) { - if(row < parents.size() && column == 1) + if (row < parents.size() && column == 1) return createIndex(row, column, PARENT); } else { int parentIdx = int(idx.internalId()); - int firstIdx = parents.at(parentIdx).firstIdx; - int lastIdx = rsData.size(); - if(parentIdx + 1 < parents.size()) + int firstIdx = parents.at(parentIdx).firstIdx; + int lastIdx = rsData.size(); + if (parentIdx + 1 < parents.size()) lastIdx = parents.at(parentIdx + 1).firstIdx; int count = firstIdx - lastIdx; - if(row < count) + if (row < count) return createIndex(row, column, parentIdx); } @@ -227,13 +228,13 @@ Qt::ItemFlags SessionStartEndModel::flags(const QModelIndex &idx) const { Qt::ItemFlags f; - if(!idx.isValid()) + if (!idx.isValid()) return f; f.setFlag(Qt::ItemIsEnabled); f.setFlag(Qt::ItemIsSelectable); - if(idx.internalId() != PARENT) + if (idx.internalId() != PARENT) f.setFlag(Qt::ItemNeverHasChildren); return f; @@ -241,11 +242,11 @@ Qt::ItemFlags SessionStartEndModel::flags(const QModelIndex &idx) const void SessionStartEndModel::setMode(SessionRSMode m, SessionRSOrder o, bool forceReload) { - if(m_mode == m && m_order == o && !forceReload) + if (m_mode == m && m_order == o && !forceReload) return; beginResetModel(); - m_mode = m; + m_mode = m; m_order = o; rsData.clear(); @@ -260,94 +261,97 @@ void SessionStartEndModel::setMode(SessionRSMode m, SessionRSOrder o, bool force rsData.reserve(count); - //TODO: fetch departure instead of arrival for start session + // TODO: fetch departure instead of arrival for start session - //Query template: MIN/MAX to get RS at start/end of session then order by station/s_owner - const auto sql = QStringLiteral("SELECT %1(stops.arrival), stops.station_id, rs_list.owner_id," - " stations.name, rs_owners.name," - " rs_list.id, rs_models.name, rs_models.suffix, rs_list.number, rs_models.type," - " stops.job_id, jobs.category," - " coupling.operation, t1.name,t2.name" - " FROM rs_list" - " JOIN coupling ON coupling.rs_id=rs_list.id" - " JOIN stops ON stops.id=coupling.stop_id" - " JOIN stations ON stations.id=stops.station_id" - " JOIN jobs ON jobs.id=stops.job_id" - " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" - " LEFT JOIN station_gate_connections g2 ON g2.id=stops.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" - " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" - " LEFT JOIN rs_owners ON rs_owners.id=rs_list.owner_id" //It might be null - " GROUP BY rs_list.id" - " ORDER BY %2, stops.arrival, stops.job_id, rs_list.model_id"); + // Query template: MIN/MAX to get RS at start/end of session then order by station/s_owner + const auto sql = QStringLiteral( + "SELECT %1(stops.arrival), stops.station_id, rs_list.owner_id," + " stations.name, rs_owners.name," + " rs_list.id, rs_models.name, rs_models.suffix, rs_list.number, rs_models.type," + " stops.job_id, jobs.category," + " coupling.operation, t1.name,t2.name" + " FROM rs_list" + " JOIN coupling ON coupling.rs_id=rs_list.id" + " JOIN stops ON stops.id=coupling.stop_id" + " JOIN stations ON stations.id=stops.station_id" + " JOIN jobs ON jobs.id=stops.job_id" + " LEFT JOIN station_gate_connections g1 ON g1.id=stops.in_gate_conn" + " LEFT JOIN station_gate_connections g2 ON g2.id=stops.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" + " LEFT JOIN rs_models ON rs_models.id=rs_list.model_id" + " LEFT JOIN rs_owners ON rs_owners.id=rs_list.owner_id" // It might be null + " GROUP BY rs_list.id" + " ORDER BY %2, stops.arrival, stops.job_id, rs_list.model_id"); - QByteArray query = sql.arg(m_mode == SessionRSMode::StartOfSession ? "MIN" : "MAX", - m_order == SessionRSOrder::ByStation ? "stops.station_id" : "rs_list.owner_id") - .toUtf8(); + QByteArray query = + sql + .arg(m_mode == SessionRSMode::StartOfSession ? "MIN" : "MAX", + m_order == SessionRSOrder::ByStation ? "stops.station_id" : "rs_list.owner_id") + .toUtf8(); q.prepare(query.constData()); db_id lastParentId = 0; - int row = 0; + int row = 0; sqlite3_stmt *stmt = q.stmt(); - for(auto rs : q) + for (auto rs : q) { RSItem item; - item.time = rs.get(0); + item.time = rs.get(0); db_id stationId = rs.get(1); - db_id ownerId = rs.get(2); + db_id ownerId = rs.get(2); - db_id parentId = 0; + db_id parentId = 0; - if(m_order == SessionRSOrder::ByStation) + if (m_order == SessionRSOrder::ByStation) { - parentId = stationId; - item.stationOrOwnerId = ownerId; + parentId = stationId; + item.stationOrOwnerId = ownerId; item.stationOrOwnerName = rs.get(4); - }else{ - parentId = ownerId; - item.stationOrOwnerId = stationId; + } + else + { + parentId = ownerId; + item.stationOrOwnerId = stationId; item.stationOrOwnerName = rs.get(3); } - if(parentId != lastParentId) + if (parentId != lastParentId) { ParentItem s; - s.id = parentId; - s.name = rs.get(m_order == SessionRSOrder::ByStation ? 3 : 4); + s.id = parentId; + s.name = rs.get(m_order == SessionRSOrder::ByStation ? 3 : 4); s.firstIdx = row; parents.append(s); lastParentId = parentId; } - item.parentIdx = parents.size() - 1; - item.rsId = rs.get(5); + item.parentIdx = parents.size() - 1; + item.rsId = rs.get(5); - int modelNameLen = sqlite3_column_bytes(stmt, 6); - const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 6)); + int modelNameLen = sqlite3_column_bytes(stmt, 6); + const char *modelName = reinterpret_cast(sqlite3_column_text(stmt, 6)); - int modelSuffixLen = sqlite3_column_bytes(stmt, 7); - const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 7)); - int number = rs.get(8); - RsType type = RsType(rs.get(9)); + int modelSuffixLen = sqlite3_column_bytes(stmt, 7); + const char *modelSuffix = reinterpret_cast(sqlite3_column_text(stmt, 7)); + int number = rs.get(8); + RsType type = RsType(rs.get(9)); - item.rsName = rs_utils::formatNameRef(modelName, modelNameLen, - number, - modelSuffix, modelSuffixLen, - type); + item.rsName = rs_utils::formatNameRef(modelName, modelNameLen, number, modelSuffix, + modelSuffixLen, type); - item.jobId = rs.get(10); + item.jobId = rs.get(10); item.jobCategory = JobCategory(rs.get(11)); - //TODO: check operation (12) + // TODO: check operation (12) item.platform = rs.get(13); - if(item.platform.isEmpty()) - item.platform = rs.get(14); //Use out gate to get track name + if (item.platform.isEmpty()) + item.platform = rs.get(14); // Use out gate to get track name rsData.append(item); diff --git a/src/viewmanager/sessionstartendmodel.h b/src/viewmanager/sessionstartendmodel.h index aac7cae..655436e 100644 --- a/src/viewmanager/sessionstartendmodel.h +++ b/src/viewmanager/sessionstartendmodel.h @@ -32,18 +32,18 @@ namespace sqlite3pp { class database; } -//FIXME: make incremental loading, cached like other on-demand models +// FIXME: make incremental loading, cached like other on-demand models class SessionStartEndModel : public QAbstractItemModel { Q_OBJECT public: - //Station or RS Owner + // Station or RS Owner struct ParentItem { db_id id; QString name; - int firstIdx; //First RS index + int firstIdx; // First RS index }; struct RSItem @@ -69,12 +69,11 @@ public: NCols }; - - SessionStartEndModel(sqlite3pp::database &db, QObject *parent = nullptr); // Header: - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; // Basic functionality: QModelIndex index(int row, int column, @@ -90,12 +89,18 @@ public: QModelIndex sibling(int row, int column, const QModelIndex &idx) const override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; + Qt::ItemFlags flags(const QModelIndex &idx) const override; void setMode(SessionRSMode m, SessionRSOrder o, bool forceReload = false); - inline SessionRSMode mode() const { return m_mode; } - inline SessionRSOrder order() const { return m_order; } + inline SessionRSMode mode() const + { + return m_mode; + } + inline SessionRSOrder order() const + { + return m_order; + } private: sqlite3pp::database &mDb; diff --git a/src/viewmanager/sessionstartendrsviewer.cpp b/src/viewmanager/sessionstartendrsviewer.cpp index fffd7ea..1686b4a 100644 --- a/src/viewmanager/sessionstartendrsviewer.cpp +++ b/src/viewmanager/sessionstartendrsviewer.cpp @@ -42,7 +42,7 @@ SessionStartEndRSViewer::SessionStartEndRSViewer(QWidget *parent) : QWidget(parent) { - QVBoxLayout *lay = new QVBoxLayout(this); + QVBoxLayout *lay = new QVBoxLayout(this); QToolBar *toolBar = new QToolBar; lay->addWidget(toolBar); @@ -57,8 +57,10 @@ SessionStartEndRSViewer::SessionStartEndRSViewer(QWidget *parent) : orderCombo->addItem(tr("Order By Owner"), int(SessionRSOrder::ByOwner)); toolBar->addWidget(orderCombo); - connect(modeCombo, qOverload(&QComboBox::activated), this, &SessionStartEndRSViewer::modeChanged); - connect(orderCombo, qOverload(&QComboBox::activated), this, &SessionStartEndRSViewer::orderChanged); + connect(modeCombo, qOverload(&QComboBox::activated), this, + &SessionStartEndRSViewer::modeChanged); + connect(orderCombo, qOverload(&QComboBox::activated), this, + &SessionStartEndRSViewer::orderChanged); toolBar->addAction(tr("Export Sheet"), this, &SessionStartEndRSViewer::exportSheet); @@ -100,7 +102,7 @@ void SessionStartEndRSViewer::exportSheet() { const QLatin1String session_rs_key = QLatin1String("session_rs_dir"); - OwningQPointer dlg = new QFileDialog(this, tr("Expoert RS session plan")); + OwningQPointer dlg = new QFileDialog(this, tr("Expoert RS session plan")); dlg->setFileMode(QFileDialog::AnyFile); dlg->setAcceptMode(QFileDialog::AcceptSave); dlg->setDirectory(RecentDirStore::getDir(session_rs_key, RecentDirStore::Documents)); @@ -109,11 +111,11 @@ void SessionStartEndRSViewer::exportSheet() 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(session_rs_key, fileName); diff --git a/src/viewmanager/sessionstartendrsviewer.h b/src/viewmanager/sessionstartendrsviewer.h index 6f422b6..b5a6a64 100644 --- a/src/viewmanager/sessionstartendrsviewer.h +++ b/src/viewmanager/sessionstartendrsviewer.h @@ -37,6 +37,7 @@ private slots: void modeChanged(); void exportSheet(); + private: SessionStartEndModel *model; diff --git a/src/viewmanager/viewmanager.cpp b/src/viewmanager/viewmanager.cpp index 3891134..8eb5ada 100644 --- a/src/viewmanager/viewmanager.cpp +++ b/src/viewmanager/viewmanager.cpp @@ -60,20 +60,20 @@ ViewManager::ViewManager(QObject *parent) : { lineGraphManager = new LineGraphManager(this); - //RollingStock + // RollingStock connect(Session, &MeetingSession::rollingstockRemoved, this, &ViewManager::onRSRemoved); connect(Session, &MeetingSession::rollingStockPlanChanged, this, &ViewManager::onRSPlanChanged); connect(Session, &MeetingSession::rollingStockModified, this, &ViewManager::onRSInfoChanged); - //Stations + // Stations connect(Session, &MeetingSession::stationRemoved, this, &ViewManager::onStRemoved); connect(Session, &MeetingSession::stationNameChanged, this, &ViewManager::onStNameChanged); connect(Session, &MeetingSession::stationJobsPlanChanged, this, &ViewManager::onStPlanChanged); - //Jobs + // Jobs connect(Session, &MeetingSession::jobRemoved, this, &ViewManager::onJobRemoved); - //Shifts + // Shifts connect(Session, &MeetingSession::shiftNameChanged, this, &ViewManager::onShiftEdited); connect(Session, &MeetingSession::shiftRemoved, this, &ViewManager::onShiftRemoved); connect(Session, &MeetingSession::shiftJobsChanged, this, &ViewManager::onShiftJobsChanged); @@ -84,14 +84,14 @@ void ViewManager::requestRSInfo(db_id rsId) DEBUG_ENTRY; RSJobViewer *viewer = nullptr; - auto it = rsHash.constFind(rsId); - if(it != rsHash.cend()) + auto it = rsHash.constFind(rsId); + if (it != rsHash.cend()) { viewer = it.value(); } else { - //Create a new viewer + // Create a new viewer viewer = createRSViewer(rsId); } @@ -113,10 +113,7 @@ RSJobViewer *ViewManager::createRSViewer(db_id rsId) viewer->setObjectName(QString("RSJobViewer_%1").arg(rsId)); rsHash.insert(rsId, viewer); - connect(viewer, &RSJobViewer::destroyed, this, [this, rsId]() - { - rsHash.remove(rsId); - }); + connect(viewer, &RSJobViewer::destroyed, this, [this, rsId]() { rsHash.remove(rsId); }); return viewer; } @@ -125,13 +122,11 @@ void ViewManager::showRSManager() { DEBUG_ENTRY; - if(rsManager == nullptr) + if (rsManager == nullptr) { rsManager = new RollingStockManager(m_mainWidget); - connect(rsManager, &RollingStockManager::destroyed, this, [this]() - { - rsManager = nullptr; - }); + connect(rsManager, &RollingStockManager::destroyed, this, + [this]() { rsManager = nullptr; }); rsManager->setAttribute(Qt::WA_DeleteOnClose); rsManager->setWindowFlag(Qt::Window); @@ -145,7 +140,7 @@ void ViewManager::showRSManager() void ViewManager::onRSRemoved(db_id rsId) { auto it = rsHash.constFind(rsId); - if(it != rsHash.cend()) + if (it != rsHash.cend()) { it.value()->close(); rsHash.erase(it); @@ -154,10 +149,10 @@ void ViewManager::onRSRemoved(db_id rsId) void ViewManager::onRSPlanChanged(QSet set) { - for(auto rsId : set) + for (auto rsId : set) { auto it = rsHash.constFind(rsId); - if(it != rsHash.cend()) + if (it != rsHash.cend()) { RSJobViewer *viewer = it.value(); viewer->updatePlan(); @@ -169,7 +164,7 @@ void ViewManager::onRSPlanChanged(QSet set) void ViewManager::onRSInfoChanged(db_id rsId) { auto it = rsHash.constFind(rsId); - if(it != rsHash.cend()) + if (it != rsHash.cend()) { RSJobViewer *viewer = it.value(); viewer->updateInfo(); @@ -180,13 +175,10 @@ void ViewManager::onRSInfoChanged(db_id rsId) void ViewManager::showStationsManager() { DEBUG_ENTRY; - if(stManager == nullptr) + if (stManager == nullptr) { stManager = new StationsManager(m_mainWidget); - connect(stManager, &StationsManager::destroyed, this, [this]() - { - stManager = nullptr; - }); + connect(stManager, &StationsManager::destroyed, this, [this]() { stManager = nullptr; }); stManager->setAttribute(Qt::WA_DeleteOnClose); stManager->setWindowFlag(Qt::Window); @@ -200,21 +192,21 @@ void ViewManager::showStationsManager() void ViewManager::onStRemoved(db_id stId) { auto it = stHash.constFind(stId); - if(it != stHash.cend()) + if (it != stHash.cend()) { it.value()->close(); stHash.erase(it); } auto it2 = stRSHash.constFind(stId); - if(it2 != stRSHash.cend()) + if (it2 != stRSHash.cend()) { it2.value()->close(); stRSHash.erase(it2); } auto it3 = stPlanHash.constFind(stId); - if(it3 != stPlanHash.cend()) + if (it3 != stPlanHash.cend()) { it3.value()->close(); stPlanHash.erase(it3); @@ -223,46 +215,47 @@ void ViewManager::onStRemoved(db_id stId) void ViewManager::onStNameChanged(db_id stId) { - //If there is a StationJobViewer window open for this station, update it's title (= new station name) + // If there is a StationJobViewer window open for this station, update it's title (= new station + // name) auto it = stHash.constFind(stId); - if(it != stHash.cend()) + if (it != stHash.cend()) { it.value()->updateName(); } - //Same for StationFreeRSViewer + // Same for StationFreeRSViewer auto it2 = stRSHash.constFind(stId); - if(it2 != stRSHash.cend()) + if (it2 != stRSHash.cend()) { it2.value()->updateTitle(); } auto it3 = stPlanHash.constFind(stId); - if(it3 != stPlanHash.cend()) + if (it3 != stPlanHash.cend()) { it3.value()->reloadDBData(); } } -void ViewManager::onStPlanChanged(const QSet& stationIds) +void ViewManager::onStPlanChanged(const QSet &stationIds) { - //If there is a StationJobViewer window open for this station, update it's contents - for(db_id stationId : stationIds) + // If there is a StationJobViewer window open for this station, update it's contents + for (db_id stationId : stationIds) { auto it = stHash.constFind(stationId); - if(it != stHash.cend()) + if (it != stHash.cend()) { it.value()->updateJobsList(); } auto it2 = stRSHash.constFind(stationId); - if(it2 != stRSHash.cend()) + if (it2 != stRSHash.cend()) { it2.value()->updateData(); } auto it3 = stPlanHash.constFind(stationId); - if(it3 != stPlanHash.cend()) + if (it3 != stPlanHash.cend()) { it3.value()->reloadDBData(); } @@ -271,24 +264,24 @@ void ViewManager::onStPlanChanged(const QSet& stationIds) void ViewManager::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 views, Shift Graph Editor already reloads itself + // If jobId is zero, it means all jobs have been deleted + // Reload all views, Shift Graph Editor already reloads itself closeJobRelatedViewsHelper(); - //Reload station plans - for(auto st : qAsConst(stPlanHash)) + // Reload station plans + for (auto st : qAsConst(stPlanHash)) { st->clearJobs(); st->update(); } } -StationJobView* ViewManager::createStJobViewer(db_id stId) +StationJobView *ViewManager::createStJobViewer(db_id stId) { DEBUG_ENTRY; StationJobView *viewer = new StationJobView(m_mainWidget); @@ -299,17 +292,14 @@ StationJobView* ViewManager::createStJobViewer(db_id stId) viewer->setObjectName(QString("StationJobView_%1").arg(stId)); stHash.insert(stId, viewer); - connect(viewer, &StationJobView::destroyed, this, [this, stId]() - { - stHash.remove(stId); - }); + connect(viewer, &StationJobView::destroyed, this, [this, stId]() { stHash.remove(stId); }); return viewer; } -StationSVGPlanDlg *ViewManager::createStPlanDlg(db_id stId, QString& stNameOut) +StationSVGPlanDlg *ViewManager::createStPlanDlg(db_id stId, QString &stNameOut) { - if(!StationSVGPlanDlg::stationHasSVG(Session->m_Db, stId, &stNameOut)) + if (!StationSVGPlanDlg::stationHasSVG(Session->m_Db, stId, &stNameOut)) return nullptr; StationSVGPlanDlg *viewer = new StationSVGPlanDlg(Session->m_Db, m_mainWidget); @@ -321,10 +311,8 @@ StationSVGPlanDlg *ViewManager::createStPlanDlg(db_id stId, QString& stNameOut) viewer->setObjectName(QString("StationSVGPlanDlg_%1").arg(stId)); stPlanHash.insert(stId, viewer); - connect(viewer, &StationSVGPlanDlg::destroyed, this, [this, stId]() - { - stPlanHash.remove(stId); - }); + connect(viewer, &StationSVGPlanDlg::destroyed, this, + [this, stId]() { stPlanHash.remove(stId); }); return viewer; } @@ -334,8 +322,8 @@ void ViewManager::requestStJobViewer(db_id stId) DEBUG_ENTRY; StationJobView *viewer = nullptr; - auto it = stHash.constFind(stId); - if(it != stHash.constEnd()) + auto it = stHash.constFind(stId); + if (it != stHash.constEnd()) { viewer = it.value(); } @@ -357,8 +345,8 @@ void ViewManager::requestStSVGPlan(db_id stId, bool showJobs, const QTime &time) DEBUG_ENTRY; StationSVGPlanDlg *viewer = nullptr; - auto it = stPlanHash.constFind(stId); - if(it != stPlanHash.constEnd()) + auto it = stPlanHash.constFind(stId); + if (it != stPlanHash.constEnd()) { viewer = it.value(); } @@ -366,7 +354,7 @@ void ViewManager::requestStSVGPlan(db_id stId, bool showJobs, const QTime &time) { QString stName; viewer = createStPlanDlg(stId, stName); - if(!viewer) + if (!viewer) { QMessageBox::warning(m_mainWidget, stName, tr("Station %1 has no SVG, please add one.").arg(stName)); @@ -374,7 +362,7 @@ void ViewManager::requestStSVGPlan(db_id stId, bool showJobs, const QTime &time) } } - if(showJobs) + if (showJobs) { viewer->setJobTime(time); viewer->showJobs(true); @@ -385,7 +373,7 @@ void ViewManager::requestStSVGPlan(db_id stId, bool showJobs, const QTime &time) viewer->raise(); } -StationFreeRSViewer* ViewManager::createStFreeRSViewer(db_id stId) +StationFreeRSViewer *ViewManager::createStFreeRSViewer(db_id stId) { DEBUG_ENTRY; StationFreeRSViewer *viewer = new StationFreeRSViewer(m_mainWidget); @@ -396,10 +384,8 @@ StationFreeRSViewer* ViewManager::createStFreeRSViewer(db_id stId) viewer->setObjectName(QString("StationFreeRSViewer_%1").arg(stId)); stRSHash.insert(stId, viewer); - connect(viewer, &StationFreeRSViewer::destroyed, this, [this, stId]() - { - stRSHash.remove(stId); - }); + connect(viewer, &StationFreeRSViewer::destroyed, this, + [this, stId]() { stRSHash.remove(stId); }); return viewer; } @@ -409,8 +395,8 @@ void ViewManager::requestStFreeRSViewer(db_id stId) DEBUG_ENTRY; StationFreeRSViewer *viewer = nullptr; - auto it = stRSHash.constFind(stId); - if(it != stRSHash.constEnd()) + auto it = stRSHash.constFind(stId); + if (it != stRSHash.constEnd()) { viewer = it.value(); } @@ -430,19 +416,16 @@ void ViewManager::requestStFreeRSViewer(db_id stId) void ViewManager::showShiftManager() { DEBUG_ENTRY; - if(shiftManager == nullptr) + if (shiftManager == nullptr) { shiftManager = new ShiftManager(m_mainWidget); - connect(shiftManager, &ShiftManager::destroyed, this, [this]() - { - shiftManager = nullptr; - }); + connect(shiftManager, &ShiftManager::destroyed, this, [this]() { shiftManager = nullptr; }); shiftManager->setAttribute(Qt::WA_DeleteOnClose); shiftManager->setWindowFlag(Qt::Window); } - //shiftManager->updateModel(); + // shiftManager->updateModel(); shiftManager->showNormal(); shiftManager->update(); @@ -451,14 +434,11 @@ void ViewManager::showShiftManager() void ViewManager::showJobsManager() { - if(jobsManager == nullptr) + if (jobsManager == nullptr) { jobsManager = new JobsManager(m_mainWidget); - connect(jobsManager, &JobsManager::destroyed, this, [this]() - { - jobsManager = nullptr; - }); + connect(jobsManager, &JobsManager::destroyed, this, [this]() { jobsManager = nullptr; }); jobsManager->setAttribute(Qt::WA_DeleteOnClose); jobsManager->setWindowFlag(Qt::Window); @@ -470,12 +450,11 @@ void ViewManager::showJobsManager() void ViewManager::showSessionStartEndRSViewer() { - if(!sessionRSViewer) + if (!sessionRSViewer) { sessionRSViewer = new SessionStartEndRSViewer(m_mainWidget); - connect(sessionRSViewer, &QObject::destroyed, this, [this](){ - sessionRSViewer = nullptr; - }); + connect(sessionRSViewer, &QObject::destroyed, this, + [this]() { sessionRSViewer = nullptr; }); sessionRSViewer->setAttribute(Qt::WA_DeleteOnClose); sessionRSViewer->setWindowFlag(Qt::Window); @@ -490,7 +469,7 @@ void ViewManager::resumeRSImportation() RollingStockManager::importRS(true, m_mainWidget); } -ShiftViewer* ViewManager::createShiftViewer(db_id id) +ShiftViewer *ViewManager::createShiftViewer(db_id id) { ShiftViewer *viewer = new ShiftViewer(m_mainWidget); viewer->setAttribute(Qt::WA_DeleteOnClose); @@ -499,36 +478,33 @@ ShiftViewer* ViewManager::createShiftViewer(db_id id) viewer->setShift(id); shiftHash.insert(id, viewer); - connect(viewer, &ShiftViewer::destroyed, this, [this, id]() - { - shiftHash.remove(id); - }); + connect(viewer, &ShiftViewer::destroyed, this, [this, id]() { shiftHash.remove(id); }); return viewer; } void ViewManager::closeJobRelatedViewsHelper() { - //Close all Job related views except managers and Shift Graph Editor - //SVG station plans are left open because they are useful also for other purposes + // Close all Job related views except managers and Shift Graph Editor + // SVG station plans are left open because they are useful also for other purposes - //NOTE: because views destroyed() signals are connected to lambda - //which remove them from the list, they invalidate iterators. - //To avoid this we copy the list (swap) and iterate from copy + // NOTE: because views destroyed() signals are connected to lambda + // which remove them from the list, they invalidate iterators. + // To avoid this we copy the list (swap) and iterate from copy - //Close all rollingstock views because we have no couplings anymore + // Close all rollingstock views because we have no couplings anymore auto rsHashCopy = std::move(rsHash); qDeleteAll(rsHashCopy); - //Close all station job view + // Close all station job view auto stHashCopy = std::move(stHash); qDeleteAll(stHashCopy); - //Close all station free RS view + // Close all station free RS view auto stRSHashCopy = std::move(stRSHash); qDeleteAll(stRSHashCopy); - //Close any shift job view + // Close any shift job view auto shiftHashCopy = std::move(shiftHash); qDeleteAll(shiftHashCopy); } @@ -536,8 +512,8 @@ void ViewManager::closeJobRelatedViewsHelper() void ViewManager::requestShiftViewer(db_id id) { ShiftViewer *viewer = nullptr; - auto it = shiftHash.constFind(id); - if(it != shiftHash.constEnd()) + auto it = shiftHash.constFind(id); + if (it != shiftHash.constEnd()) { viewer = it.value(); } @@ -556,7 +532,7 @@ void ViewManager::requestShiftViewer(db_id id) void ViewManager::onShiftRemoved(db_id shiftId) { auto it = shiftHash.constFind(shiftId); - if(it != shiftHash.constEnd()) + if (it != shiftHash.constEnd()) { it.value()->close(); shiftHash.erase(it); @@ -566,7 +542,7 @@ void ViewManager::onShiftRemoved(db_id shiftId) void ViewManager::onShiftEdited(db_id shiftId) { auto it = shiftHash.constFind(shiftId); - if(it != shiftHash.constEnd()) + if (it != shiftHash.constEnd()) { it.value()->updateName(); } @@ -575,7 +551,7 @@ void ViewManager::onShiftEdited(db_id shiftId) void ViewManager::onShiftJobsChanged(db_id shiftId) { auto it = shiftHash.constFind(shiftId); - if(it != shiftHash.constEnd()) + if (it != shiftHash.constEnd()) { it.value()->updateJobsModel(); } @@ -583,46 +559,47 @@ void ViewManager::onShiftJobsChanged(db_id shiftId) bool ViewManager::closeEditors() { - if(jobEditor) + if (jobEditor) { - if(!jobEditor->clearJob()) + if (!jobEditor->clearJob()) { return false; } jobEditor->setEnabled(false); } - if(jobsManager && !jobsManager->close()) + if (jobsManager && !jobsManager->close()) { return false; } - if(rsManager && !rsManager->close()) + if (rsManager && !rsManager->close()) { return false; } - if(stManager && !stManager->close()) + if (stManager && !stManager->close()) { return false; } - if(shiftManager && !shiftManager->close()) + if (shiftManager && !shiftManager->close()) { return false; } closeJobRelatedViewsHelper(); - //Also close SVG Station Plans now - //NOTE: use copy to avoid using invalid iterators, see closeJobRelatedViewsHelper() + // Also close SVG Station Plans now + // NOTE: use copy to avoid using invalid iterators, see closeJobRelatedViewsHelper() auto stPlanCopy = std::move(stPlanHash); qDeleteAll(stPlanCopy); - if(shiftGraphEditor) + if (shiftGraphEditor) { - //Delete immidiately so ShiftGraphHolder gets deleted and releases queries - //Calling 'close()' with WA_DeleteOnClose calls 'deleteLater()' so it gets deleted after MeetingSession tries to close database + // Delete immidiately so ShiftGraphHolder gets deleted and releases queries + // Calling 'close()' with WA_DeleteOnClose calls 'deleteLater()' so it gets deleted after + // MeetingSession tries to close database delete shiftGraphEditor; shiftGraphEditor = nullptr; } @@ -638,8 +615,8 @@ void ViewManager::clearAllLineGraphs() bool ViewManager::requestJobSelection(db_id jobId, bool select, bool ensureVisible) const { LineGraphScene *scene = lineGraphManager->getActiveScene(); - if(!scene) - return false; //No active scene, we cannot select anything + if (!scene) + return false; // No active scene, we cannot select anything LineGraphSelectionHelper helper(Session->m_Db); return helper.requestJobSelection(scene, jobId, select, ensureVisible); @@ -648,12 +625,12 @@ bool ViewManager::requestJobSelection(db_id jobId, bool select, bool ensureVisib bool ViewManager::requestJobShowPrevNextSegment(bool prev, bool absolute) { LineGraphScene *scene = lineGraphManager->getActiveScene(); - if(!scene) - return false; //No active scene, we cannot select anything + if (!scene) + return false; // No active scene, we cannot select anything LineGraphSelectionHelper helper(Session->m_Db); - if(prev) + if (prev) return helper.requestCurrentJobPrevSegmentVisible(scene, absolute); else return helper.requestCurrentJobNextSegmentVisible(scene, absolute); @@ -661,17 +638,17 @@ bool ViewManager::requestJobShowPrevNextSegment(bool prev, bool absolute) bool ViewManager::requestJobEditor(db_id jobId, db_id stopId) { - if(!jobEditor || jobId == 0) + if (!jobEditor || jobId == 0) return false; - if(!jobEditor->setJob(jobId)) + if (!jobEditor->setJob(jobId)) return false; - jobEditor->parentWidget()->show(); //DockWidget must be visible + jobEditor->parentWidget()->show(); // DockWidget must be visible jobEditor->setEnabled(true); jobEditor->show(); - if(stopId) + if (stopId) { jobEditor->selectStop(stopId); } @@ -683,26 +660,26 @@ bool ViewManager::requestJobCreation() { /* Creates a new job and opens JobPathEditor */ - if(!JobsHelper::checkShiftsExist(Session->m_Db)) + if (!JobsHelper::checkShiftsExist(Session->m_Db)) { - //It's better to create Shifts before creating Jobs, - //remind the user on every new Job + // It's better to create Shifts before creating Jobs, + // remind the user on every new Job int ret = QMessageBox::question(m_mainWidget, tr("Create Shift too?"), tr("No Shift are present in this session.\n" "Do you want to create some before creating Jobs?"), QMessageBox::Yes | QMessageBox::No); - if(ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) { - //Create shift + // Create shift showShiftManager(); return false; } } - if(!jobEditor || !jobEditor->createNewJob()) - return false; //JobPathEditor is busy, abort + if (!jobEditor || !jobEditor->createNewJob()) + return false; // JobPathEditor is busy, abort - jobEditor->parentWidget()->show(); //DockWidget must be visible + jobEditor->parentWidget()->show(); // DockWidget must be visible jobEditor->setEnabled(true); jobEditor->show(); @@ -711,13 +688,13 @@ bool ViewManager::requestJobCreation() bool ViewManager::requestClearJob(bool evenIfEditing) { - if(!jobEditor) + if (!jobEditor) return false; - if(jobEditor->isEdited() && !evenIfEditing) + if (jobEditor->isEdited() && !evenIfEditing) return false; - if(!jobEditor->clearJob()) + if (!jobEditor->clearJob()) return false; jobEditor->setEnabled(false); @@ -727,21 +704,22 @@ bool ViewManager::requestClearJob(bool evenIfEditing) bool ViewManager::removeSelectedJob() { JobStopEntry selectedJob = lineGraphManager->getCurrentSelectedJob(); - if(selectedJob.jobId == 0) + if (selectedJob.jobId == 0) return false; - //Ask user confirmation - int ret = QMessageBox::question(m_mainWidget, tr("Remove Job?"), - tr("Are you sure you want to remove Job %1?") - .arg(JobCategoryName::jobName(selectedJob.jobId, selectedJob.category))); - if(ret != QMessageBox::Yes) + // Ask user confirmation + int ret = QMessageBox::question( + m_mainWidget, tr("Remove Job?"), + tr("Are you sure you want to remove Job %1?") + .arg(JobCategoryName::jobName(selectedJob.jobId, selectedJob.category))); + if (ret != QMessageBox::Yes) return false; - if(jobEditor) + if (jobEditor) { - if(jobEditor->currentJobId() == selectedJob.jobId) + if (jobEditor->currentJobId() == selectedJob.jobId) { - if(!jobEditor->clearJob()) + if (!jobEditor->clearJob()) { requestJobSelection(selectedJob.jobId, true, false); return false; @@ -755,14 +733,12 @@ bool ViewManager::removeSelectedJob() void ViewManager::requestShiftGraphEditor() { - if(shiftGraphEditor == nullptr) + if (shiftGraphEditor == nullptr) { shiftGraphEditor = new ShiftGraphEditor(m_mainWidget); - connect(shiftGraphEditor, &ShiftGraphEditor::destroyed, this, [this]() - { - shiftGraphEditor = nullptr; - }); + connect(shiftGraphEditor, &ShiftGraphEditor::destroyed, this, + [this]() { shiftGraphEditor = nullptr; }); shiftGraphEditor->setAttribute(Qt::WA_DeleteOnClose); shiftGraphEditor->setWindowFlag(Qt::Window); diff --git a/src/viewmanager/viewmanager.h b/src/viewmanager/viewmanager.h index 73d5472..6350014 100644 --- a/src/viewmanager/viewmanager.h +++ b/src/viewmanager/viewmanager.h @@ -46,19 +46,22 @@ class JobPathEditor; class LineGraphManager; - class ViewManager : public QObject { Q_OBJECT friend class MainWindow; + public: explicit ViewManager(QObject *parent = nullptr); bool closeEditors(); void clearAllLineGraphs(); - inline LineGraphManager *getLineGraphMgr() const { return lineGraphManager; } + inline LineGraphManager *getLineGraphMgr() const + { + return lineGraphManager; + } bool requestJobSelection(db_id jobId, bool select, bool ensureVisible) const; bool requestJobEditor(db_id jobId, db_id stopId = 0); @@ -80,7 +83,7 @@ public: void requestRSInfo(db_id rsId); void requestStJobViewer(db_id stId); - void requestStSVGPlan(db_id stId, bool showJobs = false, const QTime& time = QTime()); + void requestStSVGPlan(db_id stId, bool showJobs = false, const QTime &time = QTime()); void requestStFreeRSViewer(db_id stId); void requestShiftViewer(db_id id); void requestShiftGraphEditor(); @@ -95,26 +98,26 @@ public: void resumeRSImportation(); private slots: - //Rollingstock + // Rollingstock void onRSRemoved(db_id rsId); void onRSPlanChanged(QSet set); void onRSInfoChanged(db_id rsId); - //Stations + // Stations void onStRemoved(db_id stId); void onStNameChanged(db_id stId); void onStPlanChanged(const QSet &stationIds); - //Jobs + // Jobs void onJobRemoved(db_id jobId); - //Shifts + // Shifts void onShiftRemoved(db_id shiftId); void onShiftEdited(db_id shiftId); void onShiftJobsChanged(db_id shiftId); private: - RSJobViewer* createRSViewer(db_id rsId); + RSJobViewer *createRSViewer(db_id rsId); StationJobView *createStJobViewer(db_id stId); StationSVGPlanDlg *createStPlanDlg(db_id stId, QString &stNameOut); StationFreeRSViewer *createStFreeRSViewer(db_id stId);