From 2ef44eff00cf3455203a0fc4457de82147a3a5d2 Mon Sep 17 00:00:00 2001 From: liranbg Date: Sat, 4 Oct 2014 03:47:14 +0300 Subject: [PATCH 01/58] added progress bar ; --- main/LoginTab/loginhandler.cpp | 13 +- main/LoginTab/loginhandler.h | 4 +- main/main.cpp | 14 +- main/mainscreen.cpp | 451 ++++++++++++++------------- main/mainscreen.h | 2 + main/mainscreen.ui | 39 +++ src/jceConnection/jcesslclient.cpp | 468 +++++++++++++++-------------- src/jceConnection/jcesslclient.h | 10 +- src/jceSettings/jcelogin.cpp | 8 +- src/jceSettings/jcelogin.h | 6 +- 10 files changed, 558 insertions(+), 457 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 50d75fa..572bcb0 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -1,19 +1,26 @@ #include "loginhandler.h" -loginHandler::loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr): logggedInFlag(false) +loginHandler::loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr,QProgressBar *progressbarPtr): logggedInFlag(false) { this->loginButtonPtr = loginButtonPtr; + this->progressBar = progressbarPtr; //statusBar statusBar = statusBarPtr; - iconButtomStatusLabel = new QLabel(); + iconButtomStatusLabel = new QLabel(statusBarPtr); + iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); + + //display progressbar and then ball icon. + statusBar->addPermanentWidget(progressBar,0); statusBar->addPermanentWidget(iconButtomStatusLabel,0); + setIconConnectionStatus(jceLogin::jceStatus::JCE_NOT_CONNECTED); //user settings userPtr = ptr; - this->jceLog = new jceLogin(userPtr); + this->jceLog = new jceLogin(userPtr,progressBar); QObject::connect(this->jceLog,SIGNAL(connectionReadyAfterDisconnection()),this,SLOT(readyAfterConnectionLost())); + } bool loginHandler::login(QString username,QString password) { diff --git a/main/LoginTab/loginhandler.h b/main/LoginTab/loginhandler.h index 6debc9a..8512ec1 100644 --- a/main/LoginTab/loginhandler.h +++ b/main/LoginTab/loginhandler.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "./src/jceSettings/jcelogin.h" @@ -17,7 +18,7 @@ class loginHandler : public QObject { Q_OBJECT public: - loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr); + loginHandler(user *ptr, QStatusBar *statusBarPtr, QPushButton *loginButtonPtr, QProgressBar *progressbarPtr); ~loginHandler() { delete iconButtomStatusLabel; @@ -51,6 +52,7 @@ private: QStatusBar *statusBar; QLabel *iconButtomStatusLabel; QPushButton *loginButtonPtr; + QProgressBar *progressBar; }; diff --git a/main/main.cpp b/main/main.cpp index ef2dd6d..84fb2b2 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -9,13 +9,13 @@ int main(int argc, char *argv[]) { #ifdef QT_DEBUG // Incase QtCreator is in Debug mode all qDebug messages will go to terminal - qDebug() << "Running a debug build"; + qDebug() << Q_FUNC_INFO << "Running a debug build"; #else // If QtCreator is on Release mode , qDebug messages will be logged in a log file. // qDebug() << "Running a release build"; qInstallMessageHandler(jce_logger::customMessageHandler); #endif - qDebug() << "Start : JCE Manager Launched"; + qDebug() << Q_FUNC_INFO << "Start : JCE Manager Launched"; QApplication a(argc, argv); QTranslator translator; @@ -27,13 +27,13 @@ int main(int argc, char *argv[]) { QString locale = QLocale::system().name(); translator.load("jce_"+locale , a.applicationDirPath()); - qDebug() << "Local : Default Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : Default Local Loaded"; }else if(loco == "he"){ translator.load("jce_he" , a.applicationDirPath()); - qDebug() << "Local : Hebrew Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : Hebrew Local Loaded"; }else{ translator.load("jce_en" , a.applicationDirPath()); - qDebug() << "Local : English Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : English Local Loaded"; } a.installTranslator(&translator); //Setting local MainScreen w; @@ -42,8 +42,8 @@ int main(int argc, char *argv[]) //Getting the exit code from QApplication. for debug reasons int returnCode = a.exec(); if(returnCode == 0) - qDebug() << "End : JCE Manager Ended Successfully With A Return Code: " << returnCode; + qDebug() << Q_FUNC_INFO << "End : JCE Manager Ended Successfully With A Return Code: " << returnCode; else - qCritical() << "End : JCE Manager Ended Unusccessfully With A Return Code: " << returnCode; + qCritical() << Q_FUNC_INFO << "End : JCE Manager Ended Unusccessfully With A Return Code: " << returnCode; return returnCode; } diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index fa7d03f..5425d5d 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -2,361 +2,378 @@ #include "ui_mainscreen.h" -MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) +MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen), busyFlag() { - ui->setupUi(this); - //this->setFixedSize(this->size()); //main not resizeable + ui->setupUi(this); - ui->labelMadeBy->setOpenExternalLinks(true); + ui->labelMadeBy->setOpenExternalLinks(true); - //Login Tab - iconPix.load(":/icons/iconX.png"); - ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - ui->labelUsrInputStatus->setPixmap(iconPix); - ui->labelPswInputStatus->setPixmap(iconPix); + //Login Tab + iconPix.load(":/icons/iconX.png"); + ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); + ui->labelUsrInputStatus->setPixmap(iconPix); + ui->labelPswInputStatus->setPixmap(iconPix); - //StatusBar - ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); - ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH); - ui->statusBar->showMessage(tr("Ready")); - //GPA Tab - ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); + //StatusBar & progressbar + ui->progressBar->setFixedHeight(STATUS_ICON_HEIGH); + ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); + ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH+5); + ui->statusBar->showMessage(tr("Ready")); - //Pointer allocating - qDebug() << Q_FUNC_INFO << "Allocating pointers"; - this->userLoginSetting = new user("",""); - this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); - this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton); - this->calendar = new CalendarManager(ui->calendarGridLayoutMain); - this->data = new SaveData(); + //GPA Tab + ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); - //check login File - if (data->isSaved()) + //Pointer allocating + qDebug() << Q_FUNC_INFO << "Allocating pointers"; + this->userLoginSetting = new user("",""); + this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); + this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); + this->calendar = new CalendarManager(ui->calendarGridLayoutMain); + this->data = new SaveData(); + busyFlag = false; + + //check login File + if (data->isSaved()) { - qDebug() << Q_FUNC_INFO << "Loading data from file"; - ui->usrnmLineEdit->setText(data->getUsername()); - ui->pswdLineEdit->setText(data->getPassword()); - ui->keepLogin->setChecked(true); + qDebug() << Q_FUNC_INFO << "Loading data from file"; + ui->usrnmLineEdit->setText(data->getUsername()); + ui->pswdLineEdit->setText(data->getPassword()); + ui->keepLogin->setChecked(true); } - //language - qDebug() << Q_FUNC_INFO << "Checking locale"; - checkLocale(); - qDebug() << Q_FUNC_INFO << "Ready."; + //language + qDebug() << Q_FUNC_INFO << "Checking locale"; + checkLocale(); + ui->statusBar->repaint(); + qDebug() << Q_FUNC_INFO << "Ready."; } MainScreen::~MainScreen() { - delete calendar; - delete courseTableMgr; - delete userLoginSetting; - delete loginHandel; - delete data; - delete ui; + delete calendar; + delete courseTableMgr; + delete userLoginSetting; + delete loginHandel; + delete data; + delete ui; } //EVENTS ON LOGIN TAB void MainScreen::on_loginButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) { - if (ui->usrnmLineEdit->text().isEmpty()) + if (ui->usrnmLineEdit->text().isEmpty()) { - ui->labelUsrInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "username input is empty"; + ui->labelUsrInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "username input is empty"; } - else + else + ui->labelUsrInputStatus->setVisible(false); + if (ui->pswdLineEdit->text().isEmpty()) + { + ui->labelPswInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "password input is empty"; + } + else + ui->labelPswInputStatus->setVisible(false); + return; + } + else + { ui->labelUsrInputStatus->setVisible(false); - if (ui->pswdLineEdit->text().isEmpty()) - { - ui->labelPswInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "password input is empty"; - } - else ui->labelPswInputStatus->setVisible(false); - return; } - else + qDebug() << Q_FUNC_INFO << "login session start"; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) { - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - } - qDebug() << Q_FUNC_INFO << "login session start"; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) - { - qDebug() << Q_FUNC_INFO << "login session end with true"; - ui->pswdLineEdit->setDisabled(true); - ui->usrnmLineEdit->setDisabled(true); - if (ui->keepLogin->isChecked()) + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "login session end with true"; + ui->pswdLineEdit->setDisabled(true); + ui->usrnmLineEdit->setDisabled(true); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } } - else + else { - qDebug() << Q_FUNC_INFO << "login session end with false"; - ui->pswdLineEdit->setDisabled(false); - ui->usrnmLineEdit->setDisabled(false); + qDebug() << Q_FUNC_INFO << "login session end with false"; + ui->pswdLineEdit->setDisabled(false); + ui->usrnmLineEdit->setDisabled(false); } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_keepLogin_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (ui->keepLogin->isChecked()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } - else - data->reset(); + else + data->reset(); } void MainScreen::on_usrnmLineEdit_editingFinished() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); } //EVENTS ON GPA TAB void MainScreen::on_ratesButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (!checkIfValidDates()) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (!checkIfValidDates()) { - qWarning() << Q_FUNC_INFO << "Invalid dates! return"; - QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); - return; + qWarning() << Q_FUNC_INFO << "Invalid dates! return"; + QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); + return; } - QString pageString; - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + QString pageString; + int status = 0; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag() && !busyFlag) { - if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), - ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), - ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting grades...")); + if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), + ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), + ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - qDebug() << Q_FUNC_INFO << "grade page is ready"; - pageString = loginHandel->getCurrentPageContect(); - courseTableMgr->setCoursesList(pageString); - courseTableMgr->insertJceCoursesIntoTable(); + qDebug() << Q_FUNC_INFO << "grade page is ready"; + ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); + pageString = loginHandel->getCurrentPageContect(); + courseTableMgr->setCoursesList(pageString); + courseTableMgr->insertJceCoursesIntoTable(); + ui->progressBar->setValue(100); + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else + else { - qCritical() << Q_FUNC_INFO << "grade get ended with" << status; + qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } + busyFlag = true; } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } bool MainScreen::checkIfValidDates() { - bool flag = false; - if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) + bool flag = false; + if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) { - //doesnt matter what is the semester, its valid! - flag = true; - } - else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) - { - //semester from must be equal or less than to semester - if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + //doesnt matter what is the semester, its valid! flag = true; } - return flag; + else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) + { + //semester from must be equal or less than to semester + if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + flag = true; + } + return flag; } void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) { - qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; - this->userLoginSetting->setInfluenceCourseOnly(checked); - this->courseTableMgr->influnceCourseChanged(checked); + qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; + this->userLoginSetting->setInfluenceCourseOnly(checked); + this->courseTableMgr->influnceCourseChanged(checked); } void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { - ui->spinBoxCoursesFromYear->setValue(arg1); + ui->spinBoxCoursesFromYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { - ui->spinBoxCoursesToYear->setValue(arg1); + ui->spinBoxCoursesToYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { - ui->spinBoxCoursesFromSemester->setValue(arg1%4); + ui->spinBoxCoursesFromSemester->setValue(arg1%4); } void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { - ui->spinBoxCoursesToSemester->setValue(arg1%4); + ui->spinBoxCoursesToSemester->setValue(arg1%4); } void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { - if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) - ui->avgLCD->display(courseTableMgr->getAvg()); - else + if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) + ui->avgLCD->display(courseTableMgr->getAvg()); + else { - qWarning() << Q_FUNC_INFO << "missmatch data"; - QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); + qWarning() << Q_FUNC_INFO << "missmatch data"; + QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } void MainScreen::on_clearTableButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - courseTableMgr->clearTable(); - ui->avgLCD->display(courseTableMgr->getAvg()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + courseTableMgr->clearTable(); + ui->avgLCD->display(courseTableMgr->getAvg()); } //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + int status = 0; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) { - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting schedule...")); + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request - //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); - calendar->resetTable(); - calendar->setCalendar(loginHandel->getCurrentPageContect()); - qDebug() << Q_FUNC_INFO << "calendar is loaded"; + + //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request + //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); + calendar->resetTable(); + ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); + calendar->setCalendar(loginHandel->getCurrentPageContect()); + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "calendar is loaded"; + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else - qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; + else + qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (loginHandel->isLoggedInFlag()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (loginHandel->isLoggedInFlag()) { - this->calendar->exportCalendarCSV(); + this->calendar->exportCalendarCSV(); } } //EVENTS ON MENU BAR void MainScreen::on_actionCredits_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::about(this, "About", - "Jce Manager v1.0.0

" - +tr("License:")+ - "
GNU LESSER GENERAL PUBLIC LICENSE V2.1
" - +"
"+ - "JceManager Repository"+ - "

" - +tr("Powered By: ")+ - " Jce Connection

" - +tr("Developed By")+ - ":" - ); + qDebug() << Q_FUNC_INFO; + QMessageBox::about(this, "About", + "Jce Manager v1.0.0

" + +tr("License:")+ + "
GNU LESSER GENERAL PUBLIC LICENSE V2.1
" + +"
"+ + "JceManager Repository"+ + "

" + +tr("Powered By: ")+ + " Jce Connection

" + +tr("Developed By")+ + ":" + ); } void MainScreen::on_actionExit_triggered() { - qDebug() << Q_FUNC_INFO; - exit(0); + qDebug() << Q_FUNC_INFO; + exit(0); } void MainScreen::on_actionHow_To_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::information(this,"How To", - "" - +tr("Help Guide")+ - "
    " - +tr("
  • Login:
    • Type your username and password and click Login.
    • Once you are connected, you will see a green ball in the right buttom panel.
  • ") - +tr("
  • Getting GPA sheet
    • Click on GPA Tab
    • Select your dates and click on Add
  • ") - +tr("
  • Average Changing
    • Change one of your grade and see the average in the buttom panel changing.
  • ") - +tr("
  • Getting Calendar
    • Click on Calendar Tab
    • Select your dates and click on Get Calendar
  • ") - +tr("
  • For exporting your calendar to a .CSV file:
    • Do previous step and continue to next step
    • Click on Export to CSV
    • Select your dates and click OK
    • Once you're Done, go on your calendar and import your csv file
    • ")+ - "

      " - +tr("For more information, please visit us at: Jce Manager site")); + qDebug() << Q_FUNC_INFO; + QMessageBox::information(this,"How To", + "" + +tr("Help Guide")+ + "
        " + +tr("
      • Login:
        • Type your username and password and click Login.
        • Once you are connected, you will see a green ball in the right buttom panel.
      • ") + +tr("
      • Getting GPA sheet
        • Click on GPA Tab
        • Select your dates and click on Add
      • ") + +tr("
      • Average Changing
        • Change one of your grade and see the average in the buttom panel changing.
      • ") + +tr("
      • Getting Calendar
        • Click on Calendar Tab
        • Select your dates and click on Get Calendar
      • ") + +tr("
      • For exporting your calendar to a .CSV file:
        • Do previous step and continue to next step
        • Click on Export to CSV
        • Select your dates and click OK
        • Once you're Done, go on your calendar and import your csv file
        • ")+ + "

          " + +tr("For more information, please visit us at: Jce Manager site")); } void MainScreen::on_actionHebrew_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionEnglish->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; - data->setLocal("he"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionEnglish->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; + data->setLocal("he"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionHebrew->setChecked(true); + else + ui->actionHebrew->setChecked(true); } void MainScreen::on_actionEnglish_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to English"; - data->setLocal("en"); - QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to English"; + data->setLocal("en"); + QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionEnglish->setChecked(true); + else + ui->actionEnglish->setChecked(true); } void MainScreen::on_actionOS_Default_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionEnglish->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; - data->setLocal("default"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionEnglish->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; + data->setLocal("default"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionOS_Default->setChecked(true); + else + ui->actionOS_Default->setChecked(true); } void MainScreen::checkLocale() { - if(data->getLocal() == "en") + if(data->getLocal() == "en") { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(true); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(true); }else if(data->getLocal() == "he"){ - ui->actionHebrew->setChecked(true); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(true); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(false); }else{ - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(true); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(true); + ui->actionEnglish->setChecked(false); } } void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { - qDebug() << Q_FUNC_INFO << "link: " << link; + qDebug() << Q_FUNC_INFO << "link: " << link; } diff --git a/main/mainscreen.h b/main/mainscreen.h index 7ab3d42..929ed48 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -83,6 +83,8 @@ private: coursesTableManager *courseTableMgr; loginHandler *loginHandel; + bool busyFlag; + }; #endif // MAINSCREEN_H diff --git a/main/mainscreen.ui b/main/mainscreen.ui index fc522ca..ad37d5b 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -626,6 +626,45 @@ font-size: 15px; + + + + + 0 + 0 + + + + #progressBar::horizontal { +border: 1px solid gray; +border-radius: 3px; +background: white; +padding: 1px; +} +#progressBar::chunk:horizontal { +background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 1 white); +} + + + 0 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + true + + + Qt::Horizontal + + + false + + + QProgressBar::TopToBottom + + + diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 729447e..c2b5b07 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -3,17 +3,19 @@ /** * @brief jceSSLClient::jceSSLClient Constructer, setting the signals */ -jceSSLClient::jceSSLClient() : flag(false), packet(""),networkConf(), reConnection(false) +jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : flag(false), packet(""),networkConf(), reConnection(false) { - //setting signals - connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError))); - connect(this,SIGNAL(connected()),this,SLOT(setConnected())); - connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted())); - connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected())); - connect(&networkConf,SIGNAL(onlineStateChanged(bool)),this,SLOT(setOnlineState(bool))); - //loop event will connect the server, and when it is connected, it will quit - but connection will be open - connect(this, SIGNAL(encrypted()), &loop, SLOT(quit())); - connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loop,SLOT(quit())); + this->progressBar = progressbarPtr; + //setting signals + connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError))); + connect(this,SIGNAL(connected()),this,SLOT(setConnected())); + connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted())); + connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected())); + connect(&networkConf,SIGNAL(onlineStateChanged(bool)),this,SLOT(setOnlineState(bool))); + + //loop event will connect the server, and when it is connected, it will quit - but connection will be open + connect(this, SIGNAL(encrypted()), &loop, SLOT(quit())); + connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loop,SLOT(quit())); } /** @@ -24,48 +26,48 @@ jceSSLClient::jceSSLClient() : flag(false), packet(""),networkConf(), reConnecti */ bool jceSSLClient::makeConnect(QString server, int port) { - if (this->supportsSsl() == false) + if (this->supportsSsl() == false) { - qCritical() << Q_FUNC_INFO << "Couldnt load ssl package. ERROR"; - return false; + qCritical() << Q_FUNC_INFO << "Couldnt load ssl package. ERROR"; + return false; } - else - qDebug() << Q_FUNC_INFO << "ssl loaded."; + else + qDebug() << Q_FUNC_INFO << "ssl loaded."; - if (isConnectedToNetwork() == false) + if (isConnectedToNetwork() == false) { - qDebug() << Q_FUNC_INFO << "return false. not online"; - return false; + qDebug() << Q_FUNC_INFO << "return false. not online"; + return false; } - else - qDebug() << Q_FUNC_INFO << "we're online"; + else + qDebug() << Q_FUNC_INFO << "we're online"; - if (reConnection) //reset reconnectiong flag + if (reConnection) //reset reconnectiong flag { - qDebug() << Q_FUNC_INFO << "Making Reconnection"; + qDebug() << Q_FUNC_INFO << "Making Reconnection"; } - else - qDebug() << Q_FUNC_INFO << "Making Connection"; + else + qDebug() << Q_FUNC_INFO << "Making Connection"; - if (isConnected()) + if (isConnected()) { - qDebug() << Q_FUNC_INFO << "flag=true, calling makeDisconnect()"; - makeDiconnect(); + qDebug() << Q_FUNC_INFO << "flag=true, calling makeDisconnect()"; + makeDiconnect(); } - qDebug() << Q_FUNC_INFO << "Connection to: " << server << "On Port: " << port; - connectToHostEncrypted(server.toStdString().c_str(), port); + qDebug() << Q_FUNC_INFO << "Connection to: " << server << "On Port: " << port; + connectToHostEncrypted(server.toStdString().c_str(), port); - loop.exec(); //starting connection, waiting to encryption and then it ends + loop.exec(); //starting connection, waiting to encryption and then it ends - qDebug() << Q_FUNC_INFO << "returning the connection status: " << isConnected(); - if (reConnection) + qDebug() << Q_FUNC_INFO << "returning the connection status: " << isConnected(); + if (reConnection) { - reConnection = false; - emit serverDisconnectedbyRemote(); + reConnection = false; + emit serverDisconnectedbyRemote(); } - return isConnected(); + return isConnected(); } /** @@ -74,15 +76,15 @@ bool jceSSLClient::makeConnect(QString server, int port) */ bool jceSSLClient::makeDiconnect() { - if (loop.isRunning()) + if (loop.isRunning()) { - qWarning() << Q_FUNC_INFO << "Killing connection thread"; - loop.exit(); + qWarning() << Q_FUNC_INFO << "Killing connection thread"; + loop.exit(); } - qDebug() << Q_FUNC_INFO << "disconnecting from host and emitting disconnected()"; - this->disconnectFromHost(); //emits disconnected > setDisconnected - setSocketState(QAbstractSocket::SocketState::UnconnectedState); - return (!isConnected()); + qDebug() << Q_FUNC_INFO << "disconnecting from host and emitting disconnected()"; + this->disconnectFromHost(); //emits disconnected > setDisconnected + setSocketState(QAbstractSocket::SocketState::UnconnectedState); + return (!isConnected()); } @@ -92,30 +94,30 @@ bool jceSSLClient::makeDiconnect() */ bool jceSSLClient::isConnected() { - bool tempFlag = false; - //checking state before returning flag! - if (state() == QAbstractSocket::SocketState::UnconnectedState) + bool tempFlag = false; + //checking state before returning flag! + if (state() == QAbstractSocket::SocketState::UnconnectedState) { - tempFlag = false; + tempFlag = false; } - else if (state() == QAbstractSocket::SocketState::ClosingState) + else if (state() == QAbstractSocket::SocketState::ClosingState) { - tempFlag = false; + tempFlag = false; } - else if (state() == QAbstractSocket::SocketState::ConnectedState) + else if (state() == QAbstractSocket::SocketState::ConnectedState) { - if (isConnectedToNetwork()) - tempFlag = true; - else + if (isConnectedToNetwork()) + tempFlag = true; + else { - this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); - tempFlag = false; + this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); + tempFlag = false; } } - if (!isConnectedToNetwork()) //no link, ethernet\wifi - tempFlag = false; - return ((flag) && (tempFlag)); + if (!isConnectedToNetwork()) //no link, ethernet\wifi + tempFlag = false; + return ((flag) && (tempFlag)); } /** * @brief jceSSLClient::sendData - given string, send it to server @@ -124,16 +126,16 @@ bool jceSSLClient::isConnected() */ bool jceSSLClient::sendData(QString str) { - bool sendDataFlag = false; + bool sendDataFlag = false; - if (isConnected()) //if connected + if (isConnected()) //if connected { - write(str.toStdString().c_str(),str.length()); - if (waitForBytesWritten()) - sendDataFlag = true; + write(str.toStdString().c_str(),str.length()); + if (waitForBytesWritten()) + sendDataFlag = true; } - qDebug() << Q_FUNC_INFO << "Sending Data status is: " << sendDataFlag; - return sendDataFlag; + qDebug() << Q_FUNC_INFO << "Sending Data status is: " << sendDataFlag; + return sendDataFlag; } /** * @brief jceSSLClient::recieveData @@ -143,39 +145,41 @@ bool jceSSLClient::sendData(QString str) */ bool jceSSLClient::recieveData(QString &str, bool fast) { - qDebug() << Q_FUNC_INFO << "Data receiving!"; - packet = ""; - bool sflag = false; + qDebug() << Q_FUNC_INFO << "Data receiving!"; + packet = ""; + bool sflag = false; - if (fast) //fast mode connection, good only for login step!!!! + if (fast) //fast mode connection, good only for login step!!!! { - qDebug() << "jceSSLClient::recieveData login step receiving"; - QEventLoop loop; - connect(this, SIGNAL(readyRead()), &loop, SLOT(quit())); - connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); - loop.exec(); - disconnect(this, SIGNAL(readyRead()), &loop, SLOT(quit())); - disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); + qDebug() << Q_FUNC_INFO << "login step receiving"; + //loop will exit after first read packet. + //meanwhile packet will gain data. good for small amount of data - fast connection! + connect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); + connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); + readerLoop.exec(); + disconnect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); + disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); } - else + else { - qDebug() << "jceSSLClient::recieveData normal receiving"; - QString p; - while (waitForReadyRead(milisTimeOut)) - { - do - { - p = readAll(); - packet.append(p); - }while (p.size() > 0); - } + qDebug() << Q_FUNC_INFO << "normal receiving"; + //loop will exit after timeout \ full data + connect(this, SIGNAL(packetHasData()), &readerLoop, SLOT(quit())); + + timer.setSingleShot(true); + connect(&timer, SIGNAL(timeout()), &readerLoop, SLOT(quit())); + connect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); + timer.start(5000); + readerLoop.exec(); + } - str = packet; - qDebug() << Q_FUNC_INFO << "received bytes: " << str.length() ; - if (str.length() > 0) - sflag = true; - qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; - return sflag; + str = packet; + qDebug() << Q_FUNC_INFO << "received bytes: " << str.length() ; + if (str.length() > 0) + sflag = true; + qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; + disconnect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); + return sflag; } /** @@ -183,29 +187,47 @@ bool jceSSLClient::recieveData(QString &str, bool fast) */ void jceSSLClient::readIt() { - QString p; - do + QString p; + do { - p = readAll(); - packet.append(p); + p = readAll(); + packet.append(p); + this->progressBar->setValue(this->progressBar->value() + 6); }while (p.size() > 0); } +void jceSSLClient::readItAll() +{ + QString p; + do + { + p = ""; + p = read(bytesAvailable()); + if (p.contains("") == true) + { + qDebug() << "we have the end!"; + timer.setInterval(1000); + } + this->progressBar->setValue(this->progressBar->value() + 6); +// qDebug() << "p lenght" << p.length(); + packet.append(p); + }while (p.size() > 0); +} void jceSSLClient::setOnlineState(bool isOnline) { - qWarning() << Q_FUNC_INFO << "isOnline status change: " << isOnline; - if (isOnline) //to be added later + qWarning() << Q_FUNC_INFO << "isOnline status change: " << isOnline; + if (isOnline) //to be added later { - qDebug() << Q_FUNC_INFO << "Online Statue has been changed. we are online"; - //we can add here auto reconnect if wifi\ethernet link has appear - //will be added next version + qDebug() << Q_FUNC_INFO << "Online Statue has been changed. we are online"; + //we can add here auto reconnect if wifi\ethernet link has appear + //will be added next version } - else + else { - qWarning() << Q_FUNC_INFO << "Online State has been changed. emitting NoInternetLink"; - this->makeDiconnect(); - emit noInternetLink(); + qWarning() << Q_FUNC_INFO << "Online State has been changed. emitting NoInternetLink"; + this->makeDiconnect(); + emit noInternetLink(); } } @@ -214,19 +236,19 @@ void jceSSLClient::setOnlineState(bool isOnline) */ void jceSSLClient::setConnected() { - waitForEncrypted(); + waitForEncrypted(); } /** * @brief jceSSLClient::setDisconnected closing socket, updating state and setting flag to false */ void jceSSLClient::setDisconnected() { - qDebug() << Q_FUNC_INFO << "connection has been DISCONNECTED"; - this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); - packet.clear(); - flag = false; - if (reConnection) - makeConnect(); + qDebug() << Q_FUNC_INFO << "connection has been DISCONNECTED"; + this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); + packet.clear(); + flag = false; + if (reConnection) + makeConnect(); } @@ -235,14 +257,14 @@ void jceSSLClient::setDisconnected() */ void jceSSLClient::setEncrypted() { - qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; - setReadBufferSize(10000); - setSocketOption(QAbstractSocket::KeepAliveOption,true); - flag = true; - if (!isConnected()) + qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; + setReadBufferSize(10000); + setSocketOption(QAbstractSocket::KeepAliveOption,true); + flag = true; + if (!isConnected()) { - qWarning() << Q_FUNC_INFO << "Connection status didnt change! reseting flag to false"; - flag = false; + qWarning() << Q_FUNC_INFO << "Connection status didnt change! reseting flag to false"; + flag = false; } } @@ -253,116 +275,116 @@ void jceSSLClient::setEncrypted() */ void jceSSLClient::showIfErrorMsg() { - QMessageBox msgBox; - SocketError enumError = error(); - QString errorString; - bool relevantError = false; - switch (enumError) + QMessageBox msgBox; + SocketError enumError = error(); + QString errorString; + bool relevantError = false; + switch (enumError) { case QAbstractSocket::SocketError::ConnectionRefusedError: /**/ - errorString = QObject::tr("ConnectionRefusedError"); - //The connection was refused by the peer (or timed out). - relevantError = true; - break; + errorString = QObject::tr("ConnectionRefusedError"); + //The connection was refused by the peer (or timed out). + relevantError = true; + break; case QAbstractSocket::SocketError::RemoteHostClosedError: /**/ - errorString = QObject::tr("RemoteHostClosedError"); - //The remote host closed the connection - if (isConnectedToNetwork()) //we can reconnect + errorString = QObject::tr("RemoteHostClosedError"); + //The remote host closed the connection + if (isConnectedToNetwork()) //we can reconnect { - reConnection = true; + reConnection = true; } - else - relevantError = true; - break; + else + relevantError = true; + break; case QAbstractSocket::SocketError::HostNotFoundError: /**/ - errorString = QObject::tr("HostNotFoundError"); - //The host address was not found. - relevantError = true; - break; - case QAbstractSocket::SocketError::SocketAccessError: /**/ - errorString = QObject::tr("SocketAccessError"); - //The socket operation failed because the application lacked the required privileges. - break; - case QAbstractSocket::SocketError::SocketTimeoutError: /**/ - errorString = QObject::tr("SocketTimeoutError"); - //The socket operation timed out. - if (isConnected()); //ignore it if connected. - else + errorString = QObject::tr("HostNotFoundError"); + //The host address was not found. relevantError = true; - break; + break; + case QAbstractSocket::SocketError::SocketAccessError: /**/ + errorString = QObject::tr("SocketAccessError"); + //The socket operation failed because the application lacked the required privileges. + break; + case QAbstractSocket::SocketError::SocketTimeoutError: /**/ + errorString = QObject::tr("SocketTimeoutError"); + //The socket operation timed out. + if (isConnected()); //ignore it if connected. + else + relevantError = true; + break; case QAbstractSocket::SocketError::NetworkError: /**/ - errorString = QObject::tr("NetworkError"); - //An error occurred with the network (e.g., the network cable was accidentally plugged out). - if (isConnectedToNetwork()) //we can reconnect + errorString = QObject::tr("NetworkError"); + //An error occurred with the network (e.g., the network cable was accidentally plugged out). + if (isConnectedToNetwork()) //we can reconnect { } - else - relevantError = true; - break; + else + relevantError = true; + break; case QAbstractSocket::SocketError::SslHandshakeFailedError: /**/ - errorString = QObject::tr("SslHandshakeFailedError"); - relevantError = true; - break; + errorString = QObject::tr("SslHandshakeFailedError"); + relevantError = true; + break; case QAbstractSocket::SocketError::SslInternalError: /**/ - errorString = QObject::tr("SslInternalError"); - relevantError = true; - break; + errorString = QObject::tr("SslInternalError"); + relevantError = true; + break; case QAbstractSocket::SocketError::SslInvalidUserDataError: /**/ - errorString = QObject::tr("SslInvalidUserDataError"); - relevantError = true; - break; + errorString = QObject::tr("SslInvalidUserDataError"); + relevantError = true; + break; case QAbstractSocket::SocketError::DatagramTooLargeError: //not relevant to us - errorString = QObject::tr("DatagramTooLargeError"); - break; + errorString = QObject::tr("DatagramTooLargeError"); + break; case QAbstractSocket::SocketError::SocketResourceError: //not relevant to us - break; + break; case QAbstractSocket::SocketError::OperationError: //not relevant, except for debug - errorString = QObject::tr("OperationError"); - break; + errorString = QObject::tr("OperationError"); + break; case QAbstractSocket::SocketError::AddressInUseError: //not relevant to us - errorString = QObject::tr("AddressInUseError"); - break; + errorString = QObject::tr("AddressInUseError"); + break; case QAbstractSocket::SocketError::SocketAddressNotAvailableError: //not relevant to us - errorString = QObject::tr("SocketAddressNotAvailableError"); - break; + errorString = QObject::tr("SocketAddressNotAvailableError"); + break; case QAbstractSocket::SocketError::UnsupportedSocketOperationError: //for very old computers, not relevant to us - errorString = QObject::tr("UnsupportedSocketOperationError"); - break; + errorString = QObject::tr("UnsupportedSocketOperationError"); + break; case QAbstractSocket::SocketError::ProxyAuthenticationRequiredError: //not relevant to us - errorString = QObject::tr("ProxyAuthenticationRequiredError"); - break; + errorString = QObject::tr("ProxyAuthenticationRequiredError"); + break; case QAbstractSocket::SocketError::ProxyConnectionRefusedError: //not relevant to us - errorString = QObject::tr("ProxyConnectionRefusedError"); - break; + errorString = QObject::tr("ProxyConnectionRefusedError"); + break; case QAbstractSocket::SocketError::UnfinishedSocketOperationError: //not relevant to us - errorString = QObject::tr("UnfinishedSocketOperationError"); - break; + errorString = QObject::tr("UnfinishedSocketOperationError"); + break; case QAbstractSocket::SocketError::ProxyConnectionClosedError: //not relevant to us - errorString = QObject::tr("ProxyConnectionClosedError"); - break; + errorString = QObject::tr("ProxyConnectionClosedError"); + break; case QAbstractSocket::SocketError::ProxyConnectionTimeoutError: //not relevant to us - errorString = QObject::tr("ProxyConnectionTimeoutError"); - break; + errorString = QObject::tr("ProxyConnectionTimeoutError"); + break; case QAbstractSocket::SocketError::ProxyNotFoundError: //not relevant to us - errorString = QObject::tr("ProxyNotFoundError"); - break; + errorString = QObject::tr("ProxyNotFoundError"); + break; case QAbstractSocket::SocketError::ProxyProtocolError: //not relevant to us - errorString = QObject::tr("ProxyProtocolError"); - break; + errorString = QObject::tr("ProxyProtocolError"); + break; case QAbstractSocket::SocketError::TemporaryError: //not relevant to us - errorString = QObject::tr("TemporaryError"); - break; + errorString = QObject::tr("TemporaryError"); + break; case QAbstractSocket::SocketError::UnknownSocketError: //not relevant, except for debug - errorString = QObject::tr("UnknownSocketError"); - relevantError = true; - break; + errorString = QObject::tr("UnknownSocketError"); + relevantError = true; + break; } - if (relevantError) //informative string to be shown + if (relevantError) //informative string to be shown { - qDebug() << Q_FUNC_INFO << "relevant error."; - msgBox.setIcon(QMessageBox::Warning); - msgBox.setText(errorString); - msgBox.exec(); + qDebug() << Q_FUNC_INFO << "relevant error."; + msgBox.setIcon(QMessageBox::Warning); + msgBox.setText(errorString); + msgBox.exec(); } } /** @@ -371,24 +393,24 @@ void jceSSLClient::showIfErrorMsg() */ void jceSSLClient::checkErrors(QAbstractSocket::SocketError a) { - //ignore this stupid error - bool timeout = (a == QAbstractSocket::SocketError::SocketTimeoutError); - if (!((isConnected()) && (timeout))) + //ignore this stupid error + bool timeout = (a == QAbstractSocket::SocketError::SocketTimeoutError); + if (!((isConnected()) && (timeout))) { - qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); - qWarning() << Q_FUNC_INFO << "state is: " << state(); - qWarning() << Q_FUNC_INFO << "Var Error: " << a; - qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); + qWarning() << Q_FUNC_INFO << "state is: " << state(); + qWarning() << Q_FUNC_INFO << "Var Error: " << a; + qWarning() << Q_FUNC_INFO << "Error: " << errorString(); } - else + else { - qDebug() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; - qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); - qWarning() << Q_FUNC_INFO << "state is: " << state(); - qWarning() << Q_FUNC_INFO << "Var Error: " << a; - qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + qDebug() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; + qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); + qWarning() << Q_FUNC_INFO << "state is: " << state(); + qWarning() << Q_FUNC_INFO << "Var Error: " << a; + qWarning() << Q_FUNC_INFO << "Error: " << errorString(); } - showIfErrorMsg(); + showIfErrorMsg(); } /** written by KARAN BALKAR @@ -397,20 +419,20 @@ void jceSSLClient::checkErrors(QAbstractSocket::SocketError a) */ bool jceSSLClient::isConnectedToNetwork(){ - QList ifaces = QNetworkInterface::allInterfaces(); - bool result = false; + QList ifaces = QNetworkInterface::allInterfaces(); + bool result = false; - for (int i = 0; i < ifaces.count(); ++i) + for (int i = 0; i < ifaces.count(); ++i) { - QNetworkInterface iface = ifaces.at(i); + QNetworkInterface iface = ifaces.at(i); - if ( iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) - for (int j=0; j < iface.addressEntries().count(); ++j) - // got an interface which is up, and has an ip address - if (result == false) - result = true; + if ( iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) + for (int j=0; j < iface.addressEntries().count(); ++j) + // got an interface which is up, and has an ip address + if (result == false) + result = true; } - return result; + return result; } diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index d4f95e7..a6edbed 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -8,6 +8,8 @@ #include #include #include +#include +#include #define milisTimeOut 4000 @@ -15,7 +17,7 @@ class jceSSLClient : public QSslSocket { Q_OBJECT public: - jceSSLClient(); + jceSSLClient(QProgressBar *progressbarPtr); bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); bool makeDiconnect(); @@ -28,6 +30,7 @@ signals: void serverDisconnectedbyRemote(); void noInternetLink(); void socketDisconnected(); + void packetHasData(); private slots: void checkErrors(QAbstractSocket::SocketError a); @@ -35,6 +38,7 @@ private slots: void setEncrypted(); void setDisconnected(); void readIt(); + void readItAll(); void setOnlineState(bool isOnline); private: @@ -42,9 +46,13 @@ private: bool flag; QString packet; QEventLoop loop; //handle the connection as thread + QEventLoop readerLoop; + QTimer timer; QNetworkConfigurationManager networkConf; //checking if online bool reConnection; //used for remote host disconnecting + QProgressBar *progressBar; // + }; #endif // JCESSLCLIENT_H diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 5a25587..900ef23 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -4,11 +4,12 @@ * @brief jceLogin::jceLogin * @param username pointer to allocated user settings */ -jceLogin::jceLogin(user* username) +jceLogin::jceLogin(user* username, QProgressBar *progressbarPtr) { + this->progressBar = progressbarPtr; this->recieverPage = new QString(); this->jceA = username; - this->JceConnector = new jceSSLClient(); + this->JceConnector = new jceSSLClient(progressBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); } @@ -133,7 +134,7 @@ void jceLogin::reMakeConnection() recieverPage = NULL; JceConnector = NULL; this->recieverPage = new QString(); - this->JceConnector = new jceSSLClient(); + this->JceConnector = new jceSSLClient(progressBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); emit connectionReadyAfterDisconnection(); @@ -297,6 +298,7 @@ QString jceLogin::getPage() void jceLogin::reValidation() { qDebug() << Q_FUNC_INFO << "Revalidating user"; + if (makeFirstVisit() == true) { if (checkValidation()) diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index ede8514..912b47b 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -6,6 +6,7 @@ #include "jceLoginHtmlScripts.h" #include +#include #include @@ -13,8 +14,8 @@ class jceLogin : public QObject { Q_OBJECT public: - jceLogin() {} - jceLogin(user* username); + + jceLogin(user* username,QProgressBar *progressbarPtr); ~jceLogin(); enum jceStatus { @@ -61,6 +62,7 @@ private: QString * recieverPage; user * jceA; jceSSLClient * JceConnector; + QProgressBar *progressBar; }; From 64f56d78fc9c2bc8719231ab7b5118a994e936bc Mon Sep 17 00:00:00 2001 From: liranbg Date: Sat, 4 Oct 2014 03:51:37 +0300 Subject: [PATCH 02/58] : --- src/jceConnection/jcesslclient.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index c2b5b07..1e24a92 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -205,11 +205,10 @@ void jceSSLClient::readItAll() p = read(bytesAvailable()); if (p.contains("") == true) { - qDebug() << "we have the end!"; + //we recieved the end of table. we can stop recieving timer.setInterval(1000); } this->progressBar->setValue(this->progressBar->value() + 6); -// qDebug() << "p lenght" << p.length(); packet.append(p); }while (p.size() > 0); } From 2ab9ea2c950c4c58dc0f518036074c2b5faa5bc9 Mon Sep 17 00:00:00 2001 From: liranbg Date: Sat, 4 Oct 2014 03:54:27 +0300 Subject: [PATCH 03/58] added progress bar --- main/LoginTab/loginhandler.cpp | 13 +- main/LoginTab/loginhandler.h | 4 +- main/main.cpp | 14 +- main/mainscreen.cpp | 451 ++++++++++++++-------------- main/mainscreen.h | 2 + main/mainscreen.ui | 39 +++ src/jceConnection/jcesslclient.cpp | 467 +++++++++++++++-------------- src/jceConnection/jcesslclient.h | 10 +- src/jceSettings/jcelogin.cpp | 8 +- src/jceSettings/jcelogin.h | 6 +- 10 files changed, 557 insertions(+), 457 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 50d75fa..572bcb0 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -1,19 +1,26 @@ #include "loginhandler.h" -loginHandler::loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr): logggedInFlag(false) +loginHandler::loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr,QProgressBar *progressbarPtr): logggedInFlag(false) { this->loginButtonPtr = loginButtonPtr; + this->progressBar = progressbarPtr; //statusBar statusBar = statusBarPtr; - iconButtomStatusLabel = new QLabel(); + iconButtomStatusLabel = new QLabel(statusBarPtr); + iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); + + //display progressbar and then ball icon. + statusBar->addPermanentWidget(progressBar,0); statusBar->addPermanentWidget(iconButtomStatusLabel,0); + setIconConnectionStatus(jceLogin::jceStatus::JCE_NOT_CONNECTED); //user settings userPtr = ptr; - this->jceLog = new jceLogin(userPtr); + this->jceLog = new jceLogin(userPtr,progressBar); QObject::connect(this->jceLog,SIGNAL(connectionReadyAfterDisconnection()),this,SLOT(readyAfterConnectionLost())); + } bool loginHandler::login(QString username,QString password) { diff --git a/main/LoginTab/loginhandler.h b/main/LoginTab/loginhandler.h index 6debc9a..8512ec1 100644 --- a/main/LoginTab/loginhandler.h +++ b/main/LoginTab/loginhandler.h @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "./src/jceSettings/jcelogin.h" @@ -17,7 +18,7 @@ class loginHandler : public QObject { Q_OBJECT public: - loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr); + loginHandler(user *ptr, QStatusBar *statusBarPtr, QPushButton *loginButtonPtr, QProgressBar *progressbarPtr); ~loginHandler() { delete iconButtomStatusLabel; @@ -51,6 +52,7 @@ private: QStatusBar *statusBar; QLabel *iconButtomStatusLabel; QPushButton *loginButtonPtr; + QProgressBar *progressBar; }; diff --git a/main/main.cpp b/main/main.cpp index 3f2c86b..a57848e 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -8,13 +8,13 @@ int main(int argc, char *argv[]) { #ifdef QT_DEBUG // Incase QtCreator is in Debug mode all qDebug messages will go to terminal - qDebug() << "Running a debug build"; + qDebug() << Q_FUNC_INFO << "Running a debug build"; #else // If QtCreator is on Release mode , qDebug messages will be logged in a log file. // qDebug() << "Running a release build"; qInstallMessageHandler(jce_logger::customMessageHandler); #endif - qDebug() << "Start : JCE Manager Launched"; + qDebug() << Q_FUNC_INFO << "Start : JCE Manager Launched"; QApplication a(argc, argv); QTranslator translator; @@ -26,13 +26,13 @@ int main(int argc, char *argv[]) { QString locale = QLocale::system().name(); translator.load("jce_"+locale , a.applicationDirPath()); - qDebug() << "Local : Default Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : Default Local Loaded"; }else if(loco == "he"){ translator.load("jce_he" , a.applicationDirPath()); - qDebug() << "Local : Hebrew Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : Hebrew Local Loaded"; }else{ translator.load("jce_en" , a.applicationDirPath()); - qDebug() << "Local : English Local Loaded"; + qDebug() << Q_FUNC_INFO << "Local : English Local Loaded"; } a.installTranslator(&translator); //Setting local a.setApplicationVersion(APP_VERSION); @@ -42,8 +42,8 @@ int main(int argc, char *argv[]) //Getting the exit code from QApplication. for debug reasons int returnCode = a.exec(); if(returnCode == 0) - qDebug() << "End : JCE Manager Ended Successfully With A Return Code: " << returnCode; + qDebug() << Q_FUNC_INFO << "End : JCE Manager Ended Successfully With A Return Code: " << returnCode; else - qCritical() << "End : JCE Manager Ended Unusccessfully With A Return Code: " << returnCode; + qCritical() << Q_FUNC_INFO << "End : JCE Manager Ended Unusccessfully With A Return Code: " << returnCode; return returnCode; } diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index fa7d03f..5425d5d 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -2,361 +2,378 @@ #include "ui_mainscreen.h" -MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) +MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen), busyFlag() { - ui->setupUi(this); - //this->setFixedSize(this->size()); //main not resizeable + ui->setupUi(this); - ui->labelMadeBy->setOpenExternalLinks(true); + ui->labelMadeBy->setOpenExternalLinks(true); - //Login Tab - iconPix.load(":/icons/iconX.png"); - ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - ui->labelUsrInputStatus->setPixmap(iconPix); - ui->labelPswInputStatus->setPixmap(iconPix); + //Login Tab + iconPix.load(":/icons/iconX.png"); + ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); + ui->labelUsrInputStatus->setPixmap(iconPix); + ui->labelPswInputStatus->setPixmap(iconPix); - //StatusBar - ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); - ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH); - ui->statusBar->showMessage(tr("Ready")); - //GPA Tab - ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); + //StatusBar & progressbar + ui->progressBar->setFixedHeight(STATUS_ICON_HEIGH); + ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); + ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH+5); + ui->statusBar->showMessage(tr("Ready")); - //Pointer allocating - qDebug() << Q_FUNC_INFO << "Allocating pointers"; - this->userLoginSetting = new user("",""); - this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); - this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton); - this->calendar = new CalendarManager(ui->calendarGridLayoutMain); - this->data = new SaveData(); + //GPA Tab + ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); - //check login File - if (data->isSaved()) + //Pointer allocating + qDebug() << Q_FUNC_INFO << "Allocating pointers"; + this->userLoginSetting = new user("",""); + this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); + this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); + this->calendar = new CalendarManager(ui->calendarGridLayoutMain); + this->data = new SaveData(); + busyFlag = false; + + //check login File + if (data->isSaved()) { - qDebug() << Q_FUNC_INFO << "Loading data from file"; - ui->usrnmLineEdit->setText(data->getUsername()); - ui->pswdLineEdit->setText(data->getPassword()); - ui->keepLogin->setChecked(true); + qDebug() << Q_FUNC_INFO << "Loading data from file"; + ui->usrnmLineEdit->setText(data->getUsername()); + ui->pswdLineEdit->setText(data->getPassword()); + ui->keepLogin->setChecked(true); } - //language - qDebug() << Q_FUNC_INFO << "Checking locale"; - checkLocale(); - qDebug() << Q_FUNC_INFO << "Ready."; + //language + qDebug() << Q_FUNC_INFO << "Checking locale"; + checkLocale(); + ui->statusBar->repaint(); + qDebug() << Q_FUNC_INFO << "Ready."; } MainScreen::~MainScreen() { - delete calendar; - delete courseTableMgr; - delete userLoginSetting; - delete loginHandel; - delete data; - delete ui; + delete calendar; + delete courseTableMgr; + delete userLoginSetting; + delete loginHandel; + delete data; + delete ui; } //EVENTS ON LOGIN TAB void MainScreen::on_loginButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) { - if (ui->usrnmLineEdit->text().isEmpty()) + if (ui->usrnmLineEdit->text().isEmpty()) { - ui->labelUsrInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "username input is empty"; + ui->labelUsrInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "username input is empty"; } - else + else + ui->labelUsrInputStatus->setVisible(false); + if (ui->pswdLineEdit->text().isEmpty()) + { + ui->labelPswInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "password input is empty"; + } + else + ui->labelPswInputStatus->setVisible(false); + return; + } + else + { ui->labelUsrInputStatus->setVisible(false); - if (ui->pswdLineEdit->text().isEmpty()) - { - ui->labelPswInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "password input is empty"; - } - else ui->labelPswInputStatus->setVisible(false); - return; } - else + qDebug() << Q_FUNC_INFO << "login session start"; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) { - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - } - qDebug() << Q_FUNC_INFO << "login session start"; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) - { - qDebug() << Q_FUNC_INFO << "login session end with true"; - ui->pswdLineEdit->setDisabled(true); - ui->usrnmLineEdit->setDisabled(true); - if (ui->keepLogin->isChecked()) + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "login session end with true"; + ui->pswdLineEdit->setDisabled(true); + ui->usrnmLineEdit->setDisabled(true); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } } - else + else { - qDebug() << Q_FUNC_INFO << "login session end with false"; - ui->pswdLineEdit->setDisabled(false); - ui->usrnmLineEdit->setDisabled(false); + qDebug() << Q_FUNC_INFO << "login session end with false"; + ui->pswdLineEdit->setDisabled(false); + ui->usrnmLineEdit->setDisabled(false); } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_keepLogin_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (ui->keepLogin->isChecked()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } - else - data->reset(); + else + data->reset(); } void MainScreen::on_usrnmLineEdit_editingFinished() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); } //EVENTS ON GPA TAB void MainScreen::on_ratesButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (!checkIfValidDates()) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (!checkIfValidDates()) { - qWarning() << Q_FUNC_INFO << "Invalid dates! return"; - QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); - return; + qWarning() << Q_FUNC_INFO << "Invalid dates! return"; + QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); + return; } - QString pageString; - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + QString pageString; + int status = 0; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag() && !busyFlag) { - if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), - ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), - ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting grades...")); + if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), + ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), + ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - qDebug() << Q_FUNC_INFO << "grade page is ready"; - pageString = loginHandel->getCurrentPageContect(); - courseTableMgr->setCoursesList(pageString); - courseTableMgr->insertJceCoursesIntoTable(); + qDebug() << Q_FUNC_INFO << "grade page is ready"; + ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); + pageString = loginHandel->getCurrentPageContect(); + courseTableMgr->setCoursesList(pageString); + courseTableMgr->insertJceCoursesIntoTable(); + ui->progressBar->setValue(100); + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else + else { - qCritical() << Q_FUNC_INFO << "grade get ended with" << status; + qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } + busyFlag = true; } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } bool MainScreen::checkIfValidDates() { - bool flag = false; - if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) + bool flag = false; + if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) { - //doesnt matter what is the semester, its valid! - flag = true; - } - else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) - { - //semester from must be equal or less than to semester - if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + //doesnt matter what is the semester, its valid! flag = true; } - return flag; + else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) + { + //semester from must be equal or less than to semester + if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + flag = true; + } + return flag; } void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) { - qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; - this->userLoginSetting->setInfluenceCourseOnly(checked); - this->courseTableMgr->influnceCourseChanged(checked); + qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; + this->userLoginSetting->setInfluenceCourseOnly(checked); + this->courseTableMgr->influnceCourseChanged(checked); } void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { - ui->spinBoxCoursesFromYear->setValue(arg1); + ui->spinBoxCoursesFromYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { - ui->spinBoxCoursesToYear->setValue(arg1); + ui->spinBoxCoursesToYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { - ui->spinBoxCoursesFromSemester->setValue(arg1%4); + ui->spinBoxCoursesFromSemester->setValue(arg1%4); } void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { - ui->spinBoxCoursesToSemester->setValue(arg1%4); + ui->spinBoxCoursesToSemester->setValue(arg1%4); } void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { - if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) - ui->avgLCD->display(courseTableMgr->getAvg()); - else + if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) + ui->avgLCD->display(courseTableMgr->getAvg()); + else { - qWarning() << Q_FUNC_INFO << "missmatch data"; - QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); + qWarning() << Q_FUNC_INFO << "missmatch data"; + QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } void MainScreen::on_clearTableButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - courseTableMgr->clearTable(); - ui->avgLCD->display(courseTableMgr->getAvg()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + courseTableMgr->clearTable(); + ui->avgLCD->display(courseTableMgr->getAvg()); } //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + int status = 0; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) { - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting schedule...")); + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request - //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); - calendar->resetTable(); - calendar->setCalendar(loginHandel->getCurrentPageContect()); - qDebug() << Q_FUNC_INFO << "calendar is loaded"; + + //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request + //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); + calendar->resetTable(); + ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); + calendar->setCalendar(loginHandel->getCurrentPageContect()); + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "calendar is loaded"; + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else - qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; + else + qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (loginHandel->isLoggedInFlag()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (loginHandel->isLoggedInFlag()) { - this->calendar->exportCalendarCSV(); + this->calendar->exportCalendarCSV(); } } //EVENTS ON MENU BAR void MainScreen::on_actionCredits_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::about(this, "About", - "Jce Manager v1.0.0

          " - +tr("License:")+ - "
          GNU LESSER GENERAL PUBLIC LICENSE V2.1
          " - +"
          "+ - "JceManager Repository"+ - "

          " - +tr("Powered By: ")+ - " Jce Connection

          " - +tr("Developed By")+ - ":" - ); + qDebug() << Q_FUNC_INFO; + QMessageBox::about(this, "About", + "Jce Manager v1.0.0

          " + +tr("License:")+ + "
          GNU LESSER GENERAL PUBLIC LICENSE V2.1
          " + +"
          "+ + "JceManager Repository"+ + "

          " + +tr("Powered By: ")+ + " Jce Connection

          " + +tr("Developed By")+ + ":" + ); } void MainScreen::on_actionExit_triggered() { - qDebug() << Q_FUNC_INFO; - exit(0); + qDebug() << Q_FUNC_INFO; + exit(0); } void MainScreen::on_actionHow_To_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::information(this,"How To", - "" - +tr("Help Guide")+ - "
            " - +tr("
          • Login:
            • Type your username and password and click Login.
            • Once you are connected, you will see a green ball in the right buttom panel.
          • ") - +tr("
          • Getting GPA sheet
            • Click on GPA Tab
            • Select your dates and click on Add
          • ") - +tr("
          • Average Changing
            • Change one of your grade and see the average in the buttom panel changing.
          • ") - +tr("
          • Getting Calendar
            • Click on Calendar Tab
            • Select your dates and click on Get Calendar
          • ") - +tr("
          • For exporting your calendar to a .CSV file:
            • Do previous step and continue to next step
            • Click on Export to CSV
            • Select your dates and click OK
            • Once you're Done, go on your calendar and import your csv file
            • ")+ - "

              " - +tr("For more information, please visit us at: Jce Manager site")); + qDebug() << Q_FUNC_INFO; + QMessageBox::information(this,"How To", + "" + +tr("Help Guide")+ + "
                " + +tr("
              • Login:
                • Type your username and password and click Login.
                • Once you are connected, you will see a green ball in the right buttom panel.
              • ") + +tr("
              • Getting GPA sheet
                • Click on GPA Tab
                • Select your dates and click on Add
              • ") + +tr("
              • Average Changing
                • Change one of your grade and see the average in the buttom panel changing.
              • ") + +tr("
              • Getting Calendar
                • Click on Calendar Tab
                • Select your dates and click on Get Calendar
              • ") + +tr("
              • For exporting your calendar to a .CSV file:
                • Do previous step and continue to next step
                • Click on Export to CSV
                • Select your dates and click OK
                • Once you're Done, go on your calendar and import your csv file
                • ")+ + "

                  " + +tr("For more information, please visit us at: Jce Manager site")); } void MainScreen::on_actionHebrew_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionEnglish->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; - data->setLocal("he"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionEnglish->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; + data->setLocal("he"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionHebrew->setChecked(true); + else + ui->actionHebrew->setChecked(true); } void MainScreen::on_actionEnglish_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to English"; - data->setLocal("en"); - QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to English"; + data->setLocal("en"); + QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionEnglish->setChecked(true); + else + ui->actionEnglish->setChecked(true); } void MainScreen::on_actionOS_Default_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionEnglish->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; - data->setLocal("default"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionEnglish->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; + data->setLocal("default"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionOS_Default->setChecked(true); + else + ui->actionOS_Default->setChecked(true); } void MainScreen::checkLocale() { - if(data->getLocal() == "en") + if(data->getLocal() == "en") { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(true); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(true); }else if(data->getLocal() == "he"){ - ui->actionHebrew->setChecked(true); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(true); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(false); }else{ - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(true); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(true); + ui->actionEnglish->setChecked(false); } } void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { - qDebug() << Q_FUNC_INFO << "link: " << link; + qDebug() << Q_FUNC_INFO << "link: " << link; } diff --git a/main/mainscreen.h b/main/mainscreen.h index 7ab3d42..929ed48 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -83,6 +83,8 @@ private: coursesTableManager *courseTableMgr; loginHandler *loginHandel; + bool busyFlag; + }; #endif // MAINSCREEN_H diff --git a/main/mainscreen.ui b/main/mainscreen.ui index b80a4fd..44833ed 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -629,6 +629,45 @@ font-size: 15px; + + + + + 0 + 0 + + + + #progressBar::horizontal { +border: 1px solid gray; +border-radius: 3px; +background: white; +padding: 1px; +} +#progressBar::chunk:horizontal { +background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 1 white); +} + + + 0 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + true + + + Qt::Horizontal + + + false + + + QProgressBar::TopToBottom + + + diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 729447e..1e24a92 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -3,17 +3,19 @@ /** * @brief jceSSLClient::jceSSLClient Constructer, setting the signals */ -jceSSLClient::jceSSLClient() : flag(false), packet(""),networkConf(), reConnection(false) +jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : flag(false), packet(""),networkConf(), reConnection(false) { - //setting signals - connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError))); - connect(this,SIGNAL(connected()),this,SLOT(setConnected())); - connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted())); - connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected())); - connect(&networkConf,SIGNAL(onlineStateChanged(bool)),this,SLOT(setOnlineState(bool))); - //loop event will connect the server, and when it is connected, it will quit - but connection will be open - connect(this, SIGNAL(encrypted()), &loop, SLOT(quit())); - connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loop,SLOT(quit())); + this->progressBar = progressbarPtr; + //setting signals + connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError))); + connect(this,SIGNAL(connected()),this,SLOT(setConnected())); + connect(this,SIGNAL(encrypted()),this,SLOT(setEncrypted())); + connect(this,SIGNAL(disconnected()),this,SLOT(setDisconnected())); + connect(&networkConf,SIGNAL(onlineStateChanged(bool)),this,SLOT(setOnlineState(bool))); + + //loop event will connect the server, and when it is connected, it will quit - but connection will be open + connect(this, SIGNAL(encrypted()), &loop, SLOT(quit())); + connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loop,SLOT(quit())); } /** @@ -24,48 +26,48 @@ jceSSLClient::jceSSLClient() : flag(false), packet(""),networkConf(), reConnecti */ bool jceSSLClient::makeConnect(QString server, int port) { - if (this->supportsSsl() == false) + if (this->supportsSsl() == false) { - qCritical() << Q_FUNC_INFO << "Couldnt load ssl package. ERROR"; - return false; + qCritical() << Q_FUNC_INFO << "Couldnt load ssl package. ERROR"; + return false; } - else - qDebug() << Q_FUNC_INFO << "ssl loaded."; + else + qDebug() << Q_FUNC_INFO << "ssl loaded."; - if (isConnectedToNetwork() == false) + if (isConnectedToNetwork() == false) { - qDebug() << Q_FUNC_INFO << "return false. not online"; - return false; + qDebug() << Q_FUNC_INFO << "return false. not online"; + return false; } - else - qDebug() << Q_FUNC_INFO << "we're online"; + else + qDebug() << Q_FUNC_INFO << "we're online"; - if (reConnection) //reset reconnectiong flag + if (reConnection) //reset reconnectiong flag { - qDebug() << Q_FUNC_INFO << "Making Reconnection"; + qDebug() << Q_FUNC_INFO << "Making Reconnection"; } - else - qDebug() << Q_FUNC_INFO << "Making Connection"; + else + qDebug() << Q_FUNC_INFO << "Making Connection"; - if (isConnected()) + if (isConnected()) { - qDebug() << Q_FUNC_INFO << "flag=true, calling makeDisconnect()"; - makeDiconnect(); + qDebug() << Q_FUNC_INFO << "flag=true, calling makeDisconnect()"; + makeDiconnect(); } - qDebug() << Q_FUNC_INFO << "Connection to: " << server << "On Port: " << port; - connectToHostEncrypted(server.toStdString().c_str(), port); + qDebug() << Q_FUNC_INFO << "Connection to: " << server << "On Port: " << port; + connectToHostEncrypted(server.toStdString().c_str(), port); - loop.exec(); //starting connection, waiting to encryption and then it ends + loop.exec(); //starting connection, waiting to encryption and then it ends - qDebug() << Q_FUNC_INFO << "returning the connection status: " << isConnected(); - if (reConnection) + qDebug() << Q_FUNC_INFO << "returning the connection status: " << isConnected(); + if (reConnection) { - reConnection = false; - emit serverDisconnectedbyRemote(); + reConnection = false; + emit serverDisconnectedbyRemote(); } - return isConnected(); + return isConnected(); } /** @@ -74,15 +76,15 @@ bool jceSSLClient::makeConnect(QString server, int port) */ bool jceSSLClient::makeDiconnect() { - if (loop.isRunning()) + if (loop.isRunning()) { - qWarning() << Q_FUNC_INFO << "Killing connection thread"; - loop.exit(); + qWarning() << Q_FUNC_INFO << "Killing connection thread"; + loop.exit(); } - qDebug() << Q_FUNC_INFO << "disconnecting from host and emitting disconnected()"; - this->disconnectFromHost(); //emits disconnected > setDisconnected - setSocketState(QAbstractSocket::SocketState::UnconnectedState); - return (!isConnected()); + qDebug() << Q_FUNC_INFO << "disconnecting from host and emitting disconnected()"; + this->disconnectFromHost(); //emits disconnected > setDisconnected + setSocketState(QAbstractSocket::SocketState::UnconnectedState); + return (!isConnected()); } @@ -92,30 +94,30 @@ bool jceSSLClient::makeDiconnect() */ bool jceSSLClient::isConnected() { - bool tempFlag = false; - //checking state before returning flag! - if (state() == QAbstractSocket::SocketState::UnconnectedState) + bool tempFlag = false; + //checking state before returning flag! + if (state() == QAbstractSocket::SocketState::UnconnectedState) { - tempFlag = false; + tempFlag = false; } - else if (state() == QAbstractSocket::SocketState::ClosingState) + else if (state() == QAbstractSocket::SocketState::ClosingState) { - tempFlag = false; + tempFlag = false; } - else if (state() == QAbstractSocket::SocketState::ConnectedState) + else if (state() == QAbstractSocket::SocketState::ConnectedState) { - if (isConnectedToNetwork()) - tempFlag = true; - else + if (isConnectedToNetwork()) + tempFlag = true; + else { - this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); - tempFlag = false; + this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); + tempFlag = false; } } - if (!isConnectedToNetwork()) //no link, ethernet\wifi - tempFlag = false; - return ((flag) && (tempFlag)); + if (!isConnectedToNetwork()) //no link, ethernet\wifi + tempFlag = false; + return ((flag) && (tempFlag)); } /** * @brief jceSSLClient::sendData - given string, send it to server @@ -124,16 +126,16 @@ bool jceSSLClient::isConnected() */ bool jceSSLClient::sendData(QString str) { - bool sendDataFlag = false; + bool sendDataFlag = false; - if (isConnected()) //if connected + if (isConnected()) //if connected { - write(str.toStdString().c_str(),str.length()); - if (waitForBytesWritten()) - sendDataFlag = true; + write(str.toStdString().c_str(),str.length()); + if (waitForBytesWritten()) + sendDataFlag = true; } - qDebug() << Q_FUNC_INFO << "Sending Data status is: " << sendDataFlag; - return sendDataFlag; + qDebug() << Q_FUNC_INFO << "Sending Data status is: " << sendDataFlag; + return sendDataFlag; } /** * @brief jceSSLClient::recieveData @@ -143,39 +145,41 @@ bool jceSSLClient::sendData(QString str) */ bool jceSSLClient::recieveData(QString &str, bool fast) { - qDebug() << Q_FUNC_INFO << "Data receiving!"; - packet = ""; - bool sflag = false; + qDebug() << Q_FUNC_INFO << "Data receiving!"; + packet = ""; + bool sflag = false; - if (fast) //fast mode connection, good only for login step!!!! + if (fast) //fast mode connection, good only for login step!!!! { - qDebug() << "jceSSLClient::recieveData login step receiving"; - QEventLoop loop; - connect(this, SIGNAL(readyRead()), &loop, SLOT(quit())); - connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); - loop.exec(); - disconnect(this, SIGNAL(readyRead()), &loop, SLOT(quit())); - disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); + qDebug() << Q_FUNC_INFO << "login step receiving"; + //loop will exit after first read packet. + //meanwhile packet will gain data. good for small amount of data - fast connection! + connect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); + connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); + readerLoop.exec(); + disconnect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); + disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); } - else + else { - qDebug() << "jceSSLClient::recieveData normal receiving"; - QString p; - while (waitForReadyRead(milisTimeOut)) - { - do - { - p = readAll(); - packet.append(p); - }while (p.size() > 0); - } + qDebug() << Q_FUNC_INFO << "normal receiving"; + //loop will exit after timeout \ full data + connect(this, SIGNAL(packetHasData()), &readerLoop, SLOT(quit())); + + timer.setSingleShot(true); + connect(&timer, SIGNAL(timeout()), &readerLoop, SLOT(quit())); + connect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); + timer.start(5000); + readerLoop.exec(); + } - str = packet; - qDebug() << Q_FUNC_INFO << "received bytes: " << str.length() ; - if (str.length() > 0) - sflag = true; - qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; - return sflag; + str = packet; + qDebug() << Q_FUNC_INFO << "received bytes: " << str.length() ; + if (str.length() > 0) + sflag = true; + qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; + disconnect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); + return sflag; } /** @@ -183,29 +187,46 @@ bool jceSSLClient::recieveData(QString &str, bool fast) */ void jceSSLClient::readIt() { - QString p; - do + QString p; + do { - p = readAll(); - packet.append(p); + p = readAll(); + packet.append(p); + this->progressBar->setValue(this->progressBar->value() + 6); }while (p.size() > 0); } +void jceSSLClient::readItAll() +{ + QString p; + do + { + p = ""; + p = read(bytesAvailable()); + if (p.contains("") == true) + { + //we recieved the end of table. we can stop recieving + timer.setInterval(1000); + } + this->progressBar->setValue(this->progressBar->value() + 6); + packet.append(p); + }while (p.size() > 0); +} void jceSSLClient::setOnlineState(bool isOnline) { - qWarning() << Q_FUNC_INFO << "isOnline status change: " << isOnline; - if (isOnline) //to be added later + qWarning() << Q_FUNC_INFO << "isOnline status change: " << isOnline; + if (isOnline) //to be added later { - qDebug() << Q_FUNC_INFO << "Online Statue has been changed. we are online"; - //we can add here auto reconnect if wifi\ethernet link has appear - //will be added next version + qDebug() << Q_FUNC_INFO << "Online Statue has been changed. we are online"; + //we can add here auto reconnect if wifi\ethernet link has appear + //will be added next version } - else + else { - qWarning() << Q_FUNC_INFO << "Online State has been changed. emitting NoInternetLink"; - this->makeDiconnect(); - emit noInternetLink(); + qWarning() << Q_FUNC_INFO << "Online State has been changed. emitting NoInternetLink"; + this->makeDiconnect(); + emit noInternetLink(); } } @@ -214,19 +235,19 @@ void jceSSLClient::setOnlineState(bool isOnline) */ void jceSSLClient::setConnected() { - waitForEncrypted(); + waitForEncrypted(); } /** * @brief jceSSLClient::setDisconnected closing socket, updating state and setting flag to false */ void jceSSLClient::setDisconnected() { - qDebug() << Q_FUNC_INFO << "connection has been DISCONNECTED"; - this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); - packet.clear(); - flag = false; - if (reConnection) - makeConnect(); + qDebug() << Q_FUNC_INFO << "connection has been DISCONNECTED"; + this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); + packet.clear(); + flag = false; + if (reConnection) + makeConnect(); } @@ -235,14 +256,14 @@ void jceSSLClient::setDisconnected() */ void jceSSLClient::setEncrypted() { - qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; - setReadBufferSize(10000); - setSocketOption(QAbstractSocket::KeepAliveOption,true); - flag = true; - if (!isConnected()) + qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; + setReadBufferSize(10000); + setSocketOption(QAbstractSocket::KeepAliveOption,true); + flag = true; + if (!isConnected()) { - qWarning() << Q_FUNC_INFO << "Connection status didnt change! reseting flag to false"; - flag = false; + qWarning() << Q_FUNC_INFO << "Connection status didnt change! reseting flag to false"; + flag = false; } } @@ -253,116 +274,116 @@ void jceSSLClient::setEncrypted() */ void jceSSLClient::showIfErrorMsg() { - QMessageBox msgBox; - SocketError enumError = error(); - QString errorString; - bool relevantError = false; - switch (enumError) + QMessageBox msgBox; + SocketError enumError = error(); + QString errorString; + bool relevantError = false; + switch (enumError) { case QAbstractSocket::SocketError::ConnectionRefusedError: /**/ - errorString = QObject::tr("ConnectionRefusedError"); - //The connection was refused by the peer (or timed out). - relevantError = true; - break; + errorString = QObject::tr("ConnectionRefusedError"); + //The connection was refused by the peer (or timed out). + relevantError = true; + break; case QAbstractSocket::SocketError::RemoteHostClosedError: /**/ - errorString = QObject::tr("RemoteHostClosedError"); - //The remote host closed the connection - if (isConnectedToNetwork()) //we can reconnect + errorString = QObject::tr("RemoteHostClosedError"); + //The remote host closed the connection + if (isConnectedToNetwork()) //we can reconnect { - reConnection = true; + reConnection = true; } - else - relevantError = true; - break; + else + relevantError = true; + break; case QAbstractSocket::SocketError::HostNotFoundError: /**/ - errorString = QObject::tr("HostNotFoundError"); - //The host address was not found. - relevantError = true; - break; - case QAbstractSocket::SocketError::SocketAccessError: /**/ - errorString = QObject::tr("SocketAccessError"); - //The socket operation failed because the application lacked the required privileges. - break; - case QAbstractSocket::SocketError::SocketTimeoutError: /**/ - errorString = QObject::tr("SocketTimeoutError"); - //The socket operation timed out. - if (isConnected()); //ignore it if connected. - else + errorString = QObject::tr("HostNotFoundError"); + //The host address was not found. relevantError = true; - break; + break; + case QAbstractSocket::SocketError::SocketAccessError: /**/ + errorString = QObject::tr("SocketAccessError"); + //The socket operation failed because the application lacked the required privileges. + break; + case QAbstractSocket::SocketError::SocketTimeoutError: /**/ + errorString = QObject::tr("SocketTimeoutError"); + //The socket operation timed out. + if (isConnected()); //ignore it if connected. + else + relevantError = true; + break; case QAbstractSocket::SocketError::NetworkError: /**/ - errorString = QObject::tr("NetworkError"); - //An error occurred with the network (e.g., the network cable was accidentally plugged out). - if (isConnectedToNetwork()) //we can reconnect + errorString = QObject::tr("NetworkError"); + //An error occurred with the network (e.g., the network cable was accidentally plugged out). + if (isConnectedToNetwork()) //we can reconnect { } - else - relevantError = true; - break; + else + relevantError = true; + break; case QAbstractSocket::SocketError::SslHandshakeFailedError: /**/ - errorString = QObject::tr("SslHandshakeFailedError"); - relevantError = true; - break; + errorString = QObject::tr("SslHandshakeFailedError"); + relevantError = true; + break; case QAbstractSocket::SocketError::SslInternalError: /**/ - errorString = QObject::tr("SslInternalError"); - relevantError = true; - break; + errorString = QObject::tr("SslInternalError"); + relevantError = true; + break; case QAbstractSocket::SocketError::SslInvalidUserDataError: /**/ - errorString = QObject::tr("SslInvalidUserDataError"); - relevantError = true; - break; + errorString = QObject::tr("SslInvalidUserDataError"); + relevantError = true; + break; case QAbstractSocket::SocketError::DatagramTooLargeError: //not relevant to us - errorString = QObject::tr("DatagramTooLargeError"); - break; + errorString = QObject::tr("DatagramTooLargeError"); + break; case QAbstractSocket::SocketError::SocketResourceError: //not relevant to us - break; + break; case QAbstractSocket::SocketError::OperationError: //not relevant, except for debug - errorString = QObject::tr("OperationError"); - break; + errorString = QObject::tr("OperationError"); + break; case QAbstractSocket::SocketError::AddressInUseError: //not relevant to us - errorString = QObject::tr("AddressInUseError"); - break; + errorString = QObject::tr("AddressInUseError"); + break; case QAbstractSocket::SocketError::SocketAddressNotAvailableError: //not relevant to us - errorString = QObject::tr("SocketAddressNotAvailableError"); - break; + errorString = QObject::tr("SocketAddressNotAvailableError"); + break; case QAbstractSocket::SocketError::UnsupportedSocketOperationError: //for very old computers, not relevant to us - errorString = QObject::tr("UnsupportedSocketOperationError"); - break; + errorString = QObject::tr("UnsupportedSocketOperationError"); + break; case QAbstractSocket::SocketError::ProxyAuthenticationRequiredError: //not relevant to us - errorString = QObject::tr("ProxyAuthenticationRequiredError"); - break; + errorString = QObject::tr("ProxyAuthenticationRequiredError"); + break; case QAbstractSocket::SocketError::ProxyConnectionRefusedError: //not relevant to us - errorString = QObject::tr("ProxyConnectionRefusedError"); - break; + errorString = QObject::tr("ProxyConnectionRefusedError"); + break; case QAbstractSocket::SocketError::UnfinishedSocketOperationError: //not relevant to us - errorString = QObject::tr("UnfinishedSocketOperationError"); - break; + errorString = QObject::tr("UnfinishedSocketOperationError"); + break; case QAbstractSocket::SocketError::ProxyConnectionClosedError: //not relevant to us - errorString = QObject::tr("ProxyConnectionClosedError"); - break; + errorString = QObject::tr("ProxyConnectionClosedError"); + break; case QAbstractSocket::SocketError::ProxyConnectionTimeoutError: //not relevant to us - errorString = QObject::tr("ProxyConnectionTimeoutError"); - break; + errorString = QObject::tr("ProxyConnectionTimeoutError"); + break; case QAbstractSocket::SocketError::ProxyNotFoundError: //not relevant to us - errorString = QObject::tr("ProxyNotFoundError"); - break; + errorString = QObject::tr("ProxyNotFoundError"); + break; case QAbstractSocket::SocketError::ProxyProtocolError: //not relevant to us - errorString = QObject::tr("ProxyProtocolError"); - break; + errorString = QObject::tr("ProxyProtocolError"); + break; case QAbstractSocket::SocketError::TemporaryError: //not relevant to us - errorString = QObject::tr("TemporaryError"); - break; + errorString = QObject::tr("TemporaryError"); + break; case QAbstractSocket::SocketError::UnknownSocketError: //not relevant, except for debug - errorString = QObject::tr("UnknownSocketError"); - relevantError = true; - break; + errorString = QObject::tr("UnknownSocketError"); + relevantError = true; + break; } - if (relevantError) //informative string to be shown + if (relevantError) //informative string to be shown { - qDebug() << Q_FUNC_INFO << "relevant error."; - msgBox.setIcon(QMessageBox::Warning); - msgBox.setText(errorString); - msgBox.exec(); + qDebug() << Q_FUNC_INFO << "relevant error."; + msgBox.setIcon(QMessageBox::Warning); + msgBox.setText(errorString); + msgBox.exec(); } } /** @@ -371,24 +392,24 @@ void jceSSLClient::showIfErrorMsg() */ void jceSSLClient::checkErrors(QAbstractSocket::SocketError a) { - //ignore this stupid error - bool timeout = (a == QAbstractSocket::SocketError::SocketTimeoutError); - if (!((isConnected()) && (timeout))) + //ignore this stupid error + bool timeout = (a == QAbstractSocket::SocketError::SocketTimeoutError); + if (!((isConnected()) && (timeout))) { - qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); - qWarning() << Q_FUNC_INFO << "state is: " << state(); - qWarning() << Q_FUNC_INFO << "Var Error: " << a; - qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); + qWarning() << Q_FUNC_INFO << "state is: " << state(); + qWarning() << Q_FUNC_INFO << "Var Error: " << a; + qWarning() << Q_FUNC_INFO << "Error: " << errorString(); } - else + else { - qDebug() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; - qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); - qWarning() << Q_FUNC_INFO << "state is: " << state(); - qWarning() << Q_FUNC_INFO << "Var Error: " << a; - qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + qDebug() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; + qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); + qWarning() << Q_FUNC_INFO << "state is: " << state(); + qWarning() << Q_FUNC_INFO << "Var Error: " << a; + qWarning() << Q_FUNC_INFO << "Error: " << errorString(); } - showIfErrorMsg(); + showIfErrorMsg(); } /** written by KARAN BALKAR @@ -397,20 +418,20 @@ void jceSSLClient::checkErrors(QAbstractSocket::SocketError a) */ bool jceSSLClient::isConnectedToNetwork(){ - QList ifaces = QNetworkInterface::allInterfaces(); - bool result = false; + QList ifaces = QNetworkInterface::allInterfaces(); + bool result = false; - for (int i = 0; i < ifaces.count(); ++i) + for (int i = 0; i < ifaces.count(); ++i) { - QNetworkInterface iface = ifaces.at(i); + QNetworkInterface iface = ifaces.at(i); - if ( iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) - for (int j=0; j < iface.addressEntries().count(); ++j) - // got an interface which is up, and has an ip address - if (result == false) - result = true; + if ( iface.flags().testFlag(QNetworkInterface::IsUp) && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) + for (int j=0; j < iface.addressEntries().count(); ++j) + // got an interface which is up, and has an ip address + if (result == false) + result = true; } - return result; + return result; } diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index d4f95e7..a6edbed 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -8,6 +8,8 @@ #include #include #include +#include +#include #define milisTimeOut 4000 @@ -15,7 +17,7 @@ class jceSSLClient : public QSslSocket { Q_OBJECT public: - jceSSLClient(); + jceSSLClient(QProgressBar *progressbarPtr); bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); bool makeDiconnect(); @@ -28,6 +30,7 @@ signals: void serverDisconnectedbyRemote(); void noInternetLink(); void socketDisconnected(); + void packetHasData(); private slots: void checkErrors(QAbstractSocket::SocketError a); @@ -35,6 +38,7 @@ private slots: void setEncrypted(); void setDisconnected(); void readIt(); + void readItAll(); void setOnlineState(bool isOnline); private: @@ -42,9 +46,13 @@ private: bool flag; QString packet; QEventLoop loop; //handle the connection as thread + QEventLoop readerLoop; + QTimer timer; QNetworkConfigurationManager networkConf; //checking if online bool reConnection; //used for remote host disconnecting + QProgressBar *progressBar; // + }; #endif // JCESSLCLIENT_H diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 5a25587..900ef23 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -4,11 +4,12 @@ * @brief jceLogin::jceLogin * @param username pointer to allocated user settings */ -jceLogin::jceLogin(user* username) +jceLogin::jceLogin(user* username, QProgressBar *progressbarPtr) { + this->progressBar = progressbarPtr; this->recieverPage = new QString(); this->jceA = username; - this->JceConnector = new jceSSLClient(); + this->JceConnector = new jceSSLClient(progressBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); } @@ -133,7 +134,7 @@ void jceLogin::reMakeConnection() recieverPage = NULL; JceConnector = NULL; this->recieverPage = new QString(); - this->JceConnector = new jceSSLClient(); + this->JceConnector = new jceSSLClient(progressBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); emit connectionReadyAfterDisconnection(); @@ -297,6 +298,7 @@ QString jceLogin::getPage() void jceLogin::reValidation() { qDebug() << Q_FUNC_INFO << "Revalidating user"; + if (makeFirstVisit() == true) { if (checkValidation()) diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index ede8514..912b47b 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -6,6 +6,7 @@ #include "jceLoginHtmlScripts.h" #include +#include #include @@ -13,8 +14,8 @@ class jceLogin : public QObject { Q_OBJECT public: - jceLogin() {} - jceLogin(user* username); + + jceLogin(user* username,QProgressBar *progressbarPtr); ~jceLogin(); enum jceStatus { @@ -61,6 +62,7 @@ private: QString * recieverPage; user * jceA; jceSSLClient * JceConnector; + QProgressBar *progressBar; }; From 026c6b937c5db0d61ee7d0db8237c0f033458caa Mon Sep 17 00:00:00 2001 From: liranbg Date: Sun, 5 Oct 2014 14:16:01 +0300 Subject: [PATCH 04/58] gpa contains years and semester --- jceGrade.pro | 13 +- main/CourseTab/coursestablemanager.cpp | 69 +- main/CourseTab/coursestablemanager.h | 4 + main/mainscreen.cpp | 4 + main/mainscreen.h | 2 + main/mainscreen.ui | 35 +- src/jceData/Grades/gradeCourse.cpp | 25 +- src/jceData/Grades/gradeCourse.h | 23 +- src/jceData/Grades/gradePage.cpp | 41 +- src/jceData/Grades/graph/gradegraph.cpp | 15 + src/jceData/Grades/graph/gradegraph.h | 26 + src/jceData/Grades/graph/gradegraph.ui | 51 + src/jceData/Grades/graph/qcustomplot.cpp | 21370 +++++++++++++++++++++ src/jceData/Grades/graph/qcustomplot.h | 3529 ++++ src/jceData/page.cpp | 57 +- src/jceData/page.h | 1 + 16 files changed, 25197 insertions(+), 68 deletions(-) create mode 100644 src/jceData/Grades/graph/gradegraph.cpp create mode 100644 src/jceData/Grades/graph/gradegraph.h create mode 100644 src/jceData/Grades/graph/gradegraph.ui create mode 100644 src/jceData/Grades/graph/qcustomplot.cpp create mode 100644 src/jceData/Grades/graph/qcustomplot.h diff --git a/jceGrade.pro b/jceGrade.pro index 33e64bc..8839a65 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -4,7 +4,7 @@ # #------------------------------------------------- -QT += core gui network widgets +QT += core gui network widgets printsupport CONFIG += qt c++11 @@ -25,7 +25,8 @@ TRANSLATIONS = jce_en.ts \ FORMS += \ main/mainscreen.ui \ - src/jceData/Calendar/calendarDialog.ui + src/jceData/Calendar/calendarDialog.ui \ + src/jceData/Grades/graph/gradegraph.ui RESOURCES += \ resources/connectionstatus.qrc @@ -50,7 +51,9 @@ HEADERS += \ src/jceData/CSV/csv_exporter.h \ src/appDatabase/simplecrypt.h \ src/jceData/Calendar/calendarDialog.h \ - src/appDatabase/jce_logger.h + src/appDatabase/jce_logger.h \ + src/jceData/Grades/graph/qcustomplot.h \ + src/jceData/Grades/graph/gradegraph.h SOURCES += \ main/CalendarTab/CalendarManager.cpp \ @@ -71,4 +74,6 @@ SOURCES += \ src/jceData/CSV/csv_exporter.cpp \ src/appDatabase/simplecrypt.cpp \ src/jceData/Calendar/calendarDialog.cpp \ - src/appDatabase/jce_logger.cpp + src/appDatabase/jce_logger.cpp \ + src/jceData/Grades/graph/qcustomplot.cpp \ + src/jceData/Grades/graph/gradegraph.cpp diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index d944c7a..bdf7dc8 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -12,12 +12,17 @@ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) courseTBL->setRowCount(0); courseTBL->setColumnCount(COURSE_FIELDS); QStringList mz; - mz << QObject::tr("Code") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); + mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); courseTBL->setHorizontalHeaderLabels(mz); - courseTBL->verticalHeader()->setVisible(true); + courseTBL->verticalHeader()->setVisible(false); courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); courseTBL->setShowGrid(true); courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); + + /* + * + */ + graph = new gradegraph(NULL,gp); } coursesTableManager::~coursesTableManager() @@ -61,6 +66,8 @@ bool coursesTableManager::changes(QString change, int row, int col) { bool isNumFlag = true; + if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) + return true; int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); for (gradeCourse *c: *gp->getCourses()) @@ -69,6 +76,15 @@ bool coursesTableManager::changes(QString change, int row, int col) { switch (col) { + case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): + c->setCourseNumInList(change.toInt()); + break; + case (gradeCourse::CourseScheme::YEAR): + c->setYear(change.toInt()); + break; + case (gradeCourse::CourseScheme::SEMESTER): + c->setSemester(change.toInt()); + break; case (gradeCourse::CourseScheme::NAME): c->setName(change); break; @@ -132,30 +148,40 @@ bool coursesTableManager::changes(QString change, int row, int col) */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { - int i,j; - i = courseTBL->rowCount(); + int i=1,j=1; + j = 0; - QTableWidgetItem *serial,*name,*type,*points,*hours,*grade,*addition; + QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; const gradeCourse * c; if (courseToAdd != NULL) { c = courseToAdd; if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount()+1); + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; + + number = new QTableWidgetItem(QString::number(c->getCourseNumInList())); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(QString::number(c->getYear())); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); + semester = new QTableWidgetItem(QString::number(c->getSemester())); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); serial = new QTableWidgetItem(QString::number(c->getSerialNum())); serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); points = new QTableWidgetItem(QString::number(c->getPoints())); - points->setFlags(serial->flags() & ~Qt::ItemIsEditable); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); hours = new QTableWidgetItem(QString::number(c->getHours())); - hours->setFlags(serial->flags() & ~Qt::ItemIsEditable); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); grade = new QTableWidgetItem(QString::number(c->getGrade())); name = new QTableWidgetItem(c->getName()); - name->setFlags(serial->flags() & ~Qt::ItemIsEditable); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); type = new QTableWidgetItem(c->getType()); - type->setFlags(serial->flags() & ~Qt::ItemIsEditable); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); addition = new QTableWidgetItem(c->getAddidtions()); - + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); courseTBL->setItem(i,j++,serial); courseTBL->setItem(i,j++,name); courseTBL->setItem(i,j++,type); @@ -164,10 +190,12 @@ void coursesTableManager::addRow(const gradeCourse *courseToAdd) courseTBL->setItem(i,j++,grade); courseTBL->setItem(i,j,addition); + } } else { + qCritical() << Q_FUNC_INFO << "no course to load!"; } courseTBL->resizeColumnsToContents(); @@ -179,6 +207,12 @@ double coursesTableManager::getAvg() return 0; } +void coursesTableManager::showGraph() +{ + if (gp != NULL) + this->graph->show(); +} + void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { @@ -232,12 +266,15 @@ gradeCourse *coursesTableManager::getCourseByRow(int row) bool coursesTableManager::isCourseAlreadyInserted(double courseID) { - int i=0; - for (i = 0; i < courseTBL->rowCount(); ++i) + int i; + for (i = courseTBL->rowCount(); i >= 0; --i) { - QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); - if (QString::number(courseID) == courseSerial) - return true; + if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) + { + QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); + if (QString::number(courseID) == courseSerial) + return true; + } } return false; } diff --git a/main/CourseTab/coursestablemanager.h b/main/CourseTab/coursestablemanager.h index 84f416d..d7d1021 100644 --- a/main/CourseTab/coursestablemanager.h +++ b/main/CourseTab/coursestablemanager.h @@ -13,6 +13,7 @@ #include +#include "./src/jceData/Grades/graph/gradegraph.h" #include "./src/jceData/Grades/gradePage.h" #include "./src/jceSettings/user.h" @@ -27,10 +28,13 @@ public: void addRow(const gradeCourse * courseToAdd = 0); double getAvg(); + void showGraph(); + void influnceCourseChanged(bool status); void clearTable(); private: + gradegraph *graph; QTableWidget *courseTBL; GradePage *gp; user *us; diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 5425d5d..1f6718c 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -229,6 +229,10 @@ void MainScreen::on_clearTableButton_clicked() courseTableMgr->clearTable(); ui->avgLCD->display(courseTableMgr->getAvg()); } +void MainScreen::on_graphButton_clicked() +{ + courseTableMgr->showGraph(); +} //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { diff --git a/main/mainscreen.h b/main/mainscreen.h index 929ed48..e0f5d32 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -67,6 +67,8 @@ private slots: void on_labelMadeBy_linkActivated(const QString &link); + void on_graphButton_clicked(); + private: void checkLocale(); diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 44833ed..9d0528b 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -6,8 +6,8 @@ 0 0 - 855 - 517 + 1133 + 623 @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 0 + 1 false @@ -385,6 +385,13 @@ font-size: 15px; + + + + Graph View + + + @@ -629,6 +636,13 @@ font-size: 15px; + + + + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> + + + @@ -641,7 +655,7 @@ font-size: 15px; #progressBar::horizontal { border: 1px solid gray; border-radius: 3px; -background: white; +background: transparent; padding: 1px; } #progressBar::chunk:horizontal { @@ -652,7 +666,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Qt::AlignCenter true @@ -668,13 +682,6 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: - - - - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - - - @@ -682,8 +689,8 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 - 855 - 21 + 1133 + 22 diff --git a/src/jceData/Grades/gradeCourse.cpp b/src/jceData/Grades/gradeCourse.cpp index 2cfe501..16bca5b 100644 --- a/src/jceData/Grades/gradeCourse.cpp +++ b/src/jceData/Grades/gradeCourse.cpp @@ -1,10 +1,13 @@ #include "gradeCourse.h" -gradeCourse::gradeCourse(int serial, QString name, QString type, double points, double hours, double grade, QString additions) : Course(serial,name,type,points) +gradeCourse::gradeCourse(int year, int semester, int courseNumInList, int serial, QString name, QString type, double points,double hours, double grade, QString additions) : Course(serial,name,type,points) { this->hours = hours; this->grade = grade; this->additions = additions; + this->year = year; + this->semester = semester; + this->courseNumInList = courseNumInList; } gradeCourse::~gradeCourse() @@ -34,3 +37,23 @@ void gradeCourse::setAdditions(QString additions) { this->additions = additions; } + +void gradeCourse::setYear(int year) +{ + this->year = year; + +} +void gradeCourse::setSemester(int semester) +{ + this->semester = semester; +} +int gradeCourse::getCourseNumInList() const +{ + return courseNumInList; +} + +void gradeCourse::setCourseNumInList(int value) +{ + courseNumInList = value; +} + diff --git a/src/jceData/Grades/gradeCourse.h b/src/jceData/Grades/gradeCourse.h index 768201f..d62356a 100644 --- a/src/jceData/Grades/gradeCourse.h +++ b/src/jceData/Grades/gradeCourse.h @@ -12,7 +12,7 @@ #include #include -#define COURSE_FIELDS 7 +#define COURSE_FIELDS 10 #define NO_GRADE_YET 101; @@ -21,6 +21,9 @@ class gradeCourse : public Course { public: enum CourseScheme { + YEAR, + SEMESTER, + COURSE_NUMBER_IN_LIST, SERIAL, NAME, TYPE, @@ -30,22 +33,32 @@ public: ADDITION }; - gradeCourse(int serial, QString name, QString type, double points,double hours, double grade, QString additions); + gradeCourse(int year, int semester, int courseNumInList, int serial, QString name, QString type, double points,double hours, double grade, QString additions); ~gradeCourse(); + int getYear() const { return this->year; } + int getSemester() const { return this->semester; } double getHours() const {return this->hours;} - double getGrade() const ; + double getGrade() const; QString getAddidtions() const {return this->additions;} void setHours(double hours); void setGrade(double grade); void setAdditions(QString additions); + void setYear(int year); + void setSemester(int semester); + + int getCourseNumInList() const; + void setCourseNumInList(int value); private: - double hours; - double grade; + double hours; + double grade; QString additions; + int year; + int semester; + int courseNumInList; }; diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index 1dffbf6..786f132 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -36,13 +36,13 @@ void GradePage::coursesListInit(QString &linesTokinzedString) char* tok; char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); tok = strtok(textToTok,"\n"); - while (tok != NULL) + while (tok != NULL) //putting every line in a string holder before parsing it { temp = tok; stringHolder.push_back(temp); tok = strtok(NULL, "\n"); } - for(QString temp: stringHolder) + for (QString temp: stringHolder) { cTemp = lineToCourse(temp); if (cTemp != NULL) @@ -52,7 +52,6 @@ void GradePage::coursesListInit(QString &linesTokinzedString) QString GradePage::tokenToLines(QString &textToPhrase) { - int ctr = 0; QString temp = ""; char *tok; char* textToTok = strdup(textToPhrase.toStdString().c_str()); @@ -65,7 +64,6 @@ QString GradePage::tokenToLines(QString &textToPhrase) temp += tok; temp += "\n"; } - ctr++; tok = strtok(NULL, "\n"); } return temp; @@ -75,7 +73,7 @@ gradeCourse* GradePage::lineToCourse(QString line) { gradeCourse *tempC = NULL; QString templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions] - int serial; + int serial,year,semester,courseNumInList; double points,hours,grade; QString name,type, additions; QString tempS = ""; @@ -85,35 +83,44 @@ gradeCourse* GradePage::lineToCourse(QString line) tok = strtok(cLine, "\t"); while(tok != NULL) { - tempS = tok; - if (i == 1) //skip the tokenizing loop just once + + if (i == gradeCourse::CourseScheme::SERIAL) //we need to extract the serial manually { tempS = ""; char *tokTemp; tokTemp = tok; - while (!(isdigit((int)*tokTemp))) + while (!(isdigit((int)*tokTemp))) //getting to serial number starting pointer tokTemp++; - while (isdigit((int)*tokTemp)) + while (isdigit((int)*tokTemp)) //serial number { tempS += QString(*tokTemp); tokTemp++; } - templinearray[i-1] = tempS.trimmed(); - templinearray[i] = QString(tokTemp).trimmed(); - + templinearray[i] = tempS.trimmed(); + templinearray[i+1] = QString(tokTemp).trimmed(); + i +=2; //skipping on serial and course name } - else if (i > 1) + else { - templinearray[i] = tempS; + templinearray[i] = tempS.trimmed(); + i++; } - i++; + + if (i == COURSE_FIELDS) + break; tok=strtok(NULL, "\t"); } - if (templinearray[0] == "") //empty phrasing + if (templinearray[0] == "") //empty parsing + { + qCritical() << Q_FUNC_INFO << "empty parsing"; return NULL; + } + year = templinearray[gradeCourse::CourseScheme::YEAR].toInt(); + semester = templinearray[gradeCourse::CourseScheme::SEMESTER].toInt(); + courseNumInList = templinearray[gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST].toInt(); serial = templinearray[gradeCourse::CourseScheme::SERIAL].toInt(); name = templinearray[gradeCourse::CourseScheme::NAME]; @@ -129,7 +136,7 @@ gradeCourse* GradePage::lineToCourse(QString line) additions = templinearray[gradeCourse::CourseScheme::ADDITION]; - tempC = new gradeCourse(serial,name,type,points,hours,grade,additions); + tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); return tempC; } diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp new file mode 100644 index 0000000..f581cd3 --- /dev/null +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -0,0 +1,15 @@ +#include "gradegraph.h" +#include "ui_gradegraph.h" + +gradegraph::gradegraph(QWidget *parent, GradePage *gpPTR) : + QDialog(parent), + ui(new Ui::gradegraph) +{ + ui->setupUi(this); + this->gp = gpPTR; +} + +gradegraph::~gradegraph() +{ + delete ui; +} diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h new file mode 100644 index 0000000..649c40e --- /dev/null +++ b/src/jceData/Grades/graph/gradegraph.h @@ -0,0 +1,26 @@ +#ifndef GRADEGRAPH_H +#define GRADEGRAPH_H + +#include "./src/jceData/Grades/gradePage.h" +#include "qcustomplot.h" +#include + +namespace Ui { +class gradegraph; +} + +class gradegraph : public QDialog +{ + Q_OBJECT + +public: + gradegraph(QWidget *parent = 0, GradePage *gpPTR = 0); + ~gradegraph(); + +private: + + GradePage *gp; + Ui::gradegraph *ui; +}; + +#endif // GRADEGRAPH_H diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui new file mode 100644 index 0000000..75cf324 --- /dev/null +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -0,0 +1,51 @@ + + + gradegraph + + + + 0 + 0 + 597 + 461 + + + + Dialog + + + + + + + 0 + 0 + + + + + 16777215 + 25 + + + + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">Graph View</span></p></body></html> + + + + + + + + + + + QCustomPlot + QWidget +
                  src/jceData/Grades/graph/qcustomplot.h
                  + 1 +
                  +
                  + + +
                  diff --git a/src/jceData/Grades/graph/qcustomplot.cpp b/src/jceData/Grades/graph/qcustomplot.cpp new file mode 100644 index 0000000..ad267b6 --- /dev/null +++ b/src/jceData/Grades/graph/qcustomplot.cpp @@ -0,0 +1,21370 @@ +/*************************************************************************** +** ** +** QCustomPlot, an easy to use, modern plotting widget for Qt ** +** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** +** ** +** This program is free software: you can redistribute it and/or modify ** +** it under the terms of the GNU General Public License as published by ** +** the Free Software Foundation, either version 3 of the License, or ** +** (at your option) any later version. ** +** ** +** This program is distributed in the hope that it will be useful, ** +** but WITHOUT ANY WARRANTY; without even the implied warranty of ** +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** +** GNU General Public License for more details. ** +** ** +** You should have received a copy of the GNU General Public License ** +** along with this program. If not, see http://www.gnu.org/licenses/. ** +** ** +**************************************************************************** +** Author: Emanuel Eichhammer ** +** Website/Contact: http://www.qcustomplot.com/ ** +** Date: 07.04.14 ** +** Version: 1.2.1 ** +****************************************************************************/ + +#include "qcustomplot.h" + + + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPainter +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPainter + \brief QPainter subclass used internally + + This QPainter subclass is used to provide some extended functionality e.g. for tweaking position + consistency between antialiased and non-antialiased painting. Further it provides workarounds + for QPainter quirks. + + \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and + restore. So while it is possible to pass a QCPPainter instance to a function that expects a + QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because + it will call the base class implementations of the functions actually hidden by QCPPainter). +*/ + +/*! + Creates a new QCPPainter instance and sets default values +*/ +QCPPainter::QCPPainter() : + QPainter(), + mModes(pmDefault), + mIsAntialiasing(false) +{ + // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // a call to begin() will follow +} + +/*! + Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just + like the analogous QPainter constructor, begins painting on \a device immediately. + + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. +*/ +QCPPainter::QCPPainter(QPaintDevice *device) : + QPainter(device), + mModes(pmDefault), + mIsAntialiasing(false) +{ +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. + if (isActive()) + setRenderHint(QPainter::NonCosmeticDefaultPen); +#endif +} + +QCPPainter::~QCPPainter() +{ +} + +/*! + Sets the pen of the painter and applies certain fixes to it, depending on the mode of this + QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(const QPen &pen) +{ + QPainter::setPen(pen); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of + this QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(const QColor &color) +{ + QPainter::setPen(color); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of + this QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(Qt::PenStyle penStyle) +{ + QPainter::setPen(penStyle); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when + antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to + integer coordinates and then passes it to the original drawLine. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::drawLine(const QLineF &line) +{ + if (mIsAntialiasing || mModes.testFlag(pmVectorized)) + QPainter::drawLine(line); + else + QPainter::drawLine(line.toLine()); +} + +/*! + Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint + with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between + antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for + AA/Non-AA painting). +*/ +void QCPPainter::setAntialiasing(bool enabled) +{ + setRenderHint(QPainter::Antialiasing, enabled); + if (mIsAntialiasing != enabled) + { + mIsAntialiasing = enabled; + if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs + { + if (mIsAntialiasing) + translate(0.5, 0.5); + else + translate(-0.5, -0.5); + } + } +} + +/*! + Sets the mode of the painter. This controls whether the painter shall adjust its + fixes/workarounds optimized for certain output devices. +*/ +void QCPPainter::setModes(QCPPainter::PainterModes modes) +{ + mModes = modes; +} + +/*! + Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a + device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, + all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that + behaviour. + + The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets + the render hint as appropriate. + + \note this function hides the non-virtual base class implementation. +*/ +bool QCPPainter::begin(QPaintDevice *device) +{ + bool result = QPainter::begin(device); +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. + if (result) + setRenderHint(QPainter::NonCosmeticDefaultPen); +#endif + return result; +} + +/*! \overload + + Sets the mode of the painter. This controls whether the painter shall adjust its + fixes/workarounds optimized for certain output devices. +*/ +void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) +{ + if (!enabled && mModes.testFlag(mode)) + mModes &= ~mode; + else if (enabled && !mModes.testFlag(mode)) + mModes |= mode; +} + +/*! + Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to + QPainter, the save/restore functions are reimplemented to also save/restore those members. + + \note this function hides the non-virtual base class implementation. + + \see restore +*/ +void QCPPainter::save() +{ + mAntialiasingStack.push(mIsAntialiasing); + QPainter::save(); +} + +/*! + Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to + QPainter, the save/restore functions are reimplemented to also save/restore those members. + + \note this function hides the non-virtual base class implementation. + + \see save +*/ +void QCPPainter::restore() +{ + if (!mAntialiasingStack.isEmpty()) + mIsAntialiasing = mAntialiasingStack.pop(); + else + qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; + QPainter::restore(); +} + +/*! + Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen + overrides when the \ref pmNonCosmetic mode is set. +*/ +void QCPPainter::makeNonCosmetic() +{ + if (qFuzzyIsNull(pen().widthF())) + { + QPen p = pen(); + p.setWidth(1); + QPainter::setPen(p); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPScatterStyle +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPScatterStyle + \brief Represents the visual appearance of scatter points + + This class holds information about shape, color and size of scatter points. In plottables like + QCPGraph it is used to store how scatter points shall be drawn. For example, \ref + QCPGraph::setScatterStyle takes a QCPScatterStyle instance. + + A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a + fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can + be controlled with \ref setSize. + + \section QCPScatterStyle-defining Specifying a scatter style + + You can set all these configurations either by calling the respective functions on an instance: + \code + QCPScatterStyle myScatter; + myScatter.setShape(QCPScatterStyle::ssCircle); + myScatter.setPen(Qt::blue); + myScatter.setBrush(Qt::white); + myScatter.setSize(5); + customPlot->graph(0)->setScatterStyle(myScatter); + \endcode + + Or you can use one of the various constructors that take different parameter combinations, making + it easy to specify a scatter style in a single call, like so: + \code + customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5)); + \endcode + + \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable + + There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref + QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref + isPenDefined will return false. It leads to scatter points that inherit the pen from the + plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line + color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes + it very convenient to set up typical scatter settings: + + \code + customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus); + \endcode + + Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works + because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly + into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) + constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref + ScatterShape, where actually a QCPScatterStyle is expected. + + \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps + + QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. + + For custom shapes, you can provide a QPainterPath with the desired shape to the \ref + setCustomPath function or call the constructor that takes a painter path. The scatter shape will + automatically be set to \ref ssCustom. + + For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the + constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. + Note that \ref setSize does not influence the appearance of the pixmap. +*/ + +/* start documentation of inline functions */ + +/*! \fn bool QCPScatterStyle::isNone() const + + Returns whether the scatter shape is \ref ssNone. + + \see setShape +*/ + +/*! \fn bool QCPScatterStyle::isPenDefined() const + + Returns whether a pen has been defined for this scatter style. + + The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are + \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is + left undefined, the scatter color will be inherited from the plottable that uses this scatter + style. + + \see setPen +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. + + Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited + from the plottable that uses this scatter style. +*/ +QCPScatterStyle::QCPScatterStyle() : + mSize(6), + mShape(ssNone), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or + brush is defined. + + Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited + from the plottable that uses this scatter style. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : + mSize(size), + mShape(shape), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, + and size to \a size. No brush is defined, i.e. the scatter point will not be filled. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(Qt::NoBrush), + mPenDefined(true) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, + the brush color to \a fill (with a solid pattern), and size to \a size. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(QBrush(fill)), + mPenDefined(true) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the + brush to \a brush, and size to \a size. + + \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen + and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n + QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n + doesn't necessarily lead C++ to use this constructor in some cases, but might mistake + Qt::NoPen for a QColor and use the + \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) + constructor instead (which will lead to an unexpected look of the scatter points). To prevent + this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) + instead of just Qt::blue, to clearly point out to the compiler that this constructor is + wanted. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : + mSize(size), + mShape(shape), + mPen(pen), + mBrush(brush), + mPenDefined(pen.style() != Qt::NoPen) +{ +} + +/*! + Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape + is set to \ref ssPixmap. +*/ +QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : + mSize(5), + mShape(ssPixmap), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPixmap(pixmap), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The + scatter shape is set to \ref ssCustom. + + The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly + different meaning than for built-in scatter points: The custom path will be drawn scaled by a + factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its + natural size by default. To double the size of the path for example, set \a size to 12. +*/ +QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : + mSize(size), + mShape(ssCustom), + mPen(pen), + mBrush(brush), + mCustomPath(customPath), + mPenDefined(false) +{ +} + +/*! + Sets the size (pixel diameter) of the drawn scatter points to \a size. + + \see setShape +*/ +void QCPScatterStyle::setSize(double size) +{ + mSize = size; +} + +/*! + Sets the shape to \a shape. + + Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref + ssPixmap and \ref ssCustom, respectively. + + \see setSize +*/ +void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) +{ + mShape = shape; +} + +/*! + Sets the pen that will be used to draw scatter points to \a pen. + + If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after + a call to this function, even if \a pen is Qt::NoPen. + + \see setBrush +*/ +void QCPScatterStyle::setPen(const QPen &pen) +{ + mPenDefined = true; + mPen = pen; +} + +/*! + Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter + shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. + + \see setPen +*/ +void QCPScatterStyle::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the pixmap that will be drawn as scatter point to \a pixmap. + + Note that \ref setSize does not influence the appearance of the pixmap. + + The scatter shape is automatically set to \ref ssPixmap. +*/ +void QCPScatterStyle::setPixmap(const QPixmap &pixmap) +{ + setShape(ssPixmap); + mPixmap = pixmap; +} + +/*! + Sets the custom shape that will be drawn as scatter point to \a customPath. + + The scatter shape is automatically set to \ref ssCustom. +*/ +void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) +{ + setShape(ssCustom); + mCustomPath = customPath; +} + +/*! + Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an + undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. + + This function is used by plottables (or any class that wants to draw scatters) just before a + number of scatters with this style shall be drawn with the \a painter. + + \see drawShape +*/ +void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const +{ + painter->setPen(mPenDefined ? mPen : defaultPen); + painter->setBrush(mBrush); +} + +/*! + Draws the scatter shape with \a painter at position \a pos. + + This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be + called before scatter points are drawn with \ref drawShape. + + \see applyTo +*/ +void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const +{ + drawShape(painter, pos.x(), pos.y()); +} + +/*! \overload + Draws the scatter shape with \a painter at position \a x and \a y. +*/ +void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const +{ + double w = mSize/2.0; + switch (mShape) + { + case ssNone: break; + case ssDot: + { + painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); + break; + } + case ssCross: + { + painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); + painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); + break; + } + case ssPlus: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + break; + } + case ssCircle: + { + painter->drawEllipse(QPointF(x , y), w, w); + break; + } + case ssDisc: + { + QBrush b = painter->brush(); + painter->setBrush(painter->pen().color()); + painter->drawEllipse(QPointF(x , y), w, w); + painter->setBrush(b); + break; + } + case ssSquare: + { + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssDiamond: + { + painter->drawLine(QLineF(x-w, y, x, y-w)); + painter->drawLine(QLineF( x, y-w, x+w, y)); + painter->drawLine(QLineF(x+w, y, x, y+w)); + painter->drawLine(QLineF( x, y+w, x-w, y)); + break; + } + case ssStar: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); + painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); + break; + } + case ssTriangle: + { + painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); + painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); + painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); + break; + } + case ssTriangleInverted: + { + painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); + painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); + painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); + break; + } + case ssCrossSquare: + { + painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); + painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssPlusSquare: + { + painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssCrossCircle: + { + painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); + painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPlusCircle: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPeace: + { + painter->drawLine(QLineF(x, y-w, x, y+w)); + painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); + painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPixmap: + { + painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); + break; + } + case ssCustom: + { + QTransform oldTransform = painter->transform(); + painter->translate(x, y); + painter->scale(mSize/6.0, mSize/6.0); + painter->drawPath(mCustomPath); + painter->setTransform(oldTransform); + break; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayer +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayer + \brief A layer that may contain objects, to control the rendering order + + The Layering system of QCustomPlot is the mechanism to control the rendering order of the + elements inside the plot. + + It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of + one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, + QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers + bottom to top and successively draws the layerables of the layers. + + A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base + class from which almost all visible objects derive, like axes, grids, graphs, items, etc. + + Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in + that order). The top two layers "axes" and "legend" contain the default axes and legend, so they + will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as + the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. + are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid + instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background + shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the + "background" layer. Of course, the layer affiliation of the individual objects can be changed as + required (\ref QCPLayerable::setLayer). + + Controlling the ordering of objects is easy: Create a new layer in the position you want it to + be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with + QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will + be placed on the new layer automatically, due to the current layer setting. Alternatively you + could have also ignored the current layer setting and just moved the objects with + QCPLayerable::setLayer to the desired layer after creating them. + + It is also possible to move whole layers. For example, If you want the grid to be shown in front + of all plottables/items on the "main" layer, just move it above "main" with + QCustomPlot::moveLayer. + + The rendering order within one layer is simply by order of creation or insertion. The item + created last (or added last to the layer), is drawn on top of all other objects on that layer. + + When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below + the deleted layer, see QCustomPlot::removeLayer. +*/ + +/* start documentation of inline functions */ + +/*! \fn QList QCPLayer::children() const + + Returns a list of all layerables on this layer. The order corresponds to the rendering order: + layerables with higher indices are drawn above layerables with lower indices. +*/ + +/*! \fn int QCPLayer::index() const + + Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be + accessed via \ref QCustomPlot::layer. + + Layers with higher indices will be drawn above layers with lower indices. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPLayer instance. + + Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. + + \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. + This check is only performed by \ref QCustomPlot::addLayer. +*/ +QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : + QObject(parentPlot), + mParentPlot(parentPlot), + mName(layerName), + mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function + mVisible(true) +{ + // Note: no need to make sure layerName is unique, because layer + // management is done with QCustomPlot functions. +} + +QCPLayer::~QCPLayer() +{ + // If child layerables are still on this layer, detach them, so they don't try to reach back to this + // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted + // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to + // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) + + while (!mChildren.isEmpty()) + mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() + + if (mParentPlot->currentLayer() == this) + qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; +} + +/*! + Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this + layer will be invisible. + + This function doesn't change the visibility property of the layerables (\ref + QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the + visibility of the parent layer into account. +*/ +void QCPLayer::setVisible(bool visible) +{ + mVisible = visible; +} + +/*! \internal + + Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will + be prepended to the list, i.e. be drawn beneath the other layerables already in the list. + + This function does not change the \a mLayer member of \a layerable to this layer. (Use + QCPLayerable::setLayer to change the layer of an object, not this function.) + + \see removeChild +*/ +void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) +{ + if (!mChildren.contains(layerable)) + { + if (prepend) + mChildren.prepend(layerable); + else + mChildren.append(layerable); + } else + qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); +} + +/*! \internal + + Removes the \a layerable from the list of this layer. + + This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer + to change the layer of an object, not this function.) + + \see addChild +*/ +void QCPLayer::removeChild(QCPLayerable *layerable) +{ + if (!mChildren.removeOne(layerable)) + qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayerable +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayerable + \brief Base class for all drawable objects + + This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid + etc. + + Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking + the layers accordingly. + + For details about the layering mechanism, see the QCPLayer documentation. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const + + Returns the parent layerable of this layerable. The parent layerable is used to provide + visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables + only get drawn if their parent layerables are visible, too. + + Note that a parent layerable is not necessarily also the QObject parent for memory management. + Further, a layerable doesn't always have a parent layerable, so this function may return 0. + + A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be + set manually by the user. +*/ + +/* end documentation of inline functions */ +/* start documentation of pure virtual functions */ + +/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 + \internal + + This function applies the default antialiasing setting to the specified \a painter, using the + function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when + \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing + setting may be specified individually, this function should set the antialiasing state of the + most prominent entity. In this case however, the \ref draw function usually calls the specialized + versions of this function before drawing each entity, effectively overriding the setting of the + default antialiasing hint. + + First example: QCPGraph has multiple entities that have an antialiasing setting: The graph + line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, + QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't + only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's + antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and + QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw + calls the respective specialized applyAntialiasingHint function. + + Second example: QCPItemLine consists only of a line so there is only one antialiasing + setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by + all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the + respective layerable subclass.) Consequently it only has the normal + QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to + care about setting any antialiasing states, because the default antialiasing hint is already set + on the painter when the \ref draw function is called, and that's the state it wants to draw the + line with. +*/ + +/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 + \internal + + This function draws the layerable with the specified \a painter. It is only called by + QCustomPlot, if the layerable is visible (\ref setVisible). + + Before this function is called, the painter's antialiasing state is set via \ref + applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was + set to \ref clipRect. +*/ + +/* end documentation of pure virtual functions */ +/* start documentation of signals */ + +/*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); + + This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to + a different layer. + + \see setLayer +*/ + +/* end documentation of signals */ + +/*! + Creates a new QCPLayerable instance. + + Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the + derived classes. + + If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a + targetLayer is an empty string, it places itself on the current layer of the plot (see \ref + QCustomPlot::setCurrentLayer). + + It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later + time with \ref initializeParentPlot. + + The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents + are mainly used to control visibility in a hierarchy of layerables. This means a layerable is + only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does + not become the QObject-parent (for memory management) of this layerable, \a plot does. +*/ +QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : + QObject(plot), + mVisible(true), + mParentPlot(plot), + mParentLayerable(parentLayerable), + mLayer(0), + mAntialiased(true) +{ + if (mParentPlot) + { + if (targetLayer.isEmpty()) + setLayer(mParentPlot->currentLayer()); + else if (!setLayer(targetLayer)) + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; + } +} + +QCPLayerable::~QCPLayerable() +{ + if (mLayer) + { + mLayer->removeChild(this); + mLayer = 0; + } +} + +/*! + Sets the visibility of this layerable object. If an object is not visible, it will not be drawn + on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not + possible. +*/ +void QCPLayerable::setVisible(bool on) +{ + mVisible = on; +} + +/*! + Sets the \a layer of this layerable object. The object will be placed on top of the other objects + already on \a layer. + + Returns true on success, i.e. if \a layer is a valid layer. +*/ +bool QCPLayerable::setLayer(QCPLayer *layer) +{ + return moveToLayer(layer, false); +} + +/*! \overload + Sets the layer of this layerable object by name + + Returns true on success, i.e. if \a layerName is a valid layer name. +*/ +bool QCPLayerable::setLayer(const QString &layerName) +{ + if (!mParentPlot) + { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (QCPLayer *layer = mParentPlot->layer(layerName)) + { + return setLayer(layer); + } else + { + qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; + return false; + } +} + +/*! + Sets whether this object will be drawn antialiased or not. + + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPLayerable::setAntialiased(bool enabled) +{ + mAntialiased = enabled; +} + +/*! + Returns whether this layerable is visible, taking the visibility of the layerable parent and the + visibility of the layer this layerable is on into account. This is the method that is consulted + to decide whether a layerable shall be drawn or not. + + If this layerable has a direct layerable parent (usually set via hierarchies implemented in + subclasses, like in the case of QCPLayoutElement), this function returns true only if this + layerable has its visibility set to true and the parent layerable's \ref realVisibility returns + true. + + If this layerable doesn't have a direct layerable parent, returns the state of this layerable's + visibility. +*/ +bool QCPLayerable::realVisibility() const +{ + return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); +} + +/*! + This function is used to decide whether a click hits a layerable object or not. + + \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the + shortest pixel distance of this point to the object. If the object is either invisible or the + distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the + object is not selectable, -1.0 is returned, too. + + If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a + click inside the area returns a constant value greater zero (typically the selectionTolerance of + the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function + returns -1.0. + + Providing a constant value for area objects allows selecting line objects even when they are + obscured by such area objects, by clicking close to the lines (i.e. closer than + 0.99*selectionTolerance). + + The actual setting of the selection state is not done by this function. This is handled by the + parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified + via the selectEvent/deselectEvent methods. + + \a details is an optional output parameter. Every layerable subclass may place any information + in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot + decides on the basis of this selectTest call, that the object was successfully selected. The + subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part + objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked + is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be + placed in \a details. So in the subsequent \ref selectEvent, the decision which part was + selected doesn't have to be done a second time for a single selection operation. + + You may pass 0 as \a details to indicate that you are not interested in those selection details. + + \see selectEvent, deselectEvent, QCustomPlot::setInteractions +*/ +double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(pos) + Q_UNUSED(onlySelectable) + Q_UNUSED(details) + return -1.0; +} + +/*! \internal + + Sets the parent plot of this layerable. Use this function once to set the parent plot if you have + passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to + another one. + + Note that, unlike when passing a non-null parent plot in the constructor, this function does not + make \a parentPlot the QObject-parent of this layerable. If you want this, call + QObject::setParent(\a parentPlot) in addition to this function. + + Further, you will probably want to set a layer (\ref setLayer) after calling this function, to + make the layerable appear on the QCustomPlot. + + The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized + so they can react accordingly (e.g. also initialize the parent plot of child layerables, like + QCPLayout does). +*/ +void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) +{ + if (mParentPlot) + { + qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; + return; + } + + if (!parentPlot) + qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; + + mParentPlot = parentPlot; + parentPlotInitialized(mParentPlot); +} + +/*! \internal + + Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not + become the QObject-parent (for memory management) of this layerable. + + The parent layerable has influence on the return value of the \ref realVisibility method. Only + layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be + drawn. + + \see realVisibility +*/ +void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) +{ + mParentLayerable = parentLayerable; +} + +/*! \internal + + Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to + the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is + false, the object will be appended. + + Returns true on success, i.e. if \a layer is a valid layer. +*/ +bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) +{ + if (layer && !mParentPlot) + { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (layer && layer->parentPlot() != mParentPlot) + { + qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + return false; + } + + QCPLayer *oldLayer = mLayer; + if (mLayer) + mLayer->removeChild(this); + mLayer = layer; + if (mLayer) + mLayer->addChild(this, prepend); + if (mLayer != oldLayer) + emit layerChanged(mLayer); + return true; +} + +/*! \internal + + Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a + localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is + controlled via \a overrideElement. +*/ +void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const +{ + if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) + painter->setAntialiasing(false); + else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) + painter->setAntialiasing(true); + else + painter->setAntialiasing(localAntialiased); +} + +/*! \internal + + This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting + of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the + parent plot is set at a later time. + + For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any + QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level + element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To + propagate the parent plot to all the children of the hierarchy, the top level element then uses + this function to pass the parent plot on to its child elements. + + The default implementation does nothing. + + \see initializeParentPlot +*/ +void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) +{ + Q_UNUSED(parentPlot) +} + +/*! \internal + + Returns the selection category this layerable shall belong to. The selection category is used in + conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and + which aren't. + + Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref + QCP::iSelectOther. This is what the default implementation returns. + + \see QCustomPlot::setInteractions +*/ +QCP::Interaction QCPLayerable::selectionCategory() const +{ + return QCP::iSelectOther; +} + +/*! \internal + + Returns the clipping rectangle of this layerable object. By default, this is the viewport of the + parent QCustomPlot. Specific subclasses may reimplement this function to provide different + clipping rects. + + The returned clipping rect is set on the painter before the draw function of the respective + object is called. +*/ +QRect QCPLayerable::clipRect() const +{ + if (mParentPlot) + return mParentPlot->viewport(); + else + return QRect(); +} + +/*! \internal + + This event is called when the layerable shall be selected, as a consequence of a click by the + user. Subclasses should react to it by setting their selection state appropriately. The default + implementation does nothing. + + \a event is the mouse event that caused the selection. \a additive indicates, whether the user + was holding the multi-select-modifier while performing the selection (see \ref + QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled + (i.e. become selected when unselected and unselected when selected). + + Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. + returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). + The \a details data you output from \ref selectTest is fed back via \a details here. You may + use it to transport any kind of information from the selectTest to the possibly subsequent + selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable + that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need + to do the calculation again to find out which part was actually clicked. + + \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must + set the value either to true or false, depending on whether the selection state of this layerable + was actually changed. For layerables that only are selectable as a whole and not in parts, this + is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the + selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the + layerable was previously unselected and now is switched to the selected state. + + \see selectTest, deselectEvent +*/ +void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(additive) + Q_UNUSED(details) + Q_UNUSED(selectionStateChanged) +} + +/*! \internal + + This event is called when the layerable shall be deselected, either as consequence of a user + interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by + unsetting their selection appropriately. + + just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must + return true or false when the selection state of this layerable has changed or not changed, + respectively. + + \see selectTest, selectEvent +*/ +void QCPLayerable::deselectEvent(bool *selectionStateChanged) +{ + Q_UNUSED(selectionStateChanged) +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPRange +//////////////////////////////////////////////////////////////////////////////////////////////////// +/*! \class QCPRange + \brief Represents the range an axis is encompassing. + + contains a \a lower and \a upper double value and provides convenience input, output and + modification functions. + + \see QCPAxis::setRange +*/ + +/*! + Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller + intervals would cause errors due to the 11-bit exponent of double precision numbers, + corresponding to a minimum magnitude of roughly 1e-308. + \see validRange, maxRange +*/ +const double QCPRange::minRange = 1e-280; + +/*! + Maximum values (negative and positive) the range will accept in range-changing functions. + Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, + corresponding to a maximum magnitude of roughly 1e308. + Since the number of planck-volumes in the entire visible universe is only ~1e183, this should + be enough. + \see validRange, minRange +*/ +const double QCPRange::maxRange = 1e250; + +/*! + Constructs a range with \a lower and \a upper set to zero. +*/ +QCPRange::QCPRange() : + lower(0), + upper(0) +{ +} + +/*! \overload + Constructs a range with the specified \a lower and \a upper values. +*/ +QCPRange::QCPRange(double lower, double upper) : + lower(lower), + upper(upper) +{ + normalize(); +} + +/*! + Returns the size of the range, i.e. \a upper-\a lower +*/ +double QCPRange::size() const +{ + return upper-lower; +} + +/*! + Returns the center of the range, i.e. (\a upper+\a lower)*0.5 +*/ +double QCPRange::center() const +{ + return (upper+lower)*0.5; +} + +/*! + Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values + are swapped. +*/ +void QCPRange::normalize() +{ + if (lower > upper) + qSwap(lower, upper); +} + +/*! + Expands this range such that \a otherRange is contained in the new range. It is assumed that both + this range and \a otherRange are normalized (see \ref normalize). + + If \a otherRange is already inside the current range, this function does nothing. + + \see expanded +*/ +void QCPRange::expand(const QCPRange &otherRange) +{ + if (lower > otherRange.lower) + lower = otherRange.lower; + if (upper < otherRange.upper) + upper = otherRange.upper; +} + + +/*! + Returns an expanded range that contains this and \a otherRange. It is assumed that both this + range and \a otherRange are normalized (see \ref normalize). + + \see expand +*/ +QCPRange QCPRange::expanded(const QCPRange &otherRange) const +{ + QCPRange result = *this; + result.expand(otherRange); + return result; +} + +/*! + Returns a sanitized version of the range. Sanitized means for logarithmic scales, that + the range won't span the positive and negative sign domain, i.e. contain zero. Further + \a lower will always be numerically smaller (or equal) to \a upper. + + If the original range does span positive and negative sign domains or contains zero, + the returned range will try to approximate the original range as good as possible. + If the positive interval of the original range is wider than the negative interval, the + returned range will only contain the positive interval, with lower bound set to \a rangeFac or + \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval + is wider than the positive interval, this time by changing the \a upper bound. +*/ +QCPRange QCPRange::sanitizedForLogScale() const +{ + double rangeFac = 1e-3; + QCPRange sanitizedRange(lower, upper); + sanitizedRange.normalize(); + // can't have range spanning negative and positive values in log plot, so change range to fix it + //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) + if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) + { + // case lower is 0 + if (rangeFac < sanitizedRange.upper*rangeFac) + sanitizedRange.lower = rangeFac; + else + sanitizedRange.lower = sanitizedRange.upper*rangeFac; + } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) + else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) + { + // case upper is 0 + if (-rangeFac > sanitizedRange.lower*rangeFac) + sanitizedRange.upper = -rangeFac; + else + sanitizedRange.upper = sanitizedRange.lower*rangeFac; + } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) + { + // find out whether negative or positive interval is wider to decide which sign domain will be chosen + if (-sanitizedRange.lower > sanitizedRange.upper) + { + // negative is wider, do same as in case upper is 0 + if (-rangeFac > sanitizedRange.lower*rangeFac) + sanitizedRange.upper = -rangeFac; + else + sanitizedRange.upper = sanitizedRange.lower*rangeFac; + } else + { + // positive is wider, do same as in case lower is 0 + if (rangeFac < sanitizedRange.upper*rangeFac) + sanitizedRange.lower = rangeFac; + else + sanitizedRange.lower = sanitizedRange.upper*rangeFac; + } + } + // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; +} + +/*! + Checks, whether the specified range is within valid bounds, which are defined + as QCPRange::maxRange and QCPRange::minRange. + A valid range means: + \li range bounds within -maxRange and maxRange + \li range size above minRange + \li range size below maxRange +*/ +bool QCPRange::validRange(double lower, double upper) +{ + /* + return (lower > -maxRange && + upper < maxRange && + qAbs(lower-upper) > minRange && + (lower < -minRange || lower > minRange) && + (upper < -minRange || upper > minRange)); + */ + return (lower > -maxRange && + upper < maxRange && + qAbs(lower-upper) > minRange && + qAbs(lower-upper) < maxRange); +} + +/*! + \overload + Checks, whether the specified range is within valid bounds, which are defined + as QCPRange::maxRange and QCPRange::minRange. + A valid range means: + \li range bounds within -maxRange and maxRange + \li range size above minRange + \li range size below maxRange +*/ +bool QCPRange::validRange(const QCPRange &range) +{ + /* + return (range.lower > -maxRange && + range.upper < maxRange && + qAbs(range.lower-range.upper) > minRange && + qAbs(range.lower-range.upper) < maxRange && + (range.lower < -minRange || range.lower > minRange) && + (range.upper < -minRange || range.upper > minRange)); + */ + return (range.lower > -maxRange && + range.upper < maxRange && + qAbs(range.lower-range.upper) > minRange && + qAbs(range.lower-range.upper) < maxRange); +} + + +/*! \page thelayoutsystem The Layout System + + The layout system is responsible for positioning and scaling layout elements such as axis rects, + legends and plot titles in a QCustomPlot. + + \section layoutsystem-classesandmechanisms Classes and mechanisms + + The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that + take part in the layout system derive from this class, either directly or indirectly. + + Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own + content. However, it is perfectly possible for a layout element to only serve as a structuring + and/or positioning element, not drawing anything on its own. + + \subsection layoutsystem-rects Rects of a layout element + + A layout element is a rectangular object described by two rects: the inner rect (\ref + QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect + is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward + from the outer rect. The inner rect is meant for main content while the margin area may either be + left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions + the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels + and tick labels are in the margin area. + + \subsection layoutsystem-margins Margins + + Each layout element may provide a mechanism to automatically determine its margins. Internally, + this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref + QCP::MarginSide and returns an integer value which represents the ideal margin for the specified + side. The automatic margin will be used on the sides specified in \ref + QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic + margin calculation is enabled for all four sides. In this case, a minimum margin may be set with + \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting + margins smaller than desired for a specific situation. If automatic margin calculation is unset + for a specific side, the margin of that side can be controlled directy via \ref + QCPLayoutElement::setMargins. + + If multiple layout ements are arranged next to or beneath each other, it may be desirable to + align their inner rects on certain sides. Since they all might have different automatic margins, + this usually isn't the case. The class \ref QCPMarginGroup and \ref + QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the + documentation there for details. + + \subsection layoutsystem-layout Layouts + + As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in + princple can have the only purpose to manage/arrange those child elements. This is what the + subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual + representation. It defines an interface to add, remove and manage child layout elements. + QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive + from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset + which allows placing child elements freely inside its rect. + + Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way, + complex hierarchies may be created, offering very flexible arrangements. + + \image html LayoutsystemSketch.png + + Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. + It shows how two child layout elements are placed inside the grid layout next to each other in + cells (0, 0) and (0, 1). + + \subsection layoutsystem-plotlayout The top level plot layout + + Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref + QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout + elements in the QCustomPlot. By default, this top level grid layout contains a single cell which + holds the main axis rect. + + \subsection layoutsystem-examples Examples + + Adding a plot title is a typical and simple case to demonstrate basic workings of the layout system. + \code + // first we create and prepare a plot title layout element: + QCPPlotTitle *title = new QCPPlotTitle(customPlot); + title->setText("Plot Title Example"); + title->setFont(QFont("sans", 12, QFont::Bold)); + // then we add it to the main plot layout: + customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect + customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created + \endcode + \image html layoutsystem-addingplottitle.png + + Arranging multiple axis rects actually is the central purpose of the layout system. + \code + customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect + // add the first axis rect in second row (row index 1): + QCPAxisRect *topAxisRect = new QCPAxisRect(customPlot); + customPlot->plotLayout()->addElement(1, 0, topAxisRect); + // create a sub layout that we'll place in first row: + QCPLayoutGrid *subLayout = new QCPLayoutGrid; + customPlot->plotLayout()->addElement(0, 0, subLayout); + // add two axis rects in the sub layout next to each other: + QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot); + QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot); + subLayout->addElement(0, 0, leftAxisRect); + subLayout->addElement(0, 1, rightAxisRect); + subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width + subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40) + // since we've created the axis rects and axes from scratch, we need to place them on + // according layers, if we don't want the grid to be drawn above the axes etc. + // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes": + QList allAxes; + allAxes << topAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes(); + foreach (QCPAxis *axis, allAxes) + { + axis->setLayer("axes"); + axis->grid()->setLayer("grid"); + } + \endcode + \image html layoutsystem-multipleaxisrects.png + +*/ + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPMarginGroup +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPMarginGroup + \brief A margin group allows synchronization of margin sides if working with multiple layout elements. + + QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that + they will all have the same size, based on the largest required margin in the group. + + \n + \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" + \n + + In certain situations it is desirable that margins at specific sides are synchronized across + layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will + provide a cleaner look to the user if the left and right margins of the two axis rects are of the + same size. The left axis of the top axis rect will then be at the same horizontal position as the + left axis of the lower axis rect, making them appear aligned. The same applies for the right + axes. This is what QCPMarginGroup makes possible. + + To add/remove a specific side of a layout element to/from a margin group, use the \ref + QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call + \ref clear, or just delete the margin group. + + \section QCPMarginGroup-example Example + + First create a margin group: + \code + QCPMarginGroup *group = new QCPMarginGroup(customPlot); + \endcode + Then set this group on the layout element sides: + \code + customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group); + customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group); + \endcode + Here, we've used the first two axis rects of the plot and synchronized their left margins with + each other and their right margins with each other. +*/ + +/* start documentation of inline functions */ + +/*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const + + Returns a list of all layout elements that have their margin \a side associated with this margin + group. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPMarginGroup instance in \a parentPlot. +*/ +QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : + QObject(parentPlot), + mParentPlot(parentPlot) +{ + mChildren.insert(QCP::msLeft, QList()); + mChildren.insert(QCP::msRight, QList()); + mChildren.insert(QCP::msTop, QList()); + mChildren.insert(QCP::msBottom, QList()); +} + +QCPMarginGroup::~QCPMarginGroup() +{ + clear(); +} + +/*! + Returns whether this margin group is empty. If this function returns true, no layout elements use + this margin group to synchronize margin sides. +*/ +bool QCPMarginGroup::isEmpty() const +{ + QHashIterator > it(mChildren); + while (it.hasNext()) + { + it.next(); + if (!it.value().isEmpty()) + return false; + } + return true; +} + +/*! + Clears this margin group. The synchronization of the margin sides that use this margin group is + lifted and they will use their individual margin sizes again. +*/ +void QCPMarginGroup::clear() +{ + // make all children remove themselves from this margin group: + QHashIterator > it(mChildren); + while (it.hasNext()) + { + it.next(); + const QList elements = it.value(); + for (int i=elements.size()-1; i>=0; --i) + elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild + } +} + +/*! \internal + + Returns the synchronized common margin for \a side. This is the margin value that will be used by + the layout element on the respective side, if it is part of this margin group. + + The common margin is calculated by requesting the automatic margin (\ref + QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin + group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into + account, too.) +*/ +int QCPMarginGroup::commonMargin(QCP::MarginSide side) const +{ + // query all automatic margins of the layout elements in this margin group side and find maximum: + int result = 0; + const QList elements = mChildren.value(side); + for (int i=0; iautoMargins().testFlag(side)) + continue; + int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); + if (m > result) + result = m; + } + return result; +} + +/*! \internal + + Adds \a element to the internal list of child elements, for the margin \a side. + + This function does not modify the margin group property of \a element. +*/ +void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) +{ + if (!mChildren[side].contains(element)) + mChildren[side].append(element); + else + qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); +} + +/*! \internal + + Removes \a element from the internal list of child elements, for the margin \a side. + + This function does not modify the margin group property of \a element. +*/ +void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) +{ + if (!mChildren[side].removeOne(element)) + qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayoutElement +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayoutElement + \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". + + This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. + + A Layout element is a rectangular object which can be placed in layouts. It has an outer rect + (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference + between outer and inner rect is called its margin. The margin can either be set to automatic or + manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be + set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, + the layout element subclass will control the value itself (via \ref calculateAutoMargin). + + Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level + layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref + QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. + + Thus in QCustomPlot one can divide layout elements into two categories: The ones that are + invisible by themselves, because they don't draw anything. Their only purpose is to manage the + position and size of other layout elements. This category of layout elements usually use + QCPLayout as base class. Then there is the category of layout elements which actually draw + something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does + not necessarily mean that the latter category can't have child layout elements. QCPLegend for + instance, actually derives from QCPLayoutGrid and the individual legend items are child layout + elements in the grid layout. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayout *QCPLayoutElement::layout() const + + Returns the parent layout of this layout element. +*/ + +/*! \fn QRect QCPLayoutElement::rect() const + + Returns the inner rect of this layout element. The inner rect is the outer rect (\ref + setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). + + In some cases, the area between outer and inner rect is left blank. In other cases the margin + area is used to display peripheral graphics while the main content is in the inner rect. This is + where automatic margin calculation becomes interesting because it allows the layout element to + adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect + draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if + \ref setAutoMargins is enabled) according to the space required by the labels of the axes. +*/ + +/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) + + This event is called, if the mouse was pressed while being inside the outer rect of this layout + element. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) + + This event is called, if the mouse is moved inside the outer rect of this layout element. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) + + This event is called, if the mouse was previously pressed inside the outer rect of this layout + element and is now released. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) + + This event is called, if the mouse is double-clicked inside the outer rect of this layout + element. +*/ + +/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) + + This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this + layout element. +*/ + +/* end documentation of inline functions */ + +/*! + Creates an instance of QCPLayoutElement and sets default values. +*/ +QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : + QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) + mParentLayout(0), + mMinimumSize(), + mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), + mRect(0, 0, 0, 0), + mOuterRect(0, 0, 0, 0), + mMargins(0, 0, 0, 0), + mMinimumMargins(0, 0, 0, 0), + mAutoMargins(QCP::msAll) +{ +} + +QCPLayoutElement::~QCPLayoutElement() +{ + setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any + // unregister at layout: + if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor + mParentLayout->take(this); +} + +/*! + Sets the outer rect of this layout element. If the layout element is inside a layout, the layout + sets the position and size of this layout element using this function. + + Calling this function externally has no effect, since the layout will overwrite any changes to + the outer rect upon the next replot. + + The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. + + \see rect +*/ +void QCPLayoutElement::setOuterRect(const QRect &rect) +{ + if (mOuterRect != rect) + { + mOuterRect = rect; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } +} + +/*! + Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all + sides, this function is used to manually set the margin on those sides. Sides that are still set + to be handled automatically are ignored and may have any value in \a margins. + + The margin is the distance between the outer rect (controlled by the parent layout via \ref + setOuterRect) and the inner \ref rect (which usually contains the main content of this layout + element). + + \see setAutoMargins +*/ +void QCPLayoutElement::setMargins(const QMargins &margins) +{ + if (mMargins != margins) + { + mMargins = margins; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } +} + +/*! + If \ref setAutoMargins is enabled on some or all margins, this function is used to provide + minimum values for those margins. + + The minimum values are not enforced on margin sides that were set to be under manual control via + \ref setAutoMargins. + + \see setAutoMargins +*/ +void QCPLayoutElement::setMinimumMargins(const QMargins &margins) +{ + if (mMinimumMargins != margins) + { + mMinimumMargins = margins; + } +} + +/*! + Sets on which sides the margin shall be calculated automatically. If a side is calculated + automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is + set to be controlled manually, the value may be specified with \ref setMargins. + + Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref + setMarginGroup), to synchronize (align) it with other layout elements in the plot. + + \see setMinimumMargins, setMargins +*/ +void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) +{ + mAutoMargins = sides; +} + +/*! + Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to + respect the \a size here by changing row/column sizes in the layout accordingly. + + If the parent layout size is not sufficient to satisfy all minimum size constraints of its child + layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot + propagates the layout's size constraints to the outside by setting its own minimum QWidget size + accordingly, so violations of \a size should be exceptions. +*/ +void QCPLayoutElement::setMinimumSize(const QSize &size) +{ + if (mMinimumSize != size) + { + mMinimumSize = size; + if (mParentLayout) + mParentLayout->sizeConstraintsChanged(); + } +} + +/*! \overload + + Sets the minimum size for the inner \ref rect of this layout element. +*/ +void QCPLayoutElement::setMinimumSize(int width, int height) +{ + setMinimumSize(QSize(width, height)); +} + +/*! + Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to + respect the \a size here by changing row/column sizes in the layout accordingly. +*/ +void QCPLayoutElement::setMaximumSize(const QSize &size) +{ + if (mMaximumSize != size) + { + mMaximumSize = size; + if (mParentLayout) + mParentLayout->sizeConstraintsChanged(); + } +} + +/*! \overload + + Sets the maximum size for the inner \ref rect of this layout element. +*/ +void QCPLayoutElement::setMaximumSize(int width, int height) +{ + setMaximumSize(QSize(width, height)); +} + +/*! + Sets the margin \a group of the specified margin \a sides. + + Margin groups allow synchronizing specified margins across layout elements, see the documentation + of \ref QCPMarginGroup. + + To unset the margin group of \a sides, set \a group to 0. + + Note that margin groups only work for margin sides that are set to automatic (\ref + setAutoMargins). +*/ +void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) +{ + QVector sideVector; + if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); + if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); + if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); + if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); + + for (int i=0; iremoveChild(side, this); + + if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there + { + mMarginGroups.remove(side); + } else // setting to a new group + { + mMarginGroups[side] = group; + group->addChild(side, this); + } + } + } +} + +/*! + Updates the layout element and sub-elements. This function is automatically called before every + replot by the parent layout element. It is called multiple times, once for every \ref + UpdatePhase. The phases are run through in the order of the enum values. For details about what + happens at the different phases, see the documentation of \ref UpdatePhase. + + Layout elements that have child elements should call the \ref update method of their child + elements, and pass the current \a phase unchanged. + + The default implementation executes the automatic margin mechanism in the \ref upMargins phase. + Subclasses should make sure to call the base class implementation. +*/ +void QCPLayoutElement::update(UpdatePhase phase) +{ + if (phase == upMargins) + { + if (mAutoMargins != QCP::msNone) + { + // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + QMargins newMargins = mMargins; + foreach (QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom) + { + if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically + { + if (mMarginGroups.contains(side)) + QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group + else + QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly + // apply minimum margin restrictions: + if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) + QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + } + } + setMargins(newMargins); + } + } +} + +/*! + Returns the minimum size this layout element (the inner \ref rect) may be compressed to. + + if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this + function to determine the minimum allowed size of this layout element. (A manual minimum size is + considered set if it is non-zero.) +*/ +QSize QCPLayoutElement::minimumSizeHint() const +{ + return mMinimumSize; +} + +/*! + Returns the maximum size this layout element (the inner \ref rect) may be expanded to. + + if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this + function to determine the maximum allowed size of this layout element. (A manual maximum size is + considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) +*/ +QSize QCPLayoutElement::maximumSizeHint() const +{ + return mMaximumSize; +} + +/*! + Returns a list of all child elements in this layout element. If \a recursive is true, all + sub-child elements are included in the list, too. + + \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have + empty cells which yield 0 at the respective index.) +*/ +QList QCPLayoutElement::elements(bool recursive) const +{ + Q_UNUSED(recursive) + return QList(); +} + +/*! + Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer + rect, this method returns a value corresponding to 0.99 times the parent plot's selection + tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is + true, -1.0 is returned. + + See \ref QCPLayerable::selectTest for a general explanation of this virtual method. + + QCPLayoutElement subclasses may reimplement this method to provide more specific selection test + behaviour. +*/ +double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + + if (onlySelectable) + return -1; + + if (QRectF(mOuterRect).contains(pos)) + { + if (mParentPlot) + return mParentPlot->selectionTolerance()*0.99; + else + { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else + return -1; +} + +/*! \internal + + propagates the parent plot initialization to all child elements, by calling \ref + QCPLayerable::initializeParentPlot on them. +*/ +void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) +{ + foreach (QCPLayoutElement* el, elements(false)) + { + if (!el->parentPlot()) + el->initializeParentPlot(parentPlot); + } +} + +/*! \internal + + Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a + side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the + returned value will not be smaller than the specified minimum margin. + + The default implementation just returns the respective manual margin (\ref setMargins) or the + minimum margin, whichever is larger. +*/ +int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) +{ + return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayout +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayout + \brief The abstract base class for layouts + + This is an abstract base class for layout elements whose main purpose is to define the position + and size of other child layout elements. In most cases, layouts don't draw anything themselves + (but there are exceptions to this, e.g. QCPLegend). + + QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. + + QCPLayout introduces a common interface for accessing and manipulating the child elements. Those + functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref + simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions + to this interface which are more specialized to the form of the layout. For example, \ref + QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid + more conveniently. + + Since this is an abstract base class, you can't instantiate it directly. Rather use one of its + subclasses like QCPLayoutGrid or QCPLayoutInset. + + For a general introduction to the layout system, see the dedicated documentation page \ref + thelayoutsystem "The Layout System". +*/ + +/* start documentation of pure virtual functions */ + +/*! \fn virtual int QCPLayout::elementCount() const = 0 + + Returns the number of elements/cells in the layout. + + \see elements, elementAt +*/ + +/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 + + Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. + + Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. + QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check + whether a cell is empty or not. + + \see elements, elementCount, takeAt +*/ + +/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 + + Removes the element with the given \a index from the layout and returns it. + + If the \a index is invalid or the cell with that index is empty, returns 0. + + Note that some layouts don't remove the respective cell right away but leave an empty cell after + successful removal of the layout element. To collapse empty cells, use \ref simplify. + + \see elementAt, take +*/ + +/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 + + Removes the specified \a element from the layout and returns true on success. + + If the \a element isn't in this layout, returns false. + + Note that some layouts don't remove the respective cell right away but leave an empty cell after + successful removal of the layout element. To collapse empty cells, use \ref simplify. + + \see takeAt +*/ + +/* end documentation of pure virtual functions */ + +/*! + Creates an instance of QCPLayout and sets default values. Note that since QCPLayout + is an abstract base class, it can't be instantiated directly. +*/ +QCPLayout::QCPLayout() +{ +} + +/*! + First calls the QCPLayoutElement::update base class implementation to update the margins on this + layout. + + Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. + + Finally, \ref update is called on all child elements. +*/ +void QCPLayout::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + + // set child element rects according to layout: + if (phase == upLayout) + updateLayout(); + + // propagate update call to child elements: + const int elCount = elementCount(); + for (int i=0; iupdate(phase); + } +} + +/* inherits documentation from base class */ +QList QCPLayout::elements(bool recursive) const +{ + const int c = elementCount(); + QList result; +#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) + result.reserve(c); +#endif + for (int i=0; ielements(recursive); + } + } + return result; +} + +/*! + Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the + default implementation does nothing. + + Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit + simplification while QCPLayoutGrid does. +*/ +void QCPLayout::simplify() +{ +} + +/*! + Removes and deletes the element at the provided \a index. Returns true on success. If \a index is + invalid or points to an empty cell, returns false. + + This function internally uses \ref takeAt to remove the element from the layout and then deletes + the returned element. + + \see remove, takeAt +*/ +bool QCPLayout::removeAt(int index) +{ + if (QCPLayoutElement *el = takeAt(index)) + { + delete el; + return true; + } else + return false; +} + +/*! + Removes and deletes the provided \a element. Returns true on success. If \a element is not in the + layout, returns false. + + This function internally uses \ref takeAt to remove the element from the layout and then deletes + the element. + + \see removeAt, take +*/ +bool QCPLayout::remove(QCPLayoutElement *element) +{ + if (take(element)) + { + delete element; + return true; + } else + return false; +} + +/*! + Removes and deletes all layout elements in this layout. + + \see remove, removeAt +*/ +void QCPLayout::clear() +{ + for (int i=elementCount()-1; i>=0; --i) + { + if (elementAt(i)) + removeAt(i); + } + simplify(); +} + +/*! + Subclasses call this method to report changed (minimum/maximum) size constraints. + + If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref + sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of + QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, + it may update itself and resize cells accordingly. +*/ +void QCPLayout::sizeConstraintsChanged() const +{ + if (QWidget *w = qobject_cast(parent())) + w->updateGeometry(); + else if (QCPLayout *l = qobject_cast(parent())) + l->sizeConstraintsChanged(); +} + +/*! \internal + + Subclasses reimplement this method to update the position and sizes of the child elements/cells + via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. + + The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay + within that rect. + + \ref getSectionSizes may help with the reimplementation of this function. + + \see update +*/ +void QCPLayout::updateLayout() +{ +} + + +/*! \internal + + Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the + \ref QCPLayerable::parentLayerable and the QObject parent to this layout. + + Further, if \a el didn't previously have a parent plot, calls \ref + QCPLayerable::initializeParentPlot on \a el to set the paret plot. + + This method is used by subclass specific methods that add elements to the layout. Note that this + method only changes properties in \a el. The removal from the old layout and the insertion into + the new layout must be done additionally. +*/ +void QCPLayout::adoptElement(QCPLayoutElement *el) +{ + if (el) + { + el->mParentLayout = this; + el->setParentLayerable(this); + el->setParent(this); + if (!el->parentPlot()) + el->initializeParentPlot(mParentPlot); + } else + qDebug() << Q_FUNC_INFO << "Null element passed"; +} + +/*! \internal + + Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout + and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent + QCustomPlot. + + This method is used by subclass specific methods that remove elements from the layout (e.g. \ref + take or \ref takeAt). Note that this method only changes properties in \a el. The removal from + the old layout must be done additionally. +*/ +void QCPLayout::releaseElement(QCPLayoutElement *el) +{ + if (el) + { + el->mParentLayout = 0; + el->setParentLayerable(0); + el->setParent(mParentPlot); + // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot + } else + qDebug() << Q_FUNC_INFO << "Null element passed"; +} + +/*! \internal + + This is a helper function for the implementation of \ref updateLayout in subclasses. + + It calculates the sizes of one-dimensional sections with provided constraints on maximum section + sizes, minimum section sizes, relative stretch factors and the final total size of all sections. + + The QVector entries refer to the sections. Thus all QVectors must have the same size. + + \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size + imposed, set all vector values to Qt's QWIDGETSIZE_MAX. + + \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size + imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than + \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, + not exceeding the allowed total size is taken to be more important than not going below minimum + section sizes.) + + \a stretchFactors give the relative proportions of the sections to each other. If all sections + shall be scaled equally, set all values equal. If the first section shall be double the size of + each individual other section, set the first number of \a stretchFactors to double the value of + the other individual values (e.g. {2, 1, 1, 1}). + + \a totalSize is the value that the final section sizes will add up to. Due to rounding, the + actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, + you could distribute the remaining difference on the sections. + + The return value is a QVector containing the section sizes. +*/ +QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const +{ + if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) + { + qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; + return QVector(); + } + if (stretchFactors.isEmpty()) + return QVector(); + int sectionCount = stretchFactors.size(); + QVector sectionSizes(sectionCount); + // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): + int minSizeSum = 0; + for (int i=0; i minimumLockedSections; + QList unfinishedSections; + for (int i=0; i result(sectionCount); + for (int i=0; i= 0 && row < mElements.size()) + { + if (column >= 0 && column < mElements.first().size()) + { + if (QCPLayoutElement *result = mElements.at(row).at(column)) + return result; + else + qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; + } else + qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; + } else + qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; + return 0; +} + +/*! + Returns the number of rows in the layout. + + \see columnCount +*/ +int QCPLayoutGrid::rowCount() const +{ + return mElements.size(); +} + +/*! + Returns the number of columns in the layout. + + \see rowCount +*/ +int QCPLayoutGrid::columnCount() const +{ + if (mElements.size() > 0) + return mElements.first().size(); + else + return 0; +} + +/*! + Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it + is first removed from there. If \a row or \a column don't exist yet, the layout is expanded + accordingly. + + Returns true if the element was added successfully, i.e. if the cell at \a row and \a column + didn't already have an element. + + \see element, hasElement, take, remove +*/ +bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) +{ + if (element) + { + if (!hasElement(row, column)) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + expandTo(row+1, column+1); + mElements[row][column] = element; + adoptElement(element); + return true; + } else + qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; + } else + qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; + return false; +} + +/*! + Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't + empty. + + \see element +*/ +bool QCPLayoutGrid::hasElement(int row, int column) +{ + if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) + return mElements.at(row).at(column); + else + return false; +} + +/*! + Sets the stretch \a factor of \a column. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setColumnStretchFactors, setRowStretchFactor +*/ +void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) +{ + if (column >= 0 && column < columnCount()) + { + if (factor > 0) + mColumnStretchFactors[column] = factor; + else + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } else + qDebug() << Q_FUNC_INFO << "Invalid column:" << column; +} + +/*! + Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setColumnStretchFactor, setRowStretchFactors +*/ +void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) +{ + if (factors.size() == mColumnStretchFactors.size()) + { + mColumnStretchFactors = factors; + for (int i=0; i= 0 && row < rowCount()) + { + if (factor > 0) + mRowStretchFactors[row] = factor; + else + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } else + qDebug() << Q_FUNC_INFO << "Invalid row:" << row; +} + +/*! + Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setRowStretchFactor, setColumnStretchFactors +*/ +void QCPLayoutGrid::setRowStretchFactors(const QList &factors) +{ + if (factors.size() == mRowStretchFactors.size()) + { + mRowStretchFactors = factors; + for (int i=0; i()); + mRowStretchFactors.append(1); + } + // go through rows and expand columns as necessary: + int newColCount = qMax(columnCount(), newColumnCount); + for (int i=0; i rowCount()) + newIndex = rowCount(); + + mRowStretchFactors.insert(newIndex, 1); + QList newRow; + for (int col=0; col columnCount()) + newIndex = columnCount(); + + mColumnStretchFactors.insert(newIndex, 1); + for (int row=0; row minColWidths, minRowHeights, maxColWidths, maxRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + int totalRowSpacing = (rowCount()-1) * mRowSpacing; + int totalColSpacing = (columnCount()-1) * mColumnSpacing; + QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); + QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); + + // go through cells and set rects accordingly: + int yOffset = mRect.top(); + for (int row=0; row 0) + yOffset += rowHeights.at(row-1)+mRowSpacing; + int xOffset = mRect.left(); + for (int col=0; col 0) + xOffset += colWidths.at(col-1)+mColumnSpacing; + if (mElements.at(row).at(col)) + mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + } + } +} + +/* inherits documentation from base class */ +int QCPLayoutGrid::elementCount() const +{ + return rowCount()*columnCount(); +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const +{ + if (index >= 0 && index < elementCount()) + return mElements.at(index / columnCount()).at(index % columnCount()); + else + return 0; +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutGrid::takeAt(int index) +{ + if (QCPLayoutElement *el = elementAt(index)) + { + releaseElement(el); + mElements[index / columnCount()][index % columnCount()] = 0; + return el; + } else + { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } +} + +/* inherits documentation from base class */ +bool QCPLayoutGrid::take(QCPLayoutElement *element) +{ + if (element) + { + for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +{ + QList result; + int colC = columnCount(); + int rowC = rowCount(); +#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) + result.reserve(colC*rowC); +#endif + for (int row=0; rowelements(recursive); + } + } + return result; +} + +/*! + Simplifies the layout by collapsing rows and columns which only contain empty cells. +*/ +void QCPLayoutGrid::simplify() +{ + // remove rows with only empty cells: + for (int row=rowCount()-1; row>=0; --row) + { + bool hasElements = false; + for (int col=0; col=0; --col) + { + bool hasElements = false; + for (int row=0; row minColWidths, minRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + QSize result(0, 0); + for (int i=0; i maxColWidths, maxRowHeights; + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + QSize result(0, 0); + for (int i=0; i *minColWidths, QVector *minRowHeights) const +{ + *minColWidths = QVector(columnCount(), 0); + *minRowHeights = QVector(rowCount(), 0); + for (int row=0; rowminimumSizeHint(); + QSize min = mElements.at(row).at(col)->minimumSize(); + QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); + if (minColWidths->at(col) < final.width()) + (*minColWidths)[col] = final.width(); + if (minRowHeights->at(row) < final.height()) + (*minRowHeights)[row] = final.height(); + } + } + } +} + +/*! \internal + + Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights + respectively. + + The maximum height of a row is the smallest maximum height of any element in that row. The + maximum width of a column is the smallest maximum width of any element in that column. + + This is a helper function for \ref updateLayout. + + \see getMinimumRowColSizes +*/ +void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const +{ + *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); + *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); + for (int row=0; rowmaximumSizeHint(); + QSize max = mElements.at(row).at(col)->maximumSize(); + QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); + if (maxColWidths->at(col) > final.width()) + (*maxColWidths)[col] = final.width(); + if (maxRowHeights->at(row) > final.height()) + (*maxRowHeights)[row] = final.height(); + } + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayoutInset +//////////////////////////////////////////////////////////////////////////////////////////////////// +/*! \class QCPLayoutInset + \brief A layout that places child elements aligned to the border or arbitrarily positioned + + Elements are placed either aligned to the border or at arbitrary position in the area of the + layout. Which placement applies is controlled with the \ref InsetPlacement (\ref + setInsetPlacement). + + Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or + addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset + placement will default to \ref ipBorderAligned and the element will be aligned according to the + \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at + arbitrary position and size, defined by \a rect. + + The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. + + This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. +*/ + +/* start documentation of inline functions */ + +/*! \fn virtual void QCPLayoutInset::simplify() + + The QCPInsetLayout does not need simplification since it can never have empty cells due to its + linear index structure. This method does nothing. +*/ + +/* end documentation of inline functions */ + +/*! + Creates an instance of QCPLayoutInset and sets default values. +*/ +QCPLayoutInset::QCPLayoutInset() +{ +} + +QCPLayoutInset::~QCPLayoutInset() +{ + // clear all child layout elements. This is important because only the specific layouts know how + // to handle removing elements (clear calls virtual removeAt method to do that). + clear(); +} + +/*! + Returns the placement type of the element with the specified \a index. +*/ +QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const +{ + if (elementAt(index)) + return mInsetPlacement.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return ipFree; + } +} + +/*! + Returns the alignment of the element with the specified \a index. The alignment only has a + meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. +*/ +Qt::Alignment QCPLayoutInset::insetAlignment(int index) const +{ + if (elementAt(index)) + return mInsetAlignment.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return 0; + } +} + +/*! + Returns the rect of the element with the specified \a index. The rect only has a + meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. +*/ +QRectF QCPLayoutInset::insetRect(int index) const +{ + if (elementAt(index)) + return mInsetRect.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return QRectF(); + } +} + +/*! + Sets the inset placement type of the element with the specified \a index to \a placement. + + \see InsetPlacement +*/ +void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) +{ + if (elementAt(index)) + mInsetPlacement[index] = placement; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/*! + If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function + is used to set the alignment of the element with the specified \a index to \a alignment. + + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, + Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other + alignment flags will be ignored. +*/ +void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) +{ + if (elementAt(index)) + mInsetAlignment[index] = alignment; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/*! + If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the + position and size of the element with the specified \a index to \a rect. + + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) + will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right + corner of the layout, with 35% width and height of the parent layout. + + Note that the minimum and maximum sizes of the embedded element (\ref + QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. +*/ +void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) +{ + if (elementAt(index)) + mInsetRect[index] = rect; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/* inherits documentation from base class */ +void QCPLayoutInset::updateLayout() +{ + for (int i=0; iminimumSizeHint(); + QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); + finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); + finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); + finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); + finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); + if (mInsetPlacement.at(i) == ipFree) + { + insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), + rect().y()+rect().height()*mInsetRect.at(i).y(), + rect().width()*mInsetRect.at(i).width(), + rect().height()*mInsetRect.at(i).height()); + if (insetRect.size().width() < finalMinSize.width()) + insetRect.setWidth(finalMinSize.width()); + if (insetRect.size().height() < finalMinSize.height()) + insetRect.setHeight(finalMinSize.height()); + if (insetRect.size().width() > finalMaxSize.width()) + insetRect.setWidth(finalMaxSize.width()); + if (insetRect.size().height() > finalMaxSize.height()) + insetRect.setHeight(finalMaxSize.height()); + } else if (mInsetPlacement.at(i) == ipBorderAligned) + { + insetRect.setSize(finalMinSize); + Qt::Alignment al = mInsetAlignment.at(i); + if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); + else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); + else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter + if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); + else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); + else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter + } + mElements.at(i)->setOuterRect(insetRect); + } +} + +/* inherits documentation from base class */ +int QCPLayoutInset::elementCount() const +{ + return mElements.size(); +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutInset::elementAt(int index) const +{ + if (index >= 0 && index < mElements.size()) + return mElements.at(index); + else + return 0; +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutInset::takeAt(int index) +{ + if (QCPLayoutElement *el = elementAt(index)) + { + releaseElement(el); + mElements.removeAt(index); + mInsetPlacement.removeAt(index); + mInsetAlignment.removeAt(index); + mInsetRect.removeAt(index); + return el; + } else + { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } +} + +/* inherits documentation from base class */ +bool QCPLayoutInset::take(QCPLayoutElement *element) +{ + if (element) + { + for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/*! + Adds the specified \a element to the layout as an inset aligned at the border (\ref + setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a + alignment. + + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, + Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other + alignment flags will be ignored. + + \see addElement(QCPLayoutElement *element, const QRectF &rect) +*/ +void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) +{ + if (element) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + mElements.append(element); + mInsetPlacement.append(ipBorderAligned); + mInsetAlignment.append(alignment); + mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); + adoptElement(element); + } else + qDebug() << Q_FUNC_INFO << "Can't add null element"; +} + +/*! + Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref + setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a + rect. + + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) + will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right + corner of the layout, with 35% width and height of the parent layout. + + \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) +*/ +void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) +{ + if (element) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + mElements.append(element); + mInsetPlacement.append(ipFree); + mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); + mInsetRect.append(rect); + adoptElement(element); + } else + qDebug() << Q_FUNC_INFO << "Can't add null element"; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLineEnding +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLineEnding + \brief Handles the different ending decorations for line-like items + + \image html QCPLineEnding.png "The various ending styles currently supported" + + For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine + has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. + + The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can + be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of + the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. + For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite + directions, e.g. "outward". This can be changed by \ref setInverted, which would make the + respective arrow point inward. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a + QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code + myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode +*/ + +/*! + Creates a QCPLineEnding instance with default values (style \ref esNone). +*/ +QCPLineEnding::QCPLineEnding() : + mStyle(esNone), + mWidth(8), + mLength(10), + mInverted(false) +{ +} + +/*! + Creates a QCPLineEnding instance with the specified values. +*/ +QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : + mStyle(style), + mWidth(width), + mLength(length), + mInverted(inverted) +{ +} + +/*! + Sets the style of the ending decoration. +*/ +void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) +{ + mStyle = style; +} + +/*! + Sets the width of the ending decoration, if the style supports it. On arrows, for example, the + width defines the size perpendicular to the arrow's pointing direction. + + \see setLength +*/ +void QCPLineEnding::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets the length of the ending decoration, if the style supports it. On arrows, for example, the + length defines the size in pointing direction. + + \see setWidth +*/ +void QCPLineEnding::setLength(double length) +{ + mLength = length; +} + +/*! + Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point + inward when \a inverted is set to true. + + Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or + discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are + affected by it, which can be used to control to which side the half bar points to. +*/ +void QCPLineEnding::setInverted(bool inverted) +{ + mInverted = inverted; +} + +/*! \internal + + Returns the maximum pixel radius the ending decoration might cover, starting from the position + the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). + + This is relevant for clipping. Only omit painting of the decoration when the position where the + decoration is supposed to be drawn is farther away from the clipping rect than the returned + distance. +*/ +double QCPLineEnding::boundingDistance() const +{ + switch (mStyle) + { + case esNone: + return 0; + + case esFlatArrow: + case esSpikeArrow: + case esLineArrow: + case esSkewedBar: + return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length + + case esDisc: + case esSquare: + case esDiamond: + case esBar: + case esHalfBar: + return mWidth*1.42; // items that only have a width -> width*sqrt(2) + + } + return 0; +} + +/*! + Starting from the origin of this line ending (which is style specific), returns the length + covered by the line ending symbol, in backward direction. + + For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if + both have the same \ref setLength value, because the spike arrow has an inward curved back, which + reduces the length along its center axis (the drawing origin for arrows is at the tip). + + This function is used for precise, style specific placement of line endings, for example in + QCPAxes. +*/ +double QCPLineEnding::realLength() const +{ + switch (mStyle) + { + case esNone: + case esLineArrow: + case esSkewedBar: + case esBar: + case esHalfBar: + return 0; + + case esFlatArrow: + return mLength; + + case esDisc: + case esSquare: + case esDiamond: + return mWidth*0.5; + + case esSpikeArrow: + return mLength*0.8; + } + return 0; +} + +/*! \internal + + Draws the line ending with the specified \a painter at the position \a pos. The direction of the + line ending is controlled with \a dir. +*/ +void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const +{ + if (mStyle == esNone) + return; + + QVector2D lengthVec(dir.normalized()); + if (lengthVec.isNull()) + lengthVec = QVector2D(1, 0); + QVector2D widthVec(-lengthVec.y(), lengthVec.x()); + lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); + widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); + + QPen penBackup = painter->pen(); + QBrush brushBackup = painter->brush(); + QPen miterPen = penBackup; + miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey + QBrush brush(painter->pen().color(), Qt::SolidPattern); + switch (mStyle) + { + case esNone: break; + case esFlatArrow: + { + QPointF points[3] = {pos.toPointF(), + (pos-lengthVec+widthVec).toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 3); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esSpikeArrow: + { + QPointF points[4] = {pos.toPointF(), + (pos-lengthVec+widthVec).toPointF(), + (pos-lengthVec*0.8f).toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esLineArrow: + { + QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), + pos.toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->drawPolyline(points, 3); + painter->setPen(penBackup); + break; + } + case esDisc: + { + painter->setBrush(brush); + painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); + painter->setBrush(brushBackup); + break; + } + case esSquare: + { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), + (pos-widthVecPerp-widthVec).toPointF(), + (pos+widthVecPerp-widthVec).toPointF(), + (pos+widthVecPerp+widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esDiamond: + { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos-widthVecPerp).toPointF(), + (pos-widthVec).toPointF(), + (pos+widthVecPerp).toPointF(), + (pos+widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esBar: + { + painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); + break; + } + case esHalfBar: + { + painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); + break; + } + case esSkewedBar: + { + if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) + { + // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line + painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), + (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); + } else + { + // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly + painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), + (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); + } + break; + } + } +} + +/*! \internal + \overload + + Draws the line ending. The direction is controlled with the \a angle parameter in radians. +*/ +void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const +{ + draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPGrid +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPGrid + \brief Responsible for drawing the grid of a QCPAxis. + + This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the + grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref + QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. + + The axis and grid drawing was split into two classes to allow them to be placed on different + layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid + in the background and the axes in the foreground, and any plottables/items in between. This + described situation is the default setup, see the QCPLayer documentation. +*/ + +/*! + Creates a QCPGrid instance and sets default values. + + You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. +*/ +QCPGrid::QCPGrid(QCPAxis *parentAxis) : + QCPLayerable(parentAxis->parentPlot(), "", parentAxis), + mParentAxis(parentAxis) +{ + // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); + setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); + setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); + setSubGridVisible(false); + setAntialiased(false); + setAntialiasedSubGrid(false); + setAntialiasedZeroLine(false); +} + +/*! + Sets whether grid lines at sub tick marks are drawn. + + \see setSubGridPen +*/ +void QCPGrid::setSubGridVisible(bool visible) +{ + mSubGridVisible = visible; +} + +/*! + Sets whether sub grid lines are drawn antialiased. +*/ +void QCPGrid::setAntialiasedSubGrid(bool enabled) +{ + mAntialiasedSubGrid = enabled; +} + +/*! + Sets whether zero lines are drawn antialiased. +*/ +void QCPGrid::setAntialiasedZeroLine(bool enabled) +{ + mAntialiasedZeroLine = enabled; +} + +/*! + Sets the pen with which (major) grid lines are drawn. +*/ +void QCPGrid::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen with which sub grid lines are drawn. +*/ +void QCPGrid::setSubGridPen(const QPen &pen) +{ + mSubGridPen = pen; +} + +/*! + Sets the pen with which zero lines are drawn. + + Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid + lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. +*/ +void QCPGrid::setZeroLinePen(const QPen &pen) +{ + mZeroLinePen = pen; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing the major grid lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); +} + +/*! \internal + + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning + over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). +*/ +void QCPGrid::draw(QCPPainter *painter) +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + if (mSubGridVisible) + drawSubGridLines(painter); + drawGridLines(painter); +} + +/*! \internal + + Draws the main grid lines and possibly a zero line with the specified painter. + + This is a helper function called by \ref draw. +*/ +void QCPGrid::drawGridLines(QCPPainter *painter) const +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + int lowTick = mParentAxis->mLowestVisibleTick; + int highTick = mParentAxis->mHighestVisibleTick; + double t; // helper variable, result of coordinate-to-pixel transforms + if (mParentAxis->orientation() == Qt::Horizontal) + { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) + { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero + for (int i=lowTick; i <= highTick; ++i) + { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) + { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i=lowTick; i <= highTick; ++i) + { + if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else + { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) + { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero + for (int i=lowTick; i <= highTick; ++i) + { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) + { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i=lowTick; i <= highTick; ++i) + { + if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } + } +} + +/*! \internal + + Draws the sub grid lines with the specified painter. + + This is a helper function called by \ref draw. +*/ +void QCPGrid::drawSubGridLines(QCPPainter *painter) const +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); + double t; // helper variable, result of coordinate-to-pixel transforms + painter->setPen(mSubGridPen); + if (mParentAxis->orientation() == Qt::Horizontal) + { + for (int i=0; imSubTickVector.size(); ++i) + { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else + { + for (int i=0; imSubTickVector.size(); ++i) + { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxis +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxis + \brief Manages a single axis inside a QCustomPlot. + + Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via + QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and + QCustomPlot::yAxis2 (right). + + Axes are always part of an axis rect, see QCPAxisRect. + \image html AxisNamesOverview.png +
                  Naming convention of axis parts
                  + \n + + \image html AxisRectSpacingOverview.png +
                  Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line + on the left represents the QCustomPlot widget border.
                  + +*/ + +/* start of documentation of inline functions */ + +/*! \fn Qt::Orientation QCPAxis::orientation() const + + Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced + from the axis type (left, top, right or bottom). + + \see orientation(AxisType type) +*/ + +/*! \fn QCPGrid *QCPAxis::grid() const + + Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the + grid is displayed. +*/ + +/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) + + Returns the orientation of the specified axis type + + \see orientation() +*/ + +/* end of documentation of inline functions */ +/* start of documentation of signals */ + +/*! \fn void QCPAxis::ticksRequest() + + This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick + labels for a replot. + + Modifying the tick positions can be done with \ref setTickVector. If you also want to control the + tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref + setTickVectorLabels. + + If you only want static ticks you probably don't need this signal, since you can just set the + tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and + maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this + signal and set the vector/vectors there. +*/ + +/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) + + This signal is emitted when the range of this axis has changed. You can connect it to the \ref + setRange slot of another axis to communicate the new range to the other axis, in order for it to + be synchronized. +*/ + +/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) + \overload + + Additionally to the new range, this signal also provides the previous range held by the axis as + \a oldRange. +*/ + +/*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the scale type changes, by calls to \ref setScaleType +*/ + +/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) + + This signal is emitted when the selection state of this axis has changed, either by user interaction + or by a direct call to \ref setSelectedParts. +*/ + +/*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); + + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts +*/ + +/* end of documentation of signals */ + +/*! + Constructs an Axis instance of Type \a type for the axis rect \a parent. + You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis. +*/ +QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : + QCPLayerable(parent->parentPlot(), "", parent), + // axis base: + mAxisType(type), + mAxisRect(parent), + mPadding(5), + mOrientation(orientation(type)), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabel(""), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + mTickLabels(true), + mAutoTickLabels(true), + mTickLabelType(ltNumber), + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mDateTimeFormat("hh:mm:ss\ndd.MM.yy"), + mDateTimeSpec(Qt::LocalTime), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + // ticks and subticks: + mTicks(true), + mTickStep(1), + mSubTickCount(4), + mAutoTickCount(6), + mAutoTicks(true), + mAutoTickStep(true), + mAutoSubTicks(true), + mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedTickPen(QPen(Qt::blue, 2)), + mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 5), + mRangeReversed(false), + mScaleType(stLinear), + mScaleLogBase(10), + mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), + // internal members: + mGrid(new QCPGrid(this)), + mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), + mLowestVisibleTick(0), + mHighestVisibleTick(-1), + mCachedMarginValid(false), + mCachedMargin(0) +{ + mGrid->setVisible(false); + setAntialiased(false); + setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again + + if (type == atTop) + { + setTickLabelPadding(3); + setLabelPadding(6); + } else if (type == atRight) + { + setTickLabelPadding(7); + setLabelPadding(12); + } else if (type == atBottom) + { + setTickLabelPadding(3); + setLabelPadding(3); + } else if (type == atLeft) + { + setTickLabelPadding(5); + setLabelPadding(10); + } +} + +QCPAxis::~QCPAxis() +{ + delete mAxisPainter; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLabelPadding() const +{ + return mAxisPainter->tickLabelPadding; +} + +/* No documentation as it is a property getter */ +double QCPAxis::tickLabelRotation() const +{ + return mAxisPainter->tickLabelRotation; +} + +/* No documentation as it is a property getter */ +QString QCPAxis::numberFormat() const +{ + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) + { + result.append("b"); + if (mAxisPainter->numberMultiplyCross) + result.append("c"); + } + return result; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLengthIn() const +{ + return mAxisPainter->tickLengthIn; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLengthOut() const +{ + return mAxisPainter->tickLengthOut; +} + +/* No documentation as it is a property getter */ +int QCPAxis::subTickLengthIn() const +{ + return mAxisPainter->subTickLengthIn; +} + +/* No documentation as it is a property getter */ +int QCPAxis::subTickLengthOut() const +{ + return mAxisPainter->subTickLengthOut; +} + +/* No documentation as it is a property getter */ +int QCPAxis::labelPadding() const +{ + return mAxisPainter->labelPadding; +} + +/* No documentation as it is a property getter */ +int QCPAxis::offset() const +{ + return mAxisPainter->offset; +} + +/* No documentation as it is a property getter */ +QCPLineEnding QCPAxis::lowerEnding() const +{ + return mAxisPainter->lowerEnding; +} + +/* No documentation as it is a property getter */ +QCPLineEnding QCPAxis::upperEnding() const +{ + return mAxisPainter->upperEnding; +} + +/*! + Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref + stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis + scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step + (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major + ticks, consider choosing a logarithm base of 100, 1000 or even higher. + + If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option + (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 + [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" + part). To only display the decimal power, set the number precision to zero with + \ref setNumberPrecision. +*/ +void QCPAxis::setScaleType(QCPAxis::ScaleType type) +{ + if (mScaleType != type) + { + mScaleType = type; + if (mScaleType == stLogarithmic) + setRange(mRange.sanitizedForLogScale()); + mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } +} + +/*! + If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the + scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. + + Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but + less major ticks, consider choosing \a base 100, 1000 or even higher. +*/ +void QCPAxis::setScaleLogBase(double base) +{ + if (base > 1) + { + mScaleLogBase = base; + mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation + mCachedMarginValid = false; + } else + qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; +} + +/*! + Sets the range of the axis. + + This slot may be connected with the \ref rangeChanged signal of another axis so this axis + is always synchronized with the other axis range, when it changes. + + To invert the direction of an axis, use \ref setRangeReversed. +*/ +void QCPAxis::setRange(const QCPRange &range) +{ + if (range.lower == mRange.lower && range.upper == mRange.upper) + return; + + if (!QCPRange::validRange(range)) return; + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) + { + mRange = range.sanitizedForLogScale(); + } else + { + mRange = range.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains iSelectAxes.) + + However, even when \a selectable is set to a value not allowing the selection of a specific part, + it is still possible to set the selection of this part manually, by calling \ref setSelectedParts + directly. + + \see SelectablePart, setSelectedParts +*/ +void QCPAxis::setSelectableParts(const SelectableParts &selectable) +{ + if (mSelectableParts != selectable) + { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } +} + +/*! + Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part + is selected, it uses a different pen/font. + + The entire selection mechanism for axes is handled automatically when \ref + QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you + wish to change the selection state manually. + + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, + setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor +*/ +void QCPAxis::setSelectedParts(const SelectableParts &selected) +{ + if (mSelectedParts != selected) + { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } +} + +/*! + \overload + + Sets the lower and upper bound of the axis range. + + To invert the direction of an axis, use \ref setRangeReversed. + + There is also a slot to set a range, see \ref setRange(const QCPRange &range). +*/ +void QCPAxis::setRange(double lower, double upper) +{ + if (lower == mRange.lower && upper == mRange.upper) + return; + + if (!QCPRange::validRange(lower, upper)) return; + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + \overload + + Sets the range of the axis. + + The \a position coordinate indicates together with the \a alignment parameter, where the new + range will be positioned. \a size defines the size of the new axis range. \a alignment may be + Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, + or center of the range to be aligned with \a position. Any other values of \a alignment will + default to Qt::AlignCenter. +*/ +void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) +{ + if (alignment == Qt::AlignLeft) + setRange(position, position+size); + else if (alignment == Qt::AlignRight) + setRange(position-size, position); + else // alignment == Qt::AlignCenter + setRange(position-size/2.0, position+size/2.0); +} + +/*! + Sets the lower bound of the axis range. The upper bound is not changed. + \see setRange +*/ +void QCPAxis::setRangeLower(double lower) +{ + if (mRange.lower == lower) + return; + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets the upper bound of the axis range. The lower bound is not changed. + \see setRange +*/ +void QCPAxis::setRangeUpper(double upper) +{ + if (mRange.upper == upper) + return; + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal + axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the + direction of increasing values is inverted. + + Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part + of the \ref setRange interface will still reference the mathematically smaller number than the \a + upper part. +*/ +void QCPAxis::setRangeReversed(bool reversed) +{ + if (mRangeReversed != reversed) + { + mRangeReversed = reversed; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick positions should be calculated automatically (either from an automatically + generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). + + If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. + For these manual ticks you may let QCPAxis generate the appropriate labels automatically by + leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels + manually, set \ref setAutoTickLabels to false and provide the label strings with \ref + setTickVectorLabels. + + If you need dynamically calculated tick vectors (and possibly tick label vectors), set the + vectors in a slot connected to the \ref ticksRequest signal. + + \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep +*/ +void QCPAxis::setAutoTicks(bool on) +{ + if (mAutoTicks != on) + { + mAutoTicks = on; + mCachedMarginValid = false; + } +} + +/*! + When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be + generated in the visible range, approximately. + + It's not guaranteed that this number of ticks is met exactly, but approximately within a + tolerance of about two. + + Only values greater than zero are accepted as \a approximateCount. + + \see setAutoTickStep, setAutoTicks, setAutoSubTicks +*/ +void QCPAxis::setAutoTickCount(int approximateCount) +{ + if (mAutoTickCount != approximateCount) + { + if (approximateCount > 0) + { + mAutoTickCount = approximateCount; + mCachedMarginValid = false; + } else + qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; + } +} + +/*! + Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref + ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point + number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. + + If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This + is usually used in a combination with \ref setAutoTicks set to false for complete control over + tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" + etc. as tick labels. + + If you need dynamically calculated tick vectors (and possibly tick label vectors), set the + vectors in a slot connected to the \ref ticksRequest signal. + + \see setAutoTicks +*/ +void QCPAxis::setAutoTickLabels(bool on) +{ + if (mAutoTickLabels != on) + { + mAutoTickLabels = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated + automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human + readable plots. + + The number of ticks the algorithm aims for within the visible range can be specified with \ref + setAutoTickCount. + + If \a on is set to false, you may set the tick step manually with \ref setTickStep. + + \see setAutoTicks, setAutoSubTicks, setAutoTickCount +*/ +void QCPAxis::setAutoTickStep(bool on) +{ + if (mAutoTickStep != on) + { + mAutoTickStep = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the number of sub ticks in one tick interval is determined automatically. This + works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is + enabled, this is always the case. + + When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. + + \see setAutoTickCount, setAutoTicks, setAutoTickStep +*/ +void QCPAxis::setAutoSubTicks(bool on) +{ + if (mAutoSubTicks != on) + { + mAutoSubTicks = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether tick marks are displayed. + + Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve + that, see \ref setTickLabels. +*/ +void QCPAxis::setTicks(bool show) +{ + if (mTicks != show) + { + mTicks = show; + mCachedMarginValid = false; + } +} + +/*! + Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. +*/ +void QCPAxis::setTickLabels(bool show) +{ + if (mTickLabels != show) + { + mTickLabels = show; + mCachedMarginValid = false; + } +} + +/*! + Sets the distance between the axis base line (including any outward ticks) and the tick labels. + \see setLabelPadding, setPadding +*/ +void QCPAxis::setTickLabelPadding(int padding) +{ + if (mAxisPainter->tickLabelPadding != padding) + { + mAxisPainter->tickLabelPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick labels display numbers or dates/times. + + If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. + + If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. + + In QCustomPlot, date/time coordinates are double numbers representing the seconds since + 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the + QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also + the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in + milliseconds. Divide its return value by 1000.0 to get a value with the format needed for + date/time plotting, with a resolution of one millisecond. + + Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. + (represented by a negative number), unlike the toTime_t function, which works with unsigned + integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of + toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. + + \see setTickLabels +*/ +void QCPAxis::setTickLabelType(LabelType type) +{ + if (mTickLabelType != type) + { + mTickLabelType = type; + mCachedMarginValid = false; + } +} + +/*! + Sets the font of the tick labels. + + \see setTickLabels, setTickLabelColor +*/ +void QCPAxis::setTickLabelFont(const QFont &font) +{ + if (font != mTickLabelFont) + { + mTickLabelFont = font; + mCachedMarginValid = false; + } +} + +/*! + Sets the color of the tick labels. + + \see setTickLabels, setTickLabelFont +*/ +void QCPAxis::setTickLabelColor(const QColor &color) +{ + if (color != mTickLabelColor) + { + mTickLabelColor = color; + mCachedMarginValid = false; + } +} + +/*! + Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, + the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values + from -90 to 90 degrees. + + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For + other angles, the label is drawn with an offset such that it seems to point toward or away from + the tick mark. +*/ +void QCPAxis::setTickLabelRotation(double degrees) +{ + if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) + { + mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mCachedMarginValid = false; + } +} + +/*! + Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. + for details about the \a format string, see the documentation of QDateTime::toString(). + + Newlines can be inserted with "\n". + + \see setDateTimeSpec +*/ +void QCPAxis::setDateTimeFormat(const QString &format) +{ + if (mDateTimeFormat != format) + { + mDateTimeFormat = format; + mCachedMarginValid = false; + } +} + +/*! + Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref + ltDateTime. + + The default value of QDateTime objects (and also QCustomPlot) is Qt::LocalTime. However, + if the date time values passed to QCustomPlot are given in the UTC spec, set \a + timeSpec to Qt::UTC to get the correct axis labels. + + \see setDateTimeFormat +*/ +void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) +{ + mDateTimeSpec = timeSpec; +} + +/*! + Sets the number format for the numbers drawn as tick labels (if tick label type is \ref + ltNumber). This \a formatCode is an extended version of the format code used e.g. by + QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" + section in the detailed description of the QString class. \a formatCode is a string of one, two + or three characters. The first character is identical to the normal format code used by Qt. In + short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, + whichever is shorter. + + The second and third characters are optional and specific to QCustomPlot:\n + If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. + "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for + "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 + [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. + If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can + be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the + cross and 183 (0xB7) for the dot. + + If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' + option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 + [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" + part). To only display the decimal power, set the number precision to zero with \ref + setNumberPrecision. + + Examples for \a formatCode: + \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, + normal scientific format is used + \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with + beautifully typeset decimal powers and a dot as multiplication sign + \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as + multiplication sign + \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal + powers. Format code will be reduced to 'f'. + \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format + code will not be changed. +*/ +void QCPAxis::setNumberFormat(const QString &formatCode) +{ + if (formatCode.isEmpty()) + { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; + } + mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars = "eEfgG"; + if (allowedFormatChars.contains(formatCode.at(0))) + { + mNumberFormatChar = formatCode.at(0).toLatin1(); + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + if (formatCode.length() < 2) + { + mNumberBeautifulPowers = false; + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g')) + { + mNumberBeautifulPowers = true; + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + return; + } + if (formatCode.length() < 3) + { + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == 'c') + { + mAxisPainter->numberMultiplyCross = true; + } else if (formatCode.at(2) == 'd') + { + mAxisPainter->numberMultiplyCross = false; + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + return; + } +} + +/*! + Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) + for details. The effect of precisions are most notably for number Formats starting with 'e', see + \ref setNumberFormat + + If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref + setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display + usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic + scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 + [superscript] n", set \a precision to zero. +*/ +void QCPAxis::setNumberPrecision(int precision) +{ + if (mNumberPrecision != precision) + { + mNumberPrecision = precision; + mCachedMarginValid = false; + } +} + +/*! + If \ref setAutoTickStep is set to false, use this function to set the tick step manually. + The tick step is the interval between (major) ticks, in plot coordinates. + \see setSubTickCount +*/ +void QCPAxis::setTickStep(double step) +{ + if (mTickStep != step) + { + mTickStep = step; + mCachedMarginValid = false; + } +} + +/*! + If you want full control over what ticks (and possibly labels) the axes show, this function is + used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else + the provided tick vector will be overwritten with automatically generated tick coordinates upon + replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is + left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. + + \a vec is a vector containing the positions of the ticks, in plot coordinates. + + \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. + + \see setTickVectorLabels +*/ +void QCPAxis::setTickVector(const QVector &vec) +{ + // don't check whether mTickVector != vec here, because it takes longer than we would save + mTickVector = vec; + mCachedMarginValid = false; +} + +/*! + If you want full control over what ticks and labels the axes show, this function is used to set a + number of QStrings that will be displayed at the tick positions which you need to provide with + \ref setTickVector. These two vectors should have the same size. (Note that you need to disable + \ref setAutoTicks and \ref setAutoTickLabels first.) + + \a vec is a vector containing the labels of the ticks. The entries correspond to the respective + indices in the tick vector, passed via \ref setTickVector. + + \see setTickVector +*/ +void QCPAxis::setTickVectorLabels(const QVector &vec) +{ + // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save + mTickVectorLabels = vec; + mCachedMarginValid = false; +} + +/*! + Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the + plot and \a outside is the length they will reach outside the plot. If \a outside is greater than + zero, the tick labels and axis label will increase their distance to the axis accordingly, so + they won't collide with the ticks. + + \see setSubTickLength, setTickLengthIn, setTickLengthOut +*/ +void QCPAxis::setTickLength(int inside, int outside) +{ + setTickLengthIn(inside); + setTickLengthOut(outside); +} + +/*! + Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach + inside the plot. + + \see setTickLengthOut, setTickLength, setSubTickLength +*/ +void QCPAxis::setTickLengthIn(int inside) +{ + if (mAxisPainter->tickLengthIn != inside) + { + mAxisPainter->tickLengthIn = inside; + } +} + +/*! + Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach + outside the plot. If \a outside is greater than zero, the tick labels and axis label will + increase their distance to the axis accordingly, so they won't collide with the ticks. + + \see setTickLengthIn, setTickLength, setSubTickLength +*/ +void QCPAxis::setTickLengthOut(int outside) +{ + if (mAxisPainter->tickLengthOut != outside) + { + mAxisPainter->tickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } +} + +/*! + Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, + divides the tick intervals in four sub intervals. + + By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the + mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is + always the case. + + If you want to disable automatic sub tick count and use this function to set the count manually, + see \ref setAutoSubTicks. +*/ +void QCPAxis::setSubTickCount(int count) +{ + mSubTickCount = count; +} + +/*! + Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside + the plot and \a outside is the length they will reach outside the plot. If \a outside is greater + than zero, the tick labels and axis label will increase their distance to the axis accordingly, + so they won't collide with the ticks. + + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut +*/ +void QCPAxis::setSubTickLength(int inside, int outside) +{ + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); +} + +/*! + Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside + the plot. + + \see setSubTickLengthOut, setSubTickLength, setTickLength +*/ +void QCPAxis::setSubTickLengthIn(int inside) +{ + if (mAxisPainter->subTickLengthIn != inside) + { + mAxisPainter->subTickLengthIn = inside; + } +} + +/*! + Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach + outside the plot. If \a outside is greater than zero, the tick labels will increase their + distance to the axis accordingly, so they won't collide with the ticks. + + \see setSubTickLengthIn, setSubTickLength, setTickLength +*/ +void QCPAxis::setSubTickLengthOut(int outside) +{ + if (mAxisPainter->subTickLengthOut != outside) + { + mAxisPainter->subTickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } +} + +/*! + Sets the pen, the axis base line is drawn with. + + \see setTickPen, setSubTickPen +*/ +void QCPAxis::setBasePen(const QPen &pen) +{ + mBasePen = pen; +} + +/*! + Sets the pen, tick marks will be drawn with. + + \see setTickLength, setBasePen +*/ +void QCPAxis::setTickPen(const QPen &pen) +{ + mTickPen = pen; +} + +/*! + Sets the pen, subtick marks will be drawn with. + + \see setSubTickCount, setSubTickLength, setBasePen +*/ +void QCPAxis::setSubTickPen(const QPen &pen) +{ + mSubTickPen = pen; +} + +/*! + Sets the font of the axis label. + + \see setLabelColor +*/ +void QCPAxis::setLabelFont(const QFont &font) +{ + if (mLabelFont != font) + { + mLabelFont = font; + mCachedMarginValid = false; + } +} + +/*! + Sets the color of the axis label. + + \see setLabelFont +*/ +void QCPAxis::setLabelColor(const QColor &color) +{ + mLabelColor = color; +} + +/*! + Sets the text of the axis label that will be shown below/above or next to the axis, depending on + its orientation. To disable axis labels, pass an empty string as \a str. +*/ +void QCPAxis::setLabel(const QString &str) +{ + if (mLabel != str) + { + mLabel = str; + mCachedMarginValid = false; + } +} + +/*! + Sets the distance between the tick labels and the axis label. + + \see setTickLabelPadding, setPadding +*/ +void QCPAxis::setLabelPadding(int padding) +{ + if (mAxisPainter->labelPadding != padding) + { + mAxisPainter->labelPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets the padding of the axis. + + When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, + that is left blank. + + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. + + \see setLabelPadding, setTickLabelPadding +*/ +void QCPAxis::setPadding(int padding) +{ + if (mPadding != padding) + { + mPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets the offset the axis has to its axis rect side. + + If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, + only the offset of the inner most axis has meaning (even if it is set to be invisible). The + offset of the other, outer axes is controlled automatically, to place them at appropriate + positions. +*/ +void QCPAxis::setOffset(int offset) +{ + mAxisPainter->offset = offset; +} + +/*! + Sets the font that is used for tick labels when they are selected. + + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickLabelFont(const QFont &font) +{ + if (font != mSelectedTickLabelFont) + { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } +} + +/*! + Sets the font that is used for the axis label when it is selected. + + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedLabelFont(const QFont &font) +{ + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts +} + +/*! + Sets the color that is used for tick labels when they are selected. + + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickLabelColor(const QColor &color) +{ + if (color != mSelectedTickLabelColor) + { + mSelectedTickLabelColor = color; + } +} + +/*! + Sets the color that is used for the axis label when it is selected. + + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedLabelColor(const QColor &color) +{ + mSelectedLabelColor = color; +} + +/*! + Sets the pen that is used to draw the axis base line when selected. + + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedBasePen(const QPen &pen) +{ + mSelectedBasePen = pen; +} + +/*! + Sets the pen that is used to draw the (major) ticks when selected. + + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickPen(const QPen &pen) +{ + mSelectedTickPen = pen; +} + +/*! + Sets the pen that is used to draw the subticks when selected. + + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedSubTickPen(const QPen &pen) +{ + mSelectedSubTickPen = pen; +} + +/*! + Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available + styles. + + For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. + Note that this meaning does not change when the axis range is reversed with \ref + setRangeReversed. + + \see setUpperEnding +*/ +void QCPAxis::setLowerEnding(const QCPLineEnding &ending) +{ + mAxisPainter->lowerEnding = ending; +} + +/*! + Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available + styles. + + For horizontal axes, this method refers to the right ending, for vertical axes the top ending. + Note that this meaning does not change when the axis range is reversed with \ref + setRangeReversed. + + \see setLowerEnding +*/ +void QCPAxis::setUpperEnding(const QCPLineEnding &ending) +{ + mAxisPainter->upperEnding = ending; +} + +/*! + If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper + bounds of the range. The range is simply moved by \a diff. + + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This + corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). +*/ +void QCPAxis::moveRange(double diff) +{ + QCPRange oldRange = mRange; + if (mScaleType == stLinear) + { + mRange.lower += diff; + mRange.upper += diff; + } else // mScaleType == stLogarithmic + { + mRange.lower *= diff; + mRange.upper *= diff; + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a + factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at + coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates + around 1.0 will have moved symmetrically closer to 1.0). +*/ +void QCPAxis::scaleRange(double factor, double center) +{ + QCPRange oldRange = mRange; + if (mScaleType == stLinear) + { + QCPRange newRange; + newRange.lower = (mRange.lower-center)*factor + center; + newRange.upper = (mRange.upper-center)*factor + center; + if (QCPRange::validRange(newRange)) + mRange = newRange.sanitizedForLinScale(); + } else // mScaleType == stLogarithmic + { + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range + { + QCPRange newRange; + newRange.lower = pow(mRange.lower/center, factor)*center; + newRange.upper = pow(mRange.upper/center, factor)*center; + if (QCPRange::validRange(newRange)) + mRange = newRange.sanitizedForLogScale(); + } else + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will + be done around the center of the current axis range. + + For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs + plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the + axis rect has. + + This is an operation that changes the range of this axis once, it doesn't fix the scale ratio + indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent + won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent + will follow. +*/ +void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) +{ + int otherPixelSize, ownPixelSize; + + if (otherAxis->orientation() == Qt::Horizontal) + otherPixelSize = otherAxis->axisRect()->width(); + else + otherPixelSize = otherAxis->axisRect()->height(); + + if (orientation() == Qt::Horizontal) + ownPixelSize = axisRect()->width(); + else + ownPixelSize = axisRect()->height(); + + double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; + setRange(range().center(), newRangeSize, Qt::AlignCenter); +} + +/*! + Changes the axis range such that all plottables associated with this axis are fully visible in + that dimension. + + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes +*/ +void QCPAxis::rescale(bool onlyVisiblePlottables) +{ + QList p = plottables(); + QCPRange newRange; + bool haveRange = false; + for (int i=0; irealVisibility() && onlyVisiblePlottables) + continue; + QCPRange plottableRange; + bool currentFoundRange; + QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; + if (mScaleType == stLogarithmic) + signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); + if (p.at(i)->keyAxis() == this) + plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); + else + plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); + if (currentFoundRange) + { + if (!haveRange) + newRange = plottableRange; + else + newRange.expand(plottableRange); + haveRange = true; + } + } + if (haveRange) + { + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mScaleType == stLinear) + { + newRange.lower = center-mRange.size()/2.0; + newRange.upper = center+mRange.size()/2.0; + } else // mScaleType == stLogarithmic + { + newRange.lower = center/qSqrt(mRange.upper/mRange.lower); + newRange.upper = center*qSqrt(mRange.upper/mRange.lower); + } + } + setRange(newRange); + } +} + +/*! + Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. +*/ +double QCPAxis::pixelToCoord(double value) const +{ + if (orientation() == Qt::Horizontal) + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; + else + return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; + } else // mScaleType == stLogarithmic + { + if (!mRangeReversed) + return pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; + else + return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; + } + } else // orientation() == Qt::Vertical + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; + else + return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; + } else // mScaleType == stLogarithmic + { + if (!mRangeReversed) + return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; + else + return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; + } + } +} + +/*! + Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. +*/ +double QCPAxis::coordToPixel(double value) const +{ + if (orientation() == Qt::Horizontal) + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); + else + return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); + } else // mScaleType == stLogarithmic + { + if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; + else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; + else + { + if (!mRangeReversed) + return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); + else + return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); + } + } + } else // orientation() == Qt::Vertical + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); + else + return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); + } else // mScaleType == stLogarithmic + { + if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; + else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; + else + { + if (!mRangeReversed) + return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); + else + return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); + } + } + } +} + +/*! + Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function + is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this + function does not change the current selection state of the axis. + + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. + + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions +*/ +QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const +{ + if (!mVisible) + return spNone; + + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) + return spAxis; + else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) + return spTickLabels; + else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) + return spAxisLabel; + else + return spNone; +} + +/* inherits documentation from base class */ +double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if (!mParentPlot) return -1; + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) + return -1; + + if (details) + details->setValue(part); + return mParentPlot->selectionTolerance()*0.99; +} + +/*! + Returns a list of all the plottables that have this axis as key or value axis. + + If you are only interested in plottables of type QCPGraph, see \ref graphs. + + \see graphs, items +*/ +QList QCPAxis::plottables() const +{ + QList result; + if (!mParentPlot) return result; + + for (int i=0; imPlottables.size(); ++i) + { + if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) + result.append(mParentPlot->mPlottables.at(i)); + } + return result; +} + +/*! + Returns a list of all the graphs that have this axis as key or value axis. + + \see plottables, items +*/ +QList QCPAxis::graphs() const +{ + QList result; + if (!mParentPlot) return result; + + for (int i=0; imGraphs.size(); ++i) + { + if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) + result.append(mParentPlot->mGraphs.at(i)); + } + return result; +} + +/*! + Returns a list of all the items that are associated with this axis. An item is considered + associated with an axis if at least one of its positions uses the axis as key or value axis. + + \see plottables, graphs +*/ +QList QCPAxis::items() const +{ + QList result; + if (!mParentPlot) return result; + + for (int itemId=0; itemIdmItems.size(); ++itemId) + { + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; +} + +/*! + Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to + QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) +*/ +QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) +{ + switch (side) + { + case QCP::msLeft: return atLeft; + case QCP::msRight: return atRight; + case QCP::msTop: return atTop; + case QCP::msBottom: return atBottom; + default: break; + } + qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; + return atLeft; +} + +/*! + Returns the axis type that describes the opposite axis of an axis with the specified \a type. +*/ +QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) +{ + switch (type) + { + case atLeft: return atRight; break; + case atRight: return atLeft; break; + case atBottom: return atTop; break; + case atTop: return atBottom; break; + default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; + } +} + +/*! \internal + + This function is called to prepare the tick vector, sub tick vector and tick label vector. If + \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref + generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to + provide external tick positions. Then the sub tick vectors and tick label vectors are created. +*/ +void QCPAxis::setupTickVectors() +{ + if (!mParentPlot) return; + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; + + // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself + if (mAutoTicks) + { + generateAutoTicks(); + } else + { + emit ticksRequest(); + } + + visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); + if (mTickVector.isEmpty()) + { + mSubTickVector.clear(); + return; + } + + // generate subticks between ticks: + mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); + if (mSubTickCount > 0) + { + double subTickStep = 0; + double subTickPosition = 0; + int subTickIndex = 0; + bool done = false; + int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; + int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; + for (int i=lowTick+1; i<=highTick; ++i) + { + subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); + for (int k=1; k<=mSubTickCount; ++k) + { + subTickPosition = mTickVector.at(i-1) + k*subTickStep; + if (subTickPosition < mRange.lower) + continue; + if (subTickPosition > mRange.upper) + { + done = true; + break; + } + mSubTickVector[subTickIndex] = subTickPosition; + subTickIndex++; + } + if (done) break; + } + mSubTickVector.resize(subTickIndex); + } + + // generate tick labels according to tick positions: + if (mAutoTickLabels) + { + int vecsize = mTickVector.size(); + mTickVectorLabels.resize(vecsize); + if (mTickLabelType == ltNumber) + { + for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) + mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision); + } else if (mTickLabelType == ltDateTime) + { + for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) + { +#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") + mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); +#else + mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); +#endif + } + } + } else // mAutoTickLabels == false + { + if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels + { + emit ticksRequest(); + } + // make sure provided tick label vector has correct (minimal) length: + if (mTickVectorLabels.size() < mTickVector.size()) + mTickVectorLabels.resize(mTickVector.size()); + } +} + +/*! \internal + + If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to + generate reasonable tick positions (and subtick count). The algorithm tries to create + approximately mAutoTickCount ticks (set via \ref setAutoTickCount). + + If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every + power of the current logarithm base, set via \ref setScaleLogBase. +*/ +void QCPAxis::generateAutoTicks() +{ + if (mScaleType == stLinear) + { + if (mAutoTickStep) + { + // Generate tick positions according to linear scaling: + mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers + double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. + double tickStepMantissa = mTickStep/magnitudeFactor; + if (tickStepMantissa < 5) + { + // round digit after decimal point to 0.5 + mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; + } else + { + // round to first digit in multiples of 2 + mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; + } + } + if (mAutoSubTicks) + mSubTickCount = calculateAutoSubTickCount(mTickStep); + // Generate tick positions according to mTickStep: + qint64 firstStep = floor(mRange.lower/mTickStep); + qint64 lastStep = ceil(mRange.upper/mTickStep); + int tickcount = lastStep-firstStep+1; + if (tickcount < 0) tickcount = 0; + mTickVector.resize(tickcount); + for (int i=0; i 0 && mRange.upper > 0) // positive range + { + double lowerMag = basePow((int)floor(baseLog(mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case + { + currentMag *= mScaleLogBase; + mTickVector.append(currentMag); + } + } else if (mRange.lower < 0 && mRange.upper < 0) // negative range + { + double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case + { + currentMag /= mScaleLogBase; + mTickVector.append(currentMag); + } + } else // invalid range for logarithmic scale, because lower and upper have different sign + { + mTickVector.clear(); + qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; + } + } +} + +/*! \internal + + Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a + tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For + Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, + because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note + that a subtick count of 4 means dividing the major tick step into 5 sections. + + This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps + with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no + fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is + returned. +*/ +int QCPAxis::calculateAutoSubTickCount(double tickStep) const +{ + int result = mSubTickCount; // default to current setting, if no proper value can be found + + // get mantissa of tickstep: + double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. + double tickStepMantissa = tickStep/magnitudeFactor; + + // separate integer and fractional part of mantissa: + double epsilon = 0.01; + double intPartf; + int intPart; + double fracPart = modf(tickStepMantissa, &intPartf); + intPart = intPartf; + + // handle cases with (almost) integer mantissa: + if (fracPart < epsilon || 1.0-fracPart < epsilon) + { + if (1.0-fracPart < epsilon) + ++intPart; + switch (intPart) + { + case 1: result = 4; break; // 1.0 -> 0.2 substep + case 2: result = 3; break; // 2.0 -> 0.5 substep + case 3: result = 2; break; // 3.0 -> 1.0 substep + case 4: result = 3; break; // 4.0 -> 1.0 substep + case 5: result = 4; break; // 5.0 -> 1.0 substep + case 6: result = 2; break; // 6.0 -> 2.0 substep + case 7: result = 6; break; // 7.0 -> 1.0 substep + case 8: result = 3; break; // 8.0 -> 2.0 substep + case 9: result = 2; break; // 9.0 -> 3.0 substep + } + } else + { + // handle cases with significantly fractional mantissa: + if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa + { + switch (intPart) + { + case 1: result = 2; break; // 1.5 -> 0.5 substep + case 2: result = 4; break; // 2.5 -> 0.5 substep + case 3: result = 4; break; // 3.5 -> 0.7 substep + case 4: result = 2; break; // 4.5 -> 1.5 substep + case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) + case 6: result = 4; break; // 6.5 -> 1.3 substep + case 7: result = 2; break; // 7.5 -> 2.5 substep + case 8: result = 4; break; // 8.5 -> 1.7 substep + case 9: result = 4; break; // 9.5 -> 1.9 substep + } + } + // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default + } + + return result; +} + +/* inherits documentation from base class */ +void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts^part : part); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAxis::deselectEvent(bool *selectionStateChanged) +{ + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing axis lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); +} + +/*! \internal + + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. + +*/ +void QCPAxis::draw(QCPPainter *painter) +{ + const int lowTick = mLowestVisibleTick; + const int highTick = mHighestVisibleTick; + QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(highTick-lowTick+1); + tickLabels.reserve(highTick-lowTick+1); + subTickPositions.reserve(mSubTickVector.size()); + + if (mTicks) + { + for (int i=lowTick; i<=highTick; ++i) + { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) + tickLabels.append(mTickVectorLabels.at(i)); + } + + if (mSubTickCount > 0) + { + const int subTickCount = mSubTickVector.size(); + for (int i=0; itype = mAxisType; + mAxisPainter->basePen = getBasePen(); + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->labelColor = getLabelColor(); + mAxisPainter->label = mLabel; + mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; + mAxisPainter->tickPen = getTickPen(); + mAxisPainter->subTickPen = getSubTickPen(); + mAxisPainter->tickLabelFont = getTickLabelFont(); + mAxisPainter->tickLabelColor = getTickLabelColor(); + mAxisPainter->alignmentRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; + mAxisPainter->reversedEndings = mRangeReversed; + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + mAxisPainter->subTickPositions = subTickPositions; + mAxisPainter->draw(painter); +} + +/*! \internal + + Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in + the current range. The return values are indices of the tick vector, not the positions of the + ticks themselves. + + The actual use of this function is when an external tick vector is provided, since it might + exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of + subticks. + + If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be + smaller than lowIndex. There is one case, where this function returns indices that are not really + visible in the current axis range: When the tick spacing is larger than the axis range size and + one tick is below the axis range and the next tick is already above the axis range. Because in + such cases it is usually desirable to know the tick pair, to draw proper subticks. +*/ +void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const +{ + bool lowFound = false; + bool highFound = false; + lowIndex = 0; + highIndex = -1; + + for (int i=0; i < mTickVector.size(); ++i) + { + if (mTickVector.at(i) >= mRange.lower) + { + lowFound = true; + lowIndex = i; + break; + } + } + for (int i=mTickVector.size()-1; i >= 0; --i) + { + if (mTickVector.at(i) <= mRange.upper) + { + highFound = true; + highIndex = i; + break; + } + } + + if (!lowFound && highFound) + lowIndex = highIndex+1; + else if (lowFound && !highFound) + highIndex = lowIndex-1; +} + +/*! \internal + + A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic + scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. + This is set to 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. + + \see basePow, setScaleLogBase, setScaleType +*/ +double QCPAxis::baseLog(double value) const +{ + return qLn(value)*mScaleLogBaseLogInv; +} + +/*! \internal + + A power function with the base mScaleLogBase, used mostly for coordinate transforms in + logarithmic scales with arbitrary log base. + + \see baseLog, setScaleLogBase, setScaleType +*/ +double QCPAxis::basePow(double value) const +{ + return qPow(mScaleLogBase, value); +} + +/*! \internal + + Returns the pen that is used to draw the axis base line. Depending on the selection state, this + is either mSelectedBasePen or mBasePen. +*/ +QPen QCPAxis::getBasePen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; +} + +/*! \internal + + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this + is either mSelectedTickPen or mTickPen. +*/ +QPen QCPAxis::getTickPen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; +} + +/*! \internal + + Returns the pen that is used to draw the subticks. Depending on the selection state, this + is either mSelectedSubTickPen or mSubTickPen. +*/ +QPen QCPAxis::getSubTickPen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; +} + +/*! \internal + + Returns the font that is used to draw the tick labels. Depending on the selection state, this + is either mSelectedTickLabelFont or mTickLabelFont. +*/ +QFont QCPAxis::getTickLabelFont() const +{ + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; +} + +/*! \internal + + Returns the font that is used to draw the axis label. Depending on the selection state, this + is either mSelectedLabelFont or mLabelFont. +*/ +QFont QCPAxis::getLabelFont() const +{ + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; +} + +/*! \internal + + Returns the color that is used to draw the tick labels. Depending on the selection state, this + is either mSelectedTickLabelColor or mTickLabelColor. +*/ +QColor QCPAxis::getTickLabelColor() const +{ + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; +} + +/*! \internal + + Returns the color that is used to draw the axis label. Depending on the selection state, this + is either mSelectedLabelColor or mLabelColor. +*/ +QColor QCPAxis::getLabelColor() const +{ + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; +} + +/*! \internal + + Returns the appropriate outward margin for this axis. It is needed if \ref + QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref + atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom + margin and so forth. For the calculation, this function goes through similar steps as \ref draw, + so changing one function likely requires the modification of the other one as well. + + The margin consists of the outward tick length, tick label padding, tick label size, label + padding, label size, and padding. + + The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. + unchanged are very fast. +*/ +int QCPAxis::calculateMargin() +{ + if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis + return 0; + + if (mCachedMarginValid) + return mCachedMargin; + + // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels + int margin = 0; + + int lowTick, highTick; + visibleTickBounds(lowTick, highTick); + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(highTick-lowTick+1); + tickLabels.reserve(highTick-lowTick+1); + if (mTicks) + { + for (int i=lowTick; i<=highTick; ++i) + { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) + tickLabels.append(mTickVectorLabels.at(i)); + } + } + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->label = mLabel; + mAxisPainter->tickLabelFont = mTickLabelFont; + mAxisPainter->alignmentRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + margin += mAxisPainter->size(); + margin += mPadding; + + mCachedMargin = margin; + mCachedMarginValid = true; + return margin; +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAxis::selectionCategory() const +{ + return QCP::iSelectAxes; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxisPainterPrivate +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxisPainterPrivate + + \internal + \brief (Private) + + This is a private class and not part of the public QCustomPlot interface. + + It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and + axis label. It also buffers the labels to reduce replot times. The parameters are configured by + directly accessing the public member variables. +*/ + +/*! + Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every + redraw, to utilize the caching mechanisms. +*/ +QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : + type(QCPAxis::atLeft), + basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + lowerEnding(QCPLineEnding::esNone), + upperEnding(QCPLineEnding::esNone), + labelPadding(0), + tickLabelPadding(0), + tickLabelRotation(0), + substituteExponent(true), + numberMultiplyCross(false), + tickLengthIn(5), + tickLengthOut(0), + subTickLengthIn(2), + subTickLengthOut(0), + tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + offset(0), + abbreviateDecimalPowers(false), + reversedEndings(false), + mParentPlot(parentPlot), + mLabelCache(16) // cache at most 16 (tick) labels +{ +} + +QCPAxisPainterPrivate::~QCPAxisPainterPrivate() +{ +} + +/*! \internal + + Draws the axis with the specified \a painter. + + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set + here, too. +*/ +void QCPAxisPainterPrivate::draw(QCPPainter *painter) +{ + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) + { + mLabelCache.clear(); + mLabelParameterHash = newHash; + } + + QPoint origin; + switch (type) + { + case QCPAxis::atLeft: origin = alignmentRect.bottomLeft() +QPoint(-offset, 0); break; + case QCPAxis::atRight: origin = alignmentRect.bottomRight()+QPoint(+offset, 0); break; + case QCPAxis::atTop: origin = alignmentRect.topLeft() +QPoint(0, -offset); break; + case QCPAxis::atBottom: origin = alignmentRect.bottomLeft() +QPoint(0, +offset); break; + } + + double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + switch (type) + { + case QCPAxis::atTop: yCor = -1; break; + case QCPAxis::atRight: xCor = 1; break; + default: break; + } + + int margin = 0; + // draw baseline: + QLineF baseLine; + painter->setPen(basePen); + if (QCPAxis::orientation(type) == Qt::Horizontal) + baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(alignmentRect.width()+xCor, yCor)); + else + baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -alignmentRect.height()+yCor)); + if (reversedEndings) + baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later + painter->drawLine(baseLine); + + // draw ticks: + if (!tickPositions.isEmpty()) + { + painter->setPen(tickPen); + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); + } else + { + for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); + } + } + + // draw subticks: + if (!subTickPositions.isEmpty()) + { + painter->setPen(subTickPen); + // direction of ticks ("inward" is right for left axis and left for right axis) + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); + } else + { + for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); + } + } + margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // draw axis base endings: + bool antialiasingBackup = painter->antialiasing(); + painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't + painter->setBrush(QBrush(basePen.color())); + QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); + if (lowerEnding.style() != QCPLineEnding::esNone) + lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); + if (upperEnding.style() != QCPLineEnding::esNone) + upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); + painter->setAntialiasing(antialiasingBackup); + + // tick labels: + QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label + if (!tickLabels.isEmpty()) + { + margin += tickLabelPadding; + painter->setFont(tickLabelFont); + painter->setPen(QPen(tickLabelColor)); + const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); + for (int i=0; isetFont(labelFont); + painter->setPen(QPen(labelColor)); + labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); + if (type == QCPAxis::atLeft) + { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); + painter->rotate(-90); + painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } + else if (type == QCPAxis::atRight) + { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-alignmentRect.height()); + painter->rotate(90); + painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } + else if (type == QCPAxis::atTop) + painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + else if (type == QCPAxis::atBottom) + painter->drawText(origin.x(), origin.y()+margin, alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } + + // set selection boxes: + int selectionTolerance = 0; + if (mParentPlot) + selectionTolerance = mParentPlot->selectionTolerance(); + else + qDebug() << Q_FUNC_INFO << "mParentPlot is null"; + int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisInSize = selectionTolerance; + int selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + int selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; + int selLabelSize = labelBounds.height(); + int selLabelOffset = selTickLabelOffset+selTickLabelSize+labelPadding; + if (type == QCPAxis::atLeft) + { + mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, alignmentRect.top(), origin.x()+selAxisInSize, alignmentRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, alignmentRect.top(), origin.x()-selTickLabelOffset, alignmentRect.bottom()); + mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, alignmentRect.top(), origin.x()-selLabelOffset, alignmentRect.bottom()); + } else if (type == QCPAxis::atRight) + { + mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, alignmentRect.top(), origin.x()+selAxisOutSize, alignmentRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, alignmentRect.top(), origin.x()+selTickLabelOffset, alignmentRect.bottom()); + mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, alignmentRect.top(), origin.x()+selLabelOffset, alignmentRect.bottom()); + } else if (type == QCPAxis::atTop) + { + mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisOutSize, alignmentRect.right(), origin.y()+selAxisInSize); + mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, alignmentRect.right(), origin.y()-selTickLabelOffset); + mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()-selLabelOffset-selLabelSize, alignmentRect.right(), origin.y()-selLabelOffset); + } else if (type == QCPAxis::atBottom) + { + mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisInSize, alignmentRect.right(), origin.y()+selAxisOutSize); + mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, alignmentRect.right(), origin.y()+selTickLabelOffset); + mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()+selLabelOffset+selLabelSize, alignmentRect.right(), origin.y()+selLabelOffset); + } + // draw hitboxes for debug purposes: + //painter->setBrush(Qt::NoBrush); + //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); +} + +/*! \internal + + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone + direction) needed to fit the axis. +*/ +int QCPAxisPainterPrivate::size() const +{ + int result = 0; + + // get length of tick marks pointing outwards: + if (!tickPositions.isEmpty()) + result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // calculate size of tick labels: + QSize tickLabelsSize(0, 0); + if (!tickLabels.isEmpty()) + { + for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled + { + if (!mLabelCache.contains(text)) // no cached label exists, create it + { + CachedLabel *newCachedLabel = new CachedLabel; + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF drawOffset = getTickLabelDrawOffset(labelData); + newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft(); + newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + newCachedLabel->pixmap.fill(Qt::transparent); + QCPPainter cachePainter(&newCachedLabel->pixmap); + cachePainter.setPen(painter->pen()); + drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + mLabelCache.insert(text, newCachedLabel, 1); + } + // draw cached label: + const CachedLabel *cachedLabel = mLabelCache.object(text); + // if label would be partly clipped by widget border on sides, don't draw it: + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || + labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left()) + return; + } else + { + if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() || + labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top()) + return; + } + painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); + finalSize = cachedLabel->pixmap.size(); + } else // label caching disabled, draw text directly on surface: + { + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + // if label would be partly clipped by widget border on sides, don't draw it: + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || + finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left()) + return; + } else + { + if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || + finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top()) + return; + } + drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) + tickLabelsSize->setWidth(finalSize.width()); + if (finalSize.height() > tickLabelsSize->height()) + tickLabelsSize->setHeight(finalSize.height()); +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a + y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to + directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when + QCP::phCacheLabels plotting hint is not set. +*/ +void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const +{ + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + + // transform painter to position/rotation: + painter->translate(x, y); + if (!qFuzzyIsNull(tickLabelRotation)) + painter->rotate(tickLabelRotation); + + // draw text: + if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used + { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); + painter->setFont(labelData.expFont); + painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); + } else + { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further + processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and + exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. +*/ +QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const +{ + TickLabelData result; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + int ePos = -1; + if (substituteExponent) + { + ePos = text.indexOf('e'); + if (ePos > -1) + useBeautifulPowers = true; + } + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so we check here before possibly setting a negative value in the next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + if (useBeautifulPowers) + { + // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: + result.basePart = text.left(ePos); + // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: + if (abbreviateDecimalPowers && result.basePart == "1") + result.basePart = "10"; + else + result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10"; + result.expPart = text.mid(ePos+1); + // clip "+" and leading zeros off expPart: + while (result.expPart.length() > 2 && result.expPart.at(1) == '0') // length > 2 so we leave one zero when numberFormatChar is 'e' + result.expPart.remove(1, 1); + if (!result.expPart.isEmpty() && result.expPart.at(0) == '+') + result.expPart.remove(0, 1); + // prepare smaller font for exponent: + result.expFont = font; + result.expFont.setPointSize(result.expFont.pointSize()*0.75); + // calculate bounding rects of base part, exponent part and total one: + result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); + result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); + result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA + } else // useBeautifulPowers == false + { + result.basePart = text; + result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler + + // calculate possibly different bounding rect after rotation: + result.rotatedTotalBounds = result.totalBounds; + if (!qFuzzyIsNull(tickLabelRotation)) + { + QTransform transform; + transform.rotate(tickLabelRotation); + result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + } + + return result; +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Calculates the offset at which the top left corner of the specified tick label shall be drawn. + The offset is relative to a point right next to the tick the label belongs to. + + This function is thus responsible for e.g. centering tick labels under ticks and positioning them + appropriately when they are rotated. +*/ +QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const +{ + /* + calculate label offset from base point at tick (non-trivial, for best visual appearance): short + explanation for bottom axis: The anchor, i.e. the point in the label that is placed + horizontally under the corresponding tick is always on the label side that is closer to the + axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height + is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text + will be centered under the tick (i.e. displaced horizontally by half its height). At the same + time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick + labels. + */ + bool doRotation = !qFuzzyIsNull(tickLabelRotation); + bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. + double radians = tickLabelRotation/180.0*M_PI; + int x=0, y=0; + if (type == QCPAxis::atLeft) + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = -qCos(radians)*labelData.totalBounds.width(); + y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; + } else + { + x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); + y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; + } + } else + { + x = -labelData.totalBounds.width(); + y = -labelData.totalBounds.height()/2.0; + } + } else if (type == QCPAxis::atRight) + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = +qSin(radians)*labelData.totalBounds.height(); + y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; + } else + { + x = 0; + y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; + } + } else + { + x = 0; + y = -labelData.totalBounds.height()/2.0; + } + } else if (type == QCPAxis::atTop) + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; + y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); + } else + { + x = -qSin(-radians)*labelData.totalBounds.height()/2.0; + y = -qCos(-radians)*labelData.totalBounds.height(); + } + } else + { + x = -labelData.totalBounds.width()/2.0; + y = -labelData.totalBounds.height(); + } + } else if (type == QCPAxis::atBottom) + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = +qSin(radians)*labelData.totalBounds.height()/2.0; + y = 0; + } else + { + x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; + y = +qSin(-radians)*labelData.totalBounds.width(); + } + } else + { + x = -labelData.totalBounds.width()/2.0; + y = 0; + } + } + + return QPointF(x, y); +} + +/*! \internal + + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label + to be drawn, depending on number format etc. Since only the largest tick label is wanted for the + margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a + smaller width/height. +*/ +void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const +{ + // note: this function must return the same tick label sizes as the placeTickLabel function. + QSize finalSize; + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label + { + const CachedLabel *cachedLabel = mLabelCache.object(text); + finalSize = cachedLabel->pixmap.size(); + } else // label caching disabled or no label with this text cached: + { + TickLabelData labelData = getTickLabelData(font, text); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) + tickLabelsSize->setWidth(finalSize.width()); + if (finalSize.height() > tickLabelsSize->height()) + tickLabelsSize->setHeight(finalSize.height()); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractPlottable +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractPlottable + \brief The abstract base class for all data representing objects in a plot. + + It defines a very basic interface like name, pen, brush, visibility etc. Since this class is + abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to + create new ways of displaying data (see "Creating own plottables" below). + + All further specifics are in the subclasses, for example: + \li A normal graph with possibly a line, scatter points and error bars is displayed by \ref QCPGraph + (typically created with \ref QCustomPlot::addGraph). + \li A parametric curve can be displayed with \ref QCPCurve. + \li A stackable bar chart can be achieved with \ref QCPBars. + \li A box of a statistical box plot is created with \ref QCPStatisticalBox. + + \section plottables-subclassing Creating own plottables + + To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure + virtual functions, you must implement: + \li \ref clearData + \li \ref selectTest + \li \ref draw + \li \ref drawLegendIcon + \li \ref getKeyRange + \li \ref getValueRange + + See the documentation of those functions for what they need to do. + + For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot + coordinates to pixel coordinates. This function is quite convenient, because it takes the + orientation of the key and value axes into account for you (x and y are swapped when the key axis + is vertical and the value axis horizontal). If you are worried about performance (i.e. you need + to translate many points in a loop like QCPGraph), you can directly use \ref + QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis + yourself. + + Here are some important members you inherit from QCPAbstractPlottable: + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  QCustomPlot *\b mParentPlotA pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
                  QString \b mNameThe name of the plottable.
                  QPen \b mPenThe generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
                  QPen \b mSelectedPenThe generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).
                  QBrush \b mBrushThe generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
                  QBrush \b mSelectedBrushThe generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).
                  QPointer\b mKeyAxis, \b mValueAxisThe key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. + Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.
                  bool \b mSelectedindicates whether the plottable is selected or not.
                  +*/ + +/* start of documentation of pure virtual functions */ + +/*! \fn void QCPAbstractPlottable::clearData() = 0 + Clears all data in the plottable. +*/ + +/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 + \internal + + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation + of this plottable inside \a rect, next to the plottable name. +*/ + +/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 + \internal + + called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can + set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the + returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain + to \ref sdNegative and all positive points will be ignored for range calculation. For no + restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output + parameter that indicates whether a range could be found or not. If this is false, you shouldn't + use the returned range (e.g. no points in data). + + Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by + this function may have size zero, which wouldn't count as a valid range. + + \see rescaleAxes, getValueRange +*/ + +/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 + \internal + + called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can + set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the + returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain + to \ref sdNegative and all positive points will be ignored for range calculation. For no + restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output + parameter that indicates whether a range could be found or not. If this is false, you shouldn't + use the returned range (e.g. no points in data). + + Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by + this function may have size zero, which wouldn't count as a valid range. + + \see rescaleAxes, getKeyRange +*/ + +/* end of documentation of pure virtual functions */ +/* start of documentation of signals */ + +/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) + + This signal is emitted when the selection state of this plottable has changed, either by user + interaction or by a direct call to \ref setSelected. +*/ + +/*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); + + This signal is emitted when the selectability of this plottable has changed. + + \see setSelectable +*/ + +/* end of documentation of signals */ + +/*! + Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as + its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance + and have perpendicular orientations. If either of these restrictions is violated, a corresponding + message is printed to the debug output (qDebug), the construction is not aborted, though. + + Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, + it can't be directly instantiated. + + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. +*/ +QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()), + mName(""), + mAntialiasedFill(true), + mAntialiasedScatters(true), + mAntialiasedErrorBars(false), + mPen(Qt::black), + mSelectedPen(Qt::black), + mBrush(Qt::NoBrush), + mSelectedBrush(Qt::NoBrush), + mKeyAxis(keyAxis), + mValueAxis(valueAxis), + mSelectable(true), + mSelected(false) +{ + if (keyAxis->parentPlot() != valueAxis->parentPlot()) + qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; + if (keyAxis->orientation() == valueAxis->orientation()) + qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; +} + +/*! + The name is the textual representation of this plottable as it is displayed in the legend + (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. +*/ +void QCPAbstractPlottable::setName(const QString &name) +{ + mName = name; +} + +/*! + Sets whether fills of this plottable is drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedFill(bool enabled) +{ + mAntialiasedFill = enabled; +} + +/*! + Sets whether the scatter symbols of this plottable are drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) +{ + mAntialiasedScatters = enabled; +} + +/*! + Sets whether the error bars of this plottable are drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) +{ + mAntialiasedErrorBars = enabled; +} + + +/*! + The pen is used to draw basic lines that make up the plottable representation in the + plot. + + For example, the \ref QCPGraph subclass draws its graph lines and scatter points + with this pen. + + \see setBrush +*/ +void QCPAbstractPlottable::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + When the plottable is selected, this pen is used to draw basic lines instead of the normal + pen set via \ref setPen. + + \see setSelected, setSelectable, setSelectedBrush, selectTest +*/ +void QCPAbstractPlottable::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + The brush is used to draw basic fills of the plottable representation in the + plot. The Fill can be a color, gradient or texture, see the usage of QBrush. + + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when + it's not set to Qt::NoBrush. + + \see setPen +*/ +void QCPAbstractPlottable::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + When the plottable is selected, this brush is used to draw fills instead of the normal + brush set via \ref setBrush. + + \see setSelected, setSelectable, setSelectedPen, selectTest +*/ +void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal + to the plottable's value axis. This function performs no checks to make sure this is the case. + The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the + y-axis (QCustomPlot::yAxis) as value axis. + + Normally, the key and value axes are set in the constructor of the plottable (or \ref + QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). + + \see setValueAxis +*/ +void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) +{ + mKeyAxis = axis; +} + +/*! + The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is + orthogonal to the plottable's key axis. This function performs no checks to make sure this is the + case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and + the y-axis (QCustomPlot::yAxis) as value axis. + + Normally, the key and value axes are set in the constructor of the plottable (or \ref + QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). + + \see setKeyAxis +*/ +void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) +{ + mValueAxis = axis; +} + +/*! + Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) + + However, even when \a selectable was set to false, it is possible to set the selection manually, + by calling \ref setSelected directly. + + \see setSelected +*/ +void QCPAbstractPlottable::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this plottable is selected or not. When selected, it uses a different pen and brush + to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. + + The entire selection mechanism for plottables is handled automatically when \ref + QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when + you wish to change the selection state manually. + + This function can change the selection state even when \ref setSelectable was set to false. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see setSelectable, selectTest +*/ +void QCPAbstractPlottable::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/*! + Rescales the key and value axes associated with this plottable to contain all displayed data, so + the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make + sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. + Instead it will stay in the current sign domain and ignore all parts of the plottable that lie + outside of that domain. + + \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show + multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has + \a onlyEnlarge set to false (the default), and all subsequent set to true. + + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale +*/ +void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const +{ + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); +} + +/*! + Rescales the key axis of the plottable so the whole plottable is visible. + + See \ref rescaleAxes for detailed behaviour. +*/ +void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + SignDomain signDomain = sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain); + if (foundRange) + { + if (onlyEnlarge) + newRange.expand(keyAxis->range()); + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (keyAxis->scaleType() == QCPAxis::stLinear) + { + newRange.lower = center-keyAxis->range().size()/2.0; + newRange.upper = center+keyAxis->range().size()/2.0; + } else // scaleType() == stLogarithmic + { + newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); + newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); + } + } + keyAxis->setRange(newRange); + } +} + +/*! + Rescales the value axis of the plottable so the whole plottable is visible. + + Returns true if the axis was actually scaled. This might not be the case if this plottable has an + invalid range, e.g. because it has no data points. + + See \ref rescaleAxes for detailed behaviour. +*/ +void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const +{ + QCPAxis *valueAxis = mValueAxis.data(); + if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } + + SignDomain signDomain = sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain); + if (foundRange) + { + if (onlyEnlarge) + newRange.expand(valueAxis->range()); + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + newRange.lower = center-valueAxis->range().size()/2.0; + newRange.upper = center+valueAxis->range().size()/2.0; + } else // scaleType() == stLogarithmic + { + newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); + newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); + } +} + +/*! + Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). + + Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable + needs a more specialized representation in the legend, this function will take this into account + and instead create the specialized subclass of QCPAbstractLegendItem. + + Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in + the legend. + + \see removeFromLegend, QCPLegend::addItem +*/ +bool QCPAbstractPlottable::addToLegend() +{ + if (!mParentPlot || !mParentPlot->legend) + return false; + + if (!mParentPlot->legend->hasItemWithPlottable(this)) + { + mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); + return true; + } else + return false; +} + +/*! + Removes the plottable from the legend of the parent QCustomPlot. This means the + QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable + is removed. + + Returns true on success, i.e. if the legend exists and a legend item associated with this + plottable was found and removed. + + \see addToLegend, QCPLegend::removeItem +*/ +bool QCPAbstractPlottable::removeFromLegend() const +{ + if (!mParentPlot->legend) + return false; + + if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) + return mParentPlot->legend->removeItem(lip); + else + return false; +} + +/* inherits documentation from base class */ +QRect QCPAbstractPlottable::clipRect() const +{ + if (mKeyAxis && mValueAxis) + return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + else + return QRect(); +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractPlottable::selectionCategory() const +{ + return QCP::iSelectPlottables; +} + +/*! \internal + + Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, + taking the orientations of the axes associated with this plottable into account (e.g. whether key + represents x or y). + + \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. + + \see pixelsToCoords, QCPAxis::coordToPixel +*/ +void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + if (keyAxis->orientation() == Qt::Horizontal) + { + x = keyAxis->coordToPixel(key); + y = valueAxis->coordToPixel(value); + } else + { + y = keyAxis->coordToPixel(key); + x = valueAxis->coordToPixel(value); + } +} + +/*! \internal + \overload + + Returns the input as pixel coordinates in a QPointF. +*/ +const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + if (keyAxis->orientation() == Qt::Horizontal) + return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); + else + return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); +} + +/*! \internal + + Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, + taking the orientations of the axes associated with this plottable into account (e.g. whether key + represents x or y). + + \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. + + \see coordsToPixels, QCPAxis::coordToPixel +*/ +void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + if (keyAxis->orientation() == Qt::Horizontal) + { + key = keyAxis->pixelToCoord(x); + value = valueAxis->pixelToCoord(y); + } else + { + key = keyAxis->pixelToCoord(y); + value = valueAxis->pixelToCoord(x); + } +} + +/*! \internal + \overload + + Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. +*/ +void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const +{ + pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); +} + +/*! \internal + + Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the + graph is not selected and mSelectedPen when it is. +*/ +QPen QCPAbstractPlottable::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the + graph is not selected and mSelectedBrush when it is. +*/ +QBrush QCPAbstractPlottable::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable fills. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable scatter points. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable error bars. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint +*/ +void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); +} + +/*! \internal + + Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + end. + + This function may be used to help with the implementation of the \ref selectTest function for + specific plottables. + + \note This function is identical to QCPAbstractItem::distSqrToLine +*/ +double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const +{ + QVector2D a(start); + QVector2D b(end); + QVector2D p(point); + QVector2D v(b-a); + + double vLengthSqr = v.lengthSquared(); + if (!qFuzzyIsNull(vLengthSqr)) + { + double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; + if (mu < 0) + return (a-p).lengthSquared(); + else if (mu > 1) + return (b-p).lengthSquared(); + else + return ((a + mu*v)-p).lengthSquared(); + } else + return (a-p).lengthSquared(); +} + +/* inherits documentation from base class */ +void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemAnchor +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemAnchor + \brief An anchor of an item to which positions can be attached to. + + An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't + control anything on its item, but provides a way to tie other items via their positions to the + anchor. + + For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. + Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can + attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by + calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the + QCPItemRect. This way the start of the line will now always follow the respective anchor location + on the rect item. + + Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an + anchor to other positions. + + To learn how to provide anchors in your own item subclasses, see the subclassing section of the + QCPAbstractItem documentation. +*/ + +/* start documentation of inline functions */ + +/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() + + Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if + it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). + + This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids + dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with + gcc compiler). +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if + you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as + explained in the subclassing section of the QCPAbstractItem documentation. +*/ +QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : + mName(name), + mParentPlot(parentPlot), + mParentItem(parentItem), + mAnchorId(anchorId) +{ +} + +QCPItemAnchor::~QCPItemAnchor() +{ + // unregister as parent at children: + QList currentChildren(mChildren.toList()); + for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren +} + +/*! + Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. + + The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the + parent item, QCPItemAnchor is just an intermediary. +*/ +QPointF QCPItemAnchor::pixelPoint() const +{ + if (mParentItem) + { + if (mAnchorId > -1) + { + return mParentItem->anchorPixelPoint(mAnchorId); + } else + { + qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; + return QPointF(); + } + } else + { + qDebug() << Q_FUNC_INFO << "no parent item set"; + return QPointF(); + } +} + +/*! \internal + + Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to + destruction of the anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::addChild(QCPItemPosition *pos) +{ + if (!mChildren.contains(pos)) + mChildren.insert(pos); + else + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); +} + +/*! \internal + + Removes \a pos from the child list of this anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::removeChild(QCPItemPosition *pos) +{ + if (!mChildren.remove(pos)) + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemPosition +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemPosition + \brief Manages the position of an item. + + Every item has at least one public QCPItemPosition member pointer which provides ways to position the + item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: + \a topLeft and \a bottomRight. + + QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines + how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as + plot coordinates of certain axes, etc. + + Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every + QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other + positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the + coordinates set with \ref setCoords are considered to be absolute values in the reference frame of the + parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach + the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting + point of the line always be centered under the text label, no matter where the text is moved to, or is + itself tied to. + + To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This + works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref + setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified + pixel values. +*/ + +/*! + Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if + you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as + explained in the subclassing section of the QCPAbstractItem documentation. +*/ +QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : + QCPItemAnchor(parentPlot, parentItem, name), + mPositionType(ptAbsolute), + mKey(0), + mValue(0), + mParentAnchor(0) +{ +} + +QCPItemPosition::~QCPItemPosition() +{ + // unregister as parent at children: + // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then + // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint + QList currentChildren(mChildren.toList()); + for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren + // unregister as child in parent: + if (mParentAnchor) + mParentAnchor->removeChild(this); +} + +/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ +QCPAxisRect *QCPItemPosition::axisRect() const +{ + return mAxisRect.data(); +} + +/*! + Sets the type of the position. The type defines how the coordinates passed to \ref setCoords + should be handled and how the QCPItemPosition should behave in the plot. + + The possible values for \a type can be separated in two main categories: + + \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords + and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. + By default, the QCustomPlot's x- and yAxis are used. + + \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This + corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref + ptAxisRectRatio. They differ only in the way the absolute position is described, see the + documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify + the axis rect with \ref setAxisRect. By default this is set to the main axis rect. + + Note that the position type \ref ptPlotCoords is only available (and sensible) when the position + has no parent anchor (\ref setParentAnchor). + + If the type is changed, the apparent pixel position on the plot is preserved. This means + the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. +*/ +void QCPItemPosition::setType(QCPItemPosition::PositionType type) +{ + if (mPositionType != type) + { + // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect + // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. + bool recoverPixelPosition = true; + if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) + recoverPixelPosition = false; + if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) + recoverPixelPosition = false; + + QPointF pixelP; + if (recoverPixelPosition) + pixelP = pixelPoint(); + + mPositionType = type; + + if (recoverPixelPosition) + setPixelPoint(pixelP); + } +} + +/*! + Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now + follow any position changes of the anchor. The local coordinate system of positions with a parent + anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type + shouldn't be \ref ptPlotCoords for positions with parent anchors.) + + if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved + during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position + will be exactly on top of the parent anchor. + + To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. + + If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is + set to \ref ptAbsolute, to keep the position in a valid state. +*/ +bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) +{ + // make sure self is not assigned as parent: + if (parentAnchor == this) + { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); + return false; + } + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) + { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) + { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) + { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->mParentAnchor; + } else + { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) + { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchor && mPositionType == ptPlotCoords) + setType(ptAbsolute); + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) + pixelP = pixelPoint(); + // unregister at current parent anchor: + if (mParentAnchor) + mParentAnchor->removeChild(this); + // register at new parent anchor: + if (parentAnchor) + parentAnchor->addChild(this); + mParentAnchor = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) + setPixelPoint(pixelP); + else + setCoords(0, 0); + return true; +} + +/*! + Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type + (\ref setType). + + For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position + on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the + QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the + plot coordinate system defined by the axes set by \ref setAxes. By default those are the + QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available + coordinate types and their meaning. + + \see setPixelPoint +*/ +void QCPItemPosition::setCoords(double key, double value) +{ + mKey = key; + mValue = value; +} + +/*! \overload + + Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the + meaning of \a value of the \ref setCoords(double key, double value) method. +*/ +void QCPItemPosition::setCoords(const QPointF &pos) +{ + setCoords(pos.x(), pos.y()); +} + +/*! + Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It + includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). + + \see setPixelPoint +*/ +QPointF QCPItemPosition::pixelPoint() const +{ + switch (mPositionType) + { + case ptAbsolute: + { + if (mParentAnchor) + return QPointF(mKey, mValue) + mParentAnchor->pixelPoint(); + else + return QPointF(mKey, mValue); + } + + case ptViewportRatio: + { + if (mParentAnchor) + { + return QPointF(mKey*mParentPlot->viewport().width(), + mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint(); + } else + { + return QPointF(mKey*mParentPlot->viewport().width(), + mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft(); + } + } + + case ptAxisRectRatio: + { + if (mAxisRect) + { + if (mParentAnchor) + { + return QPointF(mKey*mAxisRect.data()->width(), + mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint(); + } else + { + return QPointF(mKey*mAxisRect.data()->width(), + mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft(); + } + } else + { + qDebug() << Q_FUNC_INFO << "No axis rect defined"; + return QPointF(mKey, mValue); + } + } + + case ptPlotCoords: + { + double x, y; + if (mKeyAxis && mValueAxis) + { + // both key and value axis are given, translate key/value to x/y coordinates: + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + { + x = mKeyAxis.data()->coordToPixel(mKey); + y = mValueAxis.data()->coordToPixel(mValue); + } else + { + y = mKeyAxis.data()->coordToPixel(mKey); + x = mValueAxis.data()->coordToPixel(mValue); + } + } else if (mKeyAxis) + { + // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + { + x = mKeyAxis.data()->coordToPixel(mKey); + y = mValue; + } else + { + y = mKeyAxis.data()->coordToPixel(mKey); + x = mValue; + } + } else if (mValueAxis) + { + // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: + if (mValueAxis.data()->orientation() == Qt::Horizontal) + { + x = mValueAxis.data()->coordToPixel(mValue); + y = mKey; + } else + { + y = mValueAxis.data()->coordToPixel(mValue); + x = mKey; + } + } else + { + // no axis given, basically the same as if mPositionType were ptAbsolute + qDebug() << Q_FUNC_INFO << "No axes defined"; + x = mKey; + y = mValue; + } + return QPointF(x, y); + } + } + return QPointF(); +} + +/*! + When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the + coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and + yAxis of the QCustomPlot. +*/ +void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) +{ + mKeyAxis = keyAxis; + mValueAxis = valueAxis; +} + +/*! + When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the + coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of + the QCustomPlot. +*/ +void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) +{ + mAxisRect = axisRect; +} + +/*! + Sets the apparent pixel position. This works no matter what type (\ref setType) this + QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed + appropriately, to make the position finally appear at the specified pixel values. + + Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is + identical to that of \ref setCoords. + + \see pixelPoint, setCoords +*/ +void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) +{ + switch (mPositionType) + { + case ptAbsolute: + { + if (mParentAnchor) + setCoords(pixelPoint-mParentAnchor->pixelPoint()); + else + setCoords(pixelPoint); + break; + } + + case ptViewportRatio: + { + if (mParentAnchor) + { + QPointF p(pixelPoint-mParentAnchor->pixelPoint()); + p.rx() /= (double)mParentPlot->viewport().width(); + p.ry() /= (double)mParentPlot->viewport().height(); + setCoords(p); + } else + { + QPointF p(pixelPoint-mParentPlot->viewport().topLeft()); + p.rx() /= (double)mParentPlot->viewport().width(); + p.ry() /= (double)mParentPlot->viewport().height(); + setCoords(p); + } + break; + } + + case ptAxisRectRatio: + { + if (mAxisRect) + { + if (mParentAnchor) + { + QPointF p(pixelPoint-mParentAnchor->pixelPoint()); + p.rx() /= (double)mAxisRect.data()->width(); + p.ry() /= (double)mAxisRect.data()->height(); + setCoords(p); + } else + { + QPointF p(pixelPoint-mAxisRect.data()->topLeft()); + p.rx() /= (double)mAxisRect.data()->width(); + p.ry() /= (double)mAxisRect.data()->height(); + setCoords(p); + } + } else + { + qDebug() << Q_FUNC_INFO << "No axis rect defined"; + setCoords(pixelPoint); + } + break; + } + + case ptPlotCoords: + { + double newKey, newValue; + if (mKeyAxis && mValueAxis) + { + // both key and value axis are given, translate point to key/value coordinates: + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + { + newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); + newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); + } else + { + newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); + newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); + } + } else if (mKeyAxis) + { + // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + { + newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); + newValue = pixelPoint.y(); + } else + { + newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); + newValue = pixelPoint.x(); + } + } else if (mValueAxis) + { + // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: + if (mValueAxis.data()->orientation() == Qt::Horizontal) + { + newKey = pixelPoint.y(); + newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); + } else + { + newKey = pixelPoint.x(); + newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); + } + } else + { + // no axis given, basically the same as if mPositionType were ptAbsolute + qDebug() << Q_FUNC_INFO << "No axes defined"; + newKey = pixelPoint.x(); + newValue = pixelPoint.y(); + } + setCoords(newKey, newValue); + break; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractItem + \brief The abstract base class for all items in a plot. + + In QCustomPlot, items are supplemental graphical elements that are neither plottables + (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus + plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each + specific item has at least one QCPItemPosition member which controls the positioning. Some items + are defined by more than one coordinate and thus have two or more QCPItemPosition members (For + example, QCPItemRect has \a topLeft and \a bottomRight). + + This abstract base class defines a very basic interface like visibility and clipping. Since this + class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass + yourself to create new items. + + The built-in items are: + + + + + + + + + + +
                  QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
                  QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
                  QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
                  QCPItemRectA rectangle
                  QCPItemEllipseAn ellipse
                  QCPItemPixmapAn arbitrary pixmap
                  QCPItemTextA text label
                  QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
                  QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
                  + + Items are by default clipped to the main axis rect. To make an item visible outside that axis + rect, disable clipping via \ref setClipToAxisRect. + + \section items-using Using items + + First you instantiate the item you want to use and add it to the plot: + \code + QCPItemLine *line = new QCPItemLine(customPlot); + customPlot->addItem(line); + \endcode + by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just + set the plot coordinates where the line should start/end: + \code + line->start->setCoords(-0.1, 0.8); + line->end->setCoords(1.1, 0.2); + \endcode + If we don't want the line to be positioned in plot coordinates but a different coordinate system, + e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: + \code + line->start->setType(QCPItemPosition::ptAbsolute); + line->end->setType(QCPItemPosition::ptAbsolute); + \endcode + Then we can set the coordinates, this time in pixels: + \code + line->start->setCoords(100, 200); + line->end->setCoords(450, 320); + \endcode + + \section items-subclassing Creating own items + + To create an own item, you implement a subclass of QCPAbstractItem. These are the pure + virtual functions, you must implement: + \li \ref selectTest + \li \ref draw + + See the documentation of those functions for what they need to do. + + \subsection items-positioning Allowing the item to be positioned + + As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall + have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add + a public member of type QCPItemPosition like so: + + \code QCPItemPosition * const myPosition;\endcode + + the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition + instance it points to, can be modified, of course). + The initialization of this pointer is made easy with the \ref createPosition function. Just assign + the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition + takes a string which is the name of the position, typically this is identical to the variable name. + For example, the constructor of QCPItemExample could look like this: + + \code + QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + myPosition(createPosition("myPosition")) + { + // other constructor code + } + \endcode + + \subsection items-drawing The draw function + + To give your item a visual representation, reimplement the \ref draw function and use the passed + QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the + position member(s) via \ref QCPItemPosition::pixelPoint. + + To optimize performance you should calculate a bounding rect first (don't forget to take the pen + width into account), check whether it intersects the \ref clipRect, and only draw the item at all + if this is the case. + + \subsection items-selection The selectTest function + + Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and + \ref rectSelectTest. With these, the implementation of the selection test becomes significantly + simpler for most items. See the documentation of \ref selectTest for what the function parameters + mean and what the function should return. + + \subsection anchors Providing anchors + + Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public + member, e.g. + + \code QCPItemAnchor * const bottom;\endcode + + and create it in the constructor with the \ref createAnchor function, assigning it a name and an + anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). + Since anchors can be placed anywhere, relative to the item's position(s), your item needs to + provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int + anchorId) function. + + In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel + position when anything attached to the anchor needs to know the coordinates. +*/ + +/* start of documentation of inline functions */ + +/*! \fn QList QCPAbstractItem::positions() const + + Returns all positions of the item in a list. + + \see anchors, position +*/ + +/*! \fn QList QCPAbstractItem::anchors() const + + Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always + also an anchor, the list will also contain the positions of this item. + + \see positions, anchor +*/ + +/* end of documentation of inline functions */ +/* start documentation of pure virtual functions */ + +/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 + \internal + + Draws this item with the provided \a painter. + + The cliprect of the provided painter is set to the rect returned by \ref clipRect before this + function is called. The clipRect depends on the clipping settings defined by \ref + setClipToAxisRect and \ref setClipAxisRect. +*/ + +/* end documentation of pure virtual functions */ +/* start documentation of signals */ + +/*! \fn void QCPAbstractItem::selectionChanged(bool selected) + This signal is emitted when the selection state of this item has changed, either by user interaction + or by a direct call to \ref setSelected. +*/ + +/* end documentation of signals */ + +/*! + Base class constructor which initializes base class members. +*/ +QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : + QCPLayerable(parentPlot), + mClipToAxisRect(false), + mSelectable(true), + mSelected(false) +{ + QList rects = parentPlot->axisRects(); + if (rects.size() > 0) + { + setClipToAxisRect(true); + setClipAxisRect(rects.first()); + } +} + +QCPAbstractItem::~QCPAbstractItem() +{ + // don't delete mPositions because every position is also an anchor and thus in mAnchors + qDeleteAll(mAnchors); +} + +/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ +QCPAxisRect *QCPAbstractItem::clipAxisRect() const +{ + return mClipAxisRect.data(); +} + +/*! + Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the + entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. + + \see setClipAxisRect +*/ +void QCPAbstractItem::setClipToAxisRect(bool clip) +{ + mClipToAxisRect = clip; + if (mClipToAxisRect) + setParentLayerable(mClipAxisRect.data()); +} + +/*! + Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref + setClipToAxisRect is set to true. + + \see setClipToAxisRect +*/ +void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) +{ + mClipAxisRect = rect; + if (mClipToAxisRect) + setParentLayerable(mClipAxisRect.data()); +} + +/*! + Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) + + However, even when \a selectable was set to false, it is possible to set the selection manually, + by calling \ref setSelected. + + \see QCustomPlot::setInteractions, setSelected +*/ +void QCPAbstractItem::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this item is selected or not. When selected, it might use a different visual + appearance (e.g. pen and brush), this depends on the specific item though. + + The entire selection mechanism for items is handled automatically when \ref + QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this + function when you wish to change the selection state manually. + + This function can change the selection state even when \ref setSelectable was set to false. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see setSelectable, selectTest +*/ +void QCPAbstractItem::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/*! + Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by + that name, returns 0. + + This function provides an alternative way to access item positions. Normally, you access + positions direcly by their member pointers (which typically have the same variable name as \a + name). + + \see positions, anchor +*/ +QCPItemPosition *QCPAbstractItem::position(const QString &name) const +{ + for (int i=0; iname() == name) + return mPositions.at(i); + } + qDebug() << Q_FUNC_INFO << "position with name not found:" << name; + return 0; +} + +/*! + Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by + that name, returns 0. + + This function provides an alternative way to access item anchors. Normally, you access + anchors direcly by their member pointers (which typically have the same variable name as \a + name). + + \see anchors, position +*/ +QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const +{ + for (int i=0; iname() == name) + return mAnchors.at(i); + } + qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; + return 0; +} + +/*! + Returns whether this item has an anchor with the specified \a name. + + Note that you can check for positions with this function, too. This is because every position is + also an anchor (QCPItemPosition inherits from QCPItemAnchor). + + \see anchor, position +*/ +bool QCPAbstractItem::hasAnchor(const QString &name) const +{ + for (int i=0; iname() == name) + return true; + } + return false; +} + +/*! \internal + + Returns the rect the visual representation of this item is clipped to. This depends on the + current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. + + If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. + + \see draw +*/ +QRect QCPAbstractItem::clipRect() const +{ + if (mClipToAxisRect && mClipAxisRect) + return mClipAxisRect.data()->rect(); + else + return mParentPlot->viewport(); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing item lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); +} + +/*! \internal + + Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + end. + + This function may be used to help with the implementation of the \ref selectTest function for + specific items. + + \note This function is identical to QCPAbstractPlottable::distSqrToLine + + \see rectSelectTest +*/ +double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const +{ + QVector2D a(start); + QVector2D b(end); + QVector2D p(point); + QVector2D v(b-a); + + double vLengthSqr = v.lengthSquared(); + if (!qFuzzyIsNull(vLengthSqr)) + { + double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; + if (mu < 0) + return (a-p).lengthSquared(); + else if (mu > 1) + return (b-p).lengthSquared(); + else + return ((a + mu*v)-p).lengthSquared(); + } else + return (a-p).lengthSquared(); +} + +/*! \internal + + A convenience function which returns the selectTest value for a specified \a rect and a specified + click position \a pos. \a filledRect defines whether a click inside the rect should also be + considered a hit or whether only the rect border is sensitive to hits. + + This function may be used to help with the implementation of the \ref selectTest function for + specific items. + + For example, if your item consists of four rects, call this function four times, once for each + rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned + values which were greater or equal to zero. (Because this function may return -1.0 when \a pos + doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item + wasn't hit. + + \see distSqrToLine +*/ +double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const +{ + double result = -1; + + // distance to border: + QList lines; + lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) + << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); + double minDistSqr = std::numeric_limits::max(); + for (int i=0; i mParentPlot->selectionTolerance()*0.99) + { + if (rect.contains(pos)) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; +} + +/*! \internal + + Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in + item subclasses if they want to provide anchors (QCPItemAnchor). + + For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor + ids and returns the respective pixel points of the specified anchor. + + \see createAnchor +*/ +QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const +{ + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified + \a name must be a unique string that is usually identical to the variable name of the position + member (This is needed to provide the name-based \ref position access to positions). + + Don't delete positions created by this function manually, as the item will take care of it. + + Use this function in the constructor (initialization list) of the specific item subclass to + create each position member. Don't create QCPItemPositions with \b new yourself, because they + won't be registered with the item properly. + + \see createAnchor +*/ +QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) +{ + if (hasAnchor(name)) + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); + mPositions.append(newPosition); + mAnchors.append(newPosition); // every position is also an anchor + newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); + newPosition->setType(QCPItemPosition::ptPlotCoords); + if (mParentPlot->axisRect()) + newPosition->setAxisRect(mParentPlot->axisRect()); + newPosition->setCoords(0, 0); + return newPosition; +} + +/*! \internal + + Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified + \a name must be a unique string that is usually identical to the variable name of the anchor + member (This is needed to provide the name based \ref anchor access to anchors). + + The \a anchorId must be a number identifying the created anchor. It is recommended to create an + enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor + to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns + the correct pixel coordinates for the passed anchor id. + + Don't delete anchors created by this function manually, as the item will take care of it. + + Use this function in the constructor (initialization list) of the specific item subclass to + create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they + won't be registered with the item properly. + + \see createPosition +*/ +QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) +{ + if (hasAnchor(name)) + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); + mAnchors.append(newAnchor); + return newAnchor; +} + +/* inherits documentation from base class */ +void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractItem::selectionCategory() const +{ + return QCP::iSelectItems; +} + + +/*! \file */ + + + +/*! \mainpage %QCustomPlot 1.2.1 Documentation + + \image html qcp-doc-logo.png + + Below is a brief overview of and guide to the classes and their relations. If you are new to + QCustomPlot and just want to start using it, it's recommended to look at the tutorials and + examples at + + http://www.qcustomplot.com/ + + This documentation is especially helpful as a reference, when you're familiar with the basic + concept of how to use %QCustomPlot and you wish to learn more about specific functionality. + See the \ref classoverview "class overview" for diagrams explaining the relationships between + the most important classes of the QCustomPlot library. + + The central widget which displays the plottables and axes on its surface is QCustomPlot. Every + QCustomPlot contains four axes by default. They can be accessed via the members \ref + QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2" + and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary + number of axes and axis rects, see the documentation of QCPAxisRect for details. + + \section mainpage-plottables Plottables + + \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive + from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph + inside the plot with different line styles, scatter styles, filling etc. + + Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working + with QCPGraph plottables, that makes it very easy to handle them:\n + You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph. + + For all other plottables, you need to use the normal plottable interface:\n + First, you create an instance of the plottable you want, e.g. + \code + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot: + \code + customPlot->addPlottable(newCurve);\endcode + and then modify the properties of the newly created plottable via the newCurve pointer. + + Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type + of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will + probably want to qobject_cast the returned pointer to the respective plottable subclass. (As + usual, if the cast returns zero, the plottable wasn't of that specific subclass.) + + All further interfacing with plottables (e.g how to set data) is specific to the plottable type. + See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox, + QCPColorMap. + + \section mainpage-axes Controlling the Axes + + As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2 + (top), \a yAxis2 (right). + + Their range is handled by the simple QCPRange class. You can set the range with the + QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic + scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely + with \ref QCPAxis::setScaleLogBase. + + By default, an axis automatically creates and labels ticks in a sensible manner. See the + following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks, + QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels, + QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep, + QCPAxis::setTickLength,... + + Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel. + + The distance of an axis backbone to the respective viewport border is called its margin. + Normally, the margins are calculated automatically. To change this, set + \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with + \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect(). + + \section mainpage-legend Plot Legend + + Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small + layout element inside the plot which lists the plottables with an icon of the plottable + line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from + the main legend via \ref QCPAbstractPlottable::addToLegend and \ref + QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot + automatically adds it to the legend, too. This behaviour can be modified with the + QCustomPlot::setAutoAddPlottableToLegend property. + + The QCPLegend provides an interface to access, add and remove legend items directly, too. See + QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for + example. + + Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a + QCPLegend simply is a normal layout element). + + \section mainpage-userinteraction User Interactions + + QCustomPlot supports dragging axis ranges with the mouse (\ref + QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref + QCPAxisRect::setRangeZoom) and a complete selection mechanism. + + The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For + details about the interaction system, see the documentation there. + + Further, QCustomPlot always emits corresponding signals, when objects are clicked or + doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick + and \ref QCustomPlot::axisClick for example. + + \section mainpage-items Items + + Apart from plottables there is another category of plot objects that are important: Items. The + base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that + it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel + coordinates or placed at a relative position on an axis rect. Further, it usually doesn't + represent data directly, but acts as decoration, emphasis, description etc. + + Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For + example, you could place the head of an arrow at a fixed plot coordinate, so it always points to + some important area in the plot. The tail of the arrow can be anchored to a text item which + always resides in the top center of the axis rect, independent of where the user drags the axis + ranges. This way the arrow stretches and turns so it always points from the label to the + specified plot coordinate, without any further code necessary. + + For a more detailed introduction, see the QCPAbstractItem documentation, and from there the + documentations of the individual built-in items, to find out how to use them. + + \section mainpage-layoutelements Layout elements and layouts + + QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like + the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by + placing them inside a \ref QCPLayout. + + Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink. + + \section mainpage-performancetweaks Performance Tweaks + + Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick + lines can cause a significant slow down. If you notice this in your application, here are some + thoughts on how to increase performance. By far the most time is spent in the drawing functions, + specifically the drawing of graphs. For maximum performance, consider the following (most + recommended/effective measures first): + + \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However + QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >= + 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8. + \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true. + \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying + "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster") + before creating the QApplication object. (Only available for Qt versions before 5.0) + \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem + opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only + available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the + quality of antialiasing, but extremely increase performance especially with alpha + (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note + however, that the maximum frame rate might be constrained by the vertical sync frequency of your + monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots + (where the potential framerate is far above 60 frames per second), OpenGL acceleration might + achieve numerically lower frame rates than the other graphics systems, because they are not + capped at the VSync frequency. + \li Avoid any kind of alpha (transparency), especially in fills + \li Avoid lines with a pen width greater than one + \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements) + \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most + data points stay unchanged, e.g. in a running measurement. + \li Set the \a copy parameter of the setData functions to false, so only pointers get + transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000) + + \section mainpage-flags Preprocessor Define Flags + + QCustomPlot understands some preprocessor defines that are useful for debugging and compilation: +
                  +
                  \c QCUSTOMPLOT_COMPILE_LIBRARY +
                  Define this flag when you compile QCustomPlot as a shared library (.so/.dll) +
                  \c QCUSTOMPLOT_USE_LIBRARY +
                  Define this flag before including the header, when using QCustomPlot as a shared library +
                  \c QCUSTOMPLOT_CHECK_DATA +
                  If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw. + This means they will give qDebug output when you plot \e inf or \e nan values, they will not + fix your data. +
                  + +*/ + +/*! \page classoverview Class Overview + + The following diagrams may help to gain a deeper understanding of the relationships between classes that make up + the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown. + + \section classoverview-relations Class Relationship Diagram + \image html RelationOverview.png "Overview of most important classes and their relations" + \section classoverview-inheritance Class Inheritance Tree + \image html InheritanceOverview.png "Inheritance tree of most important classes" + +*/ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCustomPlot +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCustomPlot + + \brief The central class of the library. This is the QWidget which displays the plot and + interacts with the user. + + For tutorials on how to use QCustomPlot, see the website\n + http://www.qcustomplot.com/ +*/ + +/* start of documentation of inline functions */ + +/*! \fn QRect QCustomPlot::viewport() const + + Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is + drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the + plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left + (0, 0) and size of the QCustomPlot widget. + + Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically + an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger + and contains also the axes themselves, their tick numbers, their labels, the plot title etc. + + Only when saving to a file (see \ref savePng, savePdf etc.) the viewport is temporarily modified + to allow saving plots with sizes independent of the current widget size. +*/ + +/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const + + Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just + one cell with the main QCPAxisRect inside. +*/ + +/* end of documentation of inline functions */ +/* start of documentation of signals */ + +/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse double click event. +*/ + +/*! \fn void QCustomPlot::mousePress(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse press event. + + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref + QCPAxisRect::setRangeDragAxes. +*/ + +/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse move event. + + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref + QCPAxisRect::setRangeDragAxes. + + \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, + because the dragging starting point was saved the moment the mouse was pressed. Thus it only has + a meaning for the range drag axes that were set at that moment. If you want to change the drag + axes, consider doing this in the \ref mousePress signal instead. +*/ + +/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse release event. + + It is emitted before QCustomPlot handles any other mechanisms like object selection. So a + slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or + \ref QCPAbstractPlottable::setSelectable. +*/ + +/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse wheel event. + + It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref + QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. +*/ + +/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) + + This signal is emitted when a plottable is clicked. + + \a event is the mouse event that caused the click and \a plottable is the plottable that received + the click. + + \see plottableDoubleClick +*/ + +/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) + + This signal is emitted when a plottable is double clicked. + + \a event is the mouse event that caused the click and \a plottable is the plottable that received + the click. + + \see plottableClick +*/ + +/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) + + This signal is emitted when an item is clicked. + + \a event is the mouse event that caused the click and \a item is the item that received the + click. + + \see itemDoubleClick +*/ + +/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) + + This signal is emitted when an item is double clicked. + + \a event is the mouse event that caused the click and \a item is the item that received the + click. + + \see itemClick +*/ + +/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) + + This signal is emitted when an axis is clicked. + + \a event is the mouse event that caused the click, \a axis is the axis that received the click and + \a part indicates the part of the axis that was clicked. + + \see axisDoubleClick +*/ + +/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) + + This signal is emitted when an axis is double clicked. + + \a event is the mouse event that caused the click, \a axis is the axis that received the click and + \a part indicates the part of the axis that was clicked. + + \see axisClick +*/ + +/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) + + This signal is emitted when a legend (item) is clicked. + + \a event is the mouse event that caused the click, \a legend is the legend that received the + click and \a item is the legend item that received the click. If only the legend and no item is + clicked, \a item is 0. This happens for a click inside the legend padding or the space between + two items. + + \see legendDoubleClick +*/ + +/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) + + This signal is emitted when a legend (item) is double clicked. + + \a event is the mouse event that caused the click, \a legend is the legend that received the + click and \a item is the legend item that received the click. If only the legend and no item is + clicked, \a item is 0. This happens for a click inside the legend padding or the space between + two items. + + \see legendClick +*/ + +/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) + + This signal is emitted when a plot title is clicked. + + \a event is the mouse event that caused the click and \a title is the plot title that received + the click. + + \see titleDoubleClick +*/ + +/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) + + This signal is emitted when a plot title is double clicked. + + \a event is the mouse event that caused the click and \a title is the plot title that received + the click. + + \see titleClick +*/ + +/*! \fn void QCustomPlot::selectionChangedByUser() + + This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by + clicking. It is not emitted when the selection state of an object has changed programmatically by + a direct call to setSelected() on an object or by calling \ref deselectAll. + + In addition to this signal, selectable objects also provide individual signals, for example + QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are + emitted even if the selection state is changed programmatically. + + See the documentation of \ref setInteractions for details about the selection mechanism. + + \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends +*/ + +/*! \fn void QCustomPlot::beforeReplot() + + This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref + replot). + + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them + replot synchronously, it won't cause an infinite recursion. + + \see replot, afterReplot +*/ + +/*! \fn void QCustomPlot::afterReplot() + + This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref + replot). + + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them + replot synchronously, it won't cause an infinite recursion. + + \see replot, beforeReplot +*/ + +/* end of documentation of signals */ +/* start of documentation of public members */ + +/*! \var QCPAxis *QCustomPlot::xAxis + + A pointer to the primary x Axis (bottom) of the main axis rect of the plot. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::yAxis + + A pointer to the primary y Axis (left) of the main axis rect of the plot. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::xAxis2 + + A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are + invisible by default. Use QCPAxis::setVisible to change this (or use \ref + QCPAxisRect::setupFullAxesBox). + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::yAxis2 + + A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are + invisible by default. Use QCPAxis::setVisible to change this (or use \ref + QCPAxisRect::setupFullAxesBox). + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPLegend *QCustomPlot::legend + + A pointer to the default legend of the main axis rect. The legend is invisible by default. Use + QCPLegend::setVisible to change this. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple legends to the plot, use the layout system interface to + access the new legend. For example, legends can be placed inside an axis rect's \ref + QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If + the default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointer becomes 0. +*/ + +/* end of documentation of public members */ + +/*! + Constructs a QCustomPlot and sets reasonable default values. +*/ +QCustomPlot::QCustomPlot(QWidget *parent) : + QWidget(parent), + xAxis(0), + yAxis(0), + xAxis2(0), + yAxis2(0), + legend(0), + mPlotLayout(0), + mAutoAddPlottableToLegend(true), + mAntialiasedElements(QCP::aeNone), + mNotAntialiasedElements(QCP::aeNone), + mInteractions(0), + mSelectionTolerance(8), + mNoAntialiasingOnDrag(false), + mBackgroundBrush(Qt::white, Qt::SolidPattern), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mCurrentLayer(0), + mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), + mMultiSelectModifier(Qt::ControlModifier), + mPaintBuffer(size()), + mMouseEventElement(0), + mReplotting(false) +{ + setAttribute(Qt::WA_NoMousePropagation); + setAttribute(Qt::WA_OpaquePaintEvent); + setMouseTracking(true); + QLocale currentLocale = locale(); + currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); + setLocale(currentLocale); + + // create initial layers: + mLayers.append(new QCPLayer(this, "background")); + mLayers.append(new QCPLayer(this, "grid")); + mLayers.append(new QCPLayer(this, "main")); + mLayers.append(new QCPLayer(this, "axes")); + mLayers.append(new QCPLayer(this, "legend")); + updateLayerIndices(); + setCurrentLayer("main"); + + // create initial layout, axis rect and legend: + mPlotLayout = new QCPLayoutGrid; + mPlotLayout->initializeParentPlot(this); + mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry + mPlotLayout->setLayer("main"); + QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); + mPlotLayout->addElement(0, 0, defaultAxisRect); + xAxis = defaultAxisRect->axis(QCPAxis::atBottom); + yAxis = defaultAxisRect->axis(QCPAxis::atLeft); + xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); + yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); + legend = new QCPLegend; + legend->setVisible(false); + defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); + defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); + + defaultAxisRect->setLayer("background"); + xAxis->setLayer("axes"); + yAxis->setLayer("axes"); + xAxis2->setLayer("axes"); + yAxis2->setLayer("axes"); + xAxis->grid()->setLayer("grid"); + yAxis->grid()->setLayer("grid"); + xAxis2->grid()->setLayer("grid"); + yAxis2->grid()->setLayer("grid"); + legend->setLayer("legend"); + + setViewport(rect()); // needs to be called after mPlotLayout has been created + + replot(); +} + +QCustomPlot::~QCustomPlot() +{ + clearPlottables(); + clearItems(); + + if (mPlotLayout) + { + delete mPlotLayout; + mPlotLayout = 0; + } + + mCurrentLayer = 0; + qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + mLayers.clear(); +} + +/*! + Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. + + This overrides the antialiasing settings for whole element groups, normally controlled with the + \a setAntialiasing function on the individual elements. If an element is neither specified in + \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on + each individual element instance is used. + + For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be + drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set + to. + + if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is + removed from there. + + \see setNotAntialiasedElements +*/ +void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) +{ + mAntialiasedElements = antialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mNotAntialiasedElements |= ~mAntialiasedElements; +} + +/*! + Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. + + See \ref setAntialiasedElements for details. + + \see setNotAntialiasedElement +*/ +void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) +{ + if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) + mAntialiasedElements &= ~antialiasedElement; + else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) + mAntialiasedElements |= antialiasedElement; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mNotAntialiasedElements |= ~mAntialiasedElements; +} + +/*! + Sets which elements are forcibly drawn not antialiased as an \a or combination of + QCP::AntialiasedElement. + + This overrides the antialiasing settings for whole element groups, normally controlled with the + \a setAntialiasing function on the individual elements. If an element is neither specified in + \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on + each individual element instance is used. + + For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be + drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set + to. + + if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is + removed from there. + + \see setAntialiasedElements +*/ +void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) +{ + mNotAntialiasedElements = notAntialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mAntialiasedElements |= ~mNotAntialiasedElements; +} + +/*! + Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. + + See \ref setNotAntialiasedElements for details. + + \see setAntialiasedElement +*/ +void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) +{ + if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) + mNotAntialiasedElements &= ~notAntialiasedElement; + else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) + mNotAntialiasedElements |= notAntialiasedElement; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mAntialiasedElements |= ~mNotAntialiasedElements; +} + +/*! + If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the + plottable to the legend (QCustomPlot::legend). + + \see addPlottable, addGraph, QCPLegend::addItem +*/ +void QCustomPlot::setAutoAddPlottableToLegend(bool on) +{ + mAutoAddPlottableToLegend = on; +} + +/*! + Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction + enums. There are the following types of interactions: + + Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the + respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. + For details how to control which axes the user may drag/zoom and in what orientations, see \ref + QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, + \ref QCPAxisRect::setRangeZoomAxes. + + Plottable selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is + set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their + vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can + further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific + plottable. To find out whether a specific plottable is selected, call + QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call + \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience + function \ref selectedGraphs. + + Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user + may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find + out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of + all currently selected items, call \ref selectedItems. + + Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user + may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick + labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for + each axis. To retrieve a list of all axes that currently contain selected parts, call \ref + selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). + + Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may + select the legend itself or individual items by clicking on them. What parts exactly are + selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the + legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To + find out which child items are selected, call \ref QCPLegend::selectedItems. + + All other selectable elements The selection of all other selectable objects (e.g. + QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the + user may select those objects by clicking on them. To find out which are currently selected, you + need to check their selected state explicitly. + + If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is + emitted. Each selectable object additionally emits an individual selectionChanged signal whenever + their selection state has changed, i.e. not only by user interaction. + + To allow multiple objects to be selected by holding the selection modifier (\ref + setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. + + \note In addition to the selection mechanism presented here, QCustomPlot always emits + corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and + \ref plottableDoubleClick for example. + + \see setInteraction, setSelectionTolerance +*/ +void QCustomPlot::setInteractions(const QCP::Interactions &interactions) +{ + mInteractions = interactions; +} + +/*! + Sets the single \a interaction of this QCustomPlot to \a enabled. + + For details about the interaction system, see \ref setInteractions. + + \see setInteractions +*/ +void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) +{ + if (!enabled && mInteractions.testFlag(interaction)) + mInteractions &= ~interaction; + else if (enabled && !mInteractions.testFlag(interaction)) + mInteractions |= interaction; +} + +/*! + Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or + not. + + If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a + potential selection when the minimum distance between the click position and the graph line is + smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks + directly inside the area and ignore this selection tolerance. In other words, it only has meaning + for parts of objects that are too thin to exactly hit with a click and thus need such a + tolerance. + + \see setInteractions, QCPLayerable::selectTest +*/ +void QCustomPlot::setSelectionTolerance(int pixels) +{ + mSelectionTolerance = pixels; +} + +/*! + Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes + ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves + performance during dragging. Thus it creates a more responsive user experience. As soon as the + user stops dragging, the last replot is done with normal antialiasing, to restore high image + quality. + + \see setAntialiasedElements, setNotAntialiasedElements +*/ +void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) +{ + mNoAntialiasingOnDrag = enabled; +} + +/*! + Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. + + \see setPlottingHint +*/ +void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) +{ + mPlottingHints = hints; +} + +/*! + Sets the specified plotting \a hint to \a enabled. + + \see setPlottingHints +*/ +void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) +{ + QCP::PlottingHints newHints = mPlottingHints; + if (!enabled) + newHints &= ~hint; + else + newHints |= hint; + + if (newHints != mPlottingHints) + setPlottingHints(newHints); +} + +/*! + Sets the keyboard modifier that will be recognized as multi-select-modifier. + + If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects + by clicking on them one after the other while holding down \a modifier. + + By default the multi-select-modifier is set to Qt::ControlModifier. + + \see setInteractions +*/ +void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) +{ + mMultiSelectModifier = modifier; +} + +/*! + Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout + (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. + + This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref + savePdf, etc. by temporarily changing the viewport size. +*/ +void QCustomPlot::setViewport(const QRect &rect) +{ + mViewport = rect; + if (mPlotLayout) + mPlotLayout->setOuterRect(mViewport); +} + +/*! + Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn + below all other objects in the plot. + + For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be + enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is + preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, + consider using the overloaded version of this function. + + If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will + first be filled with that brush, before drawing the background pixmap. This can be useful for + background pixmaps with translucent areas. + + \see setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QPixmap &pm) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); +} + +/*! + Sets the background brush of the viewport (see \ref setViewport). + + Before drawing everything else, the background is filled with \a brush. If a background pixmap + was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport + before the background pixmap is drawn. This can be useful for background pixmaps with translucent + areas. + + Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be + useful for exporting to image formats which support transparency, e.g. \ref savePng. + + \see setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QBrush &brush) +{ + mBackgroundBrush = brush; +} + +/*! \overload + + Allows setting the background pixmap of the viewport, whether it shall be scaled and how it + shall be scaled in one call. + + \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; +} + +/*! + Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is + set to true, control whether and how the aspect ratio of the original pixmap is preserved with + \ref setBackgroundScaledMode. + + Note that the scaled version of the original pixmap is buffered, so there is no performance + penalty on replots. (Except when the viewport dimensions are changed continuously.) + + \see setBackground, setBackgroundScaledMode +*/ +void QCustomPlot::setBackgroundScaled(bool scaled) +{ + mBackgroundScaled = scaled; +} + +/*! + If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this + function to define whether and how the aspect ratio of the original pixmap is preserved. + + \see setBackground, setBackgroundScaled +*/ +void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) +{ + mBackgroundScaledMode = mode; +} + +/*! + Returns the plottable with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last added + plottable, see QCustomPlot::plottable() + + \see plottableCount, addPlottable +*/ +QCPAbstractPlottable *QCustomPlot::plottable(int index) +{ + if (index >= 0 && index < mPlottables.size()) + { + return mPlottables.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last plottable that was added with \ref addPlottable. If there are no plottables in + the plot, returns 0. + + \see plottableCount, addPlottable +*/ +QCPAbstractPlottable *QCustomPlot::plottable() +{ + if (!mPlottables.isEmpty()) + { + return mPlottables.last(); + } else + return 0; +} + +/*! + Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to + the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. + + Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of + \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the + plottable's constructor). + + \see plottable, plottableCount, removePlottable, clearPlottables +*/ +bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) +{ + if (mPlottables.contains(plottable)) + { + qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); + return false; + } + if (plottable->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); + return false; + } + + mPlottables.append(plottable); + // possibly add plottable to legend: + if (mAutoAddPlottableToLegend) + plottable->addToLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) + mGraphs.append(graph); + if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) + plottable->setLayer(currentLayer()); + return true; +} + +/*! + Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). + + Returns true on success. + + \see addPlottable, clearPlottables +*/ +bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) +{ + if (!mPlottables.contains(plottable)) + { + qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); + return false; + } + + // remove plottable from legend: + plottable->removeFromLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) + mGraphs.removeOne(graph); + // remove plottable: + delete plottable; + mPlottables.removeOne(plottable); + return true; +} + +/*! \overload + + Removes the plottable by its \a index. +*/ +bool QCustomPlot::removePlottable(int index) +{ + if (index >= 0 && index < mPlottables.size()) + return removePlottable(mPlottables[index]); + else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } +} + +/*! + Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). + + Returns the number of plottables removed. + + \see removePlottable +*/ +int QCustomPlot::clearPlottables() +{ + int c = mPlottables.size(); + for (int i=c-1; i >= 0; --i) + removePlottable(mPlottables[i]); + return c; +} + +/*! + Returns the number of currently existing plottables in the plot + + \see plottable, addPlottable +*/ +int QCustomPlot::plottableCount() const +{ + return mPlottables.size(); +} + +/*! + Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. + + There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. + + \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected +*/ +QList QCustomPlot::selectedPlottables() const +{ + QList result; + foreach (QCPAbstractPlottable *plottable, mPlottables) + { + if (plottable->selected()) + result.append(plottable); + } + return result; +} + +/*! + Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines + (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple + plottables come into consideration, the one closest to \a pos is returned. + + If \a onlySelectable is true, only plottables that are selectable + (QCPAbstractPlottable::setSelectable) are considered. + + If there is no plottable at \a pos, the return value is 0. + + \see itemAt, layoutElementAt +*/ +QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const +{ + QCPAbstractPlottable *resultPlottable = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) + { + if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable + continue; + if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes + { + double currentDistance = plottable->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) + { + resultPlottable = plottable; + resultDistance = currentDistance; + } + } + } + + return resultPlottable; +} + +/*! + Returns whether this QCustomPlot instance contains the \a plottable. + + \see addPlottable +*/ +bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const +{ + return mPlottables.contains(plottable); +} + +/*! + Returns the graph with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last created + graph, see QCustomPlot::graph() + + \see graphCount, addGraph +*/ +QCPGraph *QCustomPlot::graph(int index) const +{ + if (index >= 0 && index < mGraphs.size()) + { + return mGraphs.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, + returns 0. + + \see graphCount, addGraph +*/ +QCPGraph *QCustomPlot::graph() const +{ + if (!mGraphs.isEmpty()) + { + return mGraphs.last(); + } else + return 0; +} + +/*! + Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the + bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a + keyAxis and \a valueAxis must reside in this QCustomPlot. + + \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically + "y") for the graph. + + Returns a pointer to the newly created graph, or 0 if adding the graph failed. + + \see graph, graphCount, removeGraph, clearGraphs +*/ +QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) +{ + if (!keyAxis) keyAxis = xAxis; + if (!valueAxis) valueAxis = yAxis; + if (!keyAxis || !valueAxis) + { + qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; + return 0; + } + if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; + return 0; + } + + QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); + if (addPlottable(newGraph)) + { + newGraph->setName("Graph "+QString::number(mGraphs.size())); + return newGraph; + } else + { + delete newGraph; + return 0; + } +} + +/*! + Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If + any other graphs in the plot have a channel fill set towards the removed graph, the channel fill + property of those graphs is reset to zero (no channel fill). + + Returns true on success. + + \see clearGraphs +*/ +bool QCustomPlot::removeGraph(QCPGraph *graph) +{ + return removePlottable(graph); +} + +/*! \overload + + Removes the graph by its \a index. +*/ +bool QCustomPlot::removeGraph(int index) +{ + if (index >= 0 && index < mGraphs.size()) + return removeGraph(mGraphs[index]); + else + return false; +} + +/*! + Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). + + Returns the number of graphs removed. + + \see removeGraph +*/ +int QCustomPlot::clearGraphs() +{ + int c = mGraphs.size(); + for (int i=c-1; i >= 0; --i) + removeGraph(mGraphs[i]); + return c; +} + +/*! + Returns the number of currently existing graphs in the plot + + \see graph, addGraph +*/ +int QCustomPlot::graphCount() const +{ + return mGraphs.size(); +} + +/*! + Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. + + If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, + etc., use \ref selectedPlottables. + + \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected +*/ +QList QCustomPlot::selectedGraphs() const +{ + QList result; + foreach (QCPGraph *graph, mGraphs) + { + if (graph->selected()) + result.append(graph); + } + return result; +} + +/*! + Returns the item with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last added + item, see QCustomPlot::item() + + \see itemCount, addItem +*/ +QCPAbstractItem *QCustomPlot::item(int index) const +{ + if (index >= 0 && index < mItems.size()) + { + return mItems.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last item, that was added with \ref addItem. If there are no items in the plot, + returns 0. + + \see itemCount, addItem +*/ +QCPAbstractItem *QCustomPlot::item() const +{ + if (!mItems.isEmpty()) + { + return mItems.last(); + } else + return 0; +} + +/*! + Adds the specified item to the plot. QCustomPlot takes ownership of the item. + + Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a + item is this QCustomPlot. + + \see item, itemCount, removeItem, clearItems +*/ +bool QCustomPlot::addItem(QCPAbstractItem *item) +{ + if (!mItems.contains(item) && item->parentPlot() == this) + { + mItems.append(item); + return true; + } else + { + qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); + return false; + } +} + +/*! + Removes the specified item from the plot. + + Returns true on success. + + \see addItem, clearItems +*/ +bool QCustomPlot::removeItem(QCPAbstractItem *item) +{ + if (mItems.contains(item)) + { + delete item; + mItems.removeOne(item); + return true; + } else + { + qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + return false; + } +} + +/*! \overload + + Removes the item by its \a index. +*/ +bool QCustomPlot::removeItem(int index) +{ + if (index >= 0 && index < mItems.size()) + return removeItem(mItems[index]); + else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } +} + +/*! + Removes all items from the plot. + + Returns the number of items removed. + + \see removeItem +*/ +int QCustomPlot::clearItems() +{ + int c = mItems.size(); + for (int i=c-1; i >= 0; --i) + removeItem(mItems[i]); + return c; +} + +/*! + Returns the number of currently existing items in the plot + + \see item, addItem +*/ +int QCustomPlot::itemCount() const +{ + return mItems.size(); +} + +/*! + Returns a list of the selected items. If no items are currently selected, the list is empty. + + \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected +*/ +QList QCustomPlot::selectedItems() const +{ + QList result; + foreach (QCPAbstractItem *item, mItems) + { + if (item->selected()) + result.append(item); + } + return result; +} + +/*! + Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref + QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref + setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is + returned. + + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are + considered. + + If there is no item at \a pos, the return value is 0. + + \see plottableAt, layoutElementAt +*/ +QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const +{ + QCPAbstractItem *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) + { + if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it + { + double currentDistance = item->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) + { + resultItem = item; + resultDistance = currentDistance; + } + } + } + + return resultItem; +} + +/*! + Returns whether this QCustomPlot contains the \a item. + + \see addItem +*/ +bool QCustomPlot::hasItem(QCPAbstractItem *item) const +{ + return mItems.contains(item); +} + +/*! + Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is + returned. + + Layer names are case-sensitive. + + \see addLayer, moveLayer, removeLayer +*/ +QCPLayer *QCustomPlot::layer(const QString &name) const +{ + foreach (QCPLayer *layer, mLayers) + { + if (layer->name() == name) + return layer; + } + return 0; +} + +/*! \overload + + Returns the layer by \a index. If the index is invalid, 0 is returned. + + \see addLayer, moveLayer, removeLayer +*/ +QCPLayer *QCustomPlot::layer(int index) const +{ + if (index >= 0 && index < mLayers.size()) + { + return mLayers.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! + Returns the layer that is set as current layer (see \ref setCurrentLayer). +*/ +QCPLayer *QCustomPlot::currentLayer() const +{ + return mCurrentLayer; +} + +/*! + Sets the layer with the specified \a name to be the current layer. All layerables (\ref + QCPLayerable), e.g. plottables and items, are created on the current layer. + + Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. + + Layer names are case-sensitive. + + \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer +*/ +bool QCustomPlot::setCurrentLayer(const QString &name) +{ + if (QCPLayer *newCurrentLayer = layer(name)) + { + return setCurrentLayer(newCurrentLayer); + } else + { + qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; + return false; + } +} + +/*! \overload + + Sets the provided \a layer to be the current layer. + + Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. + + \see addLayer, moveLayer, removeLayer +*/ +bool QCustomPlot::setCurrentLayer(QCPLayer *layer) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + + mCurrentLayer = layer; + return true; +} + +/*! + Returns the number of currently existing layers in the plot + + \see layer, addLayer +*/ +int QCustomPlot::layerCount() const +{ + return mLayers.size(); +} + +/*! + Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which + must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. + + Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a + valid layer inside this QCustomPlot. + + If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. + + For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. + + \see layer, moveLayer, removeLayer +*/ +bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) +{ + if (!otherLayer) + otherLayer = mLayers.last(); + if (!mLayers.contains(otherLayer)) + { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + if (layer(name)) + { + qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; + return false; + } + + QCPLayer *newLayer = new QCPLayer(this, name); + mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); + updateLayerIndices(); + return true; +} + +/*! + Removes the specified \a layer and returns true on success. + + All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below + \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both + cases, the total rendering order of all layerables in the QCustomPlot is preserved. + + If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom + layer) becomes the new current layer. + + It is not possible to remove the last layer of the plot. + + \see layer, addLayer, moveLayer +*/ +bool QCustomPlot::removeLayer(QCPLayer *layer) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (mLayers.size() < 2) + { + qDebug() << Q_FUNC_INFO << "can't remove last layer"; + return false; + } + + // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + int removedIndex = layer->index(); + bool isFirstLayer = removedIndex==0; + QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); + QList children = layer->children(); + if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) + { + for (int i=children.size()-1; i>=0; --i) + children.at(i)->moveToLayer(targetLayer, true); + } else // append normally + { + for (int i=0; imoveToLayer(targetLayer, false); + } + // if removed layer is current layer, change current layer to layer below/above: + if (layer == mCurrentLayer) + setCurrentLayer(targetLayer); + // remove layer: + delete layer; + mLayers.removeOne(layer); + updateLayerIndices(); + return true; +} + +/*! + Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or + below is controlled with \a insertMode. + + Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the + QCustomPlot. + + \see layer, addLayer, moveLayer +*/ +bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (!mLayers.contains(otherLayer)) + { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + + mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); + updateLayerIndices(); + return true; +} + +/*! + Returns the number of axis rects in the plot. + + All axis rects can be accessed via QCustomPlot::axisRect(). + + Initially, only one axis rect exists in the plot. + + \see axisRect, axisRects +*/ +int QCustomPlot::axisRectCount() const +{ + return axisRects().size(); +} + +/*! + Returns the axis rect with \a index. + + Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were + added, all of them may be accessed with this function in a linear fashion (even when they are + nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). + + \see axisRectCount, axisRects +*/ +QCPAxisRect *QCustomPlot::axisRect(int index) const +{ + const QList rectList = axisRects(); + if (index >= 0 && index < rectList.size()) + { + return rectList.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; + return 0; + } +} + +/*! + Returns all axis rects in the plot. + + \see axisRectCount, axisRect +*/ +QList QCustomPlot::axisRects() const +{ + QList result; + QStack elementStack; + if (mPlotLayout) + elementStack.push(mPlotLayout); + + while (!elementStack.isEmpty()) + { + foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) + { + if (element) + { + elementStack.push(element); + if (QCPAxisRect *ar = qobject_cast(element)) + result.append(ar); + } + } + } + + return result; +} + +/*! + Returns the layout element at pixel position \a pos. If there is no element at that position, + returns 0. + + Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on + any of its parent elements is set to false, it will not be considered. + + \see itemAt, plottableAt +*/ +QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const +{ + QCPLayoutElement *currentElement = mPlotLayout; + bool searchSubElements = true; + while (searchSubElements && currentElement) + { + searchSubElements = false; + foreach (QCPLayoutElement *subElement, currentElement->elements(false)) + { + if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) + { + currentElement = subElement; + searchSubElements = true; + break; + } + } + } + return currentElement; +} + +/*! + Returns the axes that currently have selected parts, i.e. whose selection state is not \ref + QCPAxis::spNone. + + \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, + QCPAxis::setSelectableParts +*/ +QList QCustomPlot::selectedAxes() const +{ + QList result, allAxes; + foreach (QCPAxisRect *rect, axisRects()) + allAxes << rect->axes(); + + foreach (QCPAxis *axis, allAxes) + { + if (axis->selectedParts() != QCPAxis::spNone) + result.append(axis); + } + + return result; +} + +/*! + Returns the legends that currently have selected parts, i.e. whose selection state is not \ref + QCPLegend::spNone. + + \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, + QCPLegend::setSelectableParts, QCPLegend::selectedItems +*/ +QList QCustomPlot::selectedLegends() const +{ + QList result; + + QStack elementStack; + if (mPlotLayout) + elementStack.push(mPlotLayout); + + while (!elementStack.isEmpty()) + { + foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) + { + if (subElement) + { + elementStack.push(subElement); + if (QCPLegend *leg = qobject_cast(subElement)) + { + if (leg->selectedParts() != QCPLegend::spNone) + result.append(leg); + } + } + } + } + + return result; +} + +/*! + Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. + + Since calling this function is not a user interaction, this does not emit the \ref + selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the + objects were previously selected. + + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends +*/ +void QCustomPlot::deselectAll() +{ + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *layerable, layer->children()) + layerable->deselectEvent(0); + } +} + +/*! + Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the + buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, + for example on the axis ranges or data points of graphs, visible. + + Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the + QCustomPlot widget and user interactions (object selection and range dragging/zooming). + + Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref + afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two + signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite + recursion. +*/ +void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) +{ + if (mReplotting) // incase signals loop back to replot slot + return; + mReplotting = true; + emit beforeReplot(); + + mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); + QCPPainter painter; + painter.begin(&mPaintBuffer); + if (painter.isActive()) + { + painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) + painter.fillRect(mViewport, mBackgroundBrush); + draw(&painter); + painter.end(); + if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) + repaint(); + else + update(); + } else // might happen if QCustomPlot has width or height zero + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer"; + + emit afterReplot(); + mReplotting = false; +} + +/*! + Rescales the axes such that all plottables (like graphs) in the plot are fully visible. + + if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true + (QCPLayerable::setVisible), will be used to rescale the axes. + + \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale +*/ +void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) +{ + QList allAxes; + foreach (QCPAxisRect *rect, axisRects()) + allAxes << rect->axes(); + + foreach (QCPAxis *axis, allAxes) + axis->rescale(onlyVisiblePlottables); +} + +/*! + Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale + of texts and lines will be derived from the specified \a width and \a height. This means, the + output will look like the normal on-screen output of a QCustomPlot widget with the corresponding + pixel width and height. If either \a width or \a height is zero, the exported image will have the + same dimensions as the QCustomPlot widget currently has. + + \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens + are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what + zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter + and QPen documentation. + + The objects of the plot will appear in the current selection state. If you don't want any + selected objects to be painted in their selected look, deselect everything with \ref deselectAll + before calling this function. + + Returns true on success. + + \warning + \li If you plan on editing the exported PDF file with a vector graphics editor like + Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines + (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). + \li If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting + PDF file. + + \note On Android systems, this method does nothing and issues an according qDebug warning + message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. + + \see savePng, saveBmp, saveJpg, saveRastered +*/ +bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) +{ + bool success = false; +#ifdef QT_NO_PRINTER + Q_UNUSED(fileName) + Q_UNUSED(noCosmeticPen) + Q_UNUSED(width) + Q_UNUSED(height) + qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; +#else + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + + QPrinter printer(QPrinter::ScreenResolution); + printer.setOutputFileName(fileName); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setFullPage(true); + printer.setColorMode(QPrinter::Color); + printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); + printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); + QCPPainter printpainter; + if (printpainter.begin(&printer)) + { + printpainter.setMode(QCPPainter::pmVectorized); + printpainter.setMode(QCPPainter::pmNoCaching); + printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); + printpainter.setWindow(mViewport); + if (mBackgroundBrush.style() != Qt::NoBrush && + mBackgroundBrush.color() != Qt::white && + mBackgroundBrush.color() != Qt::transparent && + mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent + printpainter.fillRect(viewport(), mBackgroundBrush); + draw(&printpainter); + printpainter.end(); + success = true; + } + setViewport(oldViewport); +#endif // QT_NO_PRINTER + return success; +} + +/*! + Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + If you want the PNG to have a transparent background, call \ref setBackground(const QBrush + &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. + + PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or + -1 to use the default setting. + + Returns true on success. If this function fails, most likely the PNG format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, saveBmp, saveJpg, saveRastered +*/ +bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) +{ + return saveRastered(fileName, width, height, scale, "PNG", quality); +} + +/*! + Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or + -1 to use the default setting. + + Returns true on success. If this function fails, most likely the JPG format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, savePng, saveBmp, saveRastered +*/ +bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) +{ + return saveRastered(fileName, width, height, scale, "JPG", quality); +} + +/*! + Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + Returns true on success. If this function fails, most likely the BMP format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, savePng, saveJpg, saveRastered +*/ +bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) +{ + return saveRastered(fileName, width, height, scale, "BMP"); +} + +/*! \internal + + Returns a minimum size hint that corresponds to the minimum size of the top level layout + (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum + size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. + This is especially important, when placed in a QLayout where other components try to take in as + much space as possible (e.g. QMdiArea). +*/ +QSize QCustomPlot::minimumSizeHint() const +{ + return mPlotLayout->minimumSizeHint(); +} + +/*! \internal + + Returns a size hint that is the same as \ref minimumSizeHint. + +*/ +QSize QCustomPlot::sizeHint() const +{ + return mPlotLayout->minimumSizeHint(); +} + +/*! \internal + + Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but + draws the internal buffer on the widget surface. +*/ +void QCustomPlot::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter painter(this); + painter.drawPixmap(0, 0, mPaintBuffer); +} + +/*! \internal + + Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to + the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized + appropriately. Finally a \ref replot is performed. +*/ +void QCustomPlot::resizeEvent(QResizeEvent *event) +{ + // resize and repaint the buffer: + mPaintBuffer = QPixmap(event->size()); + setViewport(rect()); + replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts +} + +/*! \internal + + Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits + the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref + axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to + it. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) +{ + emit mouseDoubleClick(event); + + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); + + // emit specialized object double click signals: + if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) + emit plottableDoubleClick(ap, event); + else if (QCPAxis *ax = qobject_cast(clickedLayerable)) + emit axisDoubleClick(ax, details.value(), event); + else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) + emit itemDoubleClick(ai, event); + else if (QCPLegend *lg = qobject_cast(clickedLayerable)) + emit legendDoubleClick(lg, 0, event); + else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) + emit legendDoubleClick(li->parentLegend(), li, event); + else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) + emit titleDoubleClick(event, pt); + + // call double click event of affected layout element: + if (QCPLayoutElement *el = layoutElementAt(event->pos())) + el->mouseDoubleClickEvent(event); + + // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): + if (mMouseEventElement) + { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. +} + +/*! \internal + + Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines + the affected layout element and forwards the event to it. + + \see mouseMoveEvent, mouseReleaseEvent +*/ +void QCustomPlot::mousePressEvent(QMouseEvent *event) +{ + emit mousePress(event); + mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) + + // call event of affected layout element: + mMouseEventElement = layoutElementAt(event->pos()); + if (mMouseEventElement) + mMouseEventElement->mousePressEvent(event); + + QWidget::mousePressEvent(event); +} + +/*! \internal + + Event handler for when the cursor is moved. Emits the \ref mouseMove signal. + + If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout + element before), the mouseMoveEvent is forwarded to that element. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCustomPlot::mouseMoveEvent(QMouseEvent *event) +{ + emit mouseMove(event); + + // call event of affected layout element: + if (mMouseEventElement) + mMouseEventElement->mouseMoveEvent(event); + + QWidget::mouseMoveEvent(event); +} + +/*! \internal + + Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. + + If the mouse was moved less than a certain threshold in any direction since the \ref + mousePressEvent, it is considered a click which causes the selection mechanism (if activated via + \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse + click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) + + If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout + element before), the \ref mouseReleaseEvent is forwarded to that element. + + \see mousePressEvent, mouseMoveEvent +*/ +void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) +{ + emit mouseRelease(event); + bool doReplot = false; + + if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation + { + if (event->button() == Qt::LeftButton) + { + // handle selection mechanism: + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); + bool selectionStateChanged = false; + bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); + // deselect all other layerables if not additive selection: + if (!additive) + { + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *layerable, layer->children()) + { + if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) + { + bool selChanged = false; + layerable->deselectEvent(&selChanged); + selectionStateChanged |= selChanged; + } + } + } + } + if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) + { + // a layerable was actually clicked, call its selectEvent: + bool selChanged = false; + clickedLayerable->selectEvent(event, additive, details, &selChanged); + selectionStateChanged |= selChanged; + } + doReplot = true; + if (selectionStateChanged) + emit selectionChangedByUser(); + } + + // emit specialized object click signals: + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false + if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) + emit plottableClick(ap, event); + else if (QCPAxis *ax = qobject_cast(clickedLayerable)) + emit axisClick(ax, details.value(), event); + else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) + emit itemClick(ai, event); + else if (QCPLegend *lg = qobject_cast(clickedLayerable)) + emit legendClick(lg, 0, event); + else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) + emit legendClick(li->parentLegend(), li, event); + else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) + emit titleClick(event, pt); + } + + // call event of affected layout element: + if (mMouseEventElement) + { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + if (doReplot || noAntialiasingOnDrag()) + replot(); + + QWidget::mouseReleaseEvent(event); +} + +/*! \internal + + Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then + determines the affected layout element and forwards the event to it. + +*/ +void QCustomPlot::wheelEvent(QWheelEvent *event) +{ + emit mouseWheel(event); + + // call event of affected layout element: + if (QCPLayoutElement *el = layoutElementAt(event->pos())) + el->wheelEvent(event); + + QWidget::wheelEvent(event); +} + +/*! \internal + + This is the main draw function. It draws the entire plot, including background pixmap, with the + specified \a painter. Note that it does not fill the background with the background brush (as the + user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective + functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). +*/ +void QCustomPlot::draw(QCPPainter *painter) +{ + // run through layout phases: + mPlotLayout->update(QCPLayoutElement::upPreparation); + mPlotLayout->update(QCPLayoutElement::upMargins); + mPlotLayout->update(QCPLayoutElement::upLayout); + + // draw viewport background pixmap: + drawBackground(painter); + + // draw all layered objects (grid, axes, plottables, items, legend,...): + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *child, layer->children()) + { + if (child->realVisibility()) + { + painter->save(); + painter->setClipRect(child->clipRect().translated(0, -1)); + child->applyDefaultAntialiasingHint(painter); + child->draw(painter); + painter->restore(); + } + } + } + + /* Debug code to draw all layout element rects + foreach (QCPLayoutElement* el, findChildren()) + { + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->rect()); + painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->outerRect()); + } + */ +} + +/*! \internal + + Draws the viewport background pixmap of the plot. + + If a pixmap was provided via \ref setBackground, this function buffers the scaled version + depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside + the viewport with the provided \a painter. The scaled version is buffered in + mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when + the axis rect has changed in a way that requires a rescale of the background pixmap (this is + dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was + set. + + Note that this function does not draw a fill with the background brush (\ref setBackground(const + QBrush &brush)) beneath the pixmap. + + \see setBackground, setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::drawBackground(QCPPainter *painter) +{ + // Note: background color is handled in individual replot/save functions + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) + { + if (mBackgroundScaled) + { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mViewport.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); + } else + { + painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + } + } +} + + +/*! \internal + + This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot + so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. +*/ +void QCustomPlot::axisRemoved(QCPAxis *axis) +{ + if (xAxis == axis) + xAxis = 0; + if (xAxis2 == axis) + xAxis2 = 0; + if (yAxis == axis) + yAxis = 0; + if (yAxis2 == axis) + yAxis2 = 0; + + // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers +} + +/*! \internal + + This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so + it may clear its QCustomPlot::legend member accordingly. +*/ +void QCustomPlot::legendRemoved(QCPLegend *legend) +{ + if (this->legend == legend) + this->legend = 0; +} + +/*! \internal + + Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called + after every operation that changes the layer indices, like layer removal, layer creation, layer + moving. +*/ +void QCustomPlot::updateLayerIndices() const +{ + for (int i=0; imIndex = i; +} + +/*! \internal + + Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those + layerables that are selectable will be considered. (Layerable subclasses communicate their + selectability via the QCPLayerable::selectTest method, by returning -1.) + + \a selectionDetails is an output parameter that contains selection specifics of the affected + layerable. This is useful if the respective layerable shall be given a subsequent + QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains + information about which part of the layerable was hit, in multi-part layerables (e.g. + QCPAxis::SelectablePart). +*/ +QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const +{ + for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) + { + const QList layerables = mLayers.at(layerIndex)->children(); + double minimumDistance = selectionTolerance()*1.1; + QCPLayerable *minimumDistanceLayerable = 0; + for (int i=layerables.size()-1; i>=0; --i) + { + if (!layerables.at(i)->realVisibility()) + continue; + QVariant details; + double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); + if (dist >= 0 && dist < minimumDistance) + { + minimumDistance = dist; + minimumDistanceLayerable = layerables.at(i); + if (selectionDetails) *selectionDetails = details; + } + } + if (minimumDistance < selectionTolerance()) + return minimumDistanceLayerable; + } + return 0; +} + +/*! + Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is + sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead + to a full resolution file with width 200.) If the \a format supports compression, \a quality may + be between 0 and 100 to control it. + + Returns true on success. If this function fails, most likely the given \a format isn't supported + by the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see saveBmp, saveJpg, savePng, savePdf +*/ +bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) +{ + QPixmap buffer = toPixmap(width, height, scale); + if (!buffer.isNull()) + return buffer.save(fileName, format, quality); + else + return false; +} + +/*! + Renders the plot to a pixmap and returns it. + + The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and + scale 2.0 lead to a full resolution pixmap with width 200.) + + \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf +*/ +QPixmap QCustomPlot::toPixmap(int width, int height, double scale) +{ + // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + int scaledWidth = qRound(scale*newWidth); + int scaledHeight = qRound(scale*newHeight); + + QPixmap result(scaledWidth, scaledHeight); + result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later + QCPPainter painter; + painter.begin(&result); + if (painter.isActive()) + { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter.setMode(QCPPainter::pmNoCaching); + if (!qFuzzyCompare(scale, 1.0)) + { + if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales + painter.setMode(QCPPainter::pmNonCosmetic); + painter.scale(scale, scale); + } + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) + painter.fillRect(mViewport, mBackgroundBrush); + draw(&painter); + setViewport(oldViewport); + painter.end(); + } else // might happen if pixmap has width or height zero + { + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; + return QPixmap(); + } + return result; +} + +/*! + Renders the plot using the passed \a painter. + + The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will + appear scaled accordingly. + + \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter + on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with + the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. + + \see toPixmap +*/ +void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) +{ + // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + + if (painter->isActive()) + { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter->setMode(QCPPainter::pmNoCaching); + // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill + // here, we need to do this via QPainter::fillRect. + if (mBackgroundBrush.style() != Qt::NoBrush) + painter->fillRect(mViewport, mBackgroundBrush); + draw(painter); + setViewport(oldViewport); + } else + qDebug() << Q_FUNC_INFO << "Passed painter is not active"; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorGradient +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorGradient + \brief Defines a color gradient for use with e.g. \ref QCPColorMap + + This class describes a color gradient which can be used to encode data with color. For example, + QCPColorMap and QCPColorScale have a \ref QCPColorMap::setGradient "setGradient" method which + takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) + with a \a position from 0 to 1. In between these defined color positions, the + color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. + + Alternatively, load one of the preset color gradients shown in the image below, with \ref + loadPreset, or by directly specifying the preset in the constructor. + + \image html QCPColorGradient.png + + The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly + converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref + GradientPreset to all the \a setGradient methods, e.g.: + \code + colorMap->setGradient(QCPColorGradient::gpHot); + \endcode + + The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the + color gradient shall be applied periodically (wrapping around) to data values that lie outside + the data range specified on the plottable instance can be controlled with \ref setPeriodic. +*/ + +/*! + Constructs a new QCPColorGradient initialized with the colors and color interpolation according + to \a preset. + + The color level count is initialized to 350. +*/ +QCPColorGradient::QCPColorGradient(GradientPreset preset) : + mLevelCount(350), + mColorInterpolation(ciRGB), + mPeriodic(false), + mColorBufferInvalidated(true) +{ + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + loadPreset(preset); +} + +/* undocumented operator */ +bool QCPColorGradient::operator==(const QCPColorGradient &other) const +{ + return ((other.mLevelCount == this->mLevelCount) && + (other.mColorInterpolation == this->mColorInterpolation) && + (other.mPeriodic == this->mPeriodic) && + (other.mColorStops == this->mColorStops)); +} + +/*! + Sets the number of discretization levels of the color gradient to \a n. The default is 350 which + is typically enough to create a smooth appearance. + + \image html QCPColorGradient-levelcount.png +*/ +void QCPColorGradient::setLevelCount(int n) +{ + if (n < 2) + { + qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; + n = 2; + } + if (n != mLevelCount) + { + mLevelCount = n; + mColorBufferInvalidated = true; + } +} + +/*! + Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the + colors are the values of the passed QMap \a colorStops. In between these color stops, the color + is interpolated according to \ref setColorInterpolation. + + A more convenient way to create a custom gradient may be to clear all color stops with \ref + clearColorStops and then adding them one by one with \ref setColorStopAt. + + \see clearColorStops +*/ +void QCPColorGradient::setColorStops(const QMap &colorStops) +{ + mColorStops = colorStops; + mColorBufferInvalidated = true; +} + +/*! + Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between + these color stops, the color is interpolated according to \ref setColorInterpolation. + + \see setColorStops, clearColorStops +*/ +void QCPColorGradient::setColorStopAt(double position, const QColor &color) +{ + mColorStops.insert(position, color); + mColorBufferInvalidated = true; +} + +/*! + Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be + interpolated linearly in RGB or in HSV color space. + + For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, + whereas in HSV space the intermediate color is yellow. +*/ +void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) +{ + if (interpolation != mColorInterpolation) + { + mColorInterpolation = interpolation; + mColorBufferInvalidated = true; + } +} + +/*! + Sets whether data points that are outside the configured data range (e.g. \ref + QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether + they all have the same color, corresponding to the respective gradient boundary color. + + \image html QCPColorGradient-periodic.png + + As shown in the image above, gradients that have the same start and end color are especially + suitable for a periodic gradient mapping, since they produce smooth color transitions throughout + the color map. A preset that has this property is \ref gpHues. + + In practice, using periodic color gradients makes sense when the data corresponds to a periodic + dimension, such as an angle or a phase. If this is not the case, the color encoding might become + ambiguous, because multiple different data values are shown as the same color. +*/ +void QCPColorGradient::setPeriodic(bool enabled) +{ + mPeriodic = enabled; +} + +/*! + This method is used to quickly convert a \a data array to colors. The colors will be output in + the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this + function. The data range that shall be used for mapping the data value to the gradient is passed + in \a range. \a logarithmic indicates whether the data values shall be mapped to colors + logarithmically. + + if \a data actually contains 2D-data linearized via [row*columnCount + column], you can + set \a dataIndexFactor to columnCount to convert a column instead of a row of the data + array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data + is addressed data[i*dataIndexFactor]. +*/ +void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) +{ + // If you change something here, make sure to also adapt ::color() + if (!data) + { + qDebug() << Q_FUNC_INFO << "null pointer given as data"; + return; + } + if (!scanLine) + { + qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; + return; + } + if (mColorBufferInvalidated) + updateColorBuffer(); + + if (!logarithmic) + { + const double posToIndexFactor = mLevelCount/range.size(); + if (mPeriodic) + { + for (int i=0; i= mLevelCount) + index = mLevelCount-1; + scanLine[i] = mColorBuffer.at(index); + } + } + } else // logarithmic == true + { + if (mPeriodic) + { + for (int i=0; i= mLevelCount) + index = mLevelCount-1; + scanLine[i] = mColorBuffer.at(index); + } + } + } +} + +/*! \internal + + This method is used to colorize a single data value given in \a position, to colors. The data + range that shall be used for mapping the data value to the gradient is passed in \a range. \a + logarithmic indicates whether the data value shall be mapped to a color logarithmically. + + If an entire array of data values shall be converted, rather use \ref colorize, for better + performance. +*/ +QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) +{ + // If you change something here, make sure to also adapt ::colorize() + if (mColorBufferInvalidated) + updateColorBuffer(); + int index = 0; + if (!logarithmic) + index = (position-range.lower)*mLevelCount/range.size(); + else + index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount; + if (mPeriodic) + { + index = index % mLevelCount; + if (index < 0) + index += mLevelCount; + } else + { + if (index < 0) + index = 0; + else if (index >= mLevelCount) + index = mLevelCount-1; + } + return mColorBuffer.at(index); +} + +/*! + Clears the current color stops and loads the specified \a preset. A preset consists of predefined + color stops and the corresponding color interpolation method. + + The available presets are: + \image html QCPColorGradient.png +*/ +void QCPColorGradient::loadPreset(GradientPreset preset) +{ + clearColorStops(); + switch (preset) + { + case gpGrayscale: + setColorInterpolation(ciRGB); + setColorStopAt(0, Qt::black); + setColorStopAt(1, Qt::white); + break; + case gpHot: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 0, 0)); + setColorStopAt(0.2, QColor(180, 10, 0)); + setColorStopAt(0.4, QColor(245, 50, 0)); + setColorStopAt(0.6, QColor(255, 150, 10)); + setColorStopAt(0.8, QColor(255, 255, 50)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpCold: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.2, QColor(0, 10, 180)); + setColorStopAt(0.4, QColor(0, 50, 245)); + setColorStopAt(0.6, QColor(10, 150, 255)); + setColorStopAt(0.8, QColor(50, 255, 255)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpNight: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(10, 20, 30)); + setColorStopAt(1, QColor(250, 255, 250)); + break; + case gpCandy: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(0, 0, 255)); + setColorStopAt(1, QColor(255, 250, 250)); + break; + case gpGeography: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(70, 170, 210)); + setColorStopAt(0.20, QColor(90, 160, 180)); + setColorStopAt(0.25, QColor(45, 130, 175)); + setColorStopAt(0.30, QColor(100, 140, 125)); + setColorStopAt(0.5, QColor(100, 140, 100)); + setColorStopAt(0.6, QColor(130, 145, 120)); + setColorStopAt(0.7, QColor(140, 130, 120)); + setColorStopAt(0.9, QColor(180, 190, 190)); + setColorStopAt(1, QColor(210, 210, 230)); + break; + case gpIon: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 10, 10)); + setColorStopAt(0.45, QColor(0, 0, 255)); + setColorStopAt(0.8, QColor(0, 255, 255)); + setColorStopAt(1, QColor(0, 255, 0)); + break; + case gpThermal: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.15, QColor(20, 0, 120)); + setColorStopAt(0.33, QColor(200, 30, 140)); + setColorStopAt(0.6, QColor(255, 100, 0)); + setColorStopAt(0.85, QColor(255, 255, 40)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpPolar: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 255, 255)); + setColorStopAt(0.18, QColor(10, 70, 255)); + setColorStopAt(0.28, QColor(10, 10, 190)); + setColorStopAt(0.5, QColor(0, 0, 0)); + setColorStopAt(0.72, QColor(190, 10, 10)); + setColorStopAt(0.82, QColor(255, 70, 10)); + setColorStopAt(1, QColor(255, 255, 50)); + break; + case gpSpectrum: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 0, 50)); + setColorStopAt(0.15, QColor(0, 0, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.6, QColor(255, 255, 0)); + setColorStopAt(0.75, QColor(255, 30, 0)); + setColorStopAt(1, QColor(50, 0, 0)); + break; + case gpJet: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 100)); + setColorStopAt(0.15, QColor(0, 50, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.65, QColor(255, 255, 0)); + setColorStopAt(0.85, QColor(255, 30, 0)); + setColorStopAt(1, QColor(100, 0, 0)); + break; + case gpHues: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(255, 0, 0)); + setColorStopAt(1.0/3.0, QColor(0, 0, 255)); + setColorStopAt(2.0/3.0, QColor(0, 255, 0)); + setColorStopAt(1, QColor(255, 0, 0)); + break; + } +} + +/*! + Clears all color stops. + + \see setColorStops, setColorStopAt +*/ +void QCPColorGradient::clearColorStops() +{ + mColorStops.clear(); + mColorBufferInvalidated = true; +} + +/*! + Returns an inverted gradient. The inverted gradient has all properties as this \ref + QCPColorGradient, but the order of the color stops is inverted. + + \see setColorStops, setColorStopAt +*/ +QCPColorGradient QCPColorGradient::inverted() const +{ + QCPColorGradient result(*this); + result.clearColorStops(); + for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) + result.setColorStopAt(1.0-it.key(), it.value()); + return result; +} + +/*! \internal + + Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly + convert positions to colors. This is where the interpolation between color stops is calculated. +*/ +void QCPColorGradient::updateColorBuffer() +{ + if (mColorBuffer.size() != mLevelCount) + mColorBuffer.resize(mLevelCount); + if (mColorStops.size() > 1) + { + double indexToPosFactor = 1.0/(double)(mLevelCount-1); + for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); + if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop + { + mColorBuffer[i] = (it-1).value().rgb(); + } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop + { + mColorBuffer[i] = it.value().rgb(); + } else // position is in between stops (or on an intermediate stop), interpolate color + { + QMap::const_iterator high = it; + QMap::const_iterator low = it-1; + double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 + switch (mColorInterpolation) + { + case ciRGB: + { + mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), + (1-t)*low.value().green() + t*high.value().green(), + (1-t)*low.value().blue() + t*high.value().blue()); + break; + } + case ciHSV: + { + QColor lowHsv = low.value().toHsv(); + QColor highHsv = high.value().toHsv(); + double hue = 0; + double hueDiff = highHsv.hueF()-lowHsv.hueF(); + if (hueDiff > 0.5) + hue = lowHsv.hueF() - t*(1.0-hueDiff); + else if (hueDiff < -0.5) + hue = lowHsv.hueF() + t*(1.0+hueDiff); + else + hue = lowHsv.hueF() + t*hueDiff; + if (hue < 0) hue += 1.0; + else if (hue >= 1.0) hue -= 1.0; + mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); + break; + } + } + } + } + } else if (mColorStops.size() == 1) + { + mColorBuffer.fill(mColorStops.constBegin().value().rgb()); + } else // mColorStops is empty, fill color buffer with black + { + mColorBuffer.fill(qRgb(0, 0, 0)); + } + mColorBufferInvalidated = false; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxisRect +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxisRect + \brief Holds multiple axes and arranges them in a rectangular shape. + + This class represents an axis rect, a rectangular area that is bounded on all sides with an + arbitrary number of axes. + + Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the + layout system allows to have multiple axis rects, e.g. arranged in a grid layout + (QCustomPlot::plotLayout). + + By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be + accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. + If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be + invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref + addAxes. To remove an axis, use \ref removeAxis. + + The axis rect layerable itself only draws a background pixmap or color, if specified (\ref + setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an + explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be + placed on other layers, independently of the axis rect. + + Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref + insetLayout and can be used to have other layout elements (or even other layouts with multiple + elements) hovering inside the axis rect. + + If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The + behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel + is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable + via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are + only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref + QCP::iRangeZoom. + + \image html AxisRectSpacingOverview.png +
                  Overview of the spacings and paddings that define the geometry of an axis. The dashed + line on the far left indicates the viewport/widget border.
                  +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const + + Returns the inset layout of this axis rect. It can be used to place other layout elements (or + even layouts with multiple other elements) inside/on top of an axis rect. + + \see QCPLayoutInset +*/ + +/*! \fn int QCPAxisRect::left() const + + Returns the pixel position of the left border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::right() const + + Returns the pixel position of the right border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::top() const + + Returns the pixel position of the top border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::bottom() const + + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::width() const + + Returns the pixel width of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::height() const + + Returns the pixel height of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QSize QCPAxisRect::size() const + + Returns the pixel size of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::topLeft() const + + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, + so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::topRight() const + + Returns the top right corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::bottomLeft() const + + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::bottomRight() const + + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::center() const + + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four + sides, the top and right axes are set invisible initially. +*/ +QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(Qt::Horizontal|Qt::Vertical), + mRangeZoom(Qt::Horizontal|Qt::Vertical), + mRangeZoomFactorHorz(0.85), + mRangeZoomFactorVert(0.85), + mDragging(false) +{ + mInsetLayout->initializeParentPlot(mParentPlot); + mInsetLayout->setParentLayerable(this); + mInsetLayout->setParent(this); + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(15, 15, 15, 15)); + mAxes.insert(QCPAxis::atLeft, QList()); + mAxes.insert(QCPAxis::atRight, QList()); + mAxes.insert(QCPAxis::atTop, QList()); + mAxes.insert(QCPAxis::atBottom, QList()); + + if (setupDefaultAxes) + { + QCPAxis *xAxis = addAxis(QCPAxis::atBottom); + QCPAxis *yAxis = addAxis(QCPAxis::atLeft); + QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); + QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); + setRangeDragAxes(xAxis, yAxis); + setRangeZoomAxes(xAxis, yAxis); + xAxis2->setVisible(false); + yAxis2->setVisible(false); + xAxis->grid()->setVisible(true); + yAxis->grid()->setVisible(true); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + xAxis2->grid()->setZeroLinePen(Qt::NoPen); + yAxis2->grid()->setZeroLinePen(Qt::NoPen); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + } +} + +QCPAxisRect::~QCPAxisRect() +{ + delete mInsetLayout; + mInsetLayout = 0; + + QList axesList = axes(); + for (int i=0; i ax(mAxes.value(type)); + if (index >= 0 && index < ax.size()) + { + return ax.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return 0; + } +} + +/*! + Returns all axes on the axis rect sides specified with \a types. + + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of + multiple sides. + + \see axis +*/ +QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const +{ + QList result; + if (types.testFlag(QCPAxis::atLeft)) + result << mAxes.value(QCPAxis::atLeft); + if (types.testFlag(QCPAxis::atRight)) + result << mAxes.value(QCPAxis::atRight); + if (types.testFlag(QCPAxis::atTop)) + result << mAxes.value(QCPAxis::atTop); + if (types.testFlag(QCPAxis::atBottom)) + result << mAxes.value(QCPAxis::atBottom); + return result; +} + +/*! \overload + + Returns all axes of this axis rect. +*/ +QList QCPAxisRect::axes() const +{ + QList result; + QHashIterator > it(mAxes); + while (it.hasNext()) + { + it.next(); + result << it.value(); + } + return result; +} + +/*! + Adds a new axis to the axis rect side specified with \a type, and returns it. + + If an axis rect side already contains one or more axes, the lower and upper endings of the new + axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref + QCPLineEnding::esHalfBar. + + \see addAxes, setupFullAxesBox +*/ +QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type) +{ + QCPAxis *newAxis = new QCPAxis(this, type); + if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset + { + bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); + newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); + newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); + } + mAxes[type].append(newAxis); + return newAxis; +} + +/*! + Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an + or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. + + Returns a list of the added axes. + + \see addAxis, setupFullAxesBox +*/ +QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) +{ + QList result; + if (types.testFlag(QCPAxis::atLeft)) + result << addAxis(QCPAxis::atLeft); + if (types.testFlag(QCPAxis::atRight)) + result << addAxis(QCPAxis::atRight); + if (types.testFlag(QCPAxis::atTop)) + result << addAxis(QCPAxis::atTop); + if (types.testFlag(QCPAxis::atBottom)) + result << addAxis(QCPAxis::atBottom); + return result; +} + +/*! + Removes the specified \a axis from the axis rect and deletes it. + + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. + + \see addAxis +*/ +bool QCPAxisRect::removeAxis(QCPAxis *axis) +{ + // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: + QHashIterator > it(mAxes); + while (it.hasNext()) + { + it.next(); + if (it.value().contains(axis)) + { + mAxes[it.key()].removeOne(axis); + if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) + parentPlot()->axisRemoved(axis); + delete axis; + return true; + } + } + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); + return false; +} + +/*! + Convenience function to create an axis on each side that doesn't have any axes yet and set their + visibility to true. Further, the top/right axes are assigned the following properties of the + bottom/left axes: + + \li range (\ref QCPAxis::setRange) + \li range reversed (\ref QCPAxis::setRangeReversed) + \li scale type (\ref QCPAxis::setScaleType) + \li scale log base (\ref QCPAxis::setScaleLogBase) + \li ticks (\ref QCPAxis::setTicks) + \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) + \li sub tick count (\ref QCPAxis::setSubTickCount) + \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) + \li tick step (\ref QCPAxis::setTickStep) + \li auto tick step (\ref QCPAxis::setAutoTickStep) + \li number format (\ref QCPAxis::setNumberFormat) + \li number precision (\ref QCPAxis::setNumberPrecision) + \li tick label type (\ref QCPAxis::setTickLabelType) + \li date time format (\ref QCPAxis::setDateTimeFormat) + \li date time spec (\ref QCPAxis::setDateTimeSpec) + + Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. + + If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom + and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. +*/ +void QCPAxisRect::setupFullAxesBox(bool connectRanges) +{ + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + if (axisCount(QCPAxis::atBottom) == 0) + xAxis = addAxis(QCPAxis::atBottom); + else + xAxis = axis(QCPAxis::atBottom); + + if (axisCount(QCPAxis::atLeft) == 0) + yAxis = addAxis(QCPAxis::atLeft); + else + yAxis = axis(QCPAxis::atLeft); + + if (axisCount(QCPAxis::atTop) == 0) + xAxis2 = addAxis(QCPAxis::atTop); + else + xAxis2 = axis(QCPAxis::atTop); + + if (axisCount(QCPAxis::atRight) == 0) + yAxis2 = addAxis(QCPAxis::atRight); + else + yAxis2 = axis(QCPAxis::atRight); + + xAxis->setVisible(true); + yAxis->setVisible(true); + xAxis2->setVisible(true); + yAxis2->setVisible(true); + xAxis2->setTickLabels(false); + yAxis2->setTickLabels(false); + + xAxis2->setRange(xAxis->range()); + xAxis2->setRangeReversed(xAxis->rangeReversed()); + xAxis2->setScaleType(xAxis->scaleType()); + xAxis2->setScaleLogBase(xAxis->scaleLogBase()); + xAxis2->setTicks(xAxis->ticks()); + xAxis2->setAutoTickCount(xAxis->autoTickCount()); + xAxis2->setSubTickCount(xAxis->subTickCount()); + xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); + xAxis2->setTickStep(xAxis->tickStep()); + xAxis2->setAutoTickStep(xAxis->autoTickStep()); + xAxis2->setNumberFormat(xAxis->numberFormat()); + xAxis2->setNumberPrecision(xAxis->numberPrecision()); + xAxis2->setTickLabelType(xAxis->tickLabelType()); + xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); + xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); + + yAxis2->setRange(yAxis->range()); + yAxis2->setRangeReversed(yAxis->rangeReversed()); + yAxis2->setScaleType(yAxis->scaleType()); + yAxis2->setScaleLogBase(yAxis->scaleLogBase()); + yAxis2->setTicks(yAxis->ticks()); + yAxis2->setAutoTickCount(yAxis->autoTickCount()); + yAxis2->setSubTickCount(yAxis->subTickCount()); + yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); + yAxis2->setTickStep(yAxis->tickStep()); + yAxis2->setAutoTickStep(yAxis->autoTickStep()); + yAxis2->setNumberFormat(yAxis->numberFormat()); + yAxis2->setNumberPrecision(yAxis->numberPrecision()); + yAxis2->setTickLabelType(yAxis->tickLabelType()); + yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); + yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); + + if (connectRanges) + { + connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); + connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); + } +} + +/*! + Returns a list of all the plottables that are associated with this axis rect. + + A plottable is considered associated with an axis rect if its key or value axis (or both) is in + this axis rect. + + \see graphs, items +*/ +QList QCPAxisRect::plottables() const +{ + // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries + QList result; + for (int i=0; imPlottables.size(); ++i) + { + if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) + result.append(mParentPlot->mPlottables.at(i)); + } + return result; +} + +/*! + Returns a list of all the graphs that are associated with this axis rect. + + A graph is considered associated with an axis rect if its key or value axis (or both) is in + this axis rect. + + \see plottables, items +*/ +QList QCPAxisRect::graphs() const +{ + // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries + QList result; + for (int i=0; imGraphs.size(); ++i) + { + if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) + result.append(mParentPlot->mGraphs.at(i)); + } + return result; +} + +/*! + Returns a list of all the items that are associated with this axis rect. + + An item is considered associated with an axis rect if any of its positions has key or value axis + set to an axis that is in this axis rect, or if any of its positions has \ref + QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref + QCPAbstractItem::setClipAxisRect) is set to this axis rect. + + \see plottables, graphs +*/ +QList QCPAxisRect::items() const +{ + // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries + // and miss those items that have this axis rect as clipAxisRect. + QList result; + for (int itemId=0; itemIdmItems.size(); ++itemId) + { + if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + continue; + } + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId=0; posIdaxisRect() == this || + positions.at(posId)->keyAxis()->axisRect() == this || + positions.at(posId)->valueAxis()->axisRect() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; +} + +/*! + This method is called automatically upon replot and doesn't need to be called by users of + QCPAxisRect. + + Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), + and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its + QCPInsetLayout::update function. +*/ +void QCPAxisRect::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + + switch (phase) + { + case upPreparation: + { + QList allAxes = axes(); + for (int i=0; isetupTickVectors(); + break; + } + case upLayout: + { + mInsetLayout->setOuterRect(rect()); + break; + } + default: break; + } + + // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): + mInsetLayout->update(phase); +} + +/* inherits documentation from base class */ +QList QCPAxisRect::elements(bool recursive) const +{ + QList result; + if (mInsetLayout) + { + result << mInsetLayout; + if (recursive) + result << mInsetLayout->elements(recursive); + } + return result; +} + +/* inherits documentation from base class */ +void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + painter->setAntialiasing(false); +} + +/* inherits documentation from base class */ +void QCPAxisRect::draw(QCPPainter *painter) +{ + drawBackground(painter); +} + +/*! + Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the + axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect + backgrounds are usually drawn below everything else. + + For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be + enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio + is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, + consider using the overloaded version of this function. + + Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref + setBackground(const QBrush &brush). + + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) +*/ +void QCPAxisRect::setBackground(const QPixmap &pm) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); +} + +/*! \overload + + Sets \a brush as the background brush. The axis rect background will be filled with this brush. + Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds + are usually drawn below everything else. + + The brush will be drawn before (under) any background pixmap, which may be specified with \ref + setBackground(const QPixmap &pm). + + To disable drawing of a background brush, set \a brush to Qt::NoBrush. + + \see setBackground(const QPixmap &pm) +*/ +void QCPAxisRect::setBackground(const QBrush &brush) +{ + mBackgroundBrush = brush; +} + +/*! \overload + + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it + shall be scaled in one call. + + \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode +*/ +void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; +} + +/*! + Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled + is set to true, you may control whether and how the aspect ratio of the original pixmap is + preserved with \ref setBackgroundScaledMode. + + Note that the scaled version of the original pixmap is buffered, so there is no performance + penalty on replots. (Except when the axis rect dimensions are changed continuously.) + + \see setBackground, setBackgroundScaledMode +*/ +void QCPAxisRect::setBackgroundScaled(bool scaled) +{ + mBackgroundScaled = scaled; +} + +/*! + If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to + define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. + \see setBackground, setBackgroundScaled +*/ +void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) +{ + mBackgroundScaledMode = mode; +} + +/*! + Returns the range drag axis of the \a orientation provided. + + \see setRangeDragAxes +*/ +QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); +} + +/*! + Returns the range zoom axis of the \a orientation provided. + + \see setRangeZoomAxes +*/ +QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); +} + +/*! + Returns the range zoom factor of the \a orientation provided. + + \see setRangeZoomFactor +*/ +double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); +} + +/*! + Sets which axis orientation may be range dragged by the user with mouse interaction. + What orientation corresponds to which specific axis can be set with + \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By + default, the horizontal axis is the bottom axis (xAxis) and the vertical axis + is the left axis (yAxis). + + To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref + QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | + Qt::Vertical as \a orientations. + + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions + contains \ref QCP::iRangeDrag to enable the range dragging interaction. + + \see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag +*/ +void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) +{ + mRangeDrag = orientations; +} + +/*! + Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation + corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, + QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical + axis is the left axis (yAxis). + + To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref + QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | + Qt::Vertical as \a orientations. + + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions + contains \ref QCP::iRangeZoom to enable the range zooming interaction. + + \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag +*/ +void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) +{ + mRangeZoom = orientations; +} + +/*! + Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging + on the QCustomPlot widget. + + \see setRangeZoomAxes +*/ +void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) +{ + mRangeDragHorzAxis = horizontal; + mRangeDragVertAxis = vertical; +} + +/*! + Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the + QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors + are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). + + \see setRangeDragAxes +*/ +void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) +{ + mRangeZoomHorzAxis = horizontal; + mRangeZoomVertAxis = vertical; +} + +/*! + Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with + \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to + let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal + and which is vertical, can be set with \ref setRangeZoomAxes. + + When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) + will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the + same scrolling direction will zoom out. +*/ +void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) +{ + mRangeZoomFactorHorz = horizontalFactor; + mRangeZoomFactorVert = verticalFactor; +} + +/*! \overload + + Sets both the horizontal and vertical zoom \a factor. +*/ +void QCPAxisRect::setRangeZoomFactor(double factor) +{ + mRangeZoomFactorHorz = factor; + mRangeZoomFactorVert = factor; +} + +/*! \internal + + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a + pixmap. + + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an + according filling inside the axis rect with the provided \a painter. + + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version + depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside + the axis rect with the provided \a painter. The scaled version is buffered in + mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when + the axis rect has changed in a way that requires a rescale of the background pixmap (this is + dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was + set. + + \see setBackground, setBackgroundScaled, setBackgroundScaledMode +*/ +void QCPAxisRect::drawBackground(QCPPainter *painter) +{ + // draw background fill: + if (mBackgroundBrush != Qt::NoBrush) + painter->fillRect(mRect, mBackgroundBrush); + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) + { + if (mBackgroundScaled) + { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else + { + painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } + } +} + +/*! \internal + + This function makes sure multiple axes on the side specified with \a type don't collide, but are + distributed according to their respective space requirement (QCPAxis::calculateMargin). + + It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the + one with index zero. + + This function is called by \ref calculateAutoMargin. +*/ +void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) +{ + const QList axesList = mAxes.value(type); + if (axesList.isEmpty()) + return; + + bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false + for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); + if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) + { + if (!isFirstVisible) + offset += axesList.at(i)->tickLengthIn(); + isFirstVisible = false; + } + axesList.at(i)->setOffset(offset); + } +} + +/* inherits documentation from base class */ +int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) +{ + if (!mAutoMargins.testFlag(side)) + qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; + + updateAxesOffset(QCPAxis::marginSideToAxisType(side)); + + // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); + if (axesList.size() > 0) + return axesList.last()->offset() + axesList.last()->calculateMargin(); + else + return 0; +} + +/*! \internal + + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is + pressed, the range dragging interaction is initialized (the actual range manipulation happens in + the \ref mouseMoveEvent). + + The mDragging flag is set to true and some anchor points are set that are needed to determine the + distance the mouse was dragged in the mouse move/release events later. + + \see mouseMoveEvent, mouseReleaseEvent +*/ +void QCPAxisRect::mousePressEvent(QMouseEvent *event) +{ + mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) + if (event->buttons() & Qt::LeftButton) + { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) + { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + { + if (mRangeDragHorzAxis) + mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); + if (mRangeDragVertAxis) + mDragStartVertRange = mRangeDragVertAxis.data()->range(); + } + } +} + +/*! \internal + + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a + preceding \ref mousePressEvent, the range is moved accordingly. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) +{ + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + { + if (mRangeDrag.testFlag(Qt::Horizontal)) + { + if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) + { + if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) + { + double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); + rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); + } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) + { + double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); + rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); + } + } + } + if (mRangeDrag.testFlag(Qt::Vertical)) + { + if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) + { + if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) + { + double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); + rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); + } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) + { + double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); + rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); + } + } + } + if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot + { + if (mParentPlot->noAntialiasingOnDrag()) + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + mParentPlot->replot(); + } + } +} + +/* inherits documentation from base class */ +void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) +{ + Q_UNUSED(event) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) + { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } +} + +/*! \internal + + Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the + ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of + the scaling operation is the current cursor position inside the axis rect. The scaling factor is + dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural + zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. + + Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse + wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be + multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as + exponent of the range zoom factor. This takes care of the wheel direction automatically, by + inverting the factor, when the wheel step is negative (f^-1 = 1/f). +*/ +void QCPAxisRect::wheelEvent(QWheelEvent *event) +{ + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) + { + if (mRangeZoom != 0) + { + double factor; + double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually + if (mRangeZoom.testFlag(Qt::Horizontal)) + { + factor = pow(mRangeZoomFactorHorz, wheelSteps); + if (mRangeZoomHorzAxis.data()) + mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); + } + if (mRangeZoom.testFlag(Qt::Vertical)) + { + factor = pow(mRangeZoomFactorVert, wheelSteps); + if (mRangeZoomVertAxis.data()) + mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); + } + mParentPlot->replot(); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractLegendItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractLegendItem + \brief The abstract base class for all entries in a QCPLegend. + + It defines a very basic interface for entries in a QCPLegend. For representing plottables in the + legend, the subclass \ref QCPPlottableLegendItem is more suitable. + + Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry + that's not even associated with a plottable). + + You must implement the following pure virtual functions: + \li \ref draw (from QCPLayerable) + + You inherit the following members you may use: + + + + + + + + +
                  QCPLegend *\b mParentLegendA pointer to the parent QCPLegend.
                  QFont \b mFontThe generic font of the item. You should use this font for all or at least the most prominent text of the item.
                  +*/ + +/* start of documentation of signals */ + +/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) + + This signal is emitted when the selection state of this legend item has changed, either by user + interaction or by a direct call to \ref setSelected. +*/ + +/* end of documentation of signals */ + +/*! + Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not + cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. +*/ +QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : + QCPLayoutElement(parent->parentPlot()), + mParentLegend(parent), + mFont(parent->font()), + mTextColor(parent->textColor()), + mSelectedFont(parent->selectedFont()), + mSelectedTextColor(parent->selectedTextColor()), + mSelectable(true), + mSelected(false) +{ + setLayer("legend"); + setMargins(QMargins(8, 2, 8, 2)); +} + +/*! + Sets the default font of this specific legend item to \a font. + + \see setTextColor, QCPLegend::setFont +*/ +void QCPAbstractLegendItem::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the default text color of this specific legend item to \a color. + + \see setFont, QCPLegend::setTextColor +*/ +void QCPAbstractLegendItem::setTextColor(const QColor &color) +{ + mTextColor = color; +} + +/*! + When this legend item is selected, \a font is used to draw generic text, instead of the normal + font set with \ref setFont. + + \see setFont, QCPLegend::setSelectedFont +*/ +void QCPAbstractLegendItem::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + When this legend item is selected, \a color is used to draw generic text, instead of the normal + color set with \ref setTextColor. + + \see setTextColor, QCPLegend::setSelectedTextColor +*/ +void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; +} + +/*! + Sets whether this specific legend item is selectable. + + \see setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAbstractLegendItem::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this specific legend item is selected. + + It is possible to set the selection state of this item by calling this function directly, even if + setSelectable is set to false. + + \see setSelectableParts, QCustomPlot::setInteractions +*/ +void QCPAbstractLegendItem::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/* inherits documentation from base class */ +double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (!mParentPlot) return -1; + if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) + return -1; + + if (mRect.contains(pos.toPoint())) + return mParentPlot->selectionTolerance()*0.99; + else + return -1; +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); +} + +/* inherits documentation from base class */ +QRect QCPAbstractLegendItem::clipRect() const +{ + return mOuterRect; +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPlottableLegendItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPlottableLegendItem + \brief A legend item representing a plottable with an icon and the plottable name. + + This is the standard legend item for plottables. It displays an icon of the plottable next to the + plottable name. The icon is drawn by the respective plottable itself (\ref + QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. + For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the + middle. + + Legend items of this type are always associated with one plottable (retrievable via the + plottable() function and settable with the constructor). You may change the font of the plottable + name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref + QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. + + The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend + creates/removes legend items of this type in the default implementation. However, these functions + may be reimplemented such that a different kind of legend item (e.g a direct subclass of + QCPAbstractLegendItem) is used for that plottable. + + Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of + QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout + interface, QCPLegend has specialized functions for handling legend items conveniently, see the + documentation of \ref QCPLegend. +*/ + +/*! + Creates a new legend item associated with \a plottable. + + Once it's created, it can be added to the legend via \ref QCPLegend::addItem. + + A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref + QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. +*/ +QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : + QCPAbstractLegendItem(parent), + mPlottable(plottable) +{ +} + +/*! \internal + + Returns the pen that shall be used to draw the icon border, taking into account the selection + state of this item. +*/ +QPen QCPPlottableLegendItem::getIconBorderPen() const +{ + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); +} + +/*! \internal + + Returns the text color that shall be used to draw text, taking into account the selection state + of this item. +*/ +QColor QCPPlottableLegendItem::getTextColor() const +{ + return mSelected ? mSelectedTextColor : mTextColor; +} + +/*! \internal + + Returns the font that shall be used to draw text, taking into account the selection state of this + item. +*/ +QFont QCPPlottableLegendItem::getFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Draws the item with \a painter. The size and position of the drawn legend item is defined by the + parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint + of this legend item. +*/ +void QCPPlottableLegendItem::draw(QCPPainter *painter) +{ + if (!mPlottable) return; + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSizeF iconSize = mParentLegend->iconSize(); + QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + QRectF iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPlottable->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) + { + painter->setPen(getIconBorderPen()); + painter->setBrush(Qt::NoBrush); + painter->drawRect(iconRect); + } +} + +/*! \internal + + Calculates and returns the size of this item. This includes the icon, the text and the padding in + between. +*/ +QSize QCPPlottableLegendItem::minimumSizeHint() const +{ + if (!mPlottable) return QSize(); + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); + result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); + return result; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLegend +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLegend + \brief Manages a legend inside a QCustomPlot. + + A legend is a small box somewhere in the plot which lists plottables with their name and icon. + + Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The + respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, + QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref + itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. + + The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a + QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are + placed in the grid layout of the legend. QCPLegend only adds an interface specialized for + handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any + other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. + However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will + only return the number of items with QCPAbstractLegendItems type). + + By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset + layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another + position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend + outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. +*/ + +/* start of documentation of signals */ + +/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); + + This signal is emitted when the selection state of this legend has changed. + + \see setSelectedParts, setSelectableParts +*/ + +/* end of documentation of signals */ + +/*! + Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. + + Note that by default, QCustomPlot already contains a legend ready to be used as + QCustomPlot::legend +*/ +QCPLegend::QCPLegend() +{ + setRowSpacing(0); + setColumnSpacing(10); + setMargins(QMargins(2, 3, 2, 2)); + setAntialiased(false); + setIconSize(32, 18); + + setIconTextPadding(7); + + setSelectableParts(spLegendBox | spItems); + setSelectedParts(spNone); + + setBorderPen(QPen(Qt::black)); + setSelectedBorderPen(QPen(Qt::blue, 2)); + setIconBorderPen(Qt::NoPen); + setSelectedIconBorderPen(QPen(Qt::blue, 2)); + setBrush(Qt::white); + setSelectedBrush(Qt::white); + setTextColor(Qt::black); + setSelectedTextColor(Qt::blue); +} + +QCPLegend::~QCPLegend() +{ + clearItems(); + if (mParentPlot) + mParentPlot->legendRemoved(this); +} + +/* no doc for getter, see setSelectedParts */ +QCPLegend::SelectableParts QCPLegend::selectedParts() const +{ + // check whether any legend elements selected, if yes, add spItems to return value + bool hasSelectedItems = false; + for (int i=0; iselected()) + { + hasSelectedItems = true; + break; + } + } + if (hasSelectedItems) + return mSelectedParts | spItems; + else + return mSelectedParts & ~spItems; +} + +/*! + Sets the pen, the border of the entire legend is drawn with. +*/ +void QCPLegend::setBorderPen(const QPen &pen) +{ + mBorderPen = pen; +} + +/*! + Sets the brush of the legend background. +*/ +void QCPLegend::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will + use this font by default. However, a different font can be specified on a per-item-basis by + accessing the specific legend item. + + This function will also set \a font on all already existing legend items. + + \see QCPAbstractLegendItem::setFont +*/ +void QCPLegend::setFont(const QFont &font) +{ + mFont = font; + for (int i=0; isetFont(mFont); + } +} + +/*! + Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) + will use this color by default. However, a different colors can be specified on a per-item-basis + by accessing the specific legend item. + + This function will also set \a color on all already existing legend items. + + \see QCPAbstractLegendItem::setTextColor +*/ +void QCPLegend::setTextColor(const QColor &color) +{ + mTextColor = color; + for (int i=0; isetTextColor(color); + } +} + +/*! + Sets the size of legend icons. Legend items that draw an icon (e.g. a visual + representation of the graph) will use this size by default. +*/ +void QCPLegend::setIconSize(const QSize &size) +{ + mIconSize = size; +} + +/*! \overload +*/ +void QCPLegend::setIconSize(int width, int height) +{ + mIconSize.setWidth(width); + mIconSize.setHeight(height); +} + +/*! + Sets the horizontal space in pixels between the legend icon and the text next to it. + Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the + name of the graph) will use this space by default. +*/ +void QCPLegend::setIconTextPadding(int padding) +{ + mIconTextPadding = padding; +} + +/*! + Sets the pen used to draw a border around each legend icon. Legend items that draw an + icon (e.g. a visual representation of the graph) will use this pen by default. + + If no border is wanted, set this to \a Qt::NoPen. +*/ +void QCPLegend::setIconBorderPen(const QPen &pen) +{ + mIconBorderPen = pen; +} + +/*! + Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) + + However, even when \a selectable is set to a value not allowing the selection of a specific part, + it is still possible to set the selection of this part manually, by calling \ref setSelectedParts + directly. + + \see SelectablePart, setSelectedParts +*/ +void QCPLegend::setSelectableParts(const SelectableParts &selectable) +{ + if (mSelectableParts != selectable) + { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } +} + +/*! + Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part + is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected + doesn't contain \ref spItems, those items become deselected. + + The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions + contains iSelectLegend. You only need to call this function when you wish to change the selection + state manually. + + This function can change the selection state of a part even when \ref setSelectableParts was set to a + value that actually excludes the part. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set + before, because there's no way to specify which exact items to newly select. Do this by calling + \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. + + \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, + setSelectedFont +*/ +void QCPLegend::setSelectedParts(const SelectableParts &selected) +{ + SelectableParts newSelected = selected; + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + + if (mSelectedParts != newSelected) + { + if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) + { + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; + newSelected &= ~spItems; + } + if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection + { + for (int i=0; isetSelected(false); + } + } + mSelectedParts = newSelected; + emit selectionChanged(mSelectedParts); + } +} + +/*! + When the legend box is selected, this pen is used to draw the border instead of the normal pen + set via \ref setBorderPen. + + \see setSelectedParts, setSelectableParts, setSelectedBrush +*/ +void QCPLegend::setSelectedBorderPen(const QPen &pen) +{ + mSelectedBorderPen = pen; +} + +/*! + Sets the pen legend items will use to draw their icon borders, when they are selected. + + \see setSelectedParts, setSelectableParts, setSelectedFont +*/ +void QCPLegend::setSelectedIconBorderPen(const QPen &pen) +{ + mSelectedIconBorderPen = pen; +} + +/*! + When the legend box is selected, this brush is used to draw the legend background instead of the normal brush + set via \ref setBrush. + + \see setSelectedParts, setSelectableParts, setSelectedBorderPen +*/ +void QCPLegend::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the default font that is used by legend items when they are selected. + + This function will also set \a font on all already existing legend items. + + \see setFont, QCPAbstractLegendItem::setSelectedFont +*/ +void QCPLegend::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; + for (int i=0; isetSelectedFont(font); + } +} + +/*! + Sets the default text color that is used by legend items when they are selected. + + This function will also set \a color on all already existing legend items. + + \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor +*/ +void QCPLegend::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; + for (int i=0; isetSelectedTextColor(color); + } +} + +/*! + Returns the item with index \a i. + + \see itemCount +*/ +QCPAbstractLegendItem *QCPLegend::item(int index) const +{ + return qobject_cast(elementAt(index)); +} + +/*! + Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + If such an item isn't in the legend, returns 0. + + \see hasItemWithPlottable +*/ +QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const +{ + for (int i=0; i(item(i))) + { + if (pli->plottable() == plottable) + return pli; + } + } + return 0; +} + +/*! + Returns the number of items currently in the legend. + \see item +*/ +int QCPLegend::itemCount() const +{ + return elementCount(); +} + +/*! + Returns whether the legend contains \a itm. +*/ +bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const +{ + for (int i=0; iitem(i)) + return true; + } + return false; +} + +/*! + Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + If such an item isn't in the legend, returns false. + + \see itemWithPlottable +*/ +bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const +{ + return itemWithPlottable(plottable); +} + +/*! + Adds \a item to the legend, if it's not present already. + + Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. + + The legend takes ownership of the item. +*/ +bool QCPLegend::addItem(QCPAbstractLegendItem *item) +{ + if (!hasItem(item)) + { + return addElement(rowCount(), 0, item); + } else + return false; +} + +/*! + Removes the item with index \a index from the legend. + + Returns true, if successful. + + \see itemCount, clearItems +*/ +bool QCPLegend::removeItem(int index) +{ + if (QCPAbstractLegendItem *ali = item(index)) + { + bool success = remove(ali); + simplify(); + return success; + } else + return false; +} + +/*! \overload + + Removes \a item from the legend. + + Returns true, if successful. + + \see clearItems +*/ +bool QCPLegend::removeItem(QCPAbstractLegendItem *item) +{ + bool success = remove(item); + simplify(); + return success; +} + +/*! + Removes all items from the legend. +*/ +void QCPLegend::clearItems() +{ + for (int i=itemCount()-1; i>=0; --i) + removeItem(i); +} + +/*! + Returns the legend items that are currently selected. If no items are selected, + the list is empty. + + \see QCPAbstractLegendItem::setSelected, setSelectable +*/ +QList QCPLegend::selectedItems() const +{ + QList result; + for (int i=0; iselected()) + result.append(ali); + } + } + return result; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing main legend elements. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); +} + +/*! \internal + + Returns the pen used to paint the border of the legend, taking into account the selection state + of the legend box. +*/ +QPen QCPLegend::getBorderPen() const +{ + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; +} + +/*! \internal + + Returns the brush used to paint the background of the legend, taking into account the selection + state of the legend box. +*/ +QBrush QCPLegend::getBrush() const +{ + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; +} + +/*! \internal + + Draws the legend box with the provided \a painter. The individual legend items are layerables + themselves, thus are drawn independently. +*/ +void QCPLegend::draw(QCPPainter *painter) +{ + // draw background rect: + painter->setBrush(getBrush()); + painter->setPen(getBorderPen()); + painter->drawRect(mOuterRect); +} + +/* inherits documentation from base class */ +double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if (!mParentPlot) return -1; + if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + return -1; + + if (mOuterRect.contains(pos.toPoint())) + { + if (details) details->setValue(spLegendBox); + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/* inherits documentation from base class */ +void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + mSelectedParts = selectedParts(); // in case item selection has changed + if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPLegend::deselectEvent(bool *selectionStateChanged) +{ + mSelectedParts = selectedParts(); // in case item selection has changed + if (mSelectableParts.testFlag(spLegendBox)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(selectedParts() & ~spLegendBox); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +QCP::Interaction QCPLegend::selectionCategory() const +{ + return QCP::iSelectLegend; +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractLegendItem::selectionCategory() const +{ + return QCP::iSelectLegend; +} + +/* inherits documentation from base class */ +void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) +{ + Q_UNUSED(parentPlot) +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPlotTitle +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPlotTitle + \brief A layout element displaying a plot title text + + The text may be specified with \ref setText, theformatting can be controlled with \ref setFont + and \ref setTextColor. + + A plot title can be added as follows: + \code + customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect + customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title")); + \endcode + + Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for + easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the + signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref + QCustomPlot::titleDoubleClick signal. +*/ + +/* start documentation of signals */ + +/*! \fn void QCPPlotTitle::selectionChanged(bool selected) + + This signal is emitted when the selection state has changed to \a selected, either by user + interaction or by a direct call to \ref setSelected. + + \see setSelected, setSelectable +*/ + +/* end documentation of signals */ + +/*! + Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). + + To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). +*/ +QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : + QCPLayoutElement(parentPlot), + mFont(QFont("sans serif", 13*1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) +{ + if (parentPlot) + { + setLayer(parentPlot->currentLayer()); + mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); + mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); + } + setMargins(QMargins(5, 5, 5, 0)); +} + +/*! \overload + + Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. +*/ +QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : + QCPLayoutElement(parentPlot), + mText(text), + mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) +{ + setLayer("axes"); + setMargins(QMargins(5, 5, 5, 0)); +} + +/*! + Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". + + \see setFont, setTextColor +*/ +void QCPPlotTitle::setText(const QString &text) +{ + mText = text; +} + +/*! + Sets the \a font of the title text. + + \see setTextColor, setSelectedFont +*/ +void QCPPlotTitle::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the \a color of the title text. + + \see setFont, setSelectedTextColor +*/ +void QCPPlotTitle::setTextColor(const QColor &color) +{ + mTextColor = color; +} + +/*! + Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). + + \see setFont +*/ +void QCPPlotTitle::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). + + \see setTextColor +*/ +void QCPPlotTitle::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; +} + +/*! + Sets whether the user may select this plot title to \a selectable. + + Note that even when \a selectable is set to false, the selection state may be changed + programmatically via \ref setSelected. +*/ +void QCPPlotTitle::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets the selection state of this plot title to \a selected. If the selection has changed, \ref + selectionChanged is emitted. + + Note that this function can change the selection state independently of the current \ref + setSelectable state. +*/ +void QCPPlotTitle::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/* inherits documentation from base class */ +void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); +} + +/* inherits documentation from base class */ +void QCPPlotTitle::draw(QCPPainter *painter) +{ + painter->setFont(mainFont()); + painter->setPen(QPen(mainTextColor())); + painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); +} + +/* inherits documentation from base class */ +QSize QCPPlotTitle::minimumSizeHint() const +{ + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; +} + +/* inherits documentation from base class */ +QSize QCPPlotTitle::maximumSizeHint() const +{ + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rheight() += mMargins.top() + mMargins.bottom(); + result.setWidth(QWIDGETSIZE_MAX); + return result; +} + +/* inherits documentation from base class */ +void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + if (mTextBoundingRect.contains(pos.toPoint())) + return mParentPlot->selectionTolerance()*0.99; + else + return -1; +} + +/*! \internal + + Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to + true, else mFont is returned. +*/ +QFont QCPPlotTitle::mainFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to + true, else mTextColor is returned. +*/ +QColor QCPPlotTitle::mainTextColor() const +{ + return mSelected ? mSelectedTextColor : mTextColor; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorScale +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorScale + \brief A color scale for use with color coding data such as QCPColorMap + + This layout element can be placed on the plot to correlate a color gradient with data values. It + is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". + + \image html QCPColorScale.png + + The color scale can be either horizontal or vertical, as shown in the image above. The + orientation and the side where the numbers appear is controlled with \ref setType. + + Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are + connected, they share their gradient, data range and data scale type (\ref setGradient, \ref + setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color + scale, to make them all synchronize these properties. + + To have finer control over the number display and axis behaviour, you can directly access the + \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if + you want to change the number of automatically generated ticks, call + \code + colorScale->axis()->setAutoTickCount(3); + \endcode + + Placing a color scale next to the main axis rect works like with any other layout element: + \code + QCPColorScale *colorScale = new QCPColorScale(customPlot); + customPlot->plotLayout()->addElement(0, 1, colorScale); + colorScale->setLabel("Some Label Text"); + \endcode + In this case we have placed it to the right of the default axis rect, so it wasn't necessary to + call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color + scale can be set with \ref setLabel. + + For optimum appearance (like in the image above), it may be desirable to line up the axis rect and + the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: + \code + QCPMarginGroup *group = new QCPMarginGroup(customPlot); + colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group); + customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group); + \endcode + + Color scales are initialized with a non-zero minimum top and bottom margin (\ref + setMinimumMargins), because vertical color scales are most common and the minimum top/bottom + margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a + horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you + might want to also change the minimum margins accordingly, e.g. \ref + setMinimumMargins(QMargins(6, 0, 6, 0)). +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPAxis *QCPColorScale::axis() const + + Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the + appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its + interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref + setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref + QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on + the QCPColorScale or on its QCPAxis. + + If the type of the color scale is changed with \ref setType, the axis returned by this method + will change, too, to either the left, right, bottom or top axis, depending on which type was set. +*/ + +/* end documentation of signals */ +/* start documentation of signals */ + +/*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); + + This signal is emitted when the data range changes. + + \see setDataRange +*/ + +/*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the data scale type changes. + + \see setDataScaleType +*/ + +/*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); + + This signal is emitted when the gradient changes. + + \see setGradient +*/ + +/* end documentation of signals */ + +/*! + Constructs a new QCPColorScale. +*/ +QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : + QCPLayoutElement(parentPlot), + mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight + mDataScaleType(QCPAxis::stLinear), + mBarWidth(20), + mAxisRect(new QCPColorScaleAxisRectPrivate(this)) +{ + setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) + setType(QCPAxis::atRight); + setDataRange(QCPRange(0, 6)); +} + +QCPColorScale::~QCPColorScale() +{ + delete mAxisRect; +} + +/* undocumented getter */ +QString QCPColorScale::label() const +{ + if (!mColorAxis) + { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return QString(); + } + + return mColorAxis.data()->label(); +} + +/* undocumented getter */ +bool QCPColorScale::rangeDrag() const +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); +} + +/* undocumented getter */ +bool QCPColorScale::rangeZoom() const +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); +} + +/*! + Sets at which side of the color scale the axis is placed, and thus also its orientation. + + Note that after setting \a type to a different value, the axis returned by \ref axis() will + be a different one. The new axis will adopt the following properties from the previous axis: The + range, scale type, log base and label. +*/ +void QCPColorScale::setType(QCPAxis::AxisType type) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + if (mType != type) + { + mType = type; + QCPRange rangeTransfer(0, 6); + double logBaseTransfer = 10; + QString labelTransfer; + // revert some settings on old axis: + if (mColorAxis) + { + rangeTransfer = mColorAxis.data()->range(); + labelTransfer = mColorAxis.data()->label(); + logBaseTransfer = mColorAxis.data()->scaleLogBase(); + mColorAxis.data()->setLabel(""); + disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + foreach (QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop) + { + mAxisRect.data()->axis(atype)->setTicks(atype == mType); + mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + } + // set new mColorAxis pointer: + mColorAxis = mAxisRect.data()->axis(mType); + // transfer settings to new axis: + mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) + mColorAxis.data()->setLabel(labelTransfer); + mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here + connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, + QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); + } +} + +/*! + Sets the range spanned by the color gradient and that is shown by the axis in the color scale. + + It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is + also equivalent to directly accessing the \ref axis and setting its range with \ref + QCPAxis::setRange. + + \see setDataScaleType, setGradient, rescaleDataRange +*/ +void QCPColorScale::setDataRange(const QCPRange &dataRange) +{ + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + { + mDataRange = dataRange; + if (mColorAxis) + mColorAxis.data()->setRange(mDataRange); + emit dataRangeChanged(mDataRange); + } +} + +/*! + Sets the scale type of the color scale, i.e. whether values are linearly associated with colors + or logarithmically. + + It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is + also equivalent to directly accessing the \ref axis and setting its scale type with \ref + QCPAxis::setScaleType. + + \see setDataRange, setGradient +*/ +void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) +{ + if (mDataScaleType != scaleType) + { + mDataScaleType = scaleType; + if (mColorAxis) + mColorAxis.data()->setScaleType(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) + setDataRange(mDataRange.sanitizedForLogScale()); + emit dataScaleTypeChanged(mDataScaleType); + } +} + +/*! + Sets the color gradient that will be used to represent data values. + + It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. + + \see setDataRange, setDataScaleType +*/ +void QCPColorScale::setGradient(const QCPColorGradient &gradient) +{ + if (mGradient != gradient) + { + mGradient = gradient; + if (mAxisRect) + mAxisRect.data()->mGradientImageInvalidated = true; + emit gradientChanged(mGradient); + } +} + +/*! + Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on + the internal \ref axis. +*/ +void QCPColorScale::setLabel(const QString &str) +{ + if (!mColorAxis) + { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return; + } + + mColorAxis.data()->setLabel(str); +} + +/*! + Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed + will have. +*/ +void QCPColorScale::setBarWidth(int width) +{ + mBarWidth = width; +} + +/*! + Sets whether the user can drag the data range (\ref setDataRange). + + Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref + QCustomPlot::setInteractions) to allow range dragging. +*/ +void QCPColorScale::setRangeDrag(bool enabled) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) + mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + else + mAxisRect.data()->setRangeDrag(0); +} + +/*! + Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. + + Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref + QCustomPlot::setInteractions) to allow range dragging. +*/ +void QCPColorScale::setRangeZoom(bool enabled) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) + mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + else + mAxisRect.data()->setRangeZoom(0); +} + +/*! + Returns a list of all the color maps associated with this color scale. +*/ +QList QCPColorScale::colorMaps() const +{ + QList result; + for (int i=0; iplottableCount(); ++i) + { + if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) + if (cm->colorScale() == this) + result.append(cm); + } + return result; +} + +/*! + Changes the data range such that all color maps associated with this color scale are fully mapped + to the gradient in the data dimension. + + \see setDataRange +*/ +void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) +{ + QList maps = colorMaps(); + QCPRange newRange; + bool haveRange = false; + int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) + if (mDataScaleType == QCPAxis::stLogarithmic) + sign = (mDataRange.upper < 0 ? -1 : 1); + for (int i=0; irealVisibility() && onlyVisibleMaps) + continue; + QCPRange mapRange; + if (maps.at(i)->colorScale() == this) + { + bool currentFoundRange = true; + mapRange = maps.at(i)->data()->dataBounds(); + if (sign == 1) + { + if (mapRange.lower <= 0 && mapRange.upper > 0) + mapRange.lower = mapRange.upper*1e-3; + else if (mapRange.lower <= 0 && mapRange.upper <= 0) + currentFoundRange = false; + } else if (sign == -1) + { + if (mapRange.upper >= 0 && mapRange.lower < 0) + mapRange.upper = mapRange.lower*1e-3; + else if (mapRange.upper >= 0 && mapRange.lower >= 0) + currentFoundRange = false; + } + if (currentFoundRange) + { + if (!haveRange) + newRange = mapRange; + else + newRange.expand(mapRange); + haveRange = true; + } + } + } + if (haveRange) + { + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mDataScaleType == QCPAxis::stLinear) + { + newRange.lower = center-mDataRange.size()/2.0; + newRange.upper = center+mDataRange.size()/2.0; + } else // mScaleType == stLogarithmic + { + newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); + newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); + } + } + setDataRange(newRange); + } +} + +/* inherits documentation from base class */ +void QCPColorScale::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + mAxisRect.data()->update(phase); + + switch (phase) + { + case upMargins: + { + if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) + { + setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); + setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); + } else + { + setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); + setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); + } + break; + } + case upLayout: + { + mAxisRect.data()->setOuterRect(rect()); + break; + } + default: break; + } +} + +/* inherits documentation from base class */ +void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + painter->setAntialiasing(false); +} + +/* inherits documentation from base class */ +void QCPColorScale::mousePressEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mousePressEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::mouseMoveEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseMoveEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseReleaseEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::wheelEvent(QWheelEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->wheelEvent(event); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorScaleAxisRectPrivate +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorScaleAxisRectPrivate + + \internal + \brief An axis rect subclass for use in a QCPColorScale + + This is a private class and not part of the public QCustomPlot interface. + + It provides the axis rect functionality for the QCPColorScale class. +*/ + + +/*! + Creates a new instance, as a child of \a parentColorScale. +*/ +QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : + QCPAxisRect(parentColorScale->parentPlot(), true), + mParentColorScale(parentColorScale), + mGradientImageInvalidated(true) +{ + setParentLayerable(parentColorScale); + setMinimumMargins(QMargins(0, 0, 0, 0)); + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + axis(type)->setVisible(true); + axis(type)->grid()->setVisible(false); + axis(type)->setPadding(0); + connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); + connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); + } + + connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); + + // make layer transfers of color scale transfer to axis rect and axes + // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); +} + +/*! \internal + Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws + it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. +*/ +void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) +{ + if (mGradientImageInvalidated) + updateGradientImage(); + + bool mirrorHorz = false; + bool mirrorVert = false; + if (mParentColorScale->mColorAxis) + { + mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); + mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); + } + + painter->drawImage(rect(), mGradientImage.mirrored(mirrorHorz, mirrorVert)); + QCPAxisRect::draw(painter); +} + +/*! \internal + + Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to + generate a gradient image. This gradient image will be used in the \ref draw method. +*/ +void QCPColorScaleAxisRectPrivate::updateGradientImage() +{ + if (rect().isEmpty()) + return; + + int n = mParentColorScale->mGradient.levelCount(); + int w, h; + QVector data(n); + for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) + { + w = n; + h = rect().height(); + mGradientImage = QImage(w, h, QImage::Format_RGB32); + QVector pixels; + for (int y=0; y(mGradientImage.scanLine(y))); + mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); + for (int y=1; y(mGradientImage.scanLine(y)); + const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); + for (int x=0; x() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) + continue; + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + { + if (selectedParts.testFlag(QCPAxis::spAxis)) + axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + else + axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + } + } +} + +/*! \internal + + This slot is connected to the selectableChanged signals of the four axes in the constructor. It + synchronizes the selectability of the axes. +*/ +void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) +{ + // synchronize axis base selectability: + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) + continue; + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + { + if (selectableParts.testFlag(QCPAxis::spAxis)) + axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + else + axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPData + \brief Holds the data of one single data point for QCPGraph. + + The container for storing multiple data points is \ref QCPDataMap. + + The stored data is: + \li \a key: coordinate on the key axis of this data point + \li \a value: coordinate on the value axis of this data point + \li \a keyErrorMinus: negative error in the key dimension (for error bars) + \li \a keyErrorPlus: positive error in the key dimension (for error bars) + \li \a valueErrorMinus: negative error in the value dimension (for error bars) + \li \a valueErrorPlus: positive error in the value dimension (for error bars) + + \see QCPDataMap +*/ + +/*! + Constructs a data point with key, value and all errors set to zero. +*/ +QCPData::QCPData() : + key(0), + value(0), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) +{ +} + +/*! + Constructs a data point with the specified \a key and \a value. All errors are set to zero. +*/ +QCPData::QCPData(double key, double value) : + key(key), + value(value), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPGraph +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPGraph + \brief A plottable representing a graph in a plot. + + \image html QCPGraph.png + + Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting + instance is accessed via QCustomPlot::graph. + + To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can + also access and modify the graph's data via the \ref data method, which returns a pointer to the + internal \ref QCPDataMap. + + Graphs are used to display single-valued data. Single-valued means that there should only be one + data point per unique key coordinate. In other words, the graph can't have \a loops. If you do + want to plot non-single-valued curves, rather use the QCPCurve plottable. + + \section appearance Changing the appearance + + The appearance of the graph is mainly determined by the line style, scatter style, brush and pen + of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). + + \subsection filling Filling under or between graphs + + QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to + the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, + just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. + + By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill + between this graph and another one, call \ref setChannelFillGraph with the other graph as + parameter. + + \see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph +*/ + +/* start of documentation of inline functions */ + +/*! \fn QCPDataMap *QCPGraph::data() const + + Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to + directly manipulate the data, which may be more convenient and faster than using the regular \ref + setData or \ref addData methods, in certain situations. +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the graph. + + To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. +*/ +QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis) +{ + mData = new QCPDataMap; + + setPen(QPen(Qt::blue, 0)); + setErrorPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); + setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); + setSelectedBrush(Qt::NoBrush); + + setLineStyle(lsLine); + setErrorType(etNone); + setErrorBarSize(6); + setErrorBarSkipSymbol(true); + setChannelFillGraph(0); + setAdaptiveSampling(true); +} + +QCPGraph::~QCPGraph() +{ + delete mData; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the graph + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. +*/ +void QCPGraph::setData(QCPDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a key and \a value pairs. The provided + vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical value error of the data points are set to the values in \a valueError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative value error of the data points are set to the values in \a valueErrorMinus, the positive + value error to \a valueErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical key error of the data points are set to the values in \a keyError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative key error of the data points are set to the values in \a keyErrorMinus, the positive + key error to \a keyErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive + key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + + +/*! + Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to + \ref lsNone and \ref setScatterStyle to the desired scatter style. + + \see setScatterStyle +*/ +void QCPGraph::setLineStyle(LineStyle ls) +{ + mLineStyle = ls; +} + +/*! + Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points + are drawn (e.g. for line-only-plots with appropriate line style). + + \see QCPScatterStyle, setLineStyle +*/ +void QCPGraph::setScatterStyle(const QCPScatterStyle &style) +{ + mScatterStyle = style; +} + +/*! + Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data + point. If you set \a errorType to something other than \ref etNone, make sure to actually pass + error data via the specific setData functions along with the data points (e.g. \ref + setDataValueError, \ref setDataKeyError, \ref setDataBothError). + + \see ErrorType +*/ +void QCPGraph::setErrorType(ErrorType errorType) +{ + mErrorType = errorType; +} + +/*! + Sets the pen with which the error bars will be drawn. + \see setErrorBarSize, setErrorType +*/ +void QCPGraph::setErrorPen(const QPen &pen) +{ + mErrorPen = pen; +} + +/*! + Sets the width of the handles at both ends of an error bar in pixels. +*/ +void QCPGraph::setErrorBarSize(double size) +{ + mErrorBarSize = size; +} + +/*! + If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but + leave some free space around the symbol. + + This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size + of the area to leave blank. So when drawing Pixmaps as scatter points (\ref + QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the + size of the Pixmap, if the error bars should leave gaps to its boundaries. + + \ref setErrorType, setErrorBarSize, setScatterStyle +*/ +void QCPGraph::setErrorBarSkipSymbol(bool enabled) +{ + mErrorBarSkipSymbol = enabled; +} + +/*! + Sets the target graph for filling the area between this graph and \a targetGraph with the current + brush (\ref setBrush). + + When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To + disable any filling, set the brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) +{ + // prevent setting channel target to this graph itself: + if (targetGraph == this) + { + qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; + mChannelFillGraph = 0; + return; + } + // prevent setting channel target to a graph not in the plot: + if (targetGraph && targetGraph->mParentPlot != mParentPlot) + { + qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; + mChannelFillGraph = 0; + return; + } + + mChannelFillGraph = targetGraph; +} + +/*! + Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive + sampling technique can drastically improve the replot performance for graphs with a larger number + of points (e.g. above 10,000), without notably changing the appearance of the graph. + + By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive + sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no + disadvantage in almost all cases. + + \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" + + As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are + reproduced reliably, as well as the overall shape of the data set. The replot time reduces + dramatically though. This allows QCustomPlot to display large amounts of data in realtime. + + \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" + + Care must be taken when using high-density scatter plots in combination with adaptive sampling. + The adaptive sampling algorithm treats scatter plots more carefully than line plots which still + gives a significant reduction of replot times, but not quite as much as for line plots. This is + because scatter plots inherently need more data points to be preserved in order to still resemble + the original, non-adaptive-sampling plot. As shown above, the results still aren't quite + identical, as banding occurs for the outer data points. This is in fact intentional, such that + the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, + depends on the point density, i.e. the number of points in the plot. + + For some situations with scatter plots it might thus be desirable to manually turn adaptive + sampling off. For example, when saving the plot to disk. This can be achieved by setting \a + enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled + back to true afterwards. +*/ +void QCPGraph::setAdaptiveSampling(bool enabled) +{ + mAdaptiveSampling = enabled; +} + +/*! + Adds the provided data points in \a dataMap to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QCPDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QCPData &data) +{ + mData->insertMulti(data.key, data); +} + +/*! \overload + Adds the provided single data point as \a key and \a value pair to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(double key, double value) +{ + QCPData newData; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.key, newData); +} + +/*! \overload + Adds the provided data points as \a key and \a value pairs to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QVector &keys, const QVector &values) +{ + int n = qMin(keys.size(), values.size()); + QCPData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Removes all data points with keys smaller than \a key. + \see addData, clearData +*/ +void QCPGraph::removeDataBefore(double key) +{ + QCPDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) + it = mData->erase(it); +} + +/*! + Removes all data points with keys greater than \a key. + \see addData, clearData +*/ +void QCPGraph::removeDataAfter(double key) +{ + if (mData->isEmpty()) return; + QCPDataMap::iterator it = mData->upperBound(key); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with keys between \a fromKey and \a toKey. + if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove + a single data point with known key, use \ref removeData(double key). + + \see addData, clearData +*/ +void QCPGraph::removeData(double fromKey, double toKey) +{ + if (fromKey >= toKey || mData->isEmpty()) return; + QCPDataMap::iterator it = mData->upperBound(fromKey); + QCPDataMap::iterator itEnd = mData->upperBound(toKey); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at \a key. If the position is not known with absolute precision, + consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around + the suspected position, depeding on the precision with which the key is known. + + \see addData, clearData +*/ +void QCPGraph::removeData(double key) +{ + mData->remove(key); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPGraph::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + return pointDistance(pos); + else + return -1; +} + +/*! \overload + + Allows to define whether error bars are taken into consideration when determining the new axis + range. + + \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes +*/ +void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const +{ + rescaleKeyAxis(onlyEnlarge, includeErrorBars); + rescaleValueAxis(onlyEnlarge, includeErrorBars); +} + +/*! \overload + + Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration + when determining the new axis range. + + \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis +*/ +void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const +{ + // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change + // that getKeyRange is passed the includeErrorBars value. + if (mData->isEmpty()) return; + + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + SignDomain signDomain = sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); + + if (foundRange) + { + if (onlyEnlarge) + { + if (keyAxis->range().lower < newRange.lower) + newRange.lower = keyAxis->range().lower; + if (keyAxis->range().upper > newRange.upper) + newRange.upper = keyAxis->range().upper; + } + keyAxis->setRange(newRange); + } +} + +/*! \overload + + Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration + when determining the new axis range. + + \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis +*/ +void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const +{ + // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change + // is that getValueRange is passed the includeErrorBars value. + if (mData->isEmpty()) return; + + QCPAxis *valueAxis = mValueAxis.data(); + if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } + + SignDomain signDomain = sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); + + if (foundRange) + { + if (onlyEnlarge) + { + if (valueAxis->range().lower < newRange.lower) + newRange.lower = valueAxis->range().lower; + if (valueAxis->range().upper > newRange.upper) + newRange.upper = valueAxis->range().upper; + } + valueAxis->setRange(newRange); + } +} + +/* inherits documentation from base class */ +void QCPGraph::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; + if (mLineStyle == lsNone && mScatterStyle.isNone()) return; + + // allocate line and (if necessary) point vectors: + QVector *lineData = new QVector; + QVector *scatterData = 0; + if (!mScatterStyle.isNone()) + scatterData = new QVector; + + // fill vectors with data appropriate to plot style: + getPlotData(lineData, scatterData); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + QCPDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + if (QCP::isInvalidData(it.value().key, it.value().value) || + QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || + QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); + } +#endif + + // draw fill of graph: + drawFill(painter, lineData); + + // draw line: + if (mLineStyle == lsImpulse) + drawImpulsePlot(painter, lineData); + else if (mLineStyle != lsNone) + drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot + + // draw scatters: + if (scatterData) + drawScatterPlot(painter, scatterData); + + // free allocated line and point vectors: + delete lineData; + if (scatterData) + delete scatterData; +} + +/* inherits documentation from base class */ +void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw fill: + if (mBrush.style() != Qt::NoBrush) + { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) + { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) + { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else + { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } + } +} + +/*! \internal + + This function branches out to the line style specific "get(...)PlotData" functions, according to + the line style of the graph. + + \a lineData will be filled with raw points that will be drawn with the according draw functions, + e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data + points, since for step plots for example, additional points are needed for drawing lines that + make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left + untouched. + + \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the + scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is + \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. + + \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, + getStepCenterPlotData, getImpulsePlotData +*/ +void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const +{ + switch(mLineStyle) + { + case lsNone: getScatterPlotData(scatterData); break; + case lsLine: getLinePlotData(lineData, scatterData); break; + case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; + case lsStepRight: getStepRightPlotData(lineData, scatterData); break; + case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; + case lsImpulse: getImpulsePlotData(lineData, scatterData); break; + } +} + +/*! \internal + + If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, + this function serves at providing the visible data points in \a scatterData, so the \ref + drawScatterPlot function can draw the scatter points accordingly. + + If line style is not \ref lsNone, this function is not called and the data for the scatter points + are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. + + \see drawScatterPlot +*/ +void QCPGraph::getScatterPlotData(QVector *scatterData) const +{ + getPreparedData(0, scatterData); +} + +/*! \internal + + Places the raw data points needed for a normal linearly connected graph in \a linePixelData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getLinePlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()); + + // transform lineData points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; icoordToPixel(lineData.at(i).value)); + (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); + } + } else // key axis is horizontal + { + for (int i=0; icoordToPixel(lineData.at(i).key)); + (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with left oriented steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(lastValue); + (*linePixelData)[i*2+0].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+1].setX(lastValue); + (*linePixelData)[i*2+1].setY(key); + } + } else // key axis is horizontal + { + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+1].setX(key); + (*linePixelData)[i*2+1].setY(lastValue); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with right oriented steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double value; + for (int i=0; icoordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+0].setX(value); + (*linePixelData)[i*2+0].setY(lastKey); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+1].setX(value); + (*linePixelData)[i*2+1].setY(lastKey); + } + } else // key axis is horizontal + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double value; + for (int i=0; icoordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+0].setX(lastKey); + (*linePixelData)[i*2+0].setY(value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+1].setX(lastKey); + (*linePixelData)[i*2+1].setY(value); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with centered steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + (*linePixelData)[0].setX(lastValue); + (*linePixelData)[0].setY(lastKey); + for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; + (*linePixelData)[i*2-1].setX(lastValue); + (*linePixelData)[i*2-1].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(lastValue); + (*linePixelData)[i*2+0].setY(key); + } + (*linePixelData)[lineData.size()*2-1].setX(lastValue); + (*linePixelData)[lineData.size()*2-1].setY(lastKey); + } else // key axis is horizontal + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + (*linePixelData)[0].setX(lastKey); + (*linePixelData)[0].setY(lastValue); + for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; + (*linePixelData)[i*2-1].setX(key); + (*linePixelData)[i*2-1].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(lastValue); + } + (*linePixelData)[lineData.size()*2-1].setX(lastKey); + (*linePixelData)[lineData.size()*2-1].setY(lastValue); + } + +} + +/*! + \internal + Places the raw data points needed for an impulse plot in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawImpulsePlot +*/ +void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill + + // transform lineData points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + double zeroPointX = valueAxis->coordToPixel(0); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(zeroPointX); + (*linePixelData)[i*2+0].setY(key); + (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); + (*linePixelData)[i*2+1].setY(key); + } + } else // key axis is horizontal + { + double zeroPointY = valueAxis->coordToPixel(0); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(zeroPointY); + (*linePixelData)[i*2+1].setX(key); + (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } + } +} + +/*! \internal + + Draws the fill of the graph with the specified brush. + + If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and + two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by + \ref removeFillBasePoints after the fill drawing is done). + + If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the + more complex polygon is calculated with the \ref getChannelFillPolygon function. + + \see drawLinePlot +*/ +void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const +{ + if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot + if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; + + applyFillAntialiasingHint(painter); + if (!mChannelFillGraph) + { + // draw base fill under graph, fill goes all the way to the zero-value-line: + addFillBasePoints(lineData); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(QPolygonF(*lineData)); + removeFillBasePoints(lineData); + } else + { + // draw channel fill between this graph and mChannelFillGraph: + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(getChannelFillPolygon(lineData)); + } +} + +/*! \internal + + Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent + of the line style and are always drawn if the scatter style's shape is not \ref + QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" + functions, together with the (line style dependent) line data. + + \see drawLinePlot, drawImpulsePlot +*/ +void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + // draw error bars: + if (mErrorType != etNone) + { + applyErrorBarsAntialiasingHint(painter); + painter->setPen(mErrorPen); + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; isize(); ++i) + drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); + } else + { + for (int i=0; isize(); ++i) + drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); + } + } + + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; isize(); ++i) + mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); + } else + { + for (int i=0; isize(); ++i) + mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); + } +} + +/*! \internal + + Draws line graphs from the provided data. It connects all points in \a lineData, which was + created by one of the "get(...)PlotData" functions for line styles that require simple line + connections between the point vector they create. These are for example \ref getLinePlotData, + \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. + + \see drawScatterPlot, drawImpulsePlot +*/ +void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const +{ + // draw line of graph: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + + /* Draws polyline in batches, currently not used: + int p = 0; + while (p < lineData->size()) + { + int batch = qMin(25, lineData->size()-p); + if (p != 0) + { + ++batch; + --p; // to draw the connection lines between two batches + } + painter->drawPolyline(lineData->constData()+p, batch); + p += batch; + } + */ + + // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: + if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && + painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag(QCPPainter::pmVectorized)&& + !painter->modes().testFlag(QCPPainter::pmNoCaching)) + { + for (int i=1; isize(); ++i) + painter->drawLine(lineData->at(i-1), lineData->at(i)); + } else + { + painter->drawPolyline(QPolygonF(*lineData)); + } + } +} + +/*! \internal + + Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was + created by \ref getImpulsePlotData. + + \see drawScatterPlot, drawLinePlot +*/ +void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const +{ + // draw impulses: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + QPen pen = mainPen(); + pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawLines(*lineData); + } +} + +/*! \internal + + Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into + consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point + densities. + + 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't + needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a + scatterData should be 0 to prevent unnecessary calculations. + + This method is used by the various "get(...)PlotData" methods to get the basic working set of data. +*/ +void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + // get visible data range: + QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point + getVisibleDataBounds(lower, upper); + if (lower == mData->constEnd() || upper == mData->constEnd()) + return; + + // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: + int maxCount = std::numeric_limits::max(); + if (mAdaptiveSampling) + { + int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); + maxCount = 2*keyPixelSpan+2; + } + int dataCount = countDataInBounds(lower, upper, maxCount); + + if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average + { + if (lineData) + { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator currentIntervalFirstPoint = it; + int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); + double lastIntervalEndKey = currentIntervalStartKey; + double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) + { + if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary + { + if (it.value().value < minValue) + minValue = it.value().value; + else if (it.value().value > maxValue) + maxValue = it.value().value; + ++intervalDataCount; + } else // new pixel interval started + { + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster + { + if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); + if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); + } else + lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); + lastIntervalEndKey = (it-1).value().key; + minValue = it.value().value; + maxValue = it.value().value; + currentIntervalFirstPoint = it; + currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); + if (keyEpsilonVariable) + keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); + intervalDataCount = 1; + } + ++it; + } + // handle last interval: + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster + { + if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); + } else + lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); + } + + if (scatterData) + { + double valueMaxRange = valueAxis->range().upper; + double valueMinRange = valueAxis->range().lower; + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator minValueIt = it; + QCPDataMap::const_iterator maxValueIt = it; + QCPDataMap::const_iterator currentIntervalStart = it; + int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); + double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) + { + if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary + { + if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) + { + minValue = it.value().value; + minValueIt = it; + } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) + { + maxValue = it.value().value; + maxValueIt = it; + } + ++intervalDataCount; + } else // new pixel started + { + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them + { + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) + { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) + scatterData->append(intervalIt.value()); + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) + scatterData->append(currentIntervalStart.value()); + minValue = it.value().value; + maxValue = it.value().value; + currentIntervalStart = it; + currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); + if (keyEpsilonVariable) + keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); + intervalDataCount = 1; + } + ++it; + } + // handle last interval: + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them + { + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) + { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) + scatterData->append(intervalIt.value()); + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) + scatterData->append(currentIntervalStart.value()); + } + } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters + { + QVector *dataVector = 0; + if (lineData) + dataVector = lineData; + else if (scatterData) + dataVector = scatterData; + if (dataVector) + { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + dataVector->reserve(dataCount+2); // +2 for possible fill end points + while (it != upperEnd) + { + dataVector->append(it.value()); + ++it; + } + } + if (lineData && scatterData) + *scatterData = *dataVector; + } +} + +/*! \internal + + called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data + point. \a x and \a y pixel positions of the data point are passed since they are already known in + pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a + data is therefore only used for the errors, not key and value. +*/ +void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + double a, b; // positions of error bar bounds in pixels + double barWidthHalf = mErrorBarSize*0.5; + double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true + + if (keyAxis->orientation() == Qt::Vertical) + { + // draw key error vertically and value error horizontally + if (mErrorType == etKey || mErrorType == etBoth) + { + a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); + b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); + if (keyAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); + if (y-b > skipSymbolMargin) + painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); + } else + painter->drawLine(QLineF(x, a, x, b)); + // draw handles: + painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); + painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); + } + if (mErrorType == etValue || mErrorType == etBoth) + { + a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); + b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); + if (valueAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); + if (b-x > skipSymbolMargin) + painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); + } else + painter->drawLine(QLineF(a, y, b, y)); + // draw handles: + painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); + painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); + } + } else // mKeyAxis->orientation() is Qt::Horizontal + { + // draw value error vertically and key error horizontally + if (mErrorType == etKey || mErrorType == etBoth) + { + a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); + b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); + if (keyAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); + if (b-x > skipSymbolMargin) + painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); + } else + painter->drawLine(QLineF(a, y, b, y)); + // draw handles: + painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); + painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); + } + if (mErrorType == etValue || mErrorType == etBoth) + { + a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); + b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); + if (valueAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); + if (y-b > skipSymbolMargin) + painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); + } else + painter->drawLine(QLineF(x, a, x, b)); + // draw handles: + painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); + painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); + } + } +} + +/*! \internal + + called by \ref getPreparedData to determine which data (key) range is visible at the current key + axis range setting, so only that needs to be processed. + + \a lower returns an iterator to the lowest data point that needs to be taken into account when + plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a + lower may still be just outside the visible range. + + \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie + just outside of the visible range. + + if the graph contains no data, both \a lower and \a upper point to constEnd. +*/ +void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + if (mData->isEmpty()) + { + lower = mData->constEnd(); + upper = mData->constEnd(); + return; + } + + // get visible data range as QMap iterators + QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); + QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); + bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range + bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range + + lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn + upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn +} + +/*! \internal + + Counts the number of data points between \a lower and \a upper (including them), up to a maximum + of \a maxCount. + + This function is used by \ref getPreparedData to determine whether adaptive sampling shall be + used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points + only needs to be done until \a maxCount is reached, which should be set to the number of data + points at which adaptive sampling sets in. +*/ +int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const +{ + if (upper == mData->constEnd() && lower == mData->constEnd()) + return 0; + QCPDataMap::const_iterator it = lower; + int count = 1; + while (it != upper && count < maxCount) + { + ++it; + ++count; + } + return count; +} + +/*! \internal + + The line data vector generated by e.g. getLinePlotData contains only the line that connects the + data points. If the graph needs to be filled, two additional points need to be added at the + value-zero-line in the lower and upper key positions of the graph. This function calculates these + points and adds them to the end of \a lineData. Since the fill is typically drawn before the line + stroke, these added points need to be removed again after the fill is done, with the + removeFillBasePoints function. + + The expanding of \a lineData by two points will not cause unnecessary memory reallocations, + because the data vector generation functions (getLinePlotData etc.) reserve two extra points when + they allocate memory for \a lineData. + + \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint +*/ +void QCPGraph::addFillBasePoints(QVector *lineData) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + // append points that close the polygon fill at the key axis: + if (mKeyAxis.data()->orientation() == Qt::Vertical) + { + *lineData << upperFillBasePoint(lineData->last().y()); + *lineData << lowerFillBasePoint(lineData->first().y()); + } else + { + *lineData << upperFillBasePoint(lineData->last().x()); + *lineData << lowerFillBasePoint(lineData->first().x()); + } +} + +/*! \internal + + removes the two points from \a lineData that were added by \ref addFillBasePoints. + + \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint +*/ +void QCPGraph::removeFillBasePoints(QVector *lineData) const +{ + lineData->remove(lineData->size()-2, 2); +} + +/*! \internal + + called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon + on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale + case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative + infinity. So this case is handled separately by just closing the fill polygon on the axis which + lies in the direction towards the zero value. + + \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key + axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned + point, respectively. + + \see upperFillBasePoint, addFillBasePoints +*/ +QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + if (keyAxis->axisType() == QCPAxis::atLeft) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) + { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + { + // In logarithmic scaling we can't just draw to value zero so we just fill all the way + // to the axis which is in the direction towards zero + if (keyAxis->orientation() == Qt::Vertical) + { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + else + point.setX(keyAxis->axisRect()->left()); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(lowerKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + else + point.setY(keyAxis->axisRect()->bottom()); + } + } + return point; +} + +/*! \internal + + called by \ref addFillBasePoints to conveniently assign the point which closes the fill + polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis + scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or + negative infinity. So this case is handled separately by just closing the fill polygon on the + axis which lies in the direction towards the zero value. + + \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key + axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned + point, respectively. + + \see lowerFillBasePoint, addFillBasePoints +*/ +QPointF QCPGraph::upperFillBasePoint(double upperKey) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + if (keyAxis->axisType() == QCPAxis::atLeft) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) + { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + { + // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // to the axis which is in the direction towards 0 + if (keyAxis->orientation() == Qt::Vertical) + { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + else + point.setX(keyAxis->axisRect()->left()); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(upperKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + else + point.setY(keyAxis->axisRect()->bottom()); + } + } + return point; +} + +/*! \internal + + Generates the polygon needed for drawing channel fills between this graph (data passed via \a + lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref + getPlotData function). May return an empty polygon if the key ranges have no overlap or fill + target graph and this graph don't have same orientation (i.e. both key axes horizontal or both + key axes vertical). For increased performance (due to implicit sharing), keep the returned + QPolygonF const. +*/ +const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const +{ + if (!mChannelFillGraph) + return QPolygonF(); + + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } + if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } + + if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) + return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) + + if (lineData->isEmpty()) return QPolygonF(); + QVector otherData; + mChannelFillGraph.data()->getPlotData(&otherData, 0); + if (otherData.isEmpty()) return QPolygonF(); + QVector thisData; + thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function + for (int i=0; isize(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() + thisData << lineData->at(i); + + // pointers to be able to swap them, depending which data range needs cropping: + QVector *staticData = &thisData; + QVector *croppedData = &otherData; + + // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): + if (keyAxis->orientation() == Qt::Horizontal) + { + // x is key + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().x() > staticData->last().x()) + { + int size = staticData->size(); + for (int i=0; ifirst().x() > croppedData->last().x()) + { + int size = croppedData->size(); + for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped + qSwap(staticData, croppedData); + int lowBound = findIndexBelowX(croppedData, staticData->first().x()); + if (lowBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + double slope; + if (croppedData->at(1).x()-croppedData->at(0).x() != 0) + slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); + else + slope = 0; + (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); + (*croppedData)[0].setX(staticData->first().x()); + + // crop upper bound: + if (staticData->last().x() > croppedData->last().x()) // other one must be cropped + qSwap(staticData, croppedData); + int highBound = findIndexAboveX(croppedData, staticData->last().x()); + if (highBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + int li = croppedData->size()-1; // last index + if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) + slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); + else + slope = 0; + (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); + (*croppedData)[li].setX(staticData->last().x()); + } else // mKeyAxis->orientation() == Qt::Vertical + { + // y is key + // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, + // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().y() < staticData->last().y()) + { + int size = staticData->size(); + for (int i=0; ifirst().y() < croppedData->last().y()) + { + int size = croppedData->size(); + for (int i=0; ifirst().y() > croppedData->first().y()) // other one must be cropped + qSwap(staticData, croppedData); + int lowBound = findIndexAboveY(croppedData, staticData->first().y()); + if (lowBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + double slope; + if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots + slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); + else + slope = 0; + (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); + (*croppedData)[0].setY(staticData->first().y()); + + // crop upper bound: + if (staticData->last().y() < croppedData->last().y()) // other one must be cropped + qSwap(staticData, croppedData); + int highBound = findIndexBelowY(croppedData, staticData->last().y()); + if (highBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + int li = croppedData->size()-1; // last index + if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots + slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); + else + slope = 0; + (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); + (*croppedData)[li].setY(staticData->last().y()); + } + + // return joined: + for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted + thisData << otherData.at(i); + return QPolygonF(thisData); +} + +/*! \internal + + Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in + \a data points are ordered ascending, as is the case when plotting with horizontal key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexAboveX(const QVector *data, double x) const +{ + for (int i=data->size()-1; i>=0; --i) + { + if (data->at(i).x() < x) + { + if (isize()-1) + return i+1; + else + return data->size()-1; + } + } + return -1; +} + +/*! \internal + + Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in + \a data points are ordered ascending, as is the case when plotting with horizontal key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexBelowX(const QVector *data, double x) const +{ + for (int i=0; isize(); ++i) + { + if (data->at(i).x() > x) + { + if (i>0) + return i-1; + else + return 0; + } + } + return -1; +} + +/*! \internal + + Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in + \a data points are ordered descending, as is the case when plotting with vertical key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexAboveY(const QVector *data, double y) const +{ + for (int i=0; isize(); ++i) + { + if (data->at(i).y() < y) + { + if (i>0) + return i-1; + else + return 0; + } + } + return -1; +} + +/*! \internal + + Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a + pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in + \ref selectTest. + + If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape + is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns + 500. +*/ +double QCPGraph::pointDistance(const QPointF &pixelPoint) const +{ + if (mData->isEmpty()) + { + qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data"; + return 500; + } + if (mData->size() == 1) + { + QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); + return QVector2D(dataPoint-pixelPoint).length(); + } + + if (mLineStyle == lsNone && mScatterStyle.isNone()) + return 500; + + // calculate minimum distances to graph representation: + if (mLineStyle == lsNone) + { + // no line displayed, only calculate distance to scatter points: + QVector *scatterData = new QVector; + getScatterPlotData(scatterData); + double minDistSqr = std::numeric_limits::max(); + QPointF ptA; + QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels + for (int i=1; isize(); ++i) + { + ptA = ptB; + ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value); + double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + delete scatterData; + return sqrt(minDistSqr); + } else + { + // line displayed calculate distance to line segments: + QVector *lineData = new QVector; + getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here + double minDistSqr = std::numeric_limits::max(); + if (mLineStyle == lsImpulse) + { + // impulse plot differs from other line styles in that the lineData points are only pairwise connected: + for (int i=0; isize()-1; i+=2) // iterate pairs + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } else + { + // all other line plots (line and step) connect points directly: + for (int i=0; isize()-1; ++i) + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } + delete lineData; + return sqrt(minDistSqr); + } +} + +/*! \internal + + Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in + \a data points are ordered descending, as is the case when plotting with vertical key axis (since + keys are ordered ascending). + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexBelowY(const QVector *data, double y) const +{ + for (int i=data->size()-1; i>=0; --i) + { + if (data->at(i).y() > y) + { + if (isize()-1) + return i+1; + else + return data->size()-1; + } + } + return -1; +} + +/* inherits documentation from base class */ +QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + // just call the specialized version which takes an additional argument whether error bars + // should also be taken into consideration for range calculation. We set this to true here. + return getKeyRange(foundRange, inSignDomain, true); +} + +/* inherits documentation from base class */ +QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + // just call the specialized version which takes an additional argument whether error bars + // should also be taken into consideration for range calculation. We set this to true here. + return getValueRange(foundRange, inSignDomain, true); +} + +/*! \overload + + Allows to specify whether the error bars should be included in the range calculation. + + \see getKeyRange(bool &foundRange, SignDomain inSignDomain) +*/ +QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current, currentErrorMinus, currentErrorPlus; + + if (inSignDomain == sdBoth) // range may be anywhere + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if (current-currentErrorMinus < range.lower || !haveLower) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if (current+currentErrorPlus > range.upper || !haveUpper) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + ++it; + } + } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. + { + if ((current < range.lower || !haveLower) && current < 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current < 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. + { + if ((current < range.lower || !haveLower) && current > 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current > 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! \overload + + Allows to specify whether the error bars should be included in the range calculation. + + \see getValueRange(bool &foundRange, SignDomain inSignDomain) +*/ +QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current, currentErrorMinus, currentErrorPlus; + + if (inSignDomain == sdBoth) // range may be anywhere + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if (current-currentErrorMinus < range.lower || !haveLower) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if (current+currentErrorPlus > range.upper || !haveUpper) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + ++it; + } + } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. + { + if ((current < range.lower || !haveLower) && current < 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current < 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. + { + if ((current < range.lower || !haveLower) && current > 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current > 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } + + foundRange = haveLower && haveUpper; + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPCurveData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPCurveData + \brief Holds the data of one single data point for QCPCurve. + + The container for storing multiple data points is \ref QCPCurveDataMap. + + The stored data is: + \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) + \li \a key: coordinate on the key axis of this curve point + \li \a value: coordinate on the value axis of this curve point + + \see QCPCurveDataMap +*/ + +/*! + Constructs a curve data point with t, key and value set to zero. +*/ +QCPCurveData::QCPCurveData() : + t(0), + key(0), + value(0) +{ +} + +/*! + Constructs a curve data point with the specified \a t, \a key and \a value. +*/ +QCPCurveData::QCPCurveData(double t, double key, double value) : + t(t), + key(key), + value(value) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPCurve +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPCurve + \brief A plottable representing a parametric curve in a plot. + + \image html QCPCurve.png + + Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, + so their visual representation can have \a loops. This is realized by introducing a third + coordinate \a t, which defines the order of the points described by the other two coordinates \a + x and \a y. + + To plot data, assign it with the \ref setData or \ref addData functions. + + \section appearance Changing the appearance + + The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So + the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newCurve);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newCurve->setName("Fermat's Spiral"); + newCurve->setData(tData, xData, yData);\endcode +*/ + +/*! + Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the graph. +*/ +QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis) +{ + mData = new QCPCurveDataMap; + mPen.setColor(Qt::blue); + mPen.setStyle(Qt::SolidLine); + mBrush.setColor(Qt::blue); + mBrush.setStyle(Qt::NoBrush); + mSelectedPen = mPen; + mSelectedPen.setWidthF(2.5); + mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen + mSelectedBrush = mBrush; + + setScatterStyle(QCPScatterStyle()); + setLineStyle(lsLine); +} + +QCPCurve::~QCPCurve() +{ + delete mData; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the plottable + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPCurve::setData(QCPCurveDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a t, \a key and \a value tuples. The + provided vectors should have equal length. Else, the number of added points will be the size of + the smallest vector. +*/ +void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) +{ + mData->clear(); + int n = t.size(); + n = qMin(n, key.size()); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! \overload + + Replaces the current data with the provided \a key and \a value pairs. The t parameter + of each data point will be set to the integer index of the respective key/value pair. +*/ +void QCPCurve::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! + Sets the visual appearance of single data points in the plot. If set to \ref + QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate + line style). + + \see QCPScatterStyle, setLineStyle +*/ +void QCPCurve::setScatterStyle(const QCPScatterStyle &style) +{ + mScatterStyle = style; +} + +/*! + Sets how the single data points are connected in the plot or how they are represented visually + apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref + setScatterStyle to the desired scatter style. + + \see setScatterStyle +*/ +void QCPCurve::setLineStyle(QCPCurve::LineStyle style) +{ + mLineStyle = style; +} + +/*! + Adds the provided data points in \a dataMap to the current data. + \see removeData +*/ +void QCPCurve::addData(const QCPCurveDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + \see removeData +*/ +void QCPCurve::addData(const QCPCurveData &data) +{ + mData->insertMulti(data.t, data); +} + +/*! \overload + Adds the provided single data point as \a t, \a key and \a value tuple to the current data + \see removeData +*/ +void QCPCurve::addData(double t, double key, double value) +{ + QCPCurveData newData; + newData.t = t; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); +} + +/*! \overload + + Adds the provided single data point as \a key and \a value pair to the current data The t + parameter of the data point is set to the t of the last data point plus 1. If there is no last + data point, t will be set to 0. + + \see removeData +*/ +void QCPCurve::addData(double key, double value) +{ + QCPCurveData newData; + if (!mData->isEmpty()) + newData.t = (mData->constEnd()-1).key()+1; + else + newData.t = 0; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); +} + +/*! \overload + Adds the provided data points as \a t, \a key and \a value tuples to the current data. + \see removeData +*/ +void QCPCurve::addData(const QVector &ts, const QVector &keys, const QVector &values) +{ + int n = ts.size(); + n = qMin(n, keys.size()); + n = qMin(n, values.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! + Removes all data points with curve parameter t smaller than \a t. + \see addData, clearData +*/ +void QCPCurve::removeDataBefore(double t) +{ + QCPCurveDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < t) + it = mData->erase(it); +} + +/*! + Removes all data points with curve parameter t greater than \a t. + \see addData, clearData +*/ +void QCPCurve::removeDataAfter(double t) +{ + if (mData->isEmpty()) return; + QCPCurveDataMap::iterator it = mData->upperBound(t); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is + greater or equal to \a tot, the function does nothing. To remove a single data point with known + t, use \ref removeData(double t). + + \see addData, clearData +*/ +void QCPCurve::removeData(double fromt, double tot) +{ + if (fromt >= tot || mData->isEmpty()) return; + QCPCurveDataMap::iterator it = mData->upperBound(fromt); + QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at curve parameter \a t. If the position is not known with absolute + precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness + interval around the suspected position, depeding on the precision with which the curve parameter + is known. + + \see addData, clearData +*/ +void QCPCurve::removeData(double t) +{ + mData->remove(t); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPCurve::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + return pointDistance(pos); + else + return -1; +} + +/* inherits documentation from base class */ +void QCPCurve::draw(QCPPainter *painter) +{ + if (mData->isEmpty()) return; + + // allocate line vector: + QVector *lineData = new QVector; + + // fill with curve data: + getCurveData(lineData); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + QCPCurveDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + if (QCP::isInvalidData(it.value().t) || + QCP::isInvalidData(it.value().key, it.value().value)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); + } +#endif + + // draw curve fill: + if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + { + applyFillAntialiasingHint(painter); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(QPolygonF(*lineData)); + } + + // draw curve line: + if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: + if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && + painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag(QCPPainter::pmVectorized) && + !painter->modes().testFlag(QCPPainter::pmNoCaching)) + { + for (int i=1; isize(); ++i) + painter->drawLine(lineData->at(i-1), lineData->at(i)); + } else + { + painter->drawPolyline(QPolygonF(*lineData)); + } + } + + // draw scatters: + if (!mScatterStyle.isNone()) + drawScatterPlot(painter, lineData); + + // free allocated line data: + delete lineData; +} + +/* inherits documentation from base class */ +void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw fill: + if (mBrush.style() != Qt::NoBrush) + { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) + { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) + { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else + { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } + } +} + +/*! \internal + + Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of + the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. +*/ +void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const +{ + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + for (int i=0; isize(); ++i) + mScatterStyle.drawShape(painter, pointData->at(i)); +} + +/*! \internal + + called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the + curve. Line segments that aren't visible in the current axis rect are handled in an optimized + way. +*/ +void QCPCurve::getCurveData(QVector *lineData) const +{ + /* Extended sides of axis rect R divide space into 9 regions: + 1__|_4_|__7 + 2__|_R_|__8 + 3 | 6 | 9 + General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner is removed. + Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and + fills inside R consistent. + The region R has index 5. + */ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + lineData->reserve(mData->size()); + QCPCurveDataMap::const_iterator it; + int lastRegion = 5; + int currentRegion = 5; + double RLeft = keyAxis->range().lower; + double RRight = keyAxis->range().upper; + double RBottom = valueAxis->range().lower; + double RTop = valueAxis->range().upper; + double x, y; // current key/value + bool addedLastAlready = true; + bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + x = it.value().key; + y = it.value().value; + // determine current region: + if (x < RLeft) // region 123 + { + if (y > RTop) + currentRegion = 1; + else if (y < RBottom) + currentRegion = 3; + else + currentRegion = 2; + } else if (x > RRight) // region 789 + { + if (y > RTop) + currentRegion = 7; + else if (y < RBottom) + currentRegion = 9; + else + currentRegion = 8; + } else // region 456 + { + if (y > RTop) + currentRegion = 4; + else if (y < RBottom) + currentRegion = 6; + else + currentRegion = 5; + } + + /* + Watch out, the next part is very tricky. It modifies the curve such that it seems like the + whole thing is still drawn, but actually the points outside the axisRect are simplified + ("optimized") greatly. There are some subtle special cases when line segments are large and + thereby each subsequent point may be in a different region or even skip some. + */ + // determine whether to keep current point: + if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already + { + if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly + lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector + else if (lastRegion != 5) // added last already. If that's the case, we probably added it at optimized position. So go back and make sure it's at original position (else the angle changes under which this segment enters R) + { + if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point + lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value)); + } + lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector + addedLastAlready = true; // so in next iteration, we don't add this point twice + } else if (currentRegion != lastRegion) // changed region, add current and last if not added already + { + // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away) + + // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we can't place points optimized + if (lastRegion == 5 || // coming from R + ((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal + ((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal + ((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal + ((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal + ) + { + // always add last point if not added already, original: + if (!addedLastAlready) + lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); + // add current point, original: + lineData->append(coordsToPixels(it.value().key, it.value().value)); + } else // no special case that forbids optimized point placement, so do it: + { + // always add last point if not added already, optimized: + if (!addedLastAlready) + lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect)); + // add current point, optimized: + lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect)); + } + addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice + } else // neither in R, nor crossed a region boundary, skip current point + { + addedLastAlready = false; + } + lastRegion = currentRegion; + firstPoint = false; + } + // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started inside R: + if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty()) + lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value)); +} + +/*! \internal + + Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a + pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in + \ref selectTest. +*/ +double QCPCurve::pointDistance(const QPointF &pixelPoint) const +{ + if (mData->isEmpty()) + { + qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; + return 500; + } + if (mData->size() == 1) + { + QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); + return QVector2D(dataPoint-pixelPoint).length(); + } + + // calculate minimum distance to line segments: + QVector *lineData = new QVector; + getCurveData(lineData); + double minDistSqr = std::numeric_limits::max(); + for (int i=0; isize()-1; ++i) + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + delete lineData; + return sqrt(minDistSqr); +} + +/*! \internal + + This is a specialized \ref coordsToPixels function for points that are outside the visible + axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments + to those line segments that cross region boundaries, see documentation there). It only uses the + coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just + outside the axisRect (how far is determined by the scatter size and the line width). Together + with the optimization in \ref getCurveData this improves performance for large curves (or zoomed + in ones) significantly while keeping the illusion the whole curve and its filling is still being + drawn for the viewer. +*/ +QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const +{ + int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2; + QPointF result = coordsToPixels(key, value); + switch (region) + { + case 2: result.setX(axisRect.left()-margin); break; // left + case 8: result.setX(axisRect.right()+margin); break; // right + case 4: result.setY(axisRect.top()-margin); break; // top + case 6: result.setY(axisRect.bottom()+margin); break; // bottom + case 1: result.setX(axisRect.left()-margin); + result.setY(axisRect.top()-margin); break; // top left + case 7: result.setX(axisRect.right()+margin); + result.setY(axisRect.top()-margin); break; // top right + case 9: result.setX(axisRect.right()+margin); + result.setY(axisRect.bottom()+margin); break; // bottom right + case 3: result.setX(axisRect.left()-margin); + result.setY(axisRect.bottom()+margin); break; // bottom left + } + return result; +} + +/* inherits documentation from base class */ +QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + + QCPCurveDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + + QCPCurveDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPBarData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPBarData + \brief Holds the data of one single data point (one bar) for QCPBars. + + The container for storing multiple data points is \ref QCPBarDataMap. + + The stored data is: + \li \a key: coordinate on the key axis of this bar + \li \a value: height coordinate on the value axis of this bar + + \see QCPBarDataaMap +*/ + +/*! + Constructs a bar data point with key and value set to zero. +*/ +QCPBarData::QCPBarData() : + key(0), + value(0) +{ +} + +/*! + Constructs a bar data point with the specified \a key and \a value. +*/ +QCPBarData::QCPBarData(double key, double value) : + key(key), + value(value) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPBars +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPBars + \brief A plottable representing a bar chart in a plot. + + \image html QCPBars.png + + To plot data, assign it with the \ref setData or \ref addData functions. + + \section appearance Changing the appearance + + The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). + + Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other + (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear + stacked. + + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPBars is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newBars);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newBars->setName("Country population"); + newBars->setData(xData, yData);\endcode +*/ + +/*! \fn QCPBars *QCPBars::barBelow() const + Returns the bars plottable that is directly below this bars plottable. + If there is no such plottable, returns 0. + + \see barAbove, moveBelow, moveAbove +*/ + +/*! \fn QCPBars *QCPBars::barAbove() const + Returns the bars plottable that is directly above this bars plottable. + If there is no such plottable, returns 0. + + \see barBelow, moveBelow, moveAbove +*/ + +/*! + Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the bar chart. +*/ +QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis) +{ + mData = new QCPBarDataMap; + mPen.setColor(Qt::blue); + mPen.setStyle(Qt::SolidLine); + mBrush.setColor(QColor(40, 50, 255, 30)); + mBrush.setStyle(Qt::SolidPattern); + mSelectedPen = mPen; + mSelectedPen.setWidthF(2.5); + mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen + mSelectedBrush = mBrush; + + mWidth = 0.75; +} + +QCPBars::~QCPBars() +{ + if (mBarBelow || mBarAbove) + connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + delete mData; +} + +/*! + Sets the width of the bars in plot (key) coordinates. +*/ +void QCPBars::setWidth(double width) +{ + mWidth = width; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the plottable + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPBars::setData(QCPBarDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a key and \a value tuples. The + provided vectors should have equal length. Else, the number of added points will be the size of + the smallest vector. +*/ +void QCPBars::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPBarData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear + below the bars of \a bars. The move target \a bars must use the same key and value axis as this + plottable. + + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already + has a bars object below itself, this bars object is inserted between the two. If this bars object + is already between two other bars, the two other bars will be stacked on top of each other after + the operation. + + To remove this bars plottable from any stacking, set \a bars to 0. + + \see moveBelow, barAbove, barBelow +*/ +void QCPBars::moveBelow(QCPBars *bars) +{ + if (bars == this) return; + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar below it: + if (bars) + { + if (bars->mBarBelow) + connectBars(bars->mBarBelow.data(), this); + connectBars(this, bars); + } +} + +/*! + Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear + above the bars of \a bars. The move target \a bars must use the same key and value axis as this + plottable. + + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already + has a bars object below itself, this bars object is inserted between the two. If this bars object + is already between two other bars, the two other bars will be stacked on top of each other after + the operation. + + To remove this bars plottable from any stacking, set \a bars to 0. + + \see moveBelow, barBelow, barAbove +*/ +void QCPBars::moveAbove(QCPBars *bars) +{ + if (bars == this) return; + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar above it: + if (bars) + { + if (bars->mBarAbove) + connectBars(this, bars->mBarAbove.data()); + connectBars(bars, this); + } +} + +/*! + Adds the provided data points in \a dataMap to the current data. + \see removeData +*/ +void QCPBars::addData(const QCPBarDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + \see removeData +*/ +void QCPBars::addData(const QCPBarData &data) +{ + mData->insertMulti(data.key, data); +} + +/*! \overload + Adds the provided single data point as \a key and \a value tuple to the current data + \see removeData +*/ +void QCPBars::addData(double key, double value) +{ + QCPBarData newData; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.key, newData); +} + +/*! \overload + Adds the provided data points as \a key and \a value tuples to the current data. + \see removeData +*/ +void QCPBars::addData(const QVector &keys, const QVector &values) +{ + int n = keys.size(); + n = qMin(n, values.size()); + QCPBarData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Removes all data points with key smaller than \a key. + \see addData, clearData +*/ +void QCPBars::removeDataBefore(double key) +{ + QCPBarDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) + it = mData->erase(it); +} + +/*! + Removes all data points with key greater than \a key. + \see addData, clearData +*/ +void QCPBars::removeDataAfter(double key) +{ + if (mData->isEmpty()) return; + QCPBarDataMap::iterator it = mData->upperBound(key); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is + greater or equal to \a toKey, the function does nothing. To remove a single data point with known + key, use \ref removeData(double key). + + \see addData, clearData +*/ +void QCPBars::removeData(double fromKey, double toKey) +{ + if (fromKey >= toKey || mData->isEmpty()) return; + QCPBarDataMap::iterator it = mData->upperBound(fromKey); + QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at \a key. If the position is not known with absolute precision, + consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval + around the suspected position, depeding on the precision with which the key is known. + + \see addData, clearData +*/ +void QCPBars::removeData(double key) +{ + mData->remove(key); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPBars::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + QCPBarDataMap::ConstIterator it; + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + double baseValue = getBaseValue(it.key(), it.value().value >=0); + QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5); + QCPRange valueRange(baseValue, baseValue+it.value().value); + if (keyRange.contains(posKey) && valueRange.contains(posValue)) + return mParentPlot->selectionTolerance()*0.99; + } + } + return -1; +} + +/* inherits documentation from base class */ +void QCPBars::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (mData->isEmpty()) return; + + QCPBarDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + // skip bar if not visible in key axis range: + if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper) + continue; + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + if (QCP::isInvalidData(it.value().key, it.value().value)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); +#endif + QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); + // draw bar fill: + if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + { + applyFillAntialiasingHint(painter); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(barPolygon); + } + // draw bar line: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + painter->drawPolyline(barPolygon); + } + } +} + +/* inherits documentation from base class */ +void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setBrush(mBrush); + painter->setPen(mPen); + QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); +} + +/*! \internal + + Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom + and shifted according to the bar stacking (see \ref moveAbove). +*/ +QPolygonF QCPBars::getBarPolygon(double key, double value) const +{ + QPolygonF result; + double baseValue = getBaseValue(key, value >= 0); + result << coordsToPixels(key-mWidth*0.5, baseValue); + result << coordsToPixels(key-mWidth*0.5, baseValue+value); + result << coordsToPixels(key+mWidth*0.5, baseValue+value); + result << coordsToPixels(key+mWidth*0.5, baseValue); + return result; +} + +/*! \internal + + This function is called to find at which value to start drawing the base of a bar at \a key, when + it is stacked on top of another QCPBars (e.g. with \ref moveAbove). + + positive and negative bars are separated per stack (positive are stacked above 0-value upwards, + negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the + bar for which we need the base value is negative, set \a positive to false. +*/ +double QCPBars::getBaseValue(double key, bool positive) const +{ + if (mBarBelow) + { + double max = 0; + // find bars of mBarBelow that are approximately at key and find largest one: + QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1); + QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1); + while (it != itEnd) + { + if ((positive && it.value().value > max) || + (!positive && it.value().value < max)) + max = it.value().value; + ++it; + } + // recurse down the bar-stack to find the total height: + return max + mBarBelow.data()->getBaseValue(key, positive); + } else + return 0; +} + +/*! \internal + + Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. + The bar(s) currently below lower and upper will become disconnected to lower/upper. + + If lower is zero, upper will be disconnected at the bottom. + If upper is zero, lower will be disconnected at the top. +*/ +void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) +{ + if (!lower && !upper) return; + + if (!lower) // disconnect upper at bottom + { + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) + upper->mBarBelow.data()->mBarAbove = 0; + upper->mBarBelow = 0; + } else if (!upper) // disconnect lower at top + { + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) + lower->mBarAbove.data()->mBarBelow = 0; + lower->mBarAbove = 0; + } else // connect lower and upper + { + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) + lower->mBarAbove.data()->mBarBelow = 0; + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) + upper->mBarBelow.data()->mBarAbove = 0; + lower->mBarAbove = upper; + upper->mBarBelow = lower; + } +} + +/* inherits documentation from base class */ +QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + double barWidthHalf = mWidth*0.5; + QCPBarDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0)) + { + if (current-barWidthHalf < range.lower || !haveLower) + { + range.lower = current-barWidthHalf; + haveLower = true; + } + if (current+barWidthHalf > range.upper || !haveUpper) + { + range.upper = current+barWidthHalf; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = true; // set to true, because 0 should always be visible in bar charts + bool haveUpper = true; // set to true, because 0 should always be visible in bar charts + + double current; + + QCPBarDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0); + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = true; // return true because bar charts always have the 0-line visible + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPStatisticalBox +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPStatisticalBox + \brief A plottable representing a single statistical box in a plot. + + \image html QCPStatisticalBox.png + + To plot data, assign it with the individual parameter functions or use \ref setData to set all + parameters at once. The individual functions are: + \li \ref setMinimum + \li \ref setLowerQuartile + \li \ref setMedian + \li \ref setUpperQuartile + \li \ref setMaximum + + Additionally you can define a list of outliers, drawn as scatter datapoints: + \li \ref setOutliers + + \section appearance Changing the appearance + + The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change + the width of the box with \ref setWidth in plot coordinates (not pixels). + + Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref + setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top + (maximum) and bottom (minimum). + + The median indicator line has its own pen, \ref setMedianPen. + + If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the + backbone line might exceed the whisker bars by a few pixels due to the pen cap being not + perfectly flat. + + The Outlier data points are drawn as normal scatter points. Their look can be controlled with + \ref setOutlierStyle + + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newBox);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newBox->setName("Measurement Series 1"); + newBox->setData(1, 3, 4, 5, 7); + newBox->setOutliers(QVector() << 0.5 << 0.64 << 7.2 << 7.42);\endcode +*/ + +/*! + Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its + value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and + not have the same orientation. If either of these restrictions is violated, a corresponding + message is printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, + QCustomPlot then takes ownership of the statistical box. +*/ +QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mKey(0), + mMinimum(0), + mLowerQuartile(0), + mMedian(0), + mUpperQuartile(0), + mMaximum(0) +{ + setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); + setWhiskerWidth(0.2); + setWidth(0.5); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2.5)); + setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); + setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); + setWhiskerBarPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +/*! + Sets the key coordinate of the statistical box. +*/ +void QCPStatisticalBox::setKey(double key) +{ + mKey = key; +} + +/*! + Sets the parameter "minimum" of the statistical box plot. This is the position of the lower + whisker, typically the minimum measurement of the sample that's not considered an outlier. + + \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth +*/ +void QCPStatisticalBox::setMinimum(double value) +{ + mMinimum = value; +} + +/*! + Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the + box. The lower and the upper quartiles are the two statistical quartiles around the median of the + sample, they contain 50% of the sample data. + + \see setUpperQuartile, setPen, setBrush, setWidth +*/ +void QCPStatisticalBox::setLowerQuartile(double value) +{ + mLowerQuartile = value; +} + +/*! + Sets the parameter "median" of the statistical box plot. This is the value of the median mark + inside the quartile box. The median separates the sample data in half (50% of the sample data is + below/above the median). + + \see setMedianPen +*/ +void QCPStatisticalBox::setMedian(double value) +{ + mMedian = value; +} + +/*! + Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the + box. The lower and the upper quartiles are the two statistical quartiles around the median of the + sample, they contain 50% of the sample data. + + \see setLowerQuartile, setPen, setBrush, setWidth +*/ +void QCPStatisticalBox::setUpperQuartile(double value) +{ + mUpperQuartile = value; +} + +/*! + Sets the parameter "maximum" of the statistical box plot. This is the position of the upper + whisker, typically the maximum measurement of the sample that's not considered an outlier. + + \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth +*/ +void QCPStatisticalBox::setMaximum(double value) +{ + mMaximum = value; +} + +/*! + Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample + that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers + and displayed as such. + + \see setOutlierStyle +*/ +void QCPStatisticalBox::setOutliers(const QVector &values) +{ + mOutliers = values; +} + +/*! + Sets all parameters of the statistical box plot at once. + + \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum +*/ +void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) +{ + setKey(key); + setMinimum(minimum); + setLowerQuartile(lowerQuartile); + setMedian(median); + setUpperQuartile(upperQuartile); + setMaximum(maximum); +} + +/*! + Sets the width of the box in key coordinates. + + \see setWhiskerWidth +*/ +void QCPStatisticalBox::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. + + \see setWidth +*/ +void QCPStatisticalBox::setWhiskerWidth(double width) +{ + mWhiskerWidth = width; +} + +/*! + Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). + + Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching + a few pixels past the whisker bars, when using a non-zero pen width. + + \see setWhiskerBarPen +*/ +void QCPStatisticalBox::setWhiskerPen(const QPen &pen) +{ + mWhiskerPen = pen; +} + +/*! + Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at + each end of the whisker backbone). + + \see setWhiskerPen +*/ +void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) +{ + mWhiskerBarPen = pen; +} + +/*! + Sets the pen used for drawing the median indicator line inside the statistical box. +*/ +void QCPStatisticalBox::setMedianPen(const QPen &pen) +{ + mMedianPen = pen; +} + +/*! + Sets the appearance of the outlier data points. + + \see setOutliers +*/ +void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) +{ + mOutlierStyle = style; +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::clearData() +{ + setOutliers(QVector()); + setKey(0); + setMinimum(0); + setLowerQuartile(0); + setMedian(0); + setUpperQuartile(0); + setMaximum(0); +} + +/* inherits documentation from base class */ +double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + // quartile box: + QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); + QCPRange valueRange(mLowerQuartile, mUpperQuartile); + if (keyRange.contains(posKey) && valueRange.contains(posValue)) + return mParentPlot->selectionTolerance()*0.99; + + // min/max whiskers: + if (QCPRange(mMinimum, mMaximum).contains(posValue)) + return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); + } + return -1; +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + if (QCP::isInvalidData(mKey, mMedian) || + QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || + QCP::isInvalidData(mMinimum, mMaximum)) + qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); + for (int i=0; isave(); + painter->setClipRect(quartileBox, Qt::IntersectClip); + drawMedian(painter); + painter->restore(); + + drawWhiskers(painter); + drawOutliers(painter); +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->setBrush(mBrush); + QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); +} + +/*! \internal + + Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel + coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so + the median doesn't draw outside the quartile box). +*/ +void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const +{ + QRectF box; + box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); + box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(box); + if (quartileBox) + *quartileBox = box; +} + +/*! \internal + + Draws the median line inside the quartile box. +*/ +void QCPStatisticalBox::drawMedian(QCPPainter *painter) const +{ + QLineF medianLine; + medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); + medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); + applyDefaultAntialiasingHint(painter); + painter->setPen(mMedianPen); + painter->drawLine(medianLine); +} + +/*! \internal + + Draws both whisker backbones and bars. +*/ +void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const +{ + QLineF backboneMin, backboneMax, barMin, barMax; + backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); + backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); + barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); + barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); + applyErrorBarsAntialiasingHint(painter); + painter->setPen(mWhiskerPen); + painter->drawLine(backboneMin); + painter->drawLine(backboneMax); + painter->setPen(mWhiskerBarPen); + painter->drawLine(barMin); + painter->drawLine(barMax); +} + +/*! \internal + + Draws the outlier scatter points. +*/ +void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const +{ + applyScattersAntialiasingHint(painter); + mOutlierStyle.applyTo(painter, mPen); + for (int i=0; i 0) + return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); + else if (mKey > 0) + return QCPRange(mKey, mKey+mWidth*0.5); + else + { + foundRange = false; + return QCPRange(); + } + } + foundRange = false; + return QCPRange(); +} + +/* inherits documentation from base class */ +QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) + values.reserve(mOutliers.size() + 5); + values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; + values << mOutliers; + // go through values and find the ones in legal range: + bool haveUpper = false; + bool haveLower = false; + double upper = 0; + double lower = 0; + for (int i=0; i 0) || + (inSignDomain == sdBoth)) + { + if (values.at(i) > upper || !haveUpper) + { + upper = values.at(i); + haveUpper = true; + } + if (values.at(i) < lower || !haveLower) + { + lower = values.at(i); + haveLower = true; + } + } + } + // return the bounds if we found some sensible values: + if (haveLower && haveUpper) + { + foundRange = true; + return QCPRange(lower, upper); + } else // might happen if all values are in other sign domain + { + foundRange = false; + return QCPRange(); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorMapData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorMapData + \brief Holds the two-dimensional data of a QCPColorMap plottable. + + This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref + QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a + color, depending on the value. + + The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). + Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref + setKeyRange, \ref setValueRange). + + The data cells can be accessed in two ways: They can be directly addressed by an integer index + with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot + coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are + provided by the functions \ref coordToCell and \ref cellToCoord. + + This class also buffers the minimum and maximum values that are in the data set, to provide + QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value + that is greater than the current maximum increases this maximum to the new value. However, + setting the cell that currently holds the maximum value to a smaller value doesn't decrease the + maximum again, because finding the true new maximum would require going through the entire data + array, which might be time consuming. The same holds for the data minimum. This functionality is + given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the + true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience + parameter \a recalculateDataBounds which may be set to true to automatically call \ref + recalculateDataBounds internally. +*/ + +/* start of documentation of inline functions */ + +/*! \fn bool QCPColorMapData::isEmpty() const + + Returns whether this instance carries no data. This is equivalent to having a size where at least + one of the dimensions is 0 (see \ref setSize). +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction + and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap + at the coordinates \a keyRange and \a valueRange. + + \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange +*/ +QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : + mKeySize(0), + mValueSize(0), + mKeyRange(keyRange), + mValueRange(valueRange), + mIsEmpty(true), + mData(0), + mDataModified(true) +{ + setSize(keySize, valueSize); + fill(0); +} + +QCPColorMapData::~QCPColorMapData() +{ + if (mData) + delete[] mData; +} + +/*! + Constructs a new QCPColorMapData instance copying the data and range of \a other. +*/ +QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : + mKeySize(0), + mValueSize(0), + mIsEmpty(true), + mData(0), + mDataModified(true) +{ + *this = other; +} + +/*! + Overwrites this color map data instance with the data stored in \a other. +*/ +QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) +{ + if (&other != this) + { + const int keySize = other.keySize(); + const int valueSize = other.valueSize(); + setSize(keySize, valueSize); + setRange(other.keyRange(), other.valueRange()); + if (!mIsEmpty) + memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); + mDataBounds = other.mDataBounds; + mDataModified = true; + } + return *this; +} + +/* undocumented getter */ +double QCPColorMapData::data(double key, double value) +{ + int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; + int valueCell = (1.0-(value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower))*(mValueSize-1)+0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) + return mData[valueCell*mKeySize + keyCell]; + else + return 0; +} + +/* undocumented getter */ +double QCPColorMapData::cell(int keyIndex, int valueIndex) +{ + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + return mData[valueIndex*mKeySize + keyIndex]; + else + return 0; +} + +/*! + Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in + the value dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref + isEmpty returns true. + + \see setRange, setKeySize, setValueSize +*/ +void QCPColorMapData::setSize(int keySize, int valueSize) +{ + if (keySize != mKeySize || valueSize != mValueSize) + { + mKeySize = keySize; + mValueSize = valueSize; + if (mData) + delete[] mData; + mIsEmpty = mKeySize == 0 || mValueSize == 0; + if (!mIsEmpty) + { +#ifdef __EXCEPTIONS + try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message +#endif + mData = new double[mKeySize*mValueSize]; +#ifdef __EXCEPTIONS + } catch (...) { mData = 0; } +#endif + if (mData) + fill(0); + else + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; + } else + mData = 0; + mDataModified = true; + } +} + +/*! + Resizes the data array to have \a keySize cells in the key dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. + + \see setKeyRange, setSize, setValueSize +*/ +void QCPColorMapData::setKeySize(int keySize) +{ + setSize(keySize, mValueSize); +} + +/*! + Resizes the data array to have \a valueSize cells in the value dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. + + \see setValueRange, setSize, setKeySize +*/ +void QCPColorMapData::setValueSize(int valueSize) +{ + setSize(mKeySize, valueSize); +} + +/*! + Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area + covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will + be cells centered on the key coordinates 2, 2.5 and 3. + + \see setSize +*/ +void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) +{ + setKeyRange(keyRange); + setValueRange(valueRange); +} + +/*! + Sets the coordinate range the data shall be distributed over in the key dimension. Together with + the value range, This defines the rectangular area covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will + be cells centered on the key coordinates 2, 2.5 and 3. + + \see setRange, setValueRange, setSize +*/ +void QCPColorMapData::setKeyRange(const QCPRange &keyRange) +{ + mKeyRange = keyRange; +} + +/*! + Sets the coordinate range the data shall be distributed over in the value dimension. Together with + the key range, This defines the rectangular area covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there + will be cells centered on the value coordinates 2, 2.5 and 3. + + \see setRange, setKeyRange, setSize +*/ +void QCPColorMapData::setValueRange(const QCPRange &valueRange) +{ + mValueRange = valueRange; +} + +/*! + Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a + z. + + \see setCell, setRange +*/ +void QCPColorMapData::setData(double key, double value, double z) +{ + int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; + int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) + { + mData[valueCell*mKeySize + keyCell] = z; + if (z < mDataBounds.lower) + mDataBounds.lower = z; + if (z > mDataBounds.upper) + mDataBounds.upper = z; + mDataModified = true; + } +} + +/*! + Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices + enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see + \ref setSize). + + In the standard plot configuration (horizontal key axis and vertical value axis, both not + range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with + indices (keySize-1, valueSize-1) is in the top right corner of the color map. + + \see setData, setSize +*/ +void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) +{ + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + { + mData[valueIndex*mKeySize + keyIndex] = z; + if (z < mDataBounds.lower) + mDataBounds.lower = z; + if (z > mDataBounds.upper) + mDataBounds.upper = z; + mDataModified = true; + } +} + +/*! + Goes through the data and updates the buffered minimum and maximum data values. + + Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange + and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten + with a smaller or larger value respectively, since the buffered maximum/minimum values have been + updated the last time. Why this is the case is explained in the class description (\ref + QCPColorMapData). + + Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a + recalculateDataBounds for convenience. Setting this to true will call this method for you, before + doing the rescale. +*/ +void QCPColorMapData::recalculateDataBounds() +{ + if (mKeySize > 0 && mValueSize > 0) + { + double minHeight = mData[0]; + double maxHeight = mData[0]; + const int dataCount = mValueSize*mKeySize; + for (int i=0; i maxHeight) + maxHeight = mData[i]; + if (mData[i] < minHeight) + minHeight = mData[i]; + } + mDataBounds.lower = minHeight; + mDataBounds.upper = maxHeight; + } +} + +/*! + Frees the internal data memory. + + This is equivalent to calling \ref setSize "setSize(0, 0)". +*/ +void QCPColorMapData::clear() +{ + setSize(0, 0); +} + +/*! + Sets all cells to the value \a z. +*/ +void QCPColorMapData::fill(double z) +{ + const int dataCount = mValueSize*mKeySize; + for (int i=0; ixAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(colorMap);\endcode + and then modify the properties of the newly created color map, e.g.: + \code + colorMap->data()->setSize(50, 50); + colorMap->data()->setRange(QCPRange(0, 2), QCPRange(0, 2)); + for (int x=0; x<50; ++x) + for (int y=0; y<50; ++y) + colorMap->data()->setCell(x, y, qCos(x/10.0)+qSin(y/10.0)); + colorMap->setGradient(QCPColorGradient::gpPolar); + colorMap->rescaleDataRange(true); + customPlot->rescaleAxes(); + customPlot->replot(); + \endcode + + \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or + value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, + you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to + determine the cell index. Rather directly access the cell index with \ref + QCPColorMapData::setCell. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPColorMapData *QCPColorMap::data() const + + Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to + modify data points (cells) and the color map key/value range. + + \see setData +*/ + +/* end documentation of inline functions */ + +/* start documentation of signals */ + +/*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange); + + This signal is emitted when the data range changes. + + \see setDataRange +*/ + +/*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the data scale type changes. + + \see setDataScaleType +*/ + +/*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient); + + This signal is emitted when the gradient changes. + + \see setGradient +*/ + +/* end documentation of signals */ + +/*! + Constructs a color map with the specified \a keyAxis and \a valueAxis. + + The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the color map. +*/ +QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mDataScaleType(QCPAxis::stLinear), + mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))), + mInterpolate(true), + mTightBoundary(false), + mMapImageInvalidated(true) +{ +} + +QCPColorMap::~QCPColorMap() +{ + delete mMapData; +} + +/*! + Replaces the current \ref data with the provided \a data. + + If \a copy is set to true, the \a data object will only be copied. if false, the color map + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPColorMap::setData(QCPColorMapData *data, bool copy) +{ + if (copy) + { + *mMapData = *data; + } else + { + delete mMapData; + mMapData = data; + } + mMapImageInvalidated = true; +} + +/*! + Sets the data range of this color map to \a dataRange. The data range defines which data values + are mapped to the color gradient. + + To make the data range span the full range of the data set, use \ref rescaleDataRange. + + \see QCPColorScale::setDataRange +*/ +void QCPColorMap::setDataRange(const QCPRange &dataRange) +{ + if (!QCPRange::validRange(dataRange)) return; + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + { + if (mDataScaleType == QCPAxis::stLogarithmic) + mDataRange = dataRange.sanitizedForLogScale(); + else + mDataRange = dataRange.sanitizedForLinScale(); + mMapImageInvalidated = true; + emit dataRangeChanged(mDataRange); + } +} + +/*! + Sets whether the data is correlated with the color gradient linearly or logarithmically. + + \see QCPColorScale::setDataScaleType +*/ +void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) +{ + if (mDataScaleType != scaleType) + { + mDataScaleType = scaleType; + mMapImageInvalidated = true; + emit dataScaleTypeChanged(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) + setDataRange(mDataRange.sanitizedForLogScale()); + } +} + +/*! + Sets the color gradient that is used to represent the data. For more details on how to create an + own gradient or use one of the preset gradients, see \ref QCPColorGradient. + + The colors defined by the gradient will be used to represent data values in the currently set + data range, see \ref setDataRange. Data points that are outside this data range will either be + colored uniformly with the respective gradient boundary color, or the gradient will repeat, + depending on \ref QCPColorGradient::setPeriodic. + + \see QCPColorScale::setGradient +*/ +void QCPColorMap::setGradient(const QCPColorGradient &gradient) +{ + if (mGradient != gradient) + { + mGradient = gradient; + mMapImageInvalidated = true; + emit gradientChanged(mGradient); + } +} + +/*! + Sets whether the color map image shall use bicubic interpolation when displaying the color map + shrinked or expanded, and not at a 1:1 pixel-to-data scale. + + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" +*/ +void QCPColorMap::setInterpolate(bool enabled) +{ + mInterpolate = enabled; +} + +/*! + Sets whether the outer most data rows and columns are clipped to the specified key and value + range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). + + if \a enabled is set to false, the data points at the border of the color map are drawn with the + same width and height as all other data points. Since the data points are represented by + rectangles of one color centered on the data coordinate, this means that the shown color map + extends by half a data point over the specified key/value range in each direction. + + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" +*/ +void QCPColorMap::setTightBoundary(bool enabled) +{ + mTightBoundary = enabled; +} + +/*! + Associates the color scale \a colorScale with this color map. + + This means that both the color scale and the color map synchronize their gradient, data range and + data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps + can be associated with one single color scale. This causes the color maps to also synchronize + those properties, via the mutual color scale. + + This function causes the color map to adopt the current color gradient, data range and data scale + type of \a colorScale. After this call, you may change these properties at either the color map + or the color scale, and the setting will be applied to both. + + Pass 0 as \a colorScale to disconnect the color scale from this color map again. +*/ +void QCPColorMap::setColorScale(QCPColorScale *colorScale) +{ + if (mColorScale) // unconnect signals from old color scale + { + disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + mColorScale = colorScale; + if (mColorScale) // connect signals to new color scale + { + setGradient(mColorScale.data()->gradient()); + setDataRange(mColorScale.data()->dataRange()); + setDataScaleType(mColorScale.data()->dataScaleType()); + connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } +} + +/*! + Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the + current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, + only for the third data dimension of the color map. + + The minimum and maximum values of the data set are buffered in the internal QCPColorMapData + instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref + QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For + performance reasons, however, they are only updated in an expanding fashion. So the buffered + maximum can only increase and the buffered minimum can only decrease. In consequence, changes to + the data that actually lower the maximum of the data set (by overwriting the cell holding the + current maximum with a smaller value), aren't recognized and the buffered maximum overestimates + the true maximum of the data set. The same happens for the buffered minimum. To recalculate the + true minimum and maximum by explicitly looking at each cell, the method + QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a + recalculateDataBounds calls this method before setting the data range to the buffered minimum and + maximum. + + \see setDataRange +*/ +void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) +{ + if (recalculateDataBounds) + mMapData->recalculateDataBounds(); + setDataRange(mMapData->dataBounds()); +} + +/*! + Takes the current appearance of the color map and updates the legend icon, which is used to + represent this color map in the legend (see \ref QCPLegend). + + The \a transformMode specifies whether the rescaling is done by a faster, low quality image + scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm + (Qt::SmoothTransformation). + + The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to + the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured + legend icon size, the thumb will be rescaled during drawing of the legend item. + + \see setDataRange +*/ +void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) +{ + if (mMapImage.isNull() && !data()->isEmpty()) + updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) + + if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again + { + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); + } +} + +/*! + Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also + resizes the map to 0x0 cells. +*/ +void QCPColorMap::clearData() +{ + mMapData->clear(); +} + +/* inherits documentation from base class */ +double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/*! \internal + + Updates the internal map image buffer by going through the internal \ref QCPColorMapData and + turning the data values into color pixels with \ref QCPColorGradient::colorize. + + This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image + has been invalidated for a different reason (e.g. a change of the data range with \ref + setDataRange). +*/ +void QCPColorMap::updateMapImage() +{ + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) return; + + // resize mMapImage to correct dimensions, according to key/value axes orientation: + if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize())) + mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32); + else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize())) + mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32); + + const int keySize = mMapData->keySize(); + const int valueSize = mMapData->valueSize(); + const double *rawData = mMapData->mData; + + if (keyAxis->orientation() == Qt::Horizontal) + { + const int lineCount = valueSize; + const int rowCount = keySize; + for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); + } + } else // keyAxis->orientation() == Qt::Vertical + { + const int lineCount = keySize; + const int rowCount = valueSize; + for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); + } + } + + mMapData->mDataModified = false; + mMapImageInvalidated = false; +} + +/* inherits documentation from base class */ +void QCPColorMap::draw(QCPPainter *painter) +{ + if (mMapData->isEmpty()) return; + if (!mKeyAxis || !mValueAxis) return; + applyDefaultAntialiasingHint(painter); + + if (mMapData->mDataModified || mMapImageInvalidated) + updateMapImage(); + + double halfSampleKey = 0; + double halfSampleValue = 0; + if (mMapData->keySize() > 1) + halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1); + if (mMapData->valueSize() > 1) + halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1); + QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue), + coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue)); + imageRect = imageRect.normalized(); + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform); + painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); + QRegion clipBackup; + if (mTightBoundary) + { + clipBackup = painter->clipRegion(); + painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip); + } + painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); + if (mTightBoundary) + painter->setClipRegion(clipBackup); + painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); +} + +/* inherits documentation from base class */ +void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + applyDefaultAntialiasingHint(painter); + // draw map thumbnail: + if (!mLegendIcon.isNull()) + { + QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); + QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); + iconRect.moveCenter(rect.center()); + painter->drawPixmap(iconRect.topLeft(), scaledIcon); + } + /* + // draw frame: + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::black); + painter->drawRect(rect.adjusted(1, 1, 0, 0)); + */ +} + +/* inherits documentation from base class */ +QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + foundRange = true; + QCPRange result = mMapData->keyRange(); + result.normalize(); + if (inSignDomain == QCPAbstractPlottable::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCPAbstractPlottable::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + +/* inherits documentation from base class */ +QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + foundRange = true; + QCPRange result = mMapData->valueRange(); + result.normalize(); + if (inSignDomain == QCPAbstractPlottable::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCPAbstractPlottable::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemStraightLine +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemStraightLine + \brief A straight line that spans infinitely in both directions + + \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a point1 and \a point2, which define the straight line. +*/ + +/*! + Creates a straight line item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + point1(createPosition("point1")), + point2(createPosition("point2")) +{ + point1->setCoords(0, 0); + point2->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemStraightLine::~QCPItemStraightLine() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemStraightLine::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemStraightLine::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/* inherits documentation from base class */ +double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); +} + +/* inherits documentation from base class */ +void QCPItemStraightLine::draw(QCPPainter *painter) +{ + QVector2D start(point1->pixelPoint()); + QVector2D end(point2->pixelPoint()); + // get visible segment of straight line inside clipRect: + double clipPad = mainPen().widthF(); + QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) + { + painter->setPen(mainPen()); + painter->drawLine(line); + } +} + +/*! \internal + + finds the shortest distance of \a point to the straight line defined by the base point \a + base and the direction vector \a vec. + + This is a helper function for \ref selectTest. +*/ +double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const +{ + return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); +} + +/*! \internal + + Returns the section of the straight line defined by \a base and direction vector \a + vec, that is visible in the specified \a rect. + + This is a helper function for \ref draw. +*/ +QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const +{ + double bx, by; + double gamma; + QLineF result; + if (vec.x() == 0 && vec.y() == 0) + return result; + if (qFuzzyIsNull(vec.x())) // line is vertical + { + // check top of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical + } else if (qFuzzyIsNull(vec.y())) // line is horizontal + { + // check left of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal + } else // line is skewed + { + QList pointVectors; + // check top of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + // check left of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + // check right of rect: + bx = rect.right(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + + // evaluate points: + if (pointVectors.size() == 2) + { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) + { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QVector2D pv1, pv2; + for (int i=0; i distSqrMax) + { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + } + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemStraightLine::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemLine +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemLine + \brief A line from one point to another + + \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a start and \a end, which define the end points of the line. + + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. +*/ + +/*! + Creates a line item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + start(createPosition("start")), + end(createPosition("end")) +{ + start->setCoords(0, 0); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemLine::~QCPItemLine() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemLine::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemLine::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the line ending style of the head. The head corresponds to the \a end position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode + + \see setTail +*/ +void QCPItemLine::setHead(const QCPLineEnding &head) +{ + mHead = head; +} + +/*! + Sets the line ending style of the tail. The tail corresponds to the \a start position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode + + \see setHead +*/ +void QCPItemLine::setTail(const QCPLineEnding &tail) +{ + mTail = tail; +} + +/* inherits documentation from base class */ +double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); +} + +/* inherits documentation from base class */ +void QCPItemLine::draw(QCPPainter *painter) +{ + QVector2D startVec(start->pixelPoint()); + QVector2D endVec(end->pixelPoint()); + if (startVec.toPoint() == endVec.toPoint()) + return; + // get visible segment of straight line inside clipRect: + double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); + clipPad = qMax(clipPad, (double)mainPen().widthF()); + QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) + { + painter->setPen(mainPen()); + painter->drawLine(line); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) + mTail.draw(painter, startVec, startVec-endVec); + if (mHead.style() != QCPLineEnding::esNone) + mHead.draw(painter, endVec, endVec-startVec); + } +} + +/*! \internal + + Returns the section of the line defined by \a start and \a end, that is visible in the specified + \a rect. + + This is a helper function for \ref draw. +*/ +QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const +{ + bool containsStart = rect.contains(start.x(), start.y()); + bool containsEnd = rect.contains(end.x(), end.y()); + if (containsStart && containsEnd) + return QLineF(start.toPointF(), end.toPointF()); + + QVector2D base = start; + QVector2D vec = end-start; + double bx, by; + double gamma, mu; + QLineF result; + QList pointVectors; + + if (!qFuzzyIsNull(vec.y())) // line is not horizontal + { + // check top of rect: + bx = rect.left(); + by = rect.top(); + mu = (by-base.y())/vec.y(); + if (mu >= 0 && mu <= 1) + { + gamma = base.x()-bx + mu*vec.x(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + } + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + mu = (by-base.y())/vec.y(); + if (mu >= 0 && mu <= 1) + { + gamma = base.x()-bx + mu*vec.x(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + } + } + if (!qFuzzyIsNull(vec.x())) // line is not vertical + { + // check left of rect: + bx = rect.left(); + by = rect.top(); + mu = (bx-base.x())/vec.x(); + if (mu >= 0 && mu <= 1) + { + gamma = base.y()-by + mu*vec.y(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + } + // check right of rect: + bx = rect.right(); + by = rect.top(); + mu = (bx-base.x())/vec.x(); + if (mu >= 0 && mu <= 1) + { + gamma = base.y()-by + mu*vec.y(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + } + } + + if (containsStart) + pointVectors.append(start); + if (containsEnd) + pointVectors.append(end); + + // evaluate points: + if (pointVectors.size() == 2) + { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) + { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QVector2D pv1, pv2; + for (int i=0; i distSqrMax) + { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemLine::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemCurve +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemCurve + \brief A curved line from one point to another + + \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." + + It has four positions, \a start and \a end, which define the end points of the line, and two + control points which define the direction the line exits from the start and the direction from + which it approaches the end: \a startDir and \a endDir. + + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an + arrow. + + Often it is desirable for the control points to stay at fixed relative positions to the start/end + point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, + and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. +*/ + +/*! + Creates a curve item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + start(createPosition("start")), + startDir(createPosition("startDir")), + endDir(createPosition("endDir")), + end(createPosition("end")) +{ + start->setCoords(0, 0); + startDir->setCoords(0.5, 0); + endDir->setCoords(0, 0.5); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemCurve::~QCPItemCurve() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemCurve::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemCurve::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the line ending style of the head. The head corresponds to the \a end position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode + + \see setTail +*/ +void QCPItemCurve::setHead(const QCPLineEnding &head) +{ + mHead = head; +} + +/*! + Sets the line ending style of the tail. The tail corresponds to the \a start position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode + + \see setHead +*/ +void QCPItemCurve::setTail(const QCPLineEnding &tail) +{ + mTail = tail; +} + +/* inherits documentation from base class */ +double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QPointF startVec(start->pixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + QPolygonF polygon = cubicPath.toSubpathPolygons().first(); + double minDistSqr = std::numeric_limits::max(); + for (int i=1; ipixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash + return; + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + // paint visible segment, if existent: + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + QRect cubicRect = cubicPath.controlPointRect().toRect(); + if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position + cubicRect.adjust(0, 0, 1, 1); + if (clip.intersects(cubicRect)) + { + painter->setPen(mainPen()); + painter->drawPath(cubicPath); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) + mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); + if (mHead.style() != QCPLineEnding::esNone) + mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); + } +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemCurve::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemRect +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemRect + \brief A rectangle + + \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rectangle. +*/ + +/*! + Creates a rectangle item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +QCPItemRect::~QCPItemRect() +{ +} + +/*! + Sets the pen that will be used to draw the line of the rectangle + + \see setSelectedPen, setBrush +*/ +void QCPItemRect::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the rectangle when selected + + \see setPen, setSelected +*/ +void QCPItemRect::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to + Qt::NoBrush. + + \see setSelectedBrush, setPen +*/ +void QCPItemRect::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a + brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemRect::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/* inherits documentation from base class */ +double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectSelectTest(rect, pos, filledRect); +} + +/* inherits documentation from base class */ +void QCPItemRect::draw(QCPPainter *painter) +{ + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) + return; + QRectF rect = QRectF(p1, p2).normalized(); + double clipPad = mainPen().widthF(); + QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(rect); + } +} + +/* inherits documentation from base class */ +QPointF QCPItemRect::anchorPixelPoint(int anchorId) const +{ + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) + { + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRight: return rect.topRight(); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeft: return rect.bottomLeft(); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemRect::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemRect::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemText +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemText + \brief A text label + + \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." + + Its position is defined by the member \a position and the setting of \ref setPositionAlignment. + The latter controls which part of the text rect shall be aligned with \a position. + + The text alignment itself (i.e. left, center, right) can be controlled with \ref + setTextAlignment. + + The text may be rotated around the \a position point with \ref setRotation. +*/ + +/*! + Creates a text item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemText::QCPItemText(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + position(createPosition("position")), + topLeft(createAnchor("topLeft", aiTopLeft)), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottomRight(createAnchor("bottomRight", aiBottomRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + position->setCoords(0, 0); + + setRotation(0); + setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); + setPositionAlignment(Qt::AlignCenter); + setText("text"); + + setPen(Qt::NoPen); + setSelectedPen(Qt::NoPen); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setColor(Qt::black); + setSelectedColor(Qt::blue); +} + +QCPItemText::~QCPItemText() +{ +} + +/*! + Sets the color of the text. +*/ +void QCPItemText::setColor(const QColor &color) +{ + mColor = color; +} + +/*! + Sets the color of the text that will be used when the item is selected. +*/ +void QCPItemText::setSelectedColor(const QColor &color) +{ + mSelectedColor = color; +} + +/*! + Sets the pen that will be used do draw a rectangular border around the text. To disable the + border, set \a pen to Qt::NoPen. + + \see setSelectedPen, setBrush, setPadding +*/ +void QCPItemText::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used do draw a rectangular border around the text, when the item is + selected. To disable the border, set \a pen to Qt::NoPen. + + \see setPen +*/ +void QCPItemText::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used do fill the background of the text. To disable the + background, set \a brush to Qt::NoBrush. + + \see setSelectedBrush, setPen, setPadding +*/ +void QCPItemText::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the + background, set \a brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemText::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the font of the text. + + \see setSelectedFont, setColor +*/ +void QCPItemText::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the font of the text that will be used when the item is selected. + + \see setFont +*/ +void QCPItemText::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + Sets the text that will be displayed. Multi-line texts are supported by inserting a line break + character, e.g. '\n'. + + \see setFont, setColor, setTextAlignment +*/ +void QCPItemText::setText(const QString &text) +{ + mText = text; +} + +/*! + Sets which point of the text rect shall be aligned with \a position. + + Examples: + \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such + that the top of the text rect will be horizontally centered on \a position. + \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the + bottom left corner of the text rect. + + If you want to control the alignment of (multi-lined) text within the text rect, use \ref + setTextAlignment. +*/ +void QCPItemText::setPositionAlignment(Qt::Alignment alignment) +{ + mPositionAlignment = alignment; +} + +/*! + Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). +*/ +void QCPItemText::setTextAlignment(Qt::Alignment alignment) +{ + mTextAlignment = alignment; +} + +/*! + Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated + around \a position. +*/ +void QCPItemText::setRotation(double degrees) +{ + mRotation = degrees; +} + +/*! + Sets the distance between the border of the text rectangle and the text. The appearance (and + visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. +*/ +void QCPItemText::setPadding(const QMargins &padding) +{ + mPadding = padding; +} + +/* inherits documentation from base class */ +double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + // The rect may be rotated, so we transform the actual clicked pos to the rotated + // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: + QPointF positionPixels(position->pixelPoint()); + QTransform inputTransform; + inputTransform.translate(positionPixels.x(), positionPixels.y()); + inputTransform.rotate(-mRotation); + inputTransform.translate(-positionPixels.x(), -positionPixels.y()); + QPointF rotatedPos = inputTransform.map(pos); + QFontMetrics fontMetrics(mFont); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); + textBoxRect.moveTopLeft(textPos.toPoint()); + + return rectSelectTest(textBoxRect, rotatedPos, true); +} + +/* inherits documentation from base class */ +void QCPItemText::draw(QCPPainter *painter) +{ + QPointF pos(position->pixelPoint()); + QTransform transform = painter->transform(); + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) + transform.rotate(mRotation); + painter->setFont(mainFont()); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); + textBoxRect.moveTopLeft(textPos.toPoint()); + double clipPad = mainPen().widthF(); + QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) + { + painter->setTransform(transform); + if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || + (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(textBoxRect); + } + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(mainColor())); + painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); + } +} + +/* inherits documentation from base class */ +QPointF QCPItemText::anchorPixelPoint(int anchorId) const +{ + // get actual rect points (pretty much copied from draw function): + QPointF pos(position->pixelPoint()); + QTransform transform; + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) + transform.rotate(mRotation); + QFontMetrics fontMetrics(mainFont()); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textBoxRect.moveTopLeft(textPos.toPoint()); + QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); + + switch (anchorId) + { + case aiTopLeft: return rectPoly.at(0); + case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; + case aiTopRight: return rectPoly.at(1); + case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; + case aiBottomRight: return rectPoly.at(2); + case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; + case aiBottomLeft: return rectPoly.at(3); + case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the point that must be given to the QPainter::drawText function (which expects the top + left point of the text rect), according to the position \a pos, the text bounding box \a rect and + the requested \a positionAlignment. + + For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point + will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally + drawn at that point, the lower left corner of the resulting text rect is at \a pos. +*/ +QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const +{ + if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) + return pos; + + QPointF result = pos; // start at top left + if (positionAlignment.testFlag(Qt::AlignHCenter)) + result.rx() -= rect.width()/2.0; + else if (positionAlignment.testFlag(Qt::AlignRight)) + result.rx() -= rect.width(); + if (positionAlignment.testFlag(Qt::AlignVCenter)) + result.ry() -= rect.height()/2.0; + else if (positionAlignment.testFlag(Qt::AlignBottom)) + result.ry() -= rect.height(); + return result; +} + +/*! \internal + + Returns the font that should be used for drawing text. Returns mFont when the item is not selected + and mSelectedFont when it is. +*/ +QFont QCPItemText::mainFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Returns the color that should be used for drawing text. Returns mColor when the item is not + selected and mSelectedColor when it is. +*/ +QColor QCPItemText::mainColor() const +{ + return mSelected ? mSelectedColor : mColor; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemText::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemText::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemEllipse +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemEllipse + \brief An ellipse + + \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. +*/ + +/*! + Creates an ellipse item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)), + top(createAnchor("top", aiTop)), + topRightRim(createAnchor("topRightRim", aiTopRightRim)), + right(createAnchor("right", aiRight)), + bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)), + left(createAnchor("left", aiLeft)), + center(createAnchor("center", aiCenter)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +QCPItemEllipse::~QCPItemEllipse() +{ +} + +/*! + Sets the pen that will be used to draw the line of the ellipse + + \see setSelectedPen, setBrush +*/ +void QCPItemEllipse::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the ellipse when selected + + \see setPen, setSelected +*/ +void QCPItemEllipse::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to + Qt::NoBrush. + + \see setSelectedBrush, setPen +*/ +void QCPItemEllipse::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a + brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemEllipse::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/* inherits documentation from base class */ +double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + double result = -1; + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + QPointF center((p1+p2)/2.0); + double a = qAbs(p1.x()-p2.x())/2.0; + double b = qAbs(p1.y()-p2.y())/2.0; + double x = pos.x()-center.x(); + double y = pos.y()-center.y(); + + // distance to border: + double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); + result = qAbs(c-1)*qSqrt(x*x+y*y); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) + { + if (x*x/(a*a) + y*y/(b*b) <= 1) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; +} + +/* inherits documentation from base class */ +void QCPItemEllipse::draw(QCPPainter *painter) +{ + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) + return; + QRectF ellipseRect = QRectF(p1, p2).normalized(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); +#ifdef __EXCEPTIONS + try // drawEllipse sometimes throws exceptions if ellipse is too big + { +#endif + painter->drawEllipse(ellipseRect); +#ifdef __EXCEPTIONS + } catch (...) + { + qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; + setVisible(false); + } +#endif + } +} + +/* inherits documentation from base class */ +QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const +{ + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) + { + case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; + case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemEllipse::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemEllipse::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemPixmap +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemPixmap + \brief An arbitrary pixmap + + \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will + be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to + fit the rectangle or be drawn aligned to the topLeft position. + + If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown + on the right side of the example image), the pixmap will be flipped in the respective + orientations. +*/ + +/*! + Creates a rectangle item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(Qt::NoPen); + setSelectedPen(QPen(Qt::blue)); + setScaled(false, Qt::KeepAspectRatio); +} + +QCPItemPixmap::~QCPItemPixmap() +{ +} + +/*! + Sets the pixmap that will be displayed. +*/ +void QCPItemPixmap::setPixmap(const QPixmap &pixmap) +{ + mPixmap = pixmap; + if (mPixmap.isNull()) + qDebug() << Q_FUNC_INFO << "pixmap is null"; +} + +/*! + Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a + bottomRight positions. +*/ +void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode) +{ + mScaled = scaled; + mAspectRatioMode = aspectRatioMode; + updateScaledPixmap(); +} + +/*! + Sets the pen that will be used to draw a border around the pixmap. + + \see setSelectedPen, setBrush +*/ +void QCPItemPixmap::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw a border around the pixmap when selected + + \see setPen, setSelected +*/ +void QCPItemPixmap::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/* inherits documentation from base class */ +double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return rectSelectTest(getFinalRect(), pos, true); +} + +/* inherits documentation from base class */ +void QCPItemPixmap::draw(QCPPainter *painter) +{ + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); + QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) + { + updateScaledPixmap(rect, flipHorz, flipVert); + painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + QPen pen = mainPen(); + if (pen.style() != Qt::NoPen) + { + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rect); + } + } +} + +/* inherits documentation from base class */ +QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const +{ + bool flipHorz; + bool flipVert; + QRect rect = getFinalRect(&flipHorz, &flipVert); + // we actually want denormal rects (negative width/height) here, so restore + // the flipped state: + if (flipHorz) + rect.adjust(rect.width(), 0, -rect.width(), 0); + if (flipVert) + rect.adjust(0, rect.height(), 0, -rect.height()); + + switch (anchorId) + { + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRight: return rect.topRight(); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeft: return rect.bottomLeft(); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The + parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped + horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a + bottomRight.) + + This function only creates the scaled pixmap when the buffered pixmap has a different size than + the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does + not cause expensive rescaling every time. + + If scaling is disabled, sets mScaledPixmap to a null QPixmap. +*/ +void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) +{ + if (mPixmap.isNull()) + return; + + if (mScaled) + { + if (finalRect.isNull()) + finalRect = getFinalRect(&flipHorz, &flipVert); + if (finalRect.size() != mScaledPixmap.size()) + { + mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation); + if (flipHorz || flipVert) + mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); + } + } else if (!mScaledPixmap.isNull()) + mScaledPixmap = QPixmap(); +} + +/*! \internal + + Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions + and scaling settings. + + The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn + flipped horizontally or vertically in the returned rect. (The returned rect itself is always + normalized, i.e. the top left corner of the rect is actually further to the top/left than the + bottom right corner). This is the case when the item position \a topLeft is further to the + bottom/right than \a bottomRight. + + If scaling is disabled, returns a rect with size of the original pixmap and the top left corner + aligned with the item position \a topLeft. The position \a bottomRight is ignored. +*/ +QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const +{ + QRect result; + bool flipHorz = false; + bool flipVert = false; + QPoint p1 = topLeft->pixelPoint().toPoint(); + QPoint p2 = bottomRight->pixelPoint().toPoint(); + if (p1 == p2) + return QRect(p1, QSize(0, 0)); + if (mScaled) + { + QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); + QPoint topLeft = p1; + if (newSize.width() < 0) + { + flipHorz = true; + newSize.rwidth() *= -1; + topLeft.setX(p2.x()); + } + if (newSize.height() < 0) + { + flipVert = true; + newSize.rheight() *= -1; + topLeft.setY(p2.y()); + } + QSize scaledSize = mPixmap.size(); + scaledSize.scale(newSize, mAspectRatioMode); + result = QRect(topLeft, scaledSize); + } else + { + result = QRect(p1, mPixmap.size()); + } + if (flippedHorz) + *flippedHorz = flipHorz; + if (flippedVert) + *flippedVert = flipVert; + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemPixmap::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemTracer +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemTracer + \brief Item that sticks to QCPGraph data points + + \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." + + The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt + the coordinate axes of the graph and update its \a position to be on the graph's data. This means + the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a + QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a + position will have no effect because they will be overriden in the next redraw (this is when the + coordinate update happens). + + If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will + stay at the corresponding end of the graph. + + With \ref setInterpolating you may specify whether the tracer may only stay exactly on data + points or whether it interpolates data points linearly, if given a key that lies between two data + points of the graph. + + The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer + have no own visual appearance (set the style to \ref tsNone), and just connect other item + positions to the tracer \a position (used as an anchor) via \ref + QCPItemPosition::setParentAnchor. + + \note The tracer position is only automatically updated upon redraws. So when the data of the + graph changes and immediately afterwards (without a redraw) the a position coordinates of the + tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref + updatePosition must be called manually, prior to reading the tracer coordinates. +*/ + +/*! + Creates a tracer item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + position(createPosition("position")), + mGraph(0) +{ + position->setCoords(0, 0); + + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setStyle(tsCrosshair); + setSize(6); + setInterpolating(false); + setGraphKey(0); +} + +QCPItemTracer::~QCPItemTracer() +{ +} + +/*! + Sets the pen that will be used to draw the line of the tracer + + \see setSelectedPen, setBrush +*/ +void QCPItemTracer::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the tracer when selected + + \see setPen, setSelected +*/ +void QCPItemTracer::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to draw any fills of the tracer + + \see setSelectedBrush, setPen +*/ +void QCPItemTracer::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to draw any fills of the tracer, when selected. + + \see setBrush, setSelected +*/ +void QCPItemTracer::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare + does, \ref tsCrosshair does not). +*/ +void QCPItemTracer::setSize(double size) +{ + mSize = size; +} + +/*! + Sets the style/visual appearance of the tracer. + + If you only want to use the tracer \a position as an anchor for other items, set \a style to + \ref tsNone. +*/ +void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) +{ + mStyle = style; +} + +/*! + Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type + QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. + + To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed + freely like any other item position. This is the state the tracer will assume when its graph gets + deleted while still attached to it. + + \see setGraphKey +*/ +void QCPItemTracer::setGraph(QCPGraph *graph) +{ + if (graph) + { + if (graph->parentPlot() == mParentPlot) + { + position->setType(QCPItemPosition::ptPlotCoords); + position->setAxes(graph->keyAxis(), graph->valueAxis()); + mGraph = graph; + updatePosition(); + } else + qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; + } else + { + mGraph = 0; + } +} + +/*! + Sets the key of the graph's data point the tracer will be positioned at. This is the only free + coordinate of a tracer when attached to a graph. + + Depending on \ref setInterpolating, the tracer will be either positioned on the data point + closest to \a key, or will stay exactly at \a key and interpolate the value linearly. + + \see setGraph, setInterpolating +*/ +void QCPItemTracer::setGraphKey(double key) +{ + mGraphKey = key; +} + +/*! + Sets whether the value of the graph's data points shall be interpolated, when positioning the + tracer. + + If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on + the data point of the graph which is closest to the key, but which is not necessarily exactly + there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and + the appropriate value will be interpolated from the graph's data points linearly. + + \see setGraph, setGraphKey +*/ +void QCPItemTracer::setInterpolating(bool enabled) +{ + mInterpolating = enabled; +} + +/* inherits documentation from base class */ +double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QPointF center(position->pixelPoint()); + double w = mSize/2.0; + QRect clip = clipRect(); + switch (mStyle) + { + case tsNone: return -1; + case tsPlus: + { + if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), + distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); + break; + } + case tsCrosshair: + { + return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), + distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); + } + case tsCircle: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + // distance to border: + double centerDist = QVector2D(center-pos).length(); + double circleLine = w; + double result = qAbs(centerDist-circleLine); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) + { + if (centerDist <= circleLine) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; + } + break; + } + case tsSquare: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectSelectTest(rect, pos, filledRect); + } + break; + } + } + return -1; +} + +/* inherits documentation from base class */ +void QCPItemTracer::draw(QCPPainter *painter) +{ + updatePosition(); + if (mStyle == tsNone) + return; + + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + QPointF center(position->pixelPoint()); + double w = mSize/2.0; + QRect clip = clipRect(); + switch (mStyle) + { + case tsNone: return; + case tsPlus: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); + painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); + } + break; + } + case tsCrosshair: + { + if (center.y() > clip.top() && center.y() < clip.bottom()) + painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); + if (center.x() > clip.left() && center.x() < clip.right()) + painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); + break; + } + case tsCircle: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + painter->drawEllipse(center, w, w); + break; + } + case tsSquare: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); + break; + } + } +} + +/*! + If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a + position to reside on the graph data, depending on the configured key (\ref setGraphKey). + + It is called automatically on every redraw and normally doesn't need to be called manually. One + exception is when you want to read the tracer coordinates via \a position and are not sure that + the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. + In that situation, call this function before accessing \a position, to make sure you don't get + out-of-date coordinates. + + If there is no graph set on this tracer, this function does nothing. +*/ +void QCPItemTracer::updatePosition() +{ + if (mGraph) + { + if (mParentPlot->hasPlottable(mGraph)) + { + if (mGraph->data()->size() > 1) + { + QCPDataMap::const_iterator first = mGraph->data()->constBegin(); + QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; + if (mGraphKey < first.key()) + position->setCoords(first.key(), first.value().value); + else if (mGraphKey > last.key()) + position->setCoords(last.key(), last.value().value); + else + { + QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); + if (it != first) // mGraphKey is somewhere between iterators + { + QCPDataMap::const_iterator prevIt = it-1; + if (mInterpolating) + { + // interpolate between iterators around mGraphKey: + double slope = 0; + if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) + slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); + position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); + } else + { + // find iterator with key closest to mGraphKey: + if (mGraphKey < (prevIt.key()+it.key())*0.5) + it = prevIt; + position->setCoords(it.key(), it.value().value); + } + } else // mGraphKey is exactly on first iterator + position->setCoords(it.key(), it.value().value); + } + } else if (mGraph->data()->size() == 1) + { + QCPDataMap::const_iterator it = mGraph->data()->constBegin(); + position->setCoords(it.key(), it.value().value); + } else + qDebug() << Q_FUNC_INFO << "graph has no data"; + } else + qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; + } +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemTracer::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemTracer::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemBracket +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemBracket + \brief A bracket for referencing/highlighting certain parts in the plot. + + \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a left and \a right, which define the span of the bracket. If \a left is + actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the + example image. + + The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket + stretches away from the embraced span, can be controlled with \ref setLength. + + \image html QCPItemBracket-length.png +
                  Demonstrating the effect of different values for \ref setLength, for styles \ref + bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
                  + + It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine + or QCPItemCurve) or a text label (QCPItemText), to the bracket. +*/ + +/*! + Creates a bracket item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + left(createPosition("left")), + right(createPosition("right")), + center(createAnchor("center", aiCenter)) +{ + left->setCoords(0, 0); + right->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setLength(8); + setStyle(bsCalligraphic); +} + +QCPItemBracket::~QCPItemBracket() +{ +} + +/*! + Sets the pen that will be used to draw the bracket. + + Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the + stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use + \ref setLength, which has a similar effect. + + \see setSelectedPen +*/ +void QCPItemBracket::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the bracket when selected + + \see setPen, setSelected +*/ +void QCPItemBracket::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the \a length in pixels how far the bracket extends in the direction towards the embraced + span of the bracket (i.e. perpendicular to the left-right-direction) + + \image html QCPItemBracket-length.png +
                  Demonstrating the effect of different values for \ref setLength, for styles \ref + bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
                  +*/ +void QCPItemBracket::setLength(double length) +{ + mLength = length; +} + +/*! + Sets the style of the bracket, i.e. the shape/visual appearance. + + \see setPen +*/ +void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) +{ + mStyle = style; +} + +/* inherits documentation from base class */ +double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return -1; + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos)); +} + +/* inherits documentation from base class */ +void QCPItemBracket::draw(QCPPainter *painter) +{ + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return; + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + QPolygon boundingPoly; + boundingPoly << leftVec.toPoint() << rightVec.toPoint() + << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (clip.intersects(boundingPoly.boundingRect())) + { + painter->setPen(mainPen()); + switch (mStyle) + { + case bsSquare: + { + painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); + painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); + painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + break; + } + case bsRound: + { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCurly: + { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCalligraphic: + { + painter->setPen(Qt::NoPen); + painter->setBrush(QBrush(mainPen().color())); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + + path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + + path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); + path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); + + painter->drawPath(path); + break; + } + } + } +} + +/* inherits documentation from base class */ +QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const +{ + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return leftVec.toPointF(); + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + switch (anchorId) + { + case aiCenter: + return centerVec.toPointF(); + } + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemBracket::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + diff --git a/src/jceData/Grades/graph/qcustomplot.h b/src/jceData/Grades/graph/qcustomplot.h new file mode 100644 index 0000000..2ec78b0 --- /dev/null +++ b/src/jceData/Grades/graph/qcustomplot.h @@ -0,0 +1,3529 @@ +/*************************************************************************** +** ** +** QCustomPlot, an easy to use, modern plotting widget for Qt ** +** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** +** ** +** This program is free software: you can redistribute it and/or modify ** +** it under the terms of the GNU General Public License as published by ** +** the Free Software Foundation, either version 3 of the License, or ** +** (at your option) any later version. ** +** ** +** This program is distributed in the hope that it will be useful, ** +** but WITHOUT ANY WARRANTY; without even the implied warranty of ** +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** +** GNU General Public License for more details. ** +** ** +** You should have received a copy of the GNU General Public License ** +** along with this program. If not, see http://www.gnu.org/licenses/. ** +** ** +**************************************************************************** +** Author: Emanuel Eichhammer ** +** Website/Contact: http://www.qcustomplot.com/ ** +** Date: 07.04.14 ** +** Version: 1.2.1 ** +****************************************************************************/ + +#ifndef QCUSTOMPLOT_H +#define QCUSTOMPLOT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) +# include +# include +# include +#else +# include +# include +#endif + +class QCPPainter; +class QCustomPlot; +class QCPLayerable; +class QCPLayoutElement; +class QCPLayout; +class QCPAxis; +class QCPAxisRect; +class QCPAxisPainterPrivate; +class QCPAbstractPlottable; +class QCPGraph; +class QCPAbstractItem; +class QCPItemPosition; +class QCPLayer; +class QCPPlotTitle; +class QCPLegend; +class QCPAbstractLegendItem; +class QCPColorMap; +class QCPColorScale; + + +/*! \file */ + + +// decl definitions for shared library compilation/usage: +#if defined(QCUSTOMPLOT_COMPILE_LIBRARY) +# define QCP_LIB_DECL Q_DECL_EXPORT +#elif defined(QCUSTOMPLOT_USE_LIBRARY) +# define QCP_LIB_DECL Q_DECL_IMPORT +#else +# define QCP_LIB_DECL +#endif + +/*! + The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library +*/ +namespace QCP +{ +/*! + Defines the sides of a rectangular entity to which margins can be applied. + + \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins +*/ +enum MarginSide { msLeft = 0x01 ///< 0x01 left margin + ,msRight = 0x02 ///< 0x02 right margin + ,msTop = 0x04 ///< 0x04 top margin + ,msBottom = 0x08 ///< 0x08 bottom margin + ,msAll = 0xFF ///< 0xFF all margins + ,msNone = 0x00 ///< 0x00 no margin + }; +Q_DECLARE_FLAGS(MarginSides, MarginSide) + +/*! + Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is + neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective + element how it is drawn. Typically it provides a \a setAntialiased function for this. + + \c AntialiasedElements is a flag of or-combined elements of this enum type. + + \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements +*/ +enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks + ,aeGrid = 0x0002 ///< 0x0002 Grid lines + ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines + ,aeLegend = 0x0008 ///< 0x0008 Legend box + ,aeLegendItems = 0x0010 ///< 0x0010 Legend items + ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) + ,aeItems = 0x0040 ///< 0x0040 Main lines of items + ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) + ,aeErrorBars = 0x0100 ///< 0x0100 Error bars + ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) + ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen + ,aeAll = 0xFFFF ///< 0xFFFF All elements + ,aeNone = 0x0000 ///< 0x0000 No elements + }; +Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) + +/*! + Defines plotting hints that control various aspects of the quality and speed of plotting. + + \see QCustomPlot::setPlottingHints +*/ +enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set + ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality + ///< especially of the line segment joins. (Only relevant for solid line pens.) + ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. + ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). + ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. + }; +Q_DECLARE_FLAGS(PlottingHints, PlottingHint) + +/*! + Defines the mouse interactions possible with QCustomPlot. + + \c Interactions is a flag of or-combined elements of this enum type. + + \see QCustomPlot::setInteractions +*/ +enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) + ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) + ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking + ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) + ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) + ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) + ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) + ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) + }; +Q_DECLARE_FLAGS(Interactions, Interaction) + +/*! \internal + + Returns whether the specified \a value is considered an invalid data value for plottables (i.e. + is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the + compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. +*/ +inline bool isInvalidData(double value) +{ + return qIsNaN(value) || qIsInf(value); +} + +/*! \internal + \overload + + Checks two arguments instead of one. +*/ +inline bool isInvalidData(double value1, double value2) +{ + return isInvalidData(value1) || isInvalidData(value2); +} + +/*! \internal + + Sets the specified \a side of \a margins to \a value + + \see getMarginValue +*/ +inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) +{ + switch (side) + { + case QCP::msLeft: margins.setLeft(value); break; + case QCP::msRight: margins.setRight(value); break; + case QCP::msTop: margins.setTop(value); break; + case QCP::msBottom: margins.setBottom(value); break; + case QCP::msAll: margins = QMargins(value, value, value, value); break; + default: break; + } +} + +/*! \internal + + Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or + \ref QCP::msAll, returns 0. + + \see setMarginValue +*/ +inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) +{ + switch (side) + { + case QCP::msLeft: return margins.left(); + case QCP::msRight: return margins.right(); + case QCP::msTop: return margins.top(); + case QCP::msBottom: return margins.bottom(); + default: break; + } + return 0; +} + +} // end of namespace QCP + +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) + + +class QCP_LIB_DECL QCPScatterStyle +{ + Q_GADGET +public: + /*! + Defines the shape used for scatter points. + + On plottables/items that draw scatters, the sizes of these visualizations (with exception of + \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are + drawn with the pen and brush specified with \ref setPen and \ref setBrush. + */ + Q_ENUMS(ScatterShape) + enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) + ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) + ,ssCross ///< \enumimage{ssCross.png} a cross + ,ssPlus ///< \enumimage{ssPlus.png} a plus + ,ssCircle ///< \enumimage{ssCircle.png} a circle + ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) + ,ssSquare ///< \enumimage{ssSquare.png} a square + ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond + ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus + ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline + ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner + ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside + ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside + ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside + ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside + ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines + ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates + ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) + }; + + QCPScatterStyle(); + QCPScatterStyle(ScatterShape shape, double size=6); + QCPScatterStyle(ScatterShape shape, const QColor &color, double size); + QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); + QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); + QCPScatterStyle(const QPixmap &pixmap); + QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); + + // getters: + double size() const { return mSize; } + ScatterShape shape() const { return mShape; } + QPen pen() const { return mPen; } + QBrush brush() const { return mBrush; } + QPixmap pixmap() const { return mPixmap; } + QPainterPath customPath() const { return mCustomPath; } + + // setters: + void setSize(double size); + void setShape(ScatterShape shape); + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setPixmap(const QPixmap &pixmap); + void setCustomPath(const QPainterPath &customPath); + + // non-property methods: + bool isNone() const { return mShape == ssNone; } + bool isPenDefined() const { return mPenDefined; } + void applyTo(QCPPainter *painter, const QPen &defaultPen) const; + void drawShape(QCPPainter *painter, QPointF pos) const; + void drawShape(QCPPainter *painter, double x, double y) const; + +protected: + // property members: + double mSize; + ScatterShape mShape; + QPen mPen; + QBrush mBrush; + QPixmap mPixmap; + QPainterPath mCustomPath; + + // non-property members: + bool mPenDefined; +}; +Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); + + +class QCP_LIB_DECL QCPPainter : public QPainter +{ + Q_GADGET +public: + /*! + Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + depending on whether they are wanted on the respective output device. + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels + ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) + }; + Q_FLAGS(PainterMode PainterModes) + Q_DECLARE_FLAGS(PainterModes, PainterMode) + + QCPPainter(); + QCPPainter(QPaintDevice *device); + ~QCPPainter(); + + // getters: + bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } + PainterModes modes() const { return mModes; } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled=true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); + +protected: + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) + + +class QCP_LIB_DECL QCPLayer : public QObject +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + Q_PROPERTY(int index READ index) + Q_PROPERTY(QList children READ children) + Q_PROPERTY(bool visible READ visible WRITE setVisible) + /// \endcond +public: + QCPLayer(QCustomPlot* parentPlot, const QString &layerName); + ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { return mParentPlot; } + QString name() const { return mName; } + int index() const { return mIndex; } + QList children() const { return mChildren; } + bool visible() const { return mVisible; } + + // setters: + void setVisible(bool visible); + +protected: + // property members: + QCustomPlot *mParentPlot; + QString mName; + int mIndex; + QList mChildren; + bool mVisible; + + // non-virtual methods: + void addChild(QCPLayerable *layerable, bool prepend); + void removeChild(QCPLayerable *layerable); + +private: + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; +}; + +class QCP_LIB_DECL QCPLayerable : public QObject +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond +public: + QCPLayerable(QCustomPlot *plot, QString targetLayer="", QCPLayerable *parentLayerable=0); + ~QCPLayerable(); + + // getters: + bool visible() const { return mVisible; } + QCustomPlot *parentPlot() const { return mParentPlot; } + QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } + QCPLayer *layer() const { return mLayer; } + bool antialiased() const { return mAntialiased; } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-property methods: + bool realVisibility() const; + +signals: + void layerChanged(QCPLayer *newLayer); + +protected: + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-property methods: + void initializeParentPlot(QCustomPlot *parentPlot); + void setParentLayerable(QCPLayerable* parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + +private: + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPAxisRect; +}; + + +class QCP_LIB_DECL QCPRange +{ +public: + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange& other) { return lower == other.lower && upper == other.upper; } + bool operator!=(const QCPRange& other) { return !(*this == other); } + + QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } + QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } + QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } + QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } + friend inline const QCPRange operator+(const QCPRange&, double); + friend inline const QCPRange operator+(double, const QCPRange&); + friend inline const QCPRange operator-(const QCPRange& range, double value); + friend inline const QCPRange operator*(const QCPRange& range, double value); + friend inline const QCPRange operator*(double value, const QCPRange& range); + friend inline const QCPRange operator/(const QCPRange& range, double value); + + double size() const; + double center() const; + void normalize(); + void expand(const QCPRange &otherRange); + QCPRange expanded(const QCPRange &otherRange) const; + QCPRange sanitizedForLogScale() const; + QCPRange sanitizedForLinScale() const; + bool contains(double value) const; + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; //1e-280; + static const double maxRange; //1e280; + +}; +Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); + +/* documentation of inline functions */ + +/*! \fn QCPRange &QCPRange::operator+=(const double& value) + + Adds \a value to both boundaries of the range. +*/ + +/*! \fn QCPRange &QCPRange::operator-=(const double& value) + + Subtracts \a value from both boundaries of the range. +*/ + +/*! \fn QCPRange &QCPRange::operator*=(const double& value) + + Multiplies both boundaries of the range by \a value. +*/ + +/*! \fn QCPRange &QCPRange::operator/=(const double& value) + + Divides both boundaries of the range by \a value. +*/ + +/* end documentation of inline functions */ + +/*! + Adds \a value to both boundaries of the range. +*/ +inline const QCPRange operator+(const QCPRange& range, double value) +{ + QCPRange result(range); + result += value; + return result; +} + +/*! + Adds \a value to both boundaries of the range. +*/ +inline const QCPRange operator+(double value, const QCPRange& range) +{ + QCPRange result(range); + result += value; + return result; +} + +/*! + Subtracts \a value from both boundaries of the range. +*/ +inline const QCPRange operator-(const QCPRange& range, double value) +{ + QCPRange result(range); + result -= value; + return result; +} + +/*! + Multiplies both boundaries of the range by \a value. +*/ +inline const QCPRange operator*(const QCPRange& range, double value) +{ + QCPRange result(range); + result *= value; + return result; +} + +/*! + Multiplies both boundaries of the range by \a value. +*/ +inline const QCPRange operator*(double value, const QCPRange& range) +{ + QCPRange result(range); + result *= value; + return result; +} + +/*! + Divides both boundaries of the range by \a value. +*/ +inline const QCPRange operator/(const QCPRange& range, double value) +{ + QCPRange result(range); + result /= value; + return result; +} + + +class QCP_LIB_DECL QCPMarginGroup : public QObject +{ + Q_OBJECT +public: + QCPMarginGroup(QCustomPlot *parentPlot); + ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { return mChildren.value(side); } + bool isEmpty() const; + void clear(); + +protected: + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // non-virtual methods: + int commonMargin(QCP::MarginSide side) const; + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + +private: + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; +}; + + +class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout* layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + /// \endcond +public: + /*! + Defines the phases of the update process, that happens just before a replot. At each phase, + \ref update is called with the according UpdatePhase value. + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + ,upMargins ///< Phase in which the margins are calculated and set + ,upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + explicit QCPLayoutElement(QCustomPlot *parentPlot=0); + virtual ~QCPLayoutElement(); + + // getters: + QCPLayout *layout() const { return mParentLayout; } + QRect rect() const { return mRect; } + QRect outerRect() const { return mOuterRect; } + QMargins margins() const { return mMargins; } + QMargins minimumMargins() const { return mMinimumMargins; } + QCP::MarginSides autoMargins() const { return mAutoMargins; } + QSize minimumSize() const { return mMinimumSize; } + QSize maximumSize() const { return mMaximumSize; } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } + QHash marginGroups() const { return mMarginGroups; } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // introduced virtual methods: + virtual int calculateAutoMargin(QCP::MarginSide side); + // events: + virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } + virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + +private: + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; +}; + + +class QCP_LIB_DECL QCPLayout : public QCPLayoutElement +{ + Q_OBJECT +public: + explicit QCPLayout(); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; + + // introduced virtual methods: + virtual int elementCount() const = 0; + virtual QCPLayoutElement* elementAt(int index) const = 0; + virtual QCPLayoutElement* takeAt(int index) = 0; + virtual bool take(QCPLayoutElement* element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement* element); + void clear(); + +protected: + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + +private: + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; +}; + + +class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) + Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) + Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) + /// \endcond +public: + explicit QCPLayoutGrid(); + virtual ~QCPLayoutGrid(); + + // getters: + int rowCount() const; + int columnCount() const; + QList columnStretchFactors() const { return mColumnStretchFactors; } + QList rowStretchFactors() const { return mRowStretchFactors; } + int columnSpacing() const { return mColumnSpacing; } + int rowSpacing() const { return mRowSpacing; } + + // setters: + void setColumnStretchFactor(int column, double factor); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + void setRowStretchFactors(const QList &factors); + void setColumnSpacing(int pixels); + void setRowSpacing(int pixels); + + // reimplemented virtual methods: + virtual void updateLayout(); + virtual int elementCount() const; + virtual QCPLayoutElement* elementAt(int index) const; + virtual QCPLayoutElement* takeAt(int index); + virtual bool take(QCPLayoutElement* element); + virtual QList elements(bool recursive) const; + virtual void simplify(); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + + // non-virtual methods: + QCPLayoutElement *element(int row, int column) const; + bool addElement(int row, int column, QCPLayoutElement *element); + bool hasElement(int row, int column); + void expandTo(int newRowCount, int newColumnCount); + void insertRow(int newIndex); + void insertColumn(int newIndex); + +protected: + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + +private: + Q_DISABLE_COPY(QCPLayoutGrid) +}; + + +class QCP_LIB_DECL QCPLayoutInset : public QCPLayout +{ + Q_OBJECT +public: + /*! + Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. + */ + enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect + ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment + }; + + explicit QCPLayoutInset(); + virtual ~QCPLayoutInset(); + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + void setInsetRect(int index, const QRectF &rect); + + // reimplemented virtual methods: + virtual void updateLayout(); + virtual int elementCount() const; + virtual QCPLayoutElement* elementAt(int index) const; + virtual QCPLayoutElement* takeAt(int index); + virtual bool take(QCPLayoutElement* element); + virtual void simplify() {} + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + void addElement(QCPLayoutElement *element, Qt::Alignment alignment); + void addElement(QCPLayoutElement *element, const QRectF &rect); + +protected: + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + +private: + Q_DISABLE_COPY(QCPLayoutInset) +}; + + +class QCP_LIB_DECL QCPLineEnding +{ + Q_GADGET +public: + /*! + Defines the type of ending decoration for line-like items, e.g. an arrow. + + \image html QCPLineEnding.png + + The width and length of these decorations can be controlled with the functions \ref setWidth + and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only + support a width, the length property is ignored. + + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding + */ + Q_ENUMS(EndingStyle) + enum EndingStyle { esNone ///< No ending decoration + ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) + ,esSpikeArrow ///< A filled arrow head with an indented back + ,esLineArrow ///< A non-filled arrow head with open back + ,esDisc ///< A filled circle + ,esSquare ///< A filled square + ,esDiamond ///< A filled diamond (45° rotated square) + ,esBar ///< A bar perpendicular to the line + ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) + ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) + }; + + QCPLineEnding(); + QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); + + // getters: + EndingStyle style() const { return mStyle; } + double width() const { return mWidth; } + double length() const { return mLength; } + bool inverted() const { return mInverted; } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // non-property methods: + double boundingDistance() const; + double realLength() const; + void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; + void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; + +protected: + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; +}; +Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); + + +class QCP_LIB_DECL QCPGrid :public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) + Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond +public: + QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { return mSubGridVisible; } + bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } + bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } + QPen pen() const { return mPen; } + QPen subGridPen() const { return mSubGridPen; } + QPen zeroLinePen() const { return mZeroLinePen; } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + +protected: + // property members: + bool mSubGridVisible; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mPen, mSubGridPen, mZeroLinePen; + // non-property members: + QCPAxis *mParentAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + void drawGridLines(QCPPainter *painter) const; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; +}; + + +class QCP_LIB_DECL QCPAxis : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(AxisType axisType READ axisType) + Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) + Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) + Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) + Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) + Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) + Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) + Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) + Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) + Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) + Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) + Q_PROPERTY(bool ticks READ ticks WRITE setTicks) + Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) + Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) + Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) + Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) + Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) + Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) + Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) + Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) + Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) + Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) + Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) + Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) + Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) + Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) + Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) + Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) + Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) + Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) + Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid* grid READ grid) + /// \endcond +public: + /*! + Defines at which side of the axis rect the axis will appear. This also affects how the tick + marks are drawn, on which side the labels are placed etc. + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect + ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect + }; + Q_FLAGS(AxisType AxisTypes) + Q_DECLARE_FLAGS(AxisTypes, AxisType) + /*! + When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the + coordinate of the tick is interpreted, i.e. translated into a string. + + \see setTickLabelType + */ + enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) + ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) + }; + Q_ENUMS(LabelType) + /*! + Defines the scale of an axis. + \see setScaleType + */ + enum ScaleType { stLinear ///< Linear scaling + ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + ,spAxis = 0x001 ///< The axis backbone and tick marks + ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + ,spAxisLabel = 0x004 ///< The axis label + }; + Q_FLAGS(SelectablePart SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis(); + + // getters: + AxisType axisType() const { return mAxisType; } + QCPAxisRect *axisRect() const { return mAxisRect; } + ScaleType scaleType() const { return mScaleType; } + double scaleLogBase() const { return mScaleLogBase; } + const QCPRange range() const { return mRange; } + bool rangeReversed() const { return mRangeReversed; } + bool autoTicks() const { return mAutoTicks; } + int autoTickCount() const { return mAutoTickCount; } + bool autoTickLabels() const { return mAutoTickLabels; } + bool autoTickStep() const { return mAutoTickStep; } + bool autoSubTicks() const { return mAutoSubTicks; } + bool ticks() const { return mTicks; } + bool tickLabels() const { return mTickLabels; } + int tickLabelPadding() const; + LabelType tickLabelType() const { return mTickLabelType; } + QFont tickLabelFont() const { return mTickLabelFont; } + QColor tickLabelColor() const { return mTickLabelColor; } + double tickLabelRotation() const; + QString dateTimeFormat() const { return mDateTimeFormat; } + Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } + QString numberFormat() const; + int numberPrecision() const { return mNumberPrecision; } + double tickStep() const { return mTickStep; } + QVector tickVector() const { return mTickVector; } + QVector tickVectorLabels() const { return mTickVectorLabels; } + int tickLengthIn() const; + int tickLengthOut() const; + int subTickCount() const { return mSubTickCount; } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { return mBasePen; } + QPen tickPen() const { return mTickPen; } + QPen subTickPen() const { return mSubTickPen; } + QFont labelFont() const { return mLabelFont; } + QColor labelColor() const { return mLabelColor; } + QString label() const { return mLabel; } + int labelPadding() const; + int padding() const { return mPadding; } + int offset() const; + SelectableParts selectedParts() const { return mSelectedParts; } + SelectableParts selectableParts() const { return mSelectableParts; } + QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } + QFont selectedLabelFont() const { return mSelectedLabelFont; } + QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } + QColor selectedLabelColor() const { return mSelectedLabelColor; } + QPen selectedBasePen() const { return mSelectedBasePen; } + QPen selectedTickPen() const { return mSelectedTickPen; } + QPen selectedSubTickPen() const { return mSelectedSubTickPen; } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { return mGrid; } + + // setters: + Q_SLOT void setScaleType(QCPAxis::ScaleType type); + void setScaleLogBase(double base); + Q_SLOT void setRange(const QCPRange &range); + void setRange(double lower, double upper); + void setRange(double position, double size, Qt::AlignmentFlag alignment); + void setRangeLower(double lower); + void setRangeUpper(double upper); + void setRangeReversed(bool reversed); + void setAutoTicks(bool on); + void setAutoTickCount(int approximateCount); + void setAutoTickLabels(bool on); + void setAutoTickStep(bool on); + void setAutoSubTicks(bool on); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelType(LabelType type); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setDateTimeFormat(const QString &format); + void setDateTimeSpec(const Qt::TimeSpec &timeSpec); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickStep(double step); + void setTickVector(const QVector &vec); + void setTickVectorLabels(const QVector &vec); + void setTickLength(int inside, int outside=0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTickCount(int count); + void setSubTickLength(int inside, int outside=0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-property methods: + Qt::Orientation orientation() const { return mOrientation; } + void moveRange(double diff); + void scaleRange(double factor, double center); + void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); + void rescale(bool onlyVisiblePlottables=false); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } + static AxisType opposite(AxisType type); + +signals: + void ticksRequest(); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); + +protected: + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels, mAutoTickLabels; + //double mTickLabelRotation; // in QCPAxisPainter + LabelType mTickLabelType; + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + QString mDateTimeFormat; + Qt::TimeSpec mDateTimeSpec; + int mNumberPrecision; + char mNumberFormatChar; + bool mNumberBeautifulPowers; + //bool mNumberMultiplyCross; // QCPAxisPainter + // ticks and subticks: + bool mTicks; + double mTickStep; + int mSubTickCount, mAutoTickCount; + bool mAutoTicks, mAutoTickStep, mAutoSubTicks; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + double mScaleLogBase, mScaleLogBaseLogInv; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + int mLowestVisibleTick, mHighestVisibleTick; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + int mCachedMargin; + + // introduced virtual methods: + virtual void setupTickVectors(); + virtual void generateAutoTicks(); + virtual int calculateAutoSubTickCount(double tickStep) const; + virtual int calculateMargin(); + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual QCP::Interaction selectionCategory() const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + void visibleTickBounds(int &lowIndex, int &highIndex) const; + double baseLog(double value) const; + double basePow(double value) const; + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + +private: + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) +Q_DECLARE_METATYPE(QCPAxis::SelectablePart) + + +class QCPAxisPainterPrivate +{ +public: + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size() const; + void clearCache(); + + QRect axisSelectionBox() const { return mAxisSelectionBox; } + QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } + QRect labelSelectionBox() const { return mLabelSelectionBox; } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect alignmentRect, viewportRect; + double offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + +protected: + struct CachedLabel + { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData + { + QString basePart, expPart; + QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; +}; + + +class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) + Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) + Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) + Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + QString name() const { return mName; } + bool antialiasedFill() const { return mAntialiasedFill; } + bool antialiasedScatters() const { return mAntialiasedScatters; } + bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + QCPAxis *keyAxis() const { return mKeyAxis.data(); } + QCPAxis *valueAxis() const { return mValueAxis.data(); } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setName(const QString &name); + void setAntialiasedFill(bool enabled); + void setAntialiasedScatters(bool enabled); + void setAntialiasedErrorBars(bool enabled); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setKeyAxis(QCPAxis *axis); + void setValueAxis(QCPAxis *axis); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // introduced virtual methods: + virtual void clearData() = 0; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; + virtual bool addToLegend(); + virtual bool removeFromLegend() const; + + // non-property methods: + void rescaleAxes(bool onlyEnlarge=false) const; + void rescaleKeyAxis(bool onlyEnlarge=false) const; + void rescaleValueAxis(bool onlyEnlarge=false) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + /*! + Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. + */ + enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero + ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers + ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero + }; + + // property members: + QString mName; + bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QPointer mKeyAxis, mValueAxis; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter) = 0; + virtual QCP::Interaction selectionCategory() const; + void applyDefaultAntialiasingHint(QCPPainter *painter) const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // introduced virtual methods: + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; + + // non-virtual methods: + void coordsToPixels(double key, double value, double &x, double &y) const; + const QPointF coordsToPixels(double key, double value) const; + void pixelsToCoords(double x, double y, double &key, double &value) const; + void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; + QPen mainPen() const; + QBrush mainBrush() const; + void applyFillAntialiasingHint(QCPPainter *painter) const; + void applyScattersAntialiasingHint(QCPPainter *painter) const; + void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; + double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; + +private: + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; +}; + + +class QCP_LIB_DECL QCPItemAnchor +{ +public: + QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { return mName; } + virtual QPointF pixelPoint() const; + +protected: + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildren; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { return 0; } + + // non-virtual methods: + void addChild(QCPItemPosition* pos); // called from pos when this anchor is set as parent + void removeChild(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + +private: + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; +}; + + + +class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor +{ +public: + /*! + Defines the ways an item position can be specified. Thus it defines what the numbers passed to + \ref setCoords actually mean. + + \see setType + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. + ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). + }; + + QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); + virtual ~QCPItemPosition(); + + // getters: + PositionType type() const { return mPositionType; } + QCPItemAnchor *parentAnchor() const { return mParentAnchor; } + double key() const { return mKey; } + double value() const { return mValue; } + QPointF coords() const { return QPointF(mKey, mValue); } + QCPAxis *keyAxis() const { return mKeyAxis.data(); } + QCPAxis *valueAxis() const { return mValueAxis.data(); } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPoint() const; + + // setters: + void setType(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); + void setCoords(double key, double value); + void setCoords(const QPointF &coords); + void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPoint(const QPointF &pixelPoint); + +protected: + // property members: + PositionType mPositionType; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchor; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { return this; } + +private: + Q_DISABLE_COPY(QCPItemPosition) + +}; + + +class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) + Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem(); + + // getters: + bool clipToAxisRect() const { return mClipToAxisRect; } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; + + // non-virtual methods: + QList positions() const { return mPositions; } + QList anchors() const { return mAnchors; } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // introduced virtual methods: + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; + double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + +private: + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; +}; + + +class QCP_LIB_DECL QCustomPlot : public QWidget +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) + Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) + Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) + /// \endcond +public: + /*! + Defines how a layer should be inserted relative to an other layer. + + \see addLayer, moveLayer + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + ,limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) + + /*! + Defines with what timing the QCustomPlot surface is refreshed after a replot. + + \see replot + */ + enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot + ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot + ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. + }; + + explicit QCustomPlot(QWidget *parent = 0); + virtual ~QCustomPlot(); + + // getters: + QRect viewport() const { return mViewport; } + QPixmap background() const { return mBackgroundPixmap; } + bool backgroundScaled() const { return mBackgroundScaled; } + Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } + QCPLayoutGrid *plotLayout() const { return mPlotLayout; } + QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } + QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } + bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } + const QCP::Interactions interactions() const { return mInteractions; } + int selectionTolerance() const { return mSelectionTolerance; } + bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } + QCP::PlottingHints plottingHints() const { return mPlottingHints; } + Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } + + // setters: + void setViewport(const QRect &rect); + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled=true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + void setPlottingHints(const QCP::PlottingHints &hints); + void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); + void setMultiSelectModifier(Qt::KeyboardModifier modifier); + + // non-property methods: + // plottable interface: + QCPAbstractPlottable *plottable(int index); + QCPAbstractPlottable *plottable(); + bool addPlottable(QCPAbstractPlottable *plottable); + bool removePlottable(QCPAbstractPlottable *plottable); + bool removePlottable(int index); + int clearPlottables(); + int plottableCount() const; + QList selectedPlottables() const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool addItem(QCPAbstractItem* item); + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + QCPAxisRect* axisRect(int index=0) const; + QList axisRects() const; + QCPLayoutElement* layoutElementAt(const QPointF &pos) const; + Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); + + QList selectedAxes() const; + QList selectedLegends() const; + Q_SLOT void deselectAll(); + + bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator="", const QString &pdfTitle=""); + bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); + bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); + bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); + bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); + QPixmap toPixmap(int width=0, int height=0, double scale=1.0); + void toPainter(QCPPainter *painter, int width=0, int height=0); + Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; + +signals: + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *event); + + void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void itemClick(QCPAbstractItem *item, QMouseEvent *event); + void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); + void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); + void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); + void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); + void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); + void titleClick(QMouseEvent *event, QCPPlotTitle *title); + void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); + + void selectionChangedByUser(); + void beforeReplot(); + void afterReplot(); + +protected: + // property members: + QRect mViewport; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + + // non-property members: + QPixmap mPaintBuffer; + QPoint mMousePressPos; + QPointer mMouseEventElement; + bool mReplotting; + + // reimplemented virtual methods: + virtual QSize minimumSizeHint() const; + virtual QSize sizeHint() const; + virtual void paintEvent(QPaintEvent *event); + virtual void resizeEvent(QResizeEvent *event); + virtual void mouseDoubleClickEvent(QMouseEvent *event); + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + + // introduced virtual methods: + virtual void draw(QCPPainter *painter); + virtual void axisRemoved(QCPAxis *axis); + virtual void legendRemoved(QCPLegend *legend); + + // non-virtual methods: + void updateLayerIndices() const; + QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; + void drawBackground(QCPPainter *painter); + + friend class QCPLegend; + friend class QCPAxis; + friend class QCPLayer; + friend class QCPAxisRect; +}; + + +class QCP_LIB_DECL QCPColorGradient +{ + Q_GADGET +public: + /*! + Defines the color spaces in which color interpolation between gradient stops can be performed. + + \see setColorInterpolation + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! + Defines the available presets that can be loaded with \ref loadPreset. See the documentation + there for an image of the presets. + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + ,gpCandy ///< Blue over pink to white + ,gpGeography ///< Colors suitable to represent different elevations on geographical maps + ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(GradientPreset preset=gpCold); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } + + // getters: + int levelCount() const { return mLevelCount; } + QMap colorStops() const { return mColorStops; } + ColorInterpolation colorInterpolation() const { return mColorInterpolation; } + bool periodic() const { return mPeriodic; } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setPeriodic(bool enabled); + + // non-property methods: + void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); + QRgb color(double position, const QCPRange &range, bool logarithmic=false); + void loadPreset(GradientPreset preset); + void clearColorStops(); + QCPColorGradient inverted() const; + +protected: + void updateColorBuffer(); + + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + bool mPeriodic; + + // non-property members: + QVector mColorBuffer; + bool mColorBufferInvalidated; +}; + + +class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond +public: + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); + virtual ~QCPAxisRect(); + + // getters: + QPixmap background() const { return mBackgroundPixmap; } + bool backgroundScaled() const { return mBackgroundScaled; } + Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } + Qt::Orientations rangeDrag() const { return mRangeDrag; } + Qt::Orientations rangeZoom() const { return mRangeZoom; } + QCPAxis *rangeDragAxis(Qt::Orientation orientation); + QCPAxis *rangeZoomAxis(Qt::Orientation orientation); + double rangeZoomFactor(Qt::Orientation orientation); + + // setters: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setRangeDrag(Qt::Orientations orientations); + void setRangeZoom(Qt::Orientations orientations); + void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomFactor(double horizontalFactor, double verticalFactor); + void setRangeZoomFactor(double factor); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type); + QList addAxes(QCPAxis::AxisTypes types); + bool removeAxis(QCPAxis *axis); + QCPLayoutInset *insetLayout() const { return mInsetLayout; } + + void setupFullAxesBox(bool connectRanges=false); + QList plottables() const; + QList graphs() const; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { return mRect.left(); } + int right() const { return mRect.right(); } + int top() const { return mRect.top(); } + int bottom() const { return mRect.bottom(); } + int width() const { return mRect.width(); } + int height() const { return mRect.height(); } + QSize size() const { return mRect.size(); } + QPoint topLeft() const { return mRect.topLeft(); } + QPoint topRight() const { return mRect.topRight(); } + QPoint bottomLeft() const { return mRect.bottomLeft(); } + QPoint bottomRight() const { return mRect.bottomRight(); } + QPoint center() const { return mRect.center(); } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; + +protected: + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + // non-property members: + QCPRange mDragStartHorzRange, mDragStartVertRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QPoint mDragStart; + bool mDragging; + QHash > mAxes; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual int calculateAutoMargin(QCP::MarginSide side); + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + + // non-property methods: + void drawBackground(QCPPainter *painter); + void updateAxesOffset(QCPAxis::AxisType type); + +private: + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; +}; + + +class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond +public: + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { return mParentLegend; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QCP::Interaction selectionCategory() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + +private: + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem +{ + Q_OBJECT +public: + QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { return mPlottable; } + +protected: + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QSize minimumSizeHint() const; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; +}; + + +class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond +public: + /*! + Defines the selectable parts of a legend + + \see setSelectedParts, setSelectableParts + */ + enum SelectablePart { spNone = 0x000 ///< 0x000 None + ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) + ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + }; + Q_FLAGS(SelectablePart SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend(); + + // getters: + QPen borderPen() const { return mBorderPen; } + QBrush brush() const { return mBrush; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QSize iconSize() const { return mIconSize; } + int iconTextPadding() const { return mIconTextPadding; } + QPen iconBorderPen() const { return mIconBorderPen; } + SelectableParts selectableParts() const { return mSelectableParts; } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { return mSelectedBorderPen; } + QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } + QBrush selectedBrush() const { return mSelectedBrush; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + +signals: + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + +protected: + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + QColor mSelectedTextColor; + + // reimplemented virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + +private: + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) +Q_DECLARE_METATYPE(QCPLegend::SelectablePart) + + +class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + explicit QCPPlotTitle(QCustomPlot *parentPlot); + explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); + + // getters: + QString text() const { return mText; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setText(const QString &text); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + QString mText; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + +private: + Q_DISABLE_COPY(QCPPlotTitle) +}; + + +class QCPColorScaleAxisRectPrivate : public QCPAxisRect +{ + Q_OBJECT +public: + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); +protected: + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter); + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; +}; + + +class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond +public: + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale(); + + // getters: + QCPAxis *axis() const { return mColorAxis.data(); } + QCPAxis::AxisType type() const { return mType; } + QCPRange dataRange() const { return mDataRange; } + QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } + QCPColorGradient gradient() const { return mGradient; } + QString label() const; + int barWidth () const { return mBarWidth; } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + +signals: + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); + +protected: + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + +private: + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPData +{ +public: + QCPData(); + QCPData(double key, double value); + double key, value; + double keyErrorPlus, keyErrorMinus; + double valueErrorPlus, valueErrorMinus; +}; +Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); + +/*! \typedef QCPDataMap + Container for storing QCPData items in a sorted fashion. The key of the map + is the key member of the QCPData instance. + + This is the container in which QCPGraph holds its data. + \see QCPData, QCPGraph::setData +*/ +typedef QMap QCPDataMap; +typedef QMapIterator QCPDataMapIterator; +typedef QMutableMapIterator QCPDataMutableMapIterator; + + +class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) + Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) + Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) + Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) + Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) + Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) + /// \endcond +public: + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + ,lsLine ///< data points are connected by a straight line + ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + ,lsStepCenter ///< line is drawn as steps where the step is in between two data points + ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line + }; + Q_ENUMS(LineStyle) + /*! + Defines what kind of error bars are drawn for each data point + */ + enum ErrorType { etNone ///< No error bars are shown + ,etKey ///< Error bars for the key dimension of the data point are shown + ,etValue ///< Error bars for the value dimension of the data point are shown + ,etBoth ///< Error bars for both key and value dimensions of the data point are shown + }; + Q_ENUMS(ErrorType) + + explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPGraph(); + + // getters: + QCPDataMap *data() const { return mData; } + LineStyle lineStyle() const { return mLineStyle; } + QCPScatterStyle scatterStyle() const { return mScatterStyle; } + ErrorType errorType() const { return mErrorType; } + QPen errorPen() const { return mErrorPen; } + double errorBarSize() const { return mErrorBarSize; } + bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } + QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } + bool adaptiveSampling() const { return mAdaptiveSampling; } + + // setters: + void setData(QCPDataMap *data, bool copy=false); + void setData(const QVector &key, const QVector &value); + void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); + void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); + void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); + void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); + void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); + void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); + void setLineStyle(LineStyle ls); + void setScatterStyle(const QCPScatterStyle &style); + void setErrorType(ErrorType errorType); + void setErrorPen(const QPen &pen); + void setErrorBarSize(double size); + void setErrorBarSkipSymbol(bool enabled); + void setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QCPDataMap &dataMap); + void addData(const QCPData &data); + void addData(double key, double value); + void addData(const QVector &keys, const QVector &values); + void removeDataBefore(double key); + void removeDataAfter(double key); + void removeData(double fromKey, double toKey); + void removeData(double key); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + using QCPAbstractPlottable::rescaleAxes; + using QCPAbstractPlottable::rescaleKeyAxis; + using QCPAbstractPlottable::rescaleValueAxis; + void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + +protected: + // property members: + QCPDataMap *mData; + QPen mErrorPen; + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + ErrorType mErrorType; + double mErrorBarSize; + bool mErrorBarSkipSymbol; + QPointer mChannelFillGraph; + bool mAdaptiveSampling; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface + + // introduced virtual methods: + virtual void drawFill(QCPPainter *painter, QVector *lineData) const; + virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; + virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; + virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; + + // non-virtual methods: + void getPreparedData(QVector *lineData, QVector *scatterData) const; + void getPlotData(QVector *lineData, QVector *scatterData) const; + void getScatterPlotData(QVector *scatterData) const; + void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; + void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; + void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; + void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; + int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; + void addFillBasePoints(QVector *lineData) const; + void removeFillBasePoints(QVector *lineData) const; + QPointF lowerFillBasePoint(double lowerKey) const; + QPointF upperFillBasePoint(double upperKey) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData) const; + int findIndexBelowX(const QVector *data, double x) const; + int findIndexAboveX(const QVector *data, double x) const; + int findIndexBelowY(const QVector *data, double y) const; + int findIndexAboveY(const QVector *data, double y) const; + double pointDistance(const QPointF &pixelPoint) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPCurveData +{ +public: + QCPCurveData(); + QCPCurveData(double t, double key, double value); + double t, key, value; +}; +Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); + +/*! \typedef QCPCurveDataMap + Container for storing QCPCurveData items in a sorted fashion. The key of the map + is the t member of the QCPCurveData instance. + + This is the container in which QCPCurve holds its data. + \see QCPCurveData, QCPCurve::setData +*/ + +typedef QMap QCPCurveDataMap; +typedef QMapIterator QCPCurveDataMapIterator; +typedef QMutableMapIterator QCPCurveDataMutableMapIterator; + + +class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + /// \endcond +public: + /*! + Defines how the curve's line is represented visually in the plot. The line is drawn with the + current pen of the curve (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) + ,lsLine ///< Data points are connected with a straight line + }; + explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPCurve(); + + // getters: + QCPCurveDataMap *data() const { return mData; } + QCPScatterStyle scatterStyle() const { return mScatterStyle; } + LineStyle lineStyle() const { return mLineStyle; } + + // setters: + void setData(QCPCurveDataMap *data, bool copy=false); + void setData(const QVector &t, const QVector &key, const QVector &value); + void setData(const QVector &key, const QVector &value); + void setScatterStyle(const QCPScatterStyle &style); + void setLineStyle(LineStyle style); + + // non-property methods: + void addData(const QCPCurveDataMap &dataMap); + void addData(const QCPCurveData &data); + void addData(double t, double key, double value); + void addData(double key, double value); + void addData(const QVector &ts, const QVector &keys, const QVector &values); + void removeDataBefore(double t); + void removeDataAfter(double t); + void removeData(double fromt, double tot); + void removeData(double t); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPCurveDataMap *mData; + QCPScatterStyle mScatterStyle; + LineStyle mLineStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // introduced virtual methods: + virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; + + // non-virtual methods: + void getCurveData(QVector *lineData) const; + double pointDistance(const QPointF &pixelPoint) const; + QPointF outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPBarData +{ +public: + QCPBarData(); + QCPBarData(double key, double value); + double key, value; +}; +Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); + +/*! \typedef QCPBarDataMap + Container for storing QCPBarData items in a sorted fashion. The key of the map + is the key member of the QCPBarData instance. + + This is the container in which QCPBars holds its data. + \see QCPBarData, QCPBars::setData +*/ +typedef QMap QCPBarDataMap; +typedef QMapIterator QCPBarDataMapIterator; +typedef QMutableMapIterator QCPBarDataMutableMapIterator; + + +class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(QCPBars* barBelow READ barBelow) + Q_PROPERTY(QCPBars* barAbove READ barAbove) + /// \endcond +public: + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars(); + + // getters: + double width() const { return mWidth; } + QCPBars *barBelow() const { return mBarBelow.data(); } + QCPBars *barAbove() const { return mBarAbove.data(); } + QCPBarDataMap *data() const { return mData; } + + // setters: + void setWidth(double width); + void setData(QCPBarDataMap *data, bool copy=false); + void setData(const QVector &key, const QVector &value); + + // non-property methods: + void moveBelow(QCPBars *bars); + void moveAbove(QCPBars *bars); + void addData(const QCPBarDataMap &dataMap); + void addData(const QCPBarData &data); + void addData(double key, double value); + void addData(const QVector &keys, const QVector &values); + void removeDataBefore(double key); + void removeDataAfter(double key); + void removeData(double fromKey, double toKey); + void removeData(double key); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPBarDataMap *mData; + double mWidth; + QPointer mBarBelow, mBarAbove; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // non-virtual methods: + QPolygonF getBarPolygon(double key, double value) const; + double getBaseValue(double key, bool positive) const; + static void connectBars(QCPBars* lower, QCPBars* upper); + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double key READ key WRITE setKey) + Q_PROPERTY(double minimum READ minimum WRITE setMinimum) + Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) + Q_PROPERTY(double median READ median WRITE setMedian) + Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) + Q_PROPERTY(double maximum READ maximum WRITE setMaximum) + Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) + Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) + Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) + Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) + Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) + /// \endcond +public: + explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + double key() const { return mKey; } + double minimum() const { return mMinimum; } + double lowerQuartile() const { return mLowerQuartile; } + double median() const { return mMedian; } + double upperQuartile() const { return mUpperQuartile; } + double maximum() const { return mMaximum; } + QVector outliers() const { return mOutliers; } + double width() const { return mWidth; } + double whiskerWidth() const { return mWhiskerWidth; } + QPen whiskerPen() const { return mWhiskerPen; } + QPen whiskerBarPen() const { return mWhiskerBarPen; } + QPen medianPen() const { return mMedianPen; } + QCPScatterStyle outlierStyle() const { return mOutlierStyle; } + + // setters: + void setKey(double key); + void setMinimum(double value); + void setLowerQuartile(double value); + void setMedian(double value); + void setUpperQuartile(double value); + void setMaximum(double value); + void setOutliers(const QVector &values); + void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); + void setWidth(double width); + void setWhiskerWidth(double width); + void setWhiskerPen(const QPen &pen); + void setWhiskerBarPen(const QPen &pen); + void setMedianPen(const QPen &pen); + void setOutlierStyle(const QCPScatterStyle &style); + + // non-property methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QVector mOutliers; + double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; + QCPScatterStyle mOutlierStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // introduced virtual methods: + virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; + virtual void drawMedian(QCPPainter *painter) const; + virtual void drawWhiskers(QCPPainter *painter) const; + virtual void drawOutliers(QCPPainter *painter) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPColorMapData +{ +public: + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { return mKeySize; } + int valueSize() const { return mValueSize; } + QCPRange keyRange() const { return mKeyRange; } + QCPRange valueRange() const { return mValueRange; } + QCPRange dataBounds() const { return mDataBounds; } + double data(double key, double value); + double cell(int keyIndex, int valueIndex); + + // setters: + void setSize(int keySize, int valueSize); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + void setValueRange(const QCPRange &valueRange); + void setData(double key, double value, double z); + void setCell(int keyIndex, int valueIndex, double z); + + // non-property methods: + void recalculateDataBounds(); + void clear(); + void fill(double z); + bool isEmpty() const { return mIsEmpty; } + void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; + void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; + +protected: + // property members: + int mKeySize, mValueSize; + QCPRange mKeyRange, mValueRange; + bool mIsEmpty; + // non-property members: + double *mData; + QCPRange mDataBounds; + bool mDataModified; + + friend class QCPColorMap; +}; + + +class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) + /// \endcond +public: + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap(); + + // getters: + QCPColorMapData *data() const { return mMapData; } + QCPRange dataRange() const { return mDataRange; } + QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } + bool interpolate() const { return mInterpolate; } + bool tightBoundary() const { return mTightBoundary; } + QCPColorGradient gradient() const { return mGradient; } + QCPColorScale *colorScale() const { return mColorScale.data(); } + + // setters: + void setData(QCPColorMapData *data, bool copy=false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds=false); + Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); + +protected: + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + // non-property members: + QImage mMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + virtual void updateMapImage(); + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond +public: + QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const point1; + QCPItemPosition * const point2; + +protected: + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; + QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond +public: + QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QCPLineEnding head() const { return mHead; } + QCPLineEnding tail() const { return mTail; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const start; + QCPItemPosition * const end; + +protected: + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond +public: + QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QCPLineEnding head() const { return mHead; } + QCPLineEnding tail() const { return mTail; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const start; + QCPItemPosition * const startDir; + QCPItemPosition * const endDir; + QCPItemPosition * const end; + +protected: + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + /// \endcond +public: + QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemText : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond +public: + QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText(); + + // getters: + QColor color() const { return mColor; } + QColor selectedColor() const { return mSelectedColor; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + QFont font() const { return mFont; } + QFont selectedFont() const { return mSelectedFont; } + QString text() const { return mText; } + Qt::Alignment positionAlignment() const { return mPositionAlignment; } + Qt::Alignment textAlignment() const { return mTextAlignment; } + double rotation() const { return mRotation; } + QMargins padding() const { return mPadding; } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const position; + QCPItemAnchor * const topLeft; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottomRight; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + /// \endcond +public: + QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const topLeftRim; + QCPItemAnchor * const top; + QCPItemAnchor * const topRightRim; + QCPItemAnchor * const right; + QCPItemAnchor * const bottomRightRim; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeftRim; + QCPItemAnchor * const left; + QCPItemAnchor * const center; + +protected: + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond +public: + QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap(); + + // getters: + QPixmap pixmap() const { return mPixmap; } + bool scaled() const { return mScaled; } + Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPixmap mPixmap; + QPixmap mScaledPixmap; + bool mScaled; + Qt::AspectRatioMode mAspectRatioMode; + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); + QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond +public: + /*! + The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. + + \see setStyle + */ + enum TracerStyle { tsNone ///< The tracer is not visible + ,tsPlus ///< A plus shaped crosshair with limited size + ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + ,tsCircle ///< A circle + ,tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) + + QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + double size() const { return mSize; } + TracerStyle style() const { return mStyle; } + QCPGraph *graph() const { return mGraph; } + double graphKey() const { return mGraphKey; } + bool interpolating() const { return mInterpolating; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + void updatePosition(); + + QCPItemPosition * const position; + +protected: + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + Q_PROPERTY(BracketStyle style READ style WRITE setStyle) + /// \endcond +public: + enum BracketStyle { bsSquare ///< A brace with angled edges + ,bsRound ///< A brace with round edges + ,bsCurly ///< A curly brace + ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression + }; + + QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + double length() const { return mLength; } + BracketStyle style() const { return mStyle; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const left; + QCPItemPosition * const right; + QCPItemAnchor * const center; + +protected: + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; +}; + +#endif // QCUSTOMPLOT_H + diff --git a/src/jceData/page.cpp b/src/jceData/page.cpp index 3c7e44a..38b9ac9 100644 --- a/src/jceData/page.cpp +++ b/src/jceData/page.cpp @@ -1,6 +1,6 @@ #include "page.h" -Page::Page() {} +Page::Page() { dateHeader = "";} /** * @brief Page::getString * @param htmlToPhrased @@ -29,17 +29,23 @@ void Page::manageTableContent(QString &html, int index) QString temp; for (int i = index; i < html.length(); i++) { - if(html.at(i) == '<') + if (html.at(i) == '<') { // / / QString endofTable = ""; QString tableTag = html.mid(i, 4); //legth of "tr/td" if (tableTag == "") { - temp += "\n"; //new row -> new line + temp += dateHeader; i = stitchText(html, temp, i+4); - if(i == -1) //EOF + if (i == -1) //EOF break; + + } + else if (tableTag == " new line + i+=5; } else if (tableTag == "" || tableTag == "") { @@ -55,14 +61,20 @@ void Page::manageTableContent(QString &html, int index) if (i == -1) //EOF break; } - else if(tableTag == "",index+4)-index); + QString temp; + QString date; + char* tok; + int i = 0; + char* textToTok = strdup(dateline.toStdString().c_str()); + tok = strtok(textToTok,"<> :"); + while (tok != NULL) + { + if (i == 1) + { + temp = tok; + date += temp + "\t"; + } + else if (i == 3) + { + temp = tok; + date += temp; + } + i++; + tok = strtok(NULL, "<> :"); + } + dateHeader = date; if (bTag != "") return index-1; //go back one step - for the main function to inc i - index += 3; + index += dateline.length(); } while (from.at(index) != '<' && index < (int)from.length()) @@ -103,7 +138,7 @@ int Page::stitchText(QString &from, QString &to, int index) else if (from.at(index) == '<') return index - 1; //go back one step - for the main function to inc i - if (from.at(index) != '\n') //check the actuall data before continue + if ((from.at(index) != '\n') && (from.at(index) != '\t')) //check the actuall data before continue to += from.at(index); index++; } diff --git a/src/jceData/page.h b/src/jceData/page.h index 2651366..d43543a 100644 --- a/src/jceData/page.h +++ b/src/jceData/page.h @@ -33,6 +33,7 @@ private: bool endOfString(int index, int length); QString text; + QString dateHeader; QString title; }; From fd612169d7dcf7055027cac9bd3fc37e10f00c1e Mon Sep 17 00:00:00 2001 From: liranbg Date: Sun, 5 Oct 2014 15:33:57 +0300 Subject: [PATCH 05/58] need to fix getting calendar lineToCourse --- main/LoginTab/loginhandler.cpp | 6 +- main/mainscreen.cpp | 64 +- main/mainscreen.ui | 1141 ++++++++++++++++++++- src/jceData/Calendar/calendarPage.cpp | 4 + src/jceData/Calendar/calendarSchedule.cpp | 14 +- src/jceData/page.cpp | 17 +- 6 files changed, 1205 insertions(+), 41 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 572bcb0..d83b741 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -125,13 +125,13 @@ void loginHandler::setLoginFlag(bool flag) } QString loginHandler::getCurrentPageContect() { - QTextEdit phrase; + QTextEdit parse; if (isLoggedInFlag()) - phrase.setText(jceLog->getPage()); + parse.setText(jceLog->getPage()); else throw jceLogin::ERROR_ON_GETTING_INFO; - return phrase.toPlainText(); + return parse.toPlainText(); } int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester) { diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 1f6718c..1cf5a5f 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -233,39 +233,47 @@ void MainScreen::on_graphButton_clicked() { courseTableMgr->showGraph(); } + //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { - ui->progressBar->setValue(0); - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) - { - ui->statusBar->showMessage(tr("Getting schedule...")); - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) - { + QString page; + calendar->resetTable(); + page = ui->plainTextEdit->toPlainText(); + calendar->setCalendar(page); + // ui->progressBar->setValue(0); + // qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + // int status = 0; + // QString page; + // QApplication::setOverrideCursor(Qt::WaitCursor); + // if (loginHandel->isLoggedInFlag()) + // { + // ui->statusBar->showMessage(tr("Getting schedule...")); + // if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + // { - //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request - //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); - calendar->resetTable(); - ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); - calendar->setCalendar(loginHandel->getCurrentPageContect()); - ui->progressBar->setValue(100); - qDebug() << Q_FUNC_INFO << "calendar is loaded"; - ui->statusBar->showMessage(tr("Done")); - } + // //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request + // //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); + // calendar->resetTable(); + // ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); - else if (status == jceLogin::JCE_NOT_CONNECTED) - { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - } - else - qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; - } - QApplication::restoreOverrideCursor(); + // page = loginHandel->getCurrentPageContect(); + // calendar->setCalendar(page); + // ui->progressBar->setValue(100); + // qDebug() << Q_FUNC_INFO << "calendar is loaded"; + // ui->statusBar->showMessage(tr("Done")); + // } + + // else if (status == jceLogin::JCE_NOT_CONNECTED) + // { + // qWarning() << Q_FUNC_INFO << "not connected"; + // QApplication::restoreOverrideCursor(); + // QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + // } + // else + // qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; + // } + // QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 9d0528b..74e7a2c 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 1 + 2 false @@ -586,6 +586,1145 @@ font-size: 15px;
                  + + + + class="menuheader expandable">קבצים להורדה</h3> + <ul class="categoryitems"> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0134,','_self');"> + מינהל סטודנטים + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0138,','_self');"> + ועדת הוראה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0125,','_self');"> + דיקנאט הסטודנטים + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0123,','_self');"> + מדור שכ"ל + </a> + </li> + + + </ul> + <h3 class="menuheader expandable">שאלות נפוצות</h3> + <ul class="categoryitems"> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0151,','_self');"> + מינהל סטודנטים + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0152,','_self');"> + מדור בחינות + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0153,','_self');"> + ועדת הוראה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0154,','_self');"> + מדור סיוע + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0155,','_self');"> + שכ"ל + </a> + </li> + + + </ul> + <h3 class="menuheader expandable">שנת הלימודים תשע"ה</h3> + <ul class="categoryitems"> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0139,','_self');"> + לוחות תאריכים + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0140,','_self');"> + פתיחת שנה + </a> + </li> + + + </ul> + <h3 class="menuheader expandable">תוכניות לימודים</h3> + <ul class="categoryitems"> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0126,','_self');"> + תעשייה וניהול + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0127,','_self');"> + אלקטרוניקה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0128,','_self');"> + תוכנה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0129,','_self');"> + חומרים מתקדמים + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0130,','_self');"> + פרמצבטית + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0132,','_self');"> + מכונות + </a> + </li> + + + </ul> + <h3 class="menuheader expandable">מלגות</h3> + <ul class="categoryitems"> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0008,','_self');"> + הגשת בקשה למלגה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0026,','_self');"> + צירוף קבצים למלגה + </a> + </li> + + + <li> + <a href="javascript:send_form('Menu','-N,-A,-N,-N0012,','_self');"> + עדכון פרטים אישיים + </a> + </li> + +</ul> + +</div> + +</td> + </tr> + </tbody> + </table></td> + </tr> + </tbody> + </table></td> + </tr> + + </tbody> + </table></td> + </tr> + </tbody> + </table></td> + </tr> + <tr> + <td class="bottomCornerBG"></td> + </tr> +</table> +</form> +</body> +</html> <!--FileName : Menu_Full_4.htm-->HTTP/1.1 200 OK +Date: Sun, 05 Oct 2014 11:29:00 GMT +Server: Microsoft-IIS/6.0 +X-Powered-By: ASP.NET +X-AspNet-Version: 2.0.50727 +Set-Cookie: ASP.NET_SessionId=j0hjp245bbmffs55nvais255; path=/; HttpOnly +Cache-Control: private +Content-Type: text/html; charset=utf-8 +Content-Length: 28103 + + <!DOCTYPE html> +<html lang="he"> +<head> + <meta charset="UTF-8"> + <noscript><meta http-equiv="X-Frame-Options" content="SameOrigin"></noscript> + + <title>תחנת מידע לסטודנט עזריאלי, מכללה אקדמית להנדסה ירושלים</title> + <link href="/info/MagicStyles_Type_2.css" rel="stylesheet" type="text/css"> +<link rel="stylesheet" href="/info/sort/jquery-ui-custom.css" type="text/css"> + <link rel="shortcut icon" href="/info/images/Favicon.ico"> + <link rel="icon" href="/info/images/Favicon.ico"> + <link rel="stylesheet" href="/info/sort/jquery.ui.timepicker.css" /> + <link rel="stylesheet" href="/info/sort/select2A.css"> + + <style type="text/css"> + textarea,input[type='text'], input[type='email'], input[type='password'] + { + border:1px solid #ccc; + padding:5px; + font-size:120%; + font-family:Arial,sans-serif; + } + #shadow { + background-image:url(/info/images/shade1x1.png); + position:absolute; + left:0; + top:0; + width:100%; + z-index:4999; +} +.cke_skin_kama td { + background-color: inherit !important; +} +body { + padding-right: 10px; + padding-left: 10px; +} +table.tablesorter { + font-family:arial; + background-color: #CDCDCD; + font-size: 8pt; + width: 97%; + text-align: right; +} +table.tablesorter thead tr th, table.tablesorter tfoot tr th { + border: 1px solid #FFF; + font-size: 8pt; + padding: 4px; +} +table.tablesorter tfoot td { + padding: 4px; +} +table.tablesorter thead tr .header { + background-image: url(/info/images/bgTitle.gif); + background-repeat: no-repeat; + background-position: left; + cursor: pointer; +} +table.tablesorter tbody td { + color: #3D3D3D; + padding: 4px; + background-color: #FFF; + vertical-align: top; +} +table.tablesorter tbody tr.odd td { + background-color:#F0F0F6; +} +table.tablesorter thead tr .headerSortUp { + background-image: url(/info/images/asc.gif); + background-position: left; +} +table.tablesorter thead tr .headerSortDown { + background-image: url(/info/images/desc.gif); + background-position: left; +} +table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp { +background-color: #8dbdd8; +} +#preview{ + position:absolute; + border:1px solid #ccc; + background:#333; + padding:5px; + display:none; + color:#fff; + } + + + +.buttonA, .buttonTOP { + padding: 4px 10px 3px 25px; + border: 1px solid #DE5D51; + position: relative; + cursor: pointer; + display: inline-block; + background-image: url( '/info/images/buttonJumpBackground_red.png' ); + background-repeat: repeat-x; + font-size: 11px; + text-decoration: none; + color: #9D271E; + -moz-border-radius-bottomleft: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-topleft: 5px; + -moz-border-radius-topright: 5px; + font-family: Arial, Helvetica, sans-serif; + } + .buttonA img,.buttonTOP img { + position: absolute; + top: -4px; + left: -12px; + border: none; + } + .buttonA:hover { + color: #DE5D51; + border: 1px solid #FFB3AA; + } + .buttonA:disabled { + visibility: hidden; + } + + +.buttonA_Big { + padding: 4px 10px 3px 25px; + border: 1px solid #DE5D51; + position: relative; + cursor: pointer; + display: inline-block; + background-image: url( '/info/images/buttonJumpBackground_red.png' ); + background-repeat: repeat-x; + font-size: 13px; + font-weight: bold; + text-decoration: none; + color: #9D271E; + -moz-border-radius-bottomleft: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-topleft: 5px; + -moz-border-radius-topright: 5px; + font-family: Arial, Helvetica, sans-serif; + } + .buttonA_Big img { + position: absolute; + top: -4px; + left: -12px; + border: none; + } + .buttonA_Big:hover { + color: #DE5D51; + border: 1px solid #FFB3AA; + } + .buttonA_Big:disabled { + visibility: hidden; + } + + + + + +</style> +</head> + <body OnLoad="AutoExec()" class= text style="margin: 0; direction: rtl;font-size:12px;" +> + + +<script type="text/javascript" src="/info/sort/jquery.min.js"></script> +<script type="text/javascript" src="/info/sort/jquery-migrate.js"></script> + + +<script type="text/javascript"> + var SessionMesIdStr,SessionResIdStr; + SessionMesIdStr = ","; + SessionResIdStr = ","; + + function ShowHideContent(id,type){ + if (type == "msg") { + if (SessionMesIdStr.indexOf(","+id+",") == -1){ + SessionMesIdStr = SessionMesIdStr + id + ","; + } + } + else { + if (SessionResIdStr.indexOf(","+id+",") == -1){ + + SessionResIdStr = SessionResIdStr + id + ","; + } + } + div = document.getElementById("div" + type + id); + img = document.getElementById("IMG" + id); + if (div.style.display == "none") + { + div.style.display = 'block'; + img.src = '/info/images/box_open.png'; + } + else + { + div.style.display='none'; + img.src ='/info/images/box_closed.png'; + } + window.focus() + } + + </script> +<script type="text/javascript" src="/info/sort/jquery.tooltipster.min.js"></script> +<script type="text/javascript" src="/info/sort/select2.min.js"></script> +<script type="text/javascript"> +if(!($.browser.msie && ($.browser.version=="6.0" || $.browser.version=="7.0" || $.browser.version=="8.0"))) +{ + $(document).ready(function() { + $('#bigger, #smaller, #ConB, #ConL, #ConW, #Excel, #Outlook,.AboutOpen').tooltipster(); + $("select").select2(); + }); +} +</script> + + +<script type="text/javascript" src="/info/sort/jquery.tablesorter.js"></script> + <script src="/info/sort/jquery.ui.timepicker.js"></script> + <script src="/info/sort/jquery.ui.timepicker-he.js"></script> + + <script src="/info/sort/jquery.lazyload.js" type="text/javascript" charset="utf-8"></script> + <script type="text/javascript"> + $(function() { + $("img").lazyload(); + }); + </script> + +<script type="text/javascript" src="/info/sort/jquery.cookie.js"></script> + +<script type="text/javascript"> + var min=10; + var max=20; + var fontsize=12; + var fontsizeTitles=17; + var fs_elements = 'div,td,th,#Yedion a,select,p,span'; + var fs_elementsTitles = 'h1,h2,.white'; +$(document).ready(function(e){ + if ($.cookie("fs_styles")!=null) { + if ($.cookie("fs_styles")!='white') { + change_style($.cookie("fs_styles")); + } + } + if (($.cookie("fs_elements")!=null)&&($.cookie("fs_elementsTitles")!=null)) { + fontsize=parseInt($.cookie("fs_elements")); + fontsizeTitles=parseInt($.cookie("fs_elementsTitles")); + $.cookie("fs_elements", fontsize, { expires: 30 }); + $.cookie("fs_elementsTitles", fontsizeTitles, { expires: 30 }); + set_fontsizes(); + } +}); +function set_fontsizes() { + $(fs_elements).css('fontSize',fontsize+'px'); + $(fs_elementsTitles).css('fontSize',fontsizeTitles+'px'); + $.cookie("fs_elements", fontsize, { expires: 30 }); + $.cookie("fs_elementsTitles", fontsizeTitles, { expires: 30 }); +} +function enlarge() { + if (fontsize<max) { + fontsize+=2; + fontsizeTitles+=2; + set_fontsizes(); + } +} +function change_style(styletype) { + switch(styletype) { + case 'black': $('body').css('backgroundColor','black'); + $('.text').css('color','white'); + $('body').css('backgroundImage',''); + $('.tablesorter').css('backgroundColor','#35B3DC'); + $(fs_elements).css('backgroundColor','black'); + $(fs_elements).css('color','yellow'); + $(fs_elementsTitles).css('color','yellow'); + break; + case 'blue': $('body').css('backgroundColor','rgb(194, 211, 252)'); + $('.text').css('color','white'); + $('body').css('backgroundImage',''); + $('.tablesorter').css('backgroundColor','#35B3DC'); + $(fs_elements).css('backgroundColor','rgb(194, 211, 252)'); + $(fs_elements).css('color','black'); + $(fs_elementsTitles).css('color','black'); + break; + default: $('body').css('backgroundColor','white'); + $('.text').css('color','white'); + $('body').css('backgroundImage','url(/info/images/tile.gif)'); + $('.tablesorter').css('backgroundColor','#CDCDCD'); + $(fs_elements).css('backgroundColor',''); + $(fs_elements).css('color','black'); + $(fs_elementsTitles).css('color','black'); + $('th').css('color','white'); + break; + } + $.cookie("fs_styles", styletype, { expires: 30 }); +} +function shrink() { + if (fontsize>min) { + fontsize-=2; + fontsizeTitles-=2; + set_fontsizes(); + } +} +</script> + +<noscript> +<!-- <p><br />הגדלה והקטנה של מלל<br /></p> --> +</noscript> + + + +<script type="text/javascript"> +this.imagePreview = function(){ + /* CONFIG */ + + xOffset = 10; + yOffset = -300; + + // these 2 variable determine popup's distance from the cursor + // you might want to adjust to get the right result + + /* END CONFIG */ + $("a.preview").hover(function(e){ + this.t = this.title; + this.title = ""; + var c = (this.t != "") ? "<br/>" + this.t : ""; + $("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview'>"+ c +"<\/p>"); + $("#preview") + .css("top",(e.pageY - xOffset) + "px") + .css("left",(e.pageX + yOffset) + "px") + .fadeIn("fast"); + }, + function(){ + this.title = this.t; + $("#preview").remove(); + }); + $("a.preview").mousemove(function(e){ + $("#preview") + .css("top",(e.pageY - xOffset) + "px") + .css("left",(e.pageX + yOffset) + "px"); + }); +}; + + +// starting the script on page load +$(document).ready(function(){ + imagePreview(); +}); +</script> +<noscript> +<!-- <p><br />הגדלה של תמונה כאשר עוברים עליה<br /></p> --> +</noscript> + + <script type="text/javascript" src="/info/sort/jquery-ui.custom.min.js"></script> + + <script type="text/javascript" src="/info/sort/jquery.ui.datepicker-he.js"></script> + +<noscript> +<!-- <p><br />תאריכון<br /></p> --> +</noscript> +<!-- script src="/info/Scripts/AC_RunActiveContent.js" type="text/javascript"></script> --> +<script type="text/javascript"> +function AutoExec() +{ + if (typeof(document.form) != 'undefined') { + if (typeof(document.form.R1C1) != 'undefined') + document.form.R1C1.focus(); + + document.form.onsubmit = OnSubmit; + } + return; +} + +function OnSubmit () +{ + if (typeof(document.form) != 'undefined') { + if (document.form.APPNAME.value == "") + { + return false; + } + } + return true; +} + + + +function SubmitFormConfirm(Obj,app, prg, arg, trg, confirmQuestion) +{ + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + var conf = confirm(confirmQuestion); + if (conf) { + SubmitForm(Obj,app, prg, arg, trg); + } +} + +function SubmitForm(Obj,app, prg, arg, trg) +{ + if(Obj==null) + Obj=event.srcElement; + if(Obj==null) + return; + + bConfirm=Obj.getAttribute("Confirm"); + if (bConfirm=="true") + { + confirmQuestion = Obj.getAttribute("ConfirmQuestion"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + confirmQuestion = confirmQuestion.replace("\\n","\n"); + result = confirm (confirmQuestion); + if (!result) + { + return; + } + } + + if((trg!="_blank")&&(trg!="jq_float")) trg=""; + + document.form.APPNAME.value=app; + document.form.PRGNAME.value=prg; + document.form.ARGUMENTS.value=arg; + document.form.target=trg; + + document.form.submit(); +} +</script> +<noscript> +<!-- <p><br />הפעלת כפתורים<br /></p> --> +</noscript> + + + <script type="text/javascript"> + $(document).ready(function(){ + $(".buttonJump").hover(function(){ + $(".buttonJump img") + .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump + .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump + .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump + }); + }); + </script> + + +<noscript> +<!-- <p><br />עיצוב של כפתור<br /></p> --> +</noscript> + + + +<!-- Text area --> + +<script type="text/javascript" src="/info/ckeditor/ckeditor.js"></script> + +<noscript> +<!-- <p><br />הגדרות בעת הפעלת עורך מלל<br /></p> --> +<!-- <p><br />הגדרות ראשוניות בעת אתחול עורך מלל<br /></p> --> +</noscript> + +<script type="text/javascript"> +if(!($.browser.msie)) + { + CKEDITOR.on( 'dialogDefinition', function( ev ) + { + var dialogName = ev.data.name; + var dialogDefinition = ev.data.definition; + if ( dialogName == 'link' ) + { + var targetTab = dialogDefinition.getContents( 'target' ); + var targetField = targetTab.get( 'linkTargetType' ); + targetField[ 'default' ] = '_blank'; + + } + }); + CKEDITOR.on('instanceReady', function(ev) { + ev.editor.on('paste', function(evt) { + evt.data.dataValue = evt.data.dataValue.replace(/target=".*?"/g, '' ); + evt.data.dataValue = evt.data.dataValue.replace(/href/g, 'target="_blank" href' ); + console.log(evt.data.dataValue); + }, null, null, 9); + }); + } +</script> +<!-- End of Text area --> + +<script type="text/javascript" src="/info/sort/RowColor.js"></script> + + <div style="width: 100%;"> + <span class="white" style="float:right;">תחנת מידע לסטודנט</span> + + <span style="float:left;">05/10/2014 + 14:29 + +<a class="buttonTOP" onClick="window.print()" accesskey="P"><img src="/info/images/Printer.PNG" style="top: 2px; left: 8px;" alt="">הדפס</a> + + +<a class="buttonTOP" onClick="enlarge();" accesskey="+"><img src="/info/images/zoom_in.PNG" style="top: 2px; left: 8px;" alt="הגדלת פונט ">הגדל</a> +<a class="buttonTOP" onClick="shrink();" accesskey="-"><img src="/info/images/zoom_out.PNG" style="top: 2px; left: 8px;" alt="הקטנת פונט ">הקטן</a> +<a class="buttonTOP" onClick="change_style('black');" accesskey="B"><img src="/info/images/black.gif" style="top: 1px; left: 10px;" alt="קונטרסט גבוה">&nbsp;</a> +<a class="buttonTOP" onClick="change_style('blue');" accesskey="L"><img src="/info/images/blue.gif" style="top: 1px; left: 10px;" alt="קונטרסט עדין">&nbsp;</a> +<a class="buttonTOP" onClick="change_style('white');" accesskey="W"><img src="/info/images/white.gif" style="top: 1px; left: 10px;" alt="קונטרסט ברירת מחדל">&nbsp;</a> + + + + <a class="buttonTOP" onClick="javascript:EXCEL()" accesskey="E"><img src="/info/images/xls.PNG" style="top: 2px; left: 8px;" alt="">אקסל</a> + <script type="text/javascript"> + function EXCEL() + { + window.open("fireflyweb.aspx?prgname=GetFile&Arguments=-N7","Grade_To_Excel", "menubar=yes,toolbar=no,resizable=yes,scrollbars=yes,width=700,height=500, top=100,left=100"); + } + </script> + + + + + + + + </span></div> + +<table style="width:100%;height:100%;border:0"> + <tr> + <td style="text-align:left"> + </table> +<br> + +<script type="text/javascript"> + function send_form(prgname,arguments,target) + { + var input = '<input type="hidden" name="prgname" value="'+prgname+'">'; + var input = input+'<input type="hidden" name="arguments" value="'+arguments+'">'; + $('<form method="post" action="fireflyweb.aspx" target="'+target+'">'+input+'</form>').appendTo('body').submit(); + } +</script> +<script type="text/javascript"> + function load_img(img_id,arg) + { + $.post('fireflyweb.aspx', + { + prgname: 'GetFile', + Arguments: arg, + IsItPost: 'Y' + },function(e){ + $('#'+img_id).html('<img src="data:image/jpg;base64,'+e+'" style="border:0;margin:2;" alt="תמונה ממסד הנתונים">'); + }); + } +</script> + <!--FileName : Header_Of_HTML_Type_3.HTM--> + + + <table style="text-align:right;width:98%;margin:auto;" class="text"> + <tr> + <td>שם סטודנט + </td> + + <td> + + <b>בן גידה לירן + </b> + </td> + + <td> + ת.ז. + </td> + <td> 302539556 + </td> + </tr> + + <tr> + <td>כתובת + </td> + <td> הסוללים 7 א' דירה 1 + </td> + + <td> + + תאריך + </td> + <td>05/10/2014 + </td> + + </tr> + + <tr> + <td>עיר + </td> + <td>ירושלים + </td> + + <td>מיקוד + </td> + <td>9371648 + </td> + </tr> + + <TR style="text-align:right"><td>חוג : </td><td>הנדסת תוכנה</td><td>התמחות</td><td>תוכנה</td></tr> + +</table> + +<h1 style="text-align:center">רשימת מערכת שעות שנה : 2015 סמסטר : 1 תשע"ה</h1> + + + + + + <script type="text/javascript"> + $(function() { + $("#myTable0").tablesorter(); +// $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); + }); + </script> + + +<table style="text-align:right;width:98%;margin:auto;" class="tablesorter Mtable" ID="myTable0" summary="רשימת הקורסים"> +<thead> + <Tr> + <th style="width:50px">סמסטר</th> + <th>קוד קורס </th> + <th>שם הקורס </th> + <th>סוג מקצוע </th> + <th>שם המרצה </th> + <th style="width:30">נ"ז </th> + <th style="width:30">ש"ס</th> + <th style="width:90">יום ושעות </th> + <th>חדר </th> + <th>קוד קבוצה</th> + <th>חוג</th> + <th>אתר</th> + +</tr> +</thead> +<tbody> + <tr> + <td>א&nbsp; </td> + <td> 10001&nbsp; </td> + <td>אותות ומערכות&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td>ד"ר גור ערן&nbsp; </td> + <td> 4.50&nbsp; </td> + <td> 4.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +א'&nbsp;14:00&nbsp;-&nbsp;15:45 +</td> + <td>כתה- L208&nbsp; </td> + <td>100015101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10001&nbsp; </td> + <td>אותות ומערכות&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td>ד"ר גור ערן&nbsp; </td> + <td>&nbsp; </td> + <td>&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ב'&nbsp;12:00&nbsp;-&nbsp;13:45 +</td> + <td>כיתה-A102&nbsp; </td> + <td>100015101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10001&nbsp; </td> + <td>אותות ומערכות&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td>ד"ר גור ערן&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ג'&nbsp;13:00&nbsp;-&nbsp;13:45 +</td> + <td>כתה-L201&nbsp; </td> + <td>100015103&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10016&nbsp; </td> + <td>הסתברות וסטטיסטיקה 2&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N77,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר ביגון בוריס</a>&nbsp; </td> + <td> 2.50&nbsp; </td> + <td> 2.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +א'&nbsp;12:00&nbsp;-&nbsp;13:45 +</td> + <td>כתה- L204&nbsp; </td> + <td>100165101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10016&nbsp; </td> + <td>הסתברות וסטטיסטיקה 2&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N589,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">גב' שטיינבוך ביאנה</a>&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ב'&nbsp;09:00&nbsp;-&nbsp;09:45 +</td> + <td>כתה- L206&nbsp; </td> + <td>100165103&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10039&nbsp; </td> + <td>יישומי תקשורת מחשבים&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N284,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר צור-דוד שמרית</a>&nbsp; </td> + <td> 2.50&nbsp; </td> + <td> 2.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ב'&nbsp;10:00&nbsp;-&nbsp;11:45 +</td> + <td>כיתה-A102&nbsp; </td> + <td>100395101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10039&nbsp; </td> + <td>יישומי תקשורת מחשבים&nbsp; </td> + <td>מעבדה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N284,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר צור-דוד שמרית</a>&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ד'&nbsp;12:00&nbsp;-&nbsp;12:45 +</td> + <td>כיתת מחשבים-מ326&nbsp; </td> + <td>100395103&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10061&nbsp; </td> + <td>תקשורת מחשבים&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N47,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר אקסמן יעקב</a>&nbsp; </td> + <td> 3.50&nbsp; </td> + <td> 3.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ג'&nbsp;09:00&nbsp;-&nbsp;11:45 +</td> + <td>כיתה A106&nbsp; </td> + <td>100615101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10061&nbsp; </td> + <td>תקשורת מחשבים&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N742,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">גב' נתנזון מרים</a>&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ג'&nbsp;12:00&nbsp;-&nbsp;12:45 +</td> + <td>כיתת מחשבים A114&nbsp; </td> + <td>100615102&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10077&nbsp; </td> + <td>מבוא לתכנות מדעי&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N135,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר חסין יהודה</a>&nbsp; </td> + <td> 3.50&nbsp; </td> + <td> 3.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ד'&nbsp;08:00&nbsp;-&nbsp;10:45 +</td> + <td>אודיטוריום-001&nbsp; </td> + <td>100775101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10077&nbsp; </td> + <td>מבוא לתכנות מדעי&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N172,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר הראלי שלמה</a>&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ד'&nbsp;11:00&nbsp;-&nbsp;11:45 +</td> + <td>כיתת מחשבים-מ150&nbsp; </td> + <td>100775102&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10087&nbsp; </td> + <td>אוטומטים ושפות פורמליות&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N233,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר רודה יואב</a>&nbsp; </td> + <td> 2.50&nbsp; </td> + <td> 2.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ד'&nbsp;14:00&nbsp;-&nbsp;15:45 +</td> + <td>כיתה A103&nbsp; </td> + <td>100875101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10087&nbsp; </td> + <td>אוטומטים ושפות פורמליות&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td>מר ידגר הראל עוז&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ג'&nbsp;14:00&nbsp;-&nbsp;14:45 +</td> + <td>כתה-L201&nbsp; </td> + <td>100875103&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10091&nbsp; </td> + <td>תכנות בסביבת אינטרנט&nbsp; </td> + <td>הרצאה&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N282,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר תבור שי</a>&nbsp; </td> + <td> 2.50&nbsp; </td> + <td> 2.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +א'&nbsp;10:00&nbsp;-&nbsp;11:45 +</td> + <td>אודיטוריום-201&nbsp; </td> + <td>100915101&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> + <tr> + <td>א&nbsp; </td> + <td> 10091&nbsp; </td> + <td>תכנות בסביבת אינטרנט&nbsp; </td> + <td>תרגיל&nbsp; + </td> + <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N282,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר תבור שי</a>&nbsp; </td> + <td>&nbsp; </td> + <td> 1.00&nbsp; </td> + <td style="width:direction:rtl;width:90"> +ב'&nbsp;08:00&nbsp;-&nbsp;08:45 +</td> + <td>כיתת מחשבים A114&nbsp; </td> + <td>100915102&nbsp; </td> + <td>תוכנה&nbsp; </td> + <td>&nbsp; </td> + +</tr> +</tbody> +<tfoot> + <tr> + <td colspan=5>סה"כ נקודות זכות לסמסטר זה +( + קורס שנתי יחושב כמחצית בכל סמסטר +) </td> + <td><b>21.50</b></td> + <td><b>25.00</b></td> + <td colspan=5>&nbsp; </td> +</tr> +</tfoot> +</table> + +<div style="text-align:right" class="text"> + +<br> +ט.ל.ח +<br> +רשימת מערכת שעות שנה : 2015 סמסטר : 1 מותנה בעמידה בתנאי הקדם לקורסים +<br> + +רשימת מערכת שעות שנה : 2015 סמסטר : 1 זו אינה מהווה אישור רשמי של עזריאלי, מכללה אקדמית להנדסה ירושלים +</div> + +<script type="text/javascript"> propagateEventHandler(document.getElementById("myTable0"), "onmouseover", "TR", highlightTableRow, "lightblue");</script> + </body></html> + <!--FileName : TimeTable_List_For_Student.htm-->" + + + diff --git a/src/jceData/Calendar/calendarPage.cpp b/src/jceData/Calendar/calendarPage.cpp index 4084545..2566146 100644 --- a/src/jceData/Calendar/calendarPage.cpp +++ b/src/jceData/Calendar/calendarPage.cpp @@ -8,10 +8,13 @@ QString CalendarPage::htmlToString() void CalendarPage::setPage(QString html) { + qDebug() << "parsing calendar"; courses = new std::list(); tempHtml = getString(html); tempHtml = tokenToLines(tempHtml); + qDebug() << "creating courses list"; calendarListInit(tempHtml); + qDebug() << "done"; } @@ -114,6 +117,7 @@ calendarCourse *CalendarPage::lineToCourse(QString line) else room = ROOM_DEFAULT_STRING; + qDebug() << serial << name << type << lecturer << points << semesterHours << dayAndHour << room; tempC = new calendarCourse(serial,name,type,lecturer,points,semesterHours,dayAndHour,room); return tempC; diff --git a/src/jceData/Calendar/calendarSchedule.cpp b/src/jceData/Calendar/calendarSchedule.cpp index 98f8421..e569c47 100644 --- a/src/jceData/Calendar/calendarSchedule.cpp +++ b/src/jceData/Calendar/calendarSchedule.cpp @@ -37,8 +37,8 @@ calendarSchedule::calendarSchedule() void calendarSchedule::setPage(QString html) { CalendarPage::setPage(html); - - insertCourseIntoTable(); + qDebug() << Q_FUNC_INFO << "inserting into table"; +// insertCourseIntoTable(); } void calendarSchedule::clearTableItems() @@ -57,15 +57,17 @@ void calendarSchedule::insertCourseIntoTable() QTableWidgetItem *item; QString courseString; - int currentHour,currentDay,blocksNumer; + int currentHour,currentDay,blocksNumber; int row,col; for (calendarCourse *coursePtr: *getCourses()) { + qDebug() << coursePtr->getSerialNum(); courseString = ""; currentHour = coursePtr->getHourBegin(); currentDay = coursePtr->getDay(); - blocksNumer = coursePtr->getHourEnd() - coursePtr->getHourBegin(); //every hour is a block to fill! - while (blocksNumer >= 0) + blocksNumber = coursePtr->getHourEnd() - coursePtr->getHourBegin(); //every hour is a block to fill! + qDebug() << blocksNumber; + while (blocksNumber >= 0) { row = currentHour - HOURS_BEGIN; col = currentDay-1; @@ -88,7 +90,7 @@ void calendarSchedule::insertCourseIntoTable() this->setItem(row,col,item); currentHour++; - --blocksNumer; + --blocksNumber; } horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); diff --git a/src/jceData/page.cpp b/src/jceData/page.cpp index 38b9ac9..7c65231 100644 --- a/src/jceData/page.cpp +++ b/src/jceData/page.cpp @@ -36,7 +36,8 @@ void Page::manageTableContent(QString &html, int index) QString tableTag = html.mid(i, 4); //legth of "tr/td" if (tableTag == "") { - temp += dateHeader; + if (!dateHeader.isEmpty()) + temp += dateHeader; i = stitchText(html, temp, i+4); if (i == -1) //EOF break; @@ -49,7 +50,8 @@ void Page::manageTableContent(QString &html, int index) } else if (tableTag == "" || tableTag == "") { - temp += "\t"; // new cell -> tab between data + if (!dateHeader.isEmpty()) + temp += "\t"; // new cell -> tab between data if (html.mid(i, 6) == "") + break; i++; + } i = stitchText(html, temp, i); } From 72dfc107787637c88332aefc6517138b1d4b2e38 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 6 Oct 2014 19:15:24 +0300 Subject: [PATCH 06/58] fixed bugs. ready to make graph feature --- main/LoginTab/loginhandler.cpp | 1 - main/mainscreen.cpp | 71 +- main/mainscreen.h | 2 - main/mainscreen.ui | 1141 +-------------------- src/jceData/Calendar/calendarDialog.cpp | 2 +- src/jceData/Calendar/calendarPage.cpp | 157 ++- src/jceData/Calendar/calendarPage.h | 1 - src/jceData/Calendar/calendarSchedule.cpp | 4 +- src/jceData/Grades/gradePage.cpp | 21 - src/jceData/Grades/gradePage.h | 1 - src/jceData/page.cpp | 224 ++-- src/jceSettings/jcelogin.cpp | 306 +++--- src/jceSettings/jcelogin.h | 71 +- 13 files changed, 411 insertions(+), 1591 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index d83b741..68061d5 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -130,7 +130,6 @@ QString loginHandler::getCurrentPageContect() parse.setText(jceLog->getPage()); else throw jceLogin::ERROR_ON_GETTING_INFO; - return parse.toPlainText(); } int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester) diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 1cf5a5f..0eb638a 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -2,7 +2,7 @@ #include "ui_mainscreen.h" -MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen), busyFlag() +MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) { ui->setupUi(this); @@ -33,7 +33,6 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); this->calendar = new CalendarManager(ui->calendarGridLayoutMain); this->data = new SaveData(); - busyFlag = false; //check login File if (data->isSaved()) @@ -145,7 +144,7 @@ void MainScreen::on_ratesButton_clicked() QString pageString; int status = 0; QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag() && !busyFlag) + if (loginHandel->isLoggedInFlag()) { ui->statusBar->showMessage(tr("Getting grades...")); if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), @@ -170,7 +169,6 @@ void MainScreen::on_ratesButton_clicked() { qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } - busyFlag = true; } QApplication::restoreOverrideCursor(); } @@ -237,43 +235,34 @@ void MainScreen::on_graphButton_clicked() //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { - QString page; - calendar->resetTable(); - page = ui->plainTextEdit->toPlainText(); - calendar->setCalendar(page); - // ui->progressBar->setValue(0); - // qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - // int status = 0; - // QString page; - // QApplication::setOverrideCursor(Qt::WaitCursor); - // if (loginHandel->isLoggedInFlag()) - // { - // ui->statusBar->showMessage(tr("Getting schedule...")); - // if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) - // { - - // //Use it for debug. add plain text and change the object name to 'plainTextEdit' so you will get the html request - // //ui->plainTextEdit->setPlainText(loginHandel->getCurrentPageContect()); - // calendar->resetTable(); - // ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); - - // page = loginHandel->getCurrentPageContect(); - // calendar->setCalendar(page); - // ui->progressBar->setValue(100); - // qDebug() << Q_FUNC_INFO << "calendar is loaded"; - // ui->statusBar->showMessage(tr("Done")); - // } - - // else if (status == jceLogin::JCE_NOT_CONNECTED) - // { - // qWarning() << Q_FUNC_INFO << "not connected"; - // QApplication::restoreOverrideCursor(); - // QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - // } - // else - // qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; - // } - // QApplication::restoreOverrideCursor(); + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + int status = 0; + QString page; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) + { + ui->statusBar->showMessage(tr("Getting schedule...")); + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + { + calendar->resetTable(); + ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); + page = loginHandel->getCurrentPageContect(); + calendar->setCalendar(page); + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "calendar is loaded"; + ui->statusBar->showMessage(tr("Done")); + } + else if (status == jceLogin::JCE_NOT_CONNECTED) + { + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + } + else + qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; + } + QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { diff --git a/main/mainscreen.h b/main/mainscreen.h index e0f5d32..b04691c 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -85,8 +85,6 @@ private: coursesTableManager *courseTableMgr; loginHandler *loginHandel; - bool busyFlag; - }; #endif // MAINSCREEN_H diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 74e7a2c..d7d4f53 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -586,1145 +586,6 @@ font-size: 15px; - - - - class="menuheader expandable">קבצים להורדה</h3> - <ul class="categoryitems"> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0134,','_self');"> - מינהל סטודנטים - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0138,','_self');"> - ועדת הוראה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0125,','_self');"> - דיקנאט הסטודנטים - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0123,','_self');"> - מדור שכ"ל - </a> - </li> - - - </ul> - <h3 class="menuheader expandable">שאלות נפוצות</h3> - <ul class="categoryitems"> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0151,','_self');"> - מינהל סטודנטים - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0152,','_self');"> - מדור בחינות - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0153,','_self');"> - ועדת הוראה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0154,','_self');"> - מדור סיוע - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0155,','_self');"> - שכ"ל - </a> - </li> - - - </ul> - <h3 class="menuheader expandable">שנת הלימודים תשע"ה</h3> - <ul class="categoryitems"> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0139,','_self');"> - לוחות תאריכים - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0140,','_self');"> - פתיחת שנה - </a> - </li> - - - </ul> - <h3 class="menuheader expandable">תוכניות לימודים</h3> - <ul class="categoryitems"> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0126,','_self');"> - תעשייה וניהול - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0127,','_self');"> - אלקטרוניקה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0128,','_self');"> - תוכנה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0129,','_self');"> - חומרים מתקדמים - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0130,','_self');"> - פרמצבטית - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0132,','_self');"> - מכונות - </a> - </li> - - - </ul> - <h3 class="menuheader expandable">מלגות</h3> - <ul class="categoryitems"> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0008,','_self');"> - הגשת בקשה למלגה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0026,','_self');"> - צירוף קבצים למלגה - </a> - </li> - - - <li> - <a href="javascript:send_form('Menu','-N,-A,-N,-N0012,','_self');"> - עדכון פרטים אישיים - </a> - </li> - -</ul> - -</div> - -</td> - </tr> - </tbody> - </table></td> - </tr> - </tbody> - </table></td> - </tr> - - </tbody> - </table></td> - </tr> - </tbody> - </table></td> - </tr> - <tr> - <td class="bottomCornerBG"></td> - </tr> -</table> -</form> -</body> -</html> <!--FileName : Menu_Full_4.htm-->HTTP/1.1 200 OK -Date: Sun, 05 Oct 2014 11:29:00 GMT -Server: Microsoft-IIS/6.0 -X-Powered-By: ASP.NET -X-AspNet-Version: 2.0.50727 -Set-Cookie: ASP.NET_SessionId=j0hjp245bbmffs55nvais255; path=/; HttpOnly -Cache-Control: private -Content-Type: text/html; charset=utf-8 -Content-Length: 28103 - - <!DOCTYPE html> -<html lang="he"> -<head> - <meta charset="UTF-8"> - <noscript><meta http-equiv="X-Frame-Options" content="SameOrigin"></noscript> - - <title>תחנת מידע לסטודנט עזריאלי, מכללה אקדמית להנדסה ירושלים</title> - <link href="/info/MagicStyles_Type_2.css" rel="stylesheet" type="text/css"> -<link rel="stylesheet" href="/info/sort/jquery-ui-custom.css" type="text/css"> - <link rel="shortcut icon" href="/info/images/Favicon.ico"> - <link rel="icon" href="/info/images/Favicon.ico"> - <link rel="stylesheet" href="/info/sort/jquery.ui.timepicker.css" /> - <link rel="stylesheet" href="/info/sort/select2A.css"> - - <style type="text/css"> - textarea,input[type='text'], input[type='email'], input[type='password'] - { - border:1px solid #ccc; - padding:5px; - font-size:120%; - font-family:Arial,sans-serif; - } - #shadow { - background-image:url(/info/images/shade1x1.png); - position:absolute; - left:0; - top:0; - width:100%; - z-index:4999; -} -.cke_skin_kama td { - background-color: inherit !important; -} -body { - padding-right: 10px; - padding-left: 10px; -} -table.tablesorter { - font-family:arial; - background-color: #CDCDCD; - font-size: 8pt; - width: 97%; - text-align: right; -} -table.tablesorter thead tr th, table.tablesorter tfoot tr th { - border: 1px solid #FFF; - font-size: 8pt; - padding: 4px; -} -table.tablesorter tfoot td { - padding: 4px; -} -table.tablesorter thead tr .header { - background-image: url(/info/images/bgTitle.gif); - background-repeat: no-repeat; - background-position: left; - cursor: pointer; -} -table.tablesorter tbody td { - color: #3D3D3D; - padding: 4px; - background-color: #FFF; - vertical-align: top; -} -table.tablesorter tbody tr.odd td { - background-color:#F0F0F6; -} -table.tablesorter thead tr .headerSortUp { - background-image: url(/info/images/asc.gif); - background-position: left; -} -table.tablesorter thead tr .headerSortDown { - background-image: url(/info/images/desc.gif); - background-position: left; -} -table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp { -background-color: #8dbdd8; -} -#preview{ - position:absolute; - border:1px solid #ccc; - background:#333; - padding:5px; - display:none; - color:#fff; - } - - - -.buttonA, .buttonTOP { - padding: 4px 10px 3px 25px; - border: 1px solid #DE5D51; - position: relative; - cursor: pointer; - display: inline-block; - background-image: url( '/info/images/buttonJumpBackground_red.png' ); - background-repeat: repeat-x; - font-size: 11px; - text-decoration: none; - color: #9D271E; - -moz-border-radius-bottomleft: 5px; - -moz-border-radius-bottomright: 5px; - -moz-border-radius-topleft: 5px; - -moz-border-radius-topright: 5px; - font-family: Arial, Helvetica, sans-serif; - } - .buttonA img,.buttonTOP img { - position: absolute; - top: -4px; - left: -12px; - border: none; - } - .buttonA:hover { - color: #DE5D51; - border: 1px solid #FFB3AA; - } - .buttonA:disabled { - visibility: hidden; - } - - -.buttonA_Big { - padding: 4px 10px 3px 25px; - border: 1px solid #DE5D51; - position: relative; - cursor: pointer; - display: inline-block; - background-image: url( '/info/images/buttonJumpBackground_red.png' ); - background-repeat: repeat-x; - font-size: 13px; - font-weight: bold; - text-decoration: none; - color: #9D271E; - -moz-border-radius-bottomleft: 5px; - -moz-border-radius-bottomright: 5px; - -moz-border-radius-topleft: 5px; - -moz-border-radius-topright: 5px; - font-family: Arial, Helvetica, sans-serif; - } - .buttonA_Big img { - position: absolute; - top: -4px; - left: -12px; - border: none; - } - .buttonA_Big:hover { - color: #DE5D51; - border: 1px solid #FFB3AA; - } - .buttonA_Big:disabled { - visibility: hidden; - } - - - - - -</style> -</head> - <body OnLoad="AutoExec()" class= text style="margin: 0; direction: rtl;font-size:12px;" -> - - -<script type="text/javascript" src="/info/sort/jquery.min.js"></script> -<script type="text/javascript" src="/info/sort/jquery-migrate.js"></script> - - -<script type="text/javascript"> - var SessionMesIdStr,SessionResIdStr; - SessionMesIdStr = ","; - SessionResIdStr = ","; - - function ShowHideContent(id,type){ - if (type == "msg") { - if (SessionMesIdStr.indexOf(","+id+",") == -1){ - SessionMesIdStr = SessionMesIdStr + id + ","; - } - } - else { - if (SessionResIdStr.indexOf(","+id+",") == -1){ - - SessionResIdStr = SessionResIdStr + id + ","; - } - } - div = document.getElementById("div" + type + id); - img = document.getElementById("IMG" + id); - if (div.style.display == "none") - { - div.style.display = 'block'; - img.src = '/info/images/box_open.png'; - } - else - { - div.style.display='none'; - img.src ='/info/images/box_closed.png'; - } - window.focus() - } - - </script> -<script type="text/javascript" src="/info/sort/jquery.tooltipster.min.js"></script> -<script type="text/javascript" src="/info/sort/select2.min.js"></script> -<script type="text/javascript"> -if(!($.browser.msie && ($.browser.version=="6.0" || $.browser.version=="7.0" || $.browser.version=="8.0"))) -{ - $(document).ready(function() { - $('#bigger, #smaller, #ConB, #ConL, #ConW, #Excel, #Outlook,.AboutOpen').tooltipster(); - $("select").select2(); - }); -} -</script> - - -<script type="text/javascript" src="/info/sort/jquery.tablesorter.js"></script> - <script src="/info/sort/jquery.ui.timepicker.js"></script> - <script src="/info/sort/jquery.ui.timepicker-he.js"></script> - - <script src="/info/sort/jquery.lazyload.js" type="text/javascript" charset="utf-8"></script> - <script type="text/javascript"> - $(function() { - $("img").lazyload(); - }); - </script> - -<script type="text/javascript" src="/info/sort/jquery.cookie.js"></script> - -<script type="text/javascript"> - var min=10; - var max=20; - var fontsize=12; - var fontsizeTitles=17; - var fs_elements = 'div,td,th,#Yedion a,select,p,span'; - var fs_elementsTitles = 'h1,h2,.white'; -$(document).ready(function(e){ - if ($.cookie("fs_styles")!=null) { - if ($.cookie("fs_styles")!='white') { - change_style($.cookie("fs_styles")); - } - } - if (($.cookie("fs_elements")!=null)&&($.cookie("fs_elementsTitles")!=null)) { - fontsize=parseInt($.cookie("fs_elements")); - fontsizeTitles=parseInt($.cookie("fs_elementsTitles")); - $.cookie("fs_elements", fontsize, { expires: 30 }); - $.cookie("fs_elementsTitles", fontsizeTitles, { expires: 30 }); - set_fontsizes(); - } -}); -function set_fontsizes() { - $(fs_elements).css('fontSize',fontsize+'px'); - $(fs_elementsTitles).css('fontSize',fontsizeTitles+'px'); - $.cookie("fs_elements", fontsize, { expires: 30 }); - $.cookie("fs_elementsTitles", fontsizeTitles, { expires: 30 }); -} -function enlarge() { - if (fontsize<max) { - fontsize+=2; - fontsizeTitles+=2; - set_fontsizes(); - } -} -function change_style(styletype) { - switch(styletype) { - case 'black': $('body').css('backgroundColor','black'); - $('.text').css('color','white'); - $('body').css('backgroundImage',''); - $('.tablesorter').css('backgroundColor','#35B3DC'); - $(fs_elements).css('backgroundColor','black'); - $(fs_elements).css('color','yellow'); - $(fs_elementsTitles).css('color','yellow'); - break; - case 'blue': $('body').css('backgroundColor','rgb(194, 211, 252)'); - $('.text').css('color','white'); - $('body').css('backgroundImage',''); - $('.tablesorter').css('backgroundColor','#35B3DC'); - $(fs_elements).css('backgroundColor','rgb(194, 211, 252)'); - $(fs_elements).css('color','black'); - $(fs_elementsTitles).css('color','black'); - break; - default: $('body').css('backgroundColor','white'); - $('.text').css('color','white'); - $('body').css('backgroundImage','url(/info/images/tile.gif)'); - $('.tablesorter').css('backgroundColor','#CDCDCD'); - $(fs_elements).css('backgroundColor',''); - $(fs_elements).css('color','black'); - $(fs_elementsTitles).css('color','black'); - $('th').css('color','white'); - break; - } - $.cookie("fs_styles", styletype, { expires: 30 }); -} -function shrink() { - if (fontsize>min) { - fontsize-=2; - fontsizeTitles-=2; - set_fontsizes(); - } -} -</script> - -<noscript> -<!-- <p><br />הגדלה והקטנה של מלל<br /></p> --> -</noscript> - - - -<script type="text/javascript"> -this.imagePreview = function(){ - /* CONFIG */ - - xOffset = 10; - yOffset = -300; - - // these 2 variable determine popup's distance from the cursor - // you might want to adjust to get the right result - - /* END CONFIG */ - $("a.preview").hover(function(e){ - this.t = this.title; - this.title = ""; - var c = (this.t != "") ? "<br/>" + this.t : ""; - $("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview'>"+ c +"<\/p>"); - $("#preview") - .css("top",(e.pageY - xOffset) + "px") - .css("left",(e.pageX + yOffset) + "px") - .fadeIn("fast"); - }, - function(){ - this.title = this.t; - $("#preview").remove(); - }); - $("a.preview").mousemove(function(e){ - $("#preview") - .css("top",(e.pageY - xOffset) + "px") - .css("left",(e.pageX + yOffset) + "px"); - }); -}; - - -// starting the script on page load -$(document).ready(function(){ - imagePreview(); -}); -</script> -<noscript> -<!-- <p><br />הגדלה של תמונה כאשר עוברים עליה<br /></p> --> -</noscript> - - <script type="text/javascript" src="/info/sort/jquery-ui.custom.min.js"></script> - - <script type="text/javascript" src="/info/sort/jquery.ui.datepicker-he.js"></script> - -<noscript> -<!-- <p><br />תאריכון<br /></p> --> -</noscript> -<!-- script src="/info/Scripts/AC_RunActiveContent.js" type="text/javascript"></script> --> -<script type="text/javascript"> -function AutoExec() -{ - if (typeof(document.form) != 'undefined') { - if (typeof(document.form.R1C1) != 'undefined') - document.form.R1C1.focus(); - - document.form.onsubmit = OnSubmit; - } - return; -} - -function OnSubmit () -{ - if (typeof(document.form) != 'undefined') { - if (document.form.APPNAME.value == "") - { - return false; - } - } - return true; -} - - - -function SubmitFormConfirm(Obj,app, prg, arg, trg, confirmQuestion) -{ - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - var conf = confirm(confirmQuestion); - if (conf) { - SubmitForm(Obj,app, prg, arg, trg); - } -} - -function SubmitForm(Obj,app, prg, arg, trg) -{ - if(Obj==null) - Obj=event.srcElement; - if(Obj==null) - return; - - bConfirm=Obj.getAttribute("Confirm"); - if (bConfirm=="true") - { - confirmQuestion = Obj.getAttribute("ConfirmQuestion"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - confirmQuestion = confirmQuestion.replace("\\n","\n"); - result = confirm (confirmQuestion); - if (!result) - { - return; - } - } - - if((trg!="_blank")&&(trg!="jq_float")) trg=""; - - document.form.APPNAME.value=app; - document.form.PRGNAME.value=prg; - document.form.ARGUMENTS.value=arg; - document.form.target=trg; - - document.form.submit(); -} -</script> -<noscript> -<!-- <p><br />הפעלת כפתורים<br /></p> --> -</noscript> - - - <script type="text/javascript"> - $(document).ready(function(){ - $(".buttonJump").hover(function(){ - $(".buttonJump img") - .animate({top:"-10px"}, 200).animate({top:"-4px"}, 200) // first jump - .animate({top:"-7px"}, 100).animate({top:"-4px"}, 100) // second jump - .animate({top:"-6px"}, 100).animate({top:"-4px"}, 100); // the last jump - }); - }); - </script> - - -<noscript> -<!-- <p><br />עיצוב של כפתור<br /></p> --> -</noscript> - - - -<!-- Text area --> - -<script type="text/javascript" src="/info/ckeditor/ckeditor.js"></script> - -<noscript> -<!-- <p><br />הגדרות בעת הפעלת עורך מלל<br /></p> --> -<!-- <p><br />הגדרות ראשוניות בעת אתחול עורך מלל<br /></p> --> -</noscript> - -<script type="text/javascript"> -if(!($.browser.msie)) - { - CKEDITOR.on( 'dialogDefinition', function( ev ) - { - var dialogName = ev.data.name; - var dialogDefinition = ev.data.definition; - if ( dialogName == 'link' ) - { - var targetTab = dialogDefinition.getContents( 'target' ); - var targetField = targetTab.get( 'linkTargetType' ); - targetField[ 'default' ] = '_blank'; - - } - }); - CKEDITOR.on('instanceReady', function(ev) { - ev.editor.on('paste', function(evt) { - evt.data.dataValue = evt.data.dataValue.replace(/target=".*?"/g, '' ); - evt.data.dataValue = evt.data.dataValue.replace(/href/g, 'target="_blank" href' ); - console.log(evt.data.dataValue); - }, null, null, 9); - }); - } -</script> -<!-- End of Text area --> - -<script type="text/javascript" src="/info/sort/RowColor.js"></script> - - <div style="width: 100%;"> - <span class="white" style="float:right;">תחנת מידע לסטודנט</span> - - <span style="float:left;">05/10/2014 - 14:29 - -<a class="buttonTOP" onClick="window.print()" accesskey="P"><img src="/info/images/Printer.PNG" style="top: 2px; left: 8px;" alt="">הדפס</a> - - -<a class="buttonTOP" onClick="enlarge();" accesskey="+"><img src="/info/images/zoom_in.PNG" style="top: 2px; left: 8px;" alt="הגדלת פונט ">הגדל</a> -<a class="buttonTOP" onClick="shrink();" accesskey="-"><img src="/info/images/zoom_out.PNG" style="top: 2px; left: 8px;" alt="הקטנת פונט ">הקטן</a> -<a class="buttonTOP" onClick="change_style('black');" accesskey="B"><img src="/info/images/black.gif" style="top: 1px; left: 10px;" alt="קונטרסט גבוה">&nbsp;</a> -<a class="buttonTOP" onClick="change_style('blue');" accesskey="L"><img src="/info/images/blue.gif" style="top: 1px; left: 10px;" alt="קונטרסט עדין">&nbsp;</a> -<a class="buttonTOP" onClick="change_style('white');" accesskey="W"><img src="/info/images/white.gif" style="top: 1px; left: 10px;" alt="קונטרסט ברירת מחדל">&nbsp;</a> - - - - <a class="buttonTOP" onClick="javascript:EXCEL()" accesskey="E"><img src="/info/images/xls.PNG" style="top: 2px; left: 8px;" alt="">אקסל</a> - <script type="text/javascript"> - function EXCEL() - { - window.open("fireflyweb.aspx?prgname=GetFile&Arguments=-N7","Grade_To_Excel", "menubar=yes,toolbar=no,resizable=yes,scrollbars=yes,width=700,height=500, top=100,left=100"); - } - </script> - - - - - - - - </span></div> - -<table style="width:100%;height:100%;border:0"> - <tr> - <td style="text-align:left"> - </table> -<br> - -<script type="text/javascript"> - function send_form(prgname,arguments,target) - { - var input = '<input type="hidden" name="prgname" value="'+prgname+'">'; - var input = input+'<input type="hidden" name="arguments" value="'+arguments+'">'; - $('<form method="post" action="fireflyweb.aspx" target="'+target+'">'+input+'</form>').appendTo('body').submit(); - } -</script> -<script type="text/javascript"> - function load_img(img_id,arg) - { - $.post('fireflyweb.aspx', - { - prgname: 'GetFile', - Arguments: arg, - IsItPost: 'Y' - },function(e){ - $('#'+img_id).html('<img src="data:image/jpg;base64,'+e+'" style="border:0;margin:2;" alt="תמונה ממסד הנתונים">'); - }); - } -</script> - <!--FileName : Header_Of_HTML_Type_3.HTM--> - - - <table style="text-align:right;width:98%;margin:auto;" class="text"> - <tr> - <td>שם סטודנט - </td> - - <td> - - <b>בן גידה לירן - </b> - </td> - - <td> - ת.ז. - </td> - <td> 302539556 - </td> - </tr> - - <tr> - <td>כתובת - </td> - <td> הסוללים 7 א' דירה 1 - </td> - - <td> - - תאריך - </td> - <td>05/10/2014 - </td> - - </tr> - - <tr> - <td>עיר - </td> - <td>ירושלים - </td> - - <td>מיקוד - </td> - <td>9371648 - </td> - </tr> - - <TR style="text-align:right"><td>חוג : </td><td>הנדסת תוכנה</td><td>התמחות</td><td>תוכנה</td></tr> - -</table> - -<h1 style="text-align:center">רשימת מערכת שעות שנה : 2015 סמסטר : 1 תשע"ה</h1> - - - - - - <script type="text/javascript"> - $(function() { - $("#myTable0").tablesorter(); -// $("#options").tablesorter({sortList: [[0,0]], headers: { 3:{sorter: false}, 4:{sorter: false}}}); - }); - </script> - - -<table style="text-align:right;width:98%;margin:auto;" class="tablesorter Mtable" ID="myTable0" summary="רשימת הקורסים"> -<thead> - <Tr> - <th style="width:50px">סמסטר</th> - <th>קוד קורס </th> - <th>שם הקורס </th> - <th>סוג מקצוע </th> - <th>שם המרצה </th> - <th style="width:30">נ"ז </th> - <th style="width:30">ש"ס</th> - <th style="width:90">יום ושעות </th> - <th>חדר </th> - <th>קוד קבוצה</th> - <th>חוג</th> - <th>אתר</th> - -</tr> -</thead> -<tbody> - <tr> - <td>א&nbsp; </td> - <td> 10001&nbsp; </td> - <td>אותות ומערכות&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td>ד"ר גור ערן&nbsp; </td> - <td> 4.50&nbsp; </td> - <td> 4.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -א'&nbsp;14:00&nbsp;-&nbsp;15:45 -</td> - <td>כתה- L208&nbsp; </td> - <td>100015101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10001&nbsp; </td> - <td>אותות ומערכות&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td>ד"ר גור ערן&nbsp; </td> - <td>&nbsp; </td> - <td>&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ב'&nbsp;12:00&nbsp;-&nbsp;13:45 -</td> - <td>כיתה-A102&nbsp; </td> - <td>100015101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10001&nbsp; </td> - <td>אותות ומערכות&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td>ד"ר גור ערן&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ג'&nbsp;13:00&nbsp;-&nbsp;13:45 -</td> - <td>כתה-L201&nbsp; </td> - <td>100015103&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10016&nbsp; </td> - <td>הסתברות וסטטיסטיקה 2&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N77,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר ביגון בוריס</a>&nbsp; </td> - <td> 2.50&nbsp; </td> - <td> 2.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -א'&nbsp;12:00&nbsp;-&nbsp;13:45 -</td> - <td>כתה- L204&nbsp; </td> - <td>100165101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10016&nbsp; </td> - <td>הסתברות וסטטיסטיקה 2&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N589,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">גב' שטיינבוך ביאנה</a>&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ב'&nbsp;09:00&nbsp;-&nbsp;09:45 -</td> - <td>כתה- L206&nbsp; </td> - <td>100165103&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10039&nbsp; </td> - <td>יישומי תקשורת מחשבים&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N284,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר צור-דוד שמרית</a>&nbsp; </td> - <td> 2.50&nbsp; </td> - <td> 2.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ב'&nbsp;10:00&nbsp;-&nbsp;11:45 -</td> - <td>כיתה-A102&nbsp; </td> - <td>100395101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10039&nbsp; </td> - <td>יישומי תקשורת מחשבים&nbsp; </td> - <td>מעבדה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N284,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר צור-דוד שמרית</a>&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ד'&nbsp;12:00&nbsp;-&nbsp;12:45 -</td> - <td>כיתת מחשבים-מ326&nbsp; </td> - <td>100395103&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10061&nbsp; </td> - <td>תקשורת מחשבים&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N47,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר אקסמן יעקב</a>&nbsp; </td> - <td> 3.50&nbsp; </td> - <td> 3.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ג'&nbsp;09:00&nbsp;-&nbsp;11:45 -</td> - <td>כיתה A106&nbsp; </td> - <td>100615101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10061&nbsp; </td> - <td>תקשורת מחשבים&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N742,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">גב' נתנזון מרים</a>&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ג'&nbsp;12:00&nbsp;-&nbsp;12:45 -</td> - <td>כיתת מחשבים A114&nbsp; </td> - <td>100615102&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10077&nbsp; </td> - <td>מבוא לתכנות מדעי&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N135,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר חסין יהודה</a>&nbsp; </td> - <td> 3.50&nbsp; </td> - <td> 3.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ד'&nbsp;08:00&nbsp;-&nbsp;10:45 -</td> - <td>אודיטוריום-001&nbsp; </td> - <td>100775101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10077&nbsp; </td> - <td>מבוא לתכנות מדעי&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N172,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר הראלי שלמה</a>&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ד'&nbsp;11:00&nbsp;-&nbsp;11:45 -</td> - <td>כיתת מחשבים-מ150&nbsp; </td> - <td>100775102&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10087&nbsp; </td> - <td>אוטומטים ושפות פורמליות&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N233,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">ד"ר רודה יואב</a>&nbsp; </td> - <td> 2.50&nbsp; </td> - <td> 2.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ד'&nbsp;14:00&nbsp;-&nbsp;15:45 -</td> - <td>כיתה A103&nbsp; </td> - <td>100875101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10087&nbsp; </td> - <td>אוטומטים ושפות פורמליות&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td>מר ידגר הראל עוז&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ג'&nbsp;14:00&nbsp;-&nbsp;14:45 -</td> - <td>כתה-L201&nbsp; </td> - <td>100875103&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10091&nbsp; </td> - <td>תכנות בסביבת אינטרנט&nbsp; </td> - <td>הרצאה&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N282,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר תבור שי</a>&nbsp; </td> - <td> 2.50&nbsp; </td> - <td> 2.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -א'&nbsp;10:00&nbsp;-&nbsp;11:45 -</td> - <td>אודיטוריום-201&nbsp; </td> - <td>100915101&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> - <tr> - <td>א&nbsp; </td> - <td> 10091&nbsp; </td> - <td>תכנות בסביבת אינטרנט&nbsp; </td> - <td>תרגיל&nbsp; - </td> - <td><a HREF="fireflyweb.aspx?prgname=Show_Teacher_Card&amp;arguments=-N282,-A" title="פתיחה בעמוד חדש של אתר המרצה" target="_blank">מר תבור שי</a>&nbsp; </td> - <td>&nbsp; </td> - <td> 1.00&nbsp; </td> - <td style="width:direction:rtl;width:90"> -ב'&nbsp;08:00&nbsp;-&nbsp;08:45 -</td> - <td>כיתת מחשבים A114&nbsp; </td> - <td>100915102&nbsp; </td> - <td>תוכנה&nbsp; </td> - <td>&nbsp; </td> - -</tr> -</tbody> -<tfoot> - <tr> - <td colspan=5>סה"כ נקודות זכות לסמסטר זה -( - קורס שנתי יחושב כמחצית בכל סמסטר -) </td> - <td><b>21.50</b></td> - <td><b>25.00</b></td> - <td colspan=5>&nbsp; </td> -</tr> -</tfoot> -</table> - -<div style="text-align:right" class="text"> - -<br> -ט.ל.ח -<br> -רשימת מערכת שעות שנה : 2015 סמסטר : 1 מותנה בעמידה בתנאי הקדם לקורסים -<br> - -רשימת מערכת שעות שנה : 2015 סמסטר : 1 זו אינה מהווה אישור רשמי של עזריאלי, מכללה אקדמית להנדסה ירושלים -</div> - -<script type="text/javascript"> propagateEventHandler(document.getElementById("myTable0"), "onmouseover", "TR", highlightTableRow, "lightblue");</script> - </body></html> - <!--FileName : TimeTable_List_For_Student.htm-->" - - - @@ -1829,7 +690,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 22 + 21 diff --git a/src/jceData/Calendar/calendarDialog.cpp b/src/jceData/Calendar/calendarDialog.cpp index cf6be72..f3bd71c 100644 --- a/src/jceData/Calendar/calendarDialog.cpp +++ b/src/jceData/Calendar/calendarDialog.cpp @@ -61,7 +61,7 @@ void CalendarDialog::on_calStart_selectionChanged() void CalendarDialog::on_buttonBox_accepted() { if(this->isOK) - qDebug() << "CalendarDialog: Valid input"; + qDebug() << Q_FUNC_INFO << "CalendarDialog: Valid input"; } void CalendarDialog::on_calEnd_selectionChanged() diff --git a/src/jceData/Calendar/calendarPage.cpp b/src/jceData/Calendar/calendarPage.cpp index 2566146..0a68e38 100644 --- a/src/jceData/Calendar/calendarPage.cpp +++ b/src/jceData/Calendar/calendarPage.cpp @@ -2,123 +2,108 @@ QString CalendarPage::htmlToString() { - return tempHtml; + return tempHtml; } void CalendarPage::setPage(QString html) { - qDebug() << "parsing calendar"; - courses = new std::list(); - tempHtml = getString(html); - tempHtml = tokenToLines(tempHtml); - qDebug() << "creating courses list"; - calendarListInit(tempHtml); - qDebug() << "done"; + courses = new std::list(); + tempHtml = getString(html); + calendarListInit(tempHtml); } -QString CalendarPage::tokenToLines(QString &textToParse) -{ - int ctr = 0; - QString temp = ""; - char *tok; - char* textToTok = strdup(textToParse.toStdString().c_str()); - tok = strtok(textToTok, "\n"); - while(tok != NULL) - { - //amount of data before the actual needed data and no empty lines - if (strcmp(tok," \t ") != 0) - { - temp += tok; - temp += "\n"; - } - ctr++; - tok = strtok(NULL, "\n"); - } - return temp; -} - void CalendarPage::calendarListInit(QString &linesTokinzedString) { - std::list stringHolder; - QString temp; - calendarCourse * cTemp = NULL; - char* tok; - char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); - tok = strtok(textToTok,"\n"); - while (tok != NULL) + std::list stringHolder; + QString temp; + calendarCourse * cTemp = NULL; + char* tok; + char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); + tok = strtok(textToTok,"\n"); + while (tok != NULL) { - temp = tok; - stringHolder.push_back(temp); - tok = strtok(NULL, "\n"); + temp = tok; + stringHolder.push_back(temp); + tok = strtok(NULL, "\n"); } - for (QString temp: stringHolder) + for (QString temp: stringHolder) { - cTemp = lineToCourse(temp); - if (cTemp != NULL) - courses->push_back(cTemp); + cTemp = lineToCourse(temp); + if (cTemp != NULL) + courses->push_back(cTemp); } } calendarCourse *CalendarPage::lineToCourse(QString line) { - calendarCourse *tempC = NULL; - QString templinearray[CALENDAR_COURSE_FIELDS];//[serial,name,type,lecturer,points,semesterhours,dayandhours,room] - int serial; - double points,semesterHours; - QString name,type, lecturer,dayAndHour,room; - QString tempS = ""; - int i = 0; - char* tok; - char* cLine = strdup(line.toStdString().c_str()); - tok = strtok(cLine, "\t"); - while(tok != NULL) + calendarCourse *tempC = NULL; + QString templinearray[CALENDAR_COURSE_FIELDS];//[serial,name,type,lecturer,points,semesterhours,dayandhours,room] + int serial; + double points,semesterHours; + QString name,type, lecturer,dayAndHour,room; + QString tempS = ""; + int i = 0; + char* tok; + char* cLine = strdup(line.toStdString().c_str()); + tok = strtok(cLine, "\t"); + while(tok != NULL) { - tempS = QString(tok); + tempS = QString(tok); - if (i >= 1) + if (i >= 1) //skips on semester character { - templinearray[i-1] = tempS.trimmed(); + templinearray[i-1] = tempS.trimmed(); } - i++; - if (i > 8) - break; - tok=strtok(NULL, "\t"); + i++; + if (i > 8) + break; + tok=strtok(NULL, "\t"); } - if (templinearray[0] == "") //empty parsing - return NULL; + if (templinearray[0] == "") //empty parsing + return NULL; - serial = templinearray[calendarCourse::CourseScheme::SERIAL].toInt(); - name = templinearray[calendarCourse::CourseScheme::NAME]; - type = templinearray[calendarCourse::CourseScheme::TYPE]; + serial = templinearray[calendarCourse::CourseScheme::SERIAL].toInt(); + name = templinearray[calendarCourse::CourseScheme::NAME]; + type = templinearray[calendarCourse::CourseScheme::TYPE]; - if (!templinearray[calendarCourse::CourseScheme::LECTURER].isEmpty()) - lecturer = templinearray[calendarCourse::CourseScheme::LECTURER]; - else - lecturer = LECTURER_DEFAULT_STRING; + if (!templinearray[calendarCourse::CourseScheme::LECTURER].isEmpty()) + lecturer = templinearray[calendarCourse::CourseScheme::LECTURER]; + else + lecturer = LECTURER_DEFAULT_STRING; - if (!templinearray[calendarCourse::CourseScheme::POINTS].isEmpty()) - points = templinearray[calendarCourse::CourseScheme::POINTS].toDouble(); - else - points = 0; - if (!templinearray[calendarCourse::CourseScheme::SEM_HOURS].isEmpty()) - semesterHours = templinearray[calendarCourse::CourseScheme::SEM_HOURS].toDouble(); - else - semesterHours = 0; + if (!templinearray[calendarCourse::CourseScheme::POINTS].isEmpty()) + points = templinearray[calendarCourse::CourseScheme::POINTS].toDouble(); + else + points = 0; + if (!templinearray[calendarCourse::CourseScheme::SEM_HOURS].isEmpty()) + semesterHours = templinearray[calendarCourse::CourseScheme::SEM_HOURS].toDouble(); + else + semesterHours = 0; - dayAndHour = templinearray[calendarCourse::CourseScheme::DAY_AND_HOURS]; + dayAndHour = templinearray[calendarCourse::CourseScheme::DAY_AND_HOURS]; - if (!templinearray[calendarCourse::CourseScheme::ROOM].isEmpty()) - room = templinearray[calendarCourse::CourseScheme::ROOM]; - else - room = ROOM_DEFAULT_STRING; + if (!templinearray[calendarCourse::CourseScheme::ROOM].isEmpty()) + room = templinearray[calendarCourse::CourseScheme::ROOM]; + else + room = ROOM_DEFAULT_STRING; - qDebug() << serial << name << type << lecturer << points << semesterHours << dayAndHour << room; - tempC = new calendarCourse(serial,name,type,lecturer,points,semesterHours,dayAndHour,room); - return tempC; + tempC = new calendarCourse(serial,name,type,lecturer,points,semesterHours,dayAndHour,room); +// qDebug() << "serial is: " << tempC->getSerialNum(); +// qDebug() << tempC->getName(); +// qDebug() << tempC->getType(); +// qDebug() << tempC->getLecturer(); +// qDebug() << tempC->getPoints(); +// qDebug() << tempC->getHourBegin() << ":" << tempC->getMinutesBegin(); +// qDebug() << tempC->getHourEnd() << ":" << tempC->getMinutesEnd(); + +// qDebug() << tempC->getDay(); +// qDebug() << tempC->getRoom(); + + return tempC; } diff --git a/src/jceData/Calendar/calendarPage.h b/src/jceData/Calendar/calendarPage.h index c68fcba..75de858 100644 --- a/src/jceData/Calendar/calendarPage.h +++ b/src/jceData/Calendar/calendarPage.h @@ -22,7 +22,6 @@ protected: private: - QString tokenToLines(QString &textToParse); void calendarListInit(QString &linesTokinzedString); calendarCourse* lineToCourse(QString line); diff --git a/src/jceData/Calendar/calendarSchedule.cpp b/src/jceData/Calendar/calendarSchedule.cpp index e569c47..06e1837 100644 --- a/src/jceData/Calendar/calendarSchedule.cpp +++ b/src/jceData/Calendar/calendarSchedule.cpp @@ -38,7 +38,7 @@ void calendarSchedule::setPage(QString html) { CalendarPage::setPage(html); qDebug() << Q_FUNC_INFO << "inserting into table"; -// insertCourseIntoTable(); + insertCourseIntoTable(); } void calendarSchedule::clearTableItems() @@ -61,12 +61,10 @@ void calendarSchedule::insertCourseIntoTable() int row,col; for (calendarCourse *coursePtr: *getCourses()) { - qDebug() << coursePtr->getSerialNum(); courseString = ""; currentHour = coursePtr->getHourBegin(); currentDay = coursePtr->getDay(); blocksNumber = coursePtr->getHourEnd() - coursePtr->getHourBegin(); //every hour is a block to fill! - qDebug() << blocksNumber; while (blocksNumber >= 0) { row = currentHour - HOURS_BEGIN; diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index 786f132..8e0c08d 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -4,7 +4,6 @@ GradePage::GradePage(QString html) : Page() { courses = new std::list(); tempHtml = getString(html); - tempHtml = tokenToLines(tempHtml); coursesListInit(tempHtml); } @@ -49,26 +48,6 @@ void GradePage::coursesListInit(QString &linesTokinzedString) courses->push_back(cTemp); } } - -QString GradePage::tokenToLines(QString &textToPhrase) -{ - QString temp = ""; - char *tok; - char* textToTok = strdup(textToPhrase.toStdString().c_str()); - tok = strtok(textToTok, "\n"); - while(tok != NULL) - { - //amount of data before the actual needed data and no empty lines - if (strcmp(tok," \t ") != 0) - { - temp += tok; - temp += "\n"; - } - tok = strtok(NULL, "\n"); - } - return temp; - -} gradeCourse* GradePage::lineToCourse(QString line) { gradeCourse *tempC = NULL; diff --git a/src/jceData/Grades/gradePage.h b/src/jceData/Grades/gradePage.h index 00fc613..ea4ee28 100644 --- a/src/jceData/Grades/gradePage.h +++ b/src/jceData/Grades/gradePage.h @@ -27,7 +27,6 @@ public: private: - QString tokenToLines(QString &textToPhrase); void coursesListInit(QString &linesTokinzedString); gradeCourse* lineToCourse(QString line); diff --git a/src/jceData/page.cpp b/src/jceData/page.cpp index 7c65231..2d9b455 100644 --- a/src/jceData/page.cpp +++ b/src/jceData/page.cpp @@ -8,14 +8,14 @@ Page::Page() { dateHeader = "";} */ QString Page::getString(QString &htmlToParse) { - makeText(htmlToParse); - return this->text; + makeText(htmlToParse); + return this->text; } void Page::makeText(QString &html) { - int index = 0; - index = html.indexOf("",0); //set index into the place where the data is - manageTableContent(html, index); + int index = 0; + index = html.indexOf("",0); //set index into the place where the data is + manageTableContent(html, index); } /** * @brief Page::manageTableContent strip html, make it string @@ -24,141 +24,153 @@ void Page::makeText(QString &html) */ void Page::manageTableContent(QString &html, int index) { - if (index == -1) - return; - QString temp; - for (int i = index; i < html.length(); i++) + if (index == -1) + return; + QString temp; + for (int i = index; i < html.length(); i++) { - if (html.at(i) == '<') + if (html.at(i) == '<') { - // / / - QString endofTable = ""; - QString tableTag = html.mid(i, 4); //legth of "tr/td" - if (tableTag == "") - { - if (!dateHeader.isEmpty()) - temp += dateHeader; - i = stitchText(html, temp, i+4); - if (i == -1) //EOF - break; - - } - else if (tableTag == " new line - i+=5; - } - else if (tableTag == "" || tableTag == "") - { - if (!dateHeader.isEmpty()) - temp += "\t"; // new cell -> tab between data - if (html.mid(i, 6) == "") - break; - i++; - } - i = stitchText(html, temp, i); - - } - if (html.mid(i,(endofTable).length()) == endofTable) //is end of table + // / / + QString endofTable = ""; + QString tableTag = html.mid(i, 4); //legth of "tr/td" + if (tableTag == "") { + if (!dateHeader.isEmpty()) + temp += dateHeader; + i = stitchText(html, temp, i+4); + if (i == -1) //EOF break; + + } + else if (tableTag == " new line + i+=5; + } + else if (tableTag == "" || tableTag == "") + { + if (!dateHeader.isEmpty()) + temp += "\t"; // new cell -> tab between data + if (html.mid(i, 6) == "") //for gpa. year & semester title + { + break; + } + else if ((html.at(i) == '>') && (html.mid(i+4,3) != "")) //for calendar. day and hours + { + i += 1; //lenght of > + break; + } + i++; + } + i = stitchText(html, temp, i); + temp += "\t"; + } + if (html.mid(i,(endofTable).length()) == endofTable) //is end of table + { + break; } } } - this->text = temp; + this->text = temp; } int Page::stitchText(QString &from, QString &to, int index) { - if (from.at(index) == '<') + if (from.mid(index,3) == "") { - QString bTag = from.mid(index, 3); - QString dateline = from.mid(index,from.indexOf("",index+4)-index); - QString temp; - QString date; - char* tok; - int i = 0; - char* textToTok = strdup(dateline.toStdString().c_str()); - tok = strtok(textToTok,"<> :"); - while (tok != NULL) + QString bTag = from.mid(index, 3); + QString dateline = from.mid(index,from.indexOf("",index+4)-index); + QString temp; + QString date; + char* tok; + int i = 0; + char* textToTok = strdup(dateline.toStdString().c_str()); + tok = strtok(textToTok,"<> :"); + while (tok != NULL) { - if (i == 1) + if (i == 1) { - temp = tok; - date += temp + "\t"; + temp = tok; + date += temp + "\t"; } - else if (i == 3) + else if (i == 3) { - temp = tok; - date += temp; + temp = tok; + date += temp; } - i++; - tok = strtok(NULL, "<> :"); + i++; + tok = strtok(NULL, "<> :"); } - dateHeader = date; - if (bTag != "") - return index-1; //go back one step - for the main function to inc i - index += dateline.length(); + dateHeader = date; + if (bTag != "") + return index-1; //go back one step - for the main function to inc i + index += dateline.length(); } - while (from.at(index) != '<' && index < (int)from.length()) + while (from.at(index) != '<' && index < (int)from.length()) { - if (from[index] == '&') + if (from[index] == '&') { - //  - QString nbspChr = from.mid(index, 6); - if (nbspChr == " ") + //  + QString nbspChr = from.mid(index, 6); + if (nbspChr == " ") { - index += 5; - from.replace(index,1,' '); + index += 5; + from.replace(index,1,' '); } } - if (endOfString(index,(int) from.length())) - return -1; //EOF + if (endOfString(index,(int) from.length())) + return -1; //EOF - else if (from.at(index) == '<') - return index - 1; //go back one step - for the main function to inc i + else if (from.at(index) == '<') + return index - 1; //go back one step - for the main function to inc i - if ((from.at(index) != '\n') && (from.at(index) != '\t')) //check the actuall data before continue - to += from.at(index); - index++; + if ((from.at(index) != '\n') && (from.at(index) != '\t')) //check the actuall data before continue + to += from.at(index); + index++; } - return index-1; + return index-1; } bool Page::endOfString(int index, int length) { - if(index < length) - return false; - return true; + if(index < length) + return false; + return true; } diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 900ef23..79e852c 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -6,21 +6,21 @@ */ jceLogin::jceLogin(user* username, QProgressBar *progressbarPtr) { - this->progressBar = progressbarPtr; - this->recieverPage = new QString(); - this->jceA = username; - this->JceConnector = new jceSSLClient(progressBar); - QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); - QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); + this->progressBar = progressbarPtr; + this->recieverPage = new QString(); + this->jceA = username; + this->JceConnector = new jceSSLClient(progressBar); + QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); + QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); } jceLogin::~jceLogin() { - this->jceA = NULL; - delete recieverPage; - delete JceConnector; - JceConnector = NULL; - recieverPage = NULL; + this->jceA = NULL; + delete recieverPage; + delete JceConnector; + JceConnector = NULL; + recieverPage = NULL; } /** * @brief jceLogin::makeConnection Connecting to JCE student web site with JceA (username object) and validate it. @@ -28,74 +28,74 @@ jceLogin::~jceLogin() */ int jceLogin::makeConnection() { - qDebug() << "jceLogin::makeConnection(); connection to be make"; + qDebug() << "jceLogin::makeConnection(); connection to be make"; - if (this->recieverPage == NULL) - this->recieverPage = new QString(); + if (this->recieverPage == NULL) + this->recieverPage = new QString(); - int returnMode; //gets status according to called function of validation step - jceStatus status = jceStatus::JCE_NOT_CONNECTED; + int returnMode; //gets status according to called function of validation step + jceStatus status = jceStatus::JCE_NOT_CONNECTED; - returnMode = checkConnection(); //checking socket status. is connected? + returnMode = checkConnection(); //checking socket status. is connected? - if (returnMode == false) + if (returnMode == false) { - if (JceConnector->makeConnect(dst_host,dst_port) == false) //couldnt make a connection - return jceStatus::ERROR_ON_OPEN_SOCKET; - else - returnMode = true; + if (JceConnector->makeConnect(dst_host,dst_port) == false) //couldnt make a connection + return jceStatus::ERROR_ON_OPEN_SOCKET; + else + returnMode = true; } - if (returnMode == true) //connected to host + if (returnMode == true) //connected to host { - returnMode = makeFirstVisit(); - if (returnMode == true) //requst and send first validation + returnMode = makeFirstVisit(); + if (returnMode == true) //requst and send first validation { - status = jceStatus::JCE_START_VALIDATING_PROGRESS; - returnMode = checkValidation(); - if (returnMode == true) //check if username and password are matching + status = jceStatus::JCE_START_VALIDATING_PROGRESS; + returnMode = checkValidation(); + if (returnMode == true) //check if username and password are matching { - status = jceStatus::JCE_VALIDATION_PASSED; - returnMode = makeSecondVisit(); - if (returnMode == true) //siging in the website + status = jceStatus::JCE_VALIDATION_PASSED; + returnMode = makeSecondVisit(); + if (returnMode == true) //siging in the website { - qDebug() << "jceLogin::makeConnection(); Signed in succeesfully"; - status = jceStatus::JCE_YOU_ARE_IN; - setLoginFlag(true); + qDebug() << "jceLogin::makeConnection(); Signed in succeesfully"; + status = jceStatus::JCE_YOU_ARE_IN; + setLoginFlag(true); } - else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO) + else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO) { - status = jceLogin::ERROR_ON_GETTING_INFO; + status = jceLogin::ERROR_ON_GETTING_INFO; } - else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST) + else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST) { - status = jceLogin::ERROR_ON_SEND_REQUEST; + status = jceLogin::ERROR_ON_SEND_REQUEST; } - else - status = jceStatus::ERROR_ON_VALIDATION; - } - else + else status = jceStatus::ERROR_ON_VALIDATION; + } + else + status = jceStatus::ERROR_ON_VALIDATION; } - else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO) + else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO) { - status = jceLogin::ERROR_ON_GETTING_INFO; + status = jceLogin::ERROR_ON_GETTING_INFO; } - else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST) + else if (returnMode == jceLogin::ERROR_ON_SEND_REQUEST) { - status = jceLogin::ERROR_ON_SEND_REQUEST; + status = jceLogin::ERROR_ON_SEND_REQUEST; } - else - status = jceStatus::ERROR_ON_VALIDATION_USER_BLOCKED; + else + status = jceStatus::ERROR_ON_VALIDATION_USER_BLOCKED; } - else - status = jceStatus::JCE_NOT_CONNECTED; + else + status = jceStatus::JCE_NOT_CONNECTED; - //we throw status even if we are IN! - qDebug() << "jceLogin::makeConnection(); return status: " << status; - return status; + //we throw status even if we are IN! + qDebug() << "jceLogin::makeConnection(); return status: " << status; + return status; } /** @@ -104,21 +104,21 @@ int jceLogin::makeConnection() */ bool jceLogin::checkConnection() const { - if (JceConnector->isConnected()) - return true; + if (JceConnector->isConnected()) + return true; - return false; + return false; } /** * @brief jceLogin::closeAll */ void jceLogin::closeAll() { - this->JceConnector->makeDiconnect(); - if ((this->recieverPage != NULL) && (!this->recieverPage->isEmpty())) + this->JceConnector->makeDiconnect(); + if ((this->recieverPage != NULL) && (!this->recieverPage->isEmpty())) { - delete recieverPage; - recieverPage = NULL; + delete recieverPage; + recieverPage = NULL; } } @@ -127,17 +127,17 @@ void jceLogin::closeAll() */ void jceLogin::reMakeConnection() { - if (this->JceConnector != NULL) - delete JceConnector; - if (this->recieverPage != NULL) - delete recieverPage; - recieverPage = NULL; - JceConnector = NULL; - this->recieverPage = new QString(); - this->JceConnector = new jceSSLClient(progressBar); - QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); - QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); - emit connectionReadyAfterDisconnection(); + if (this->JceConnector != NULL) + delete JceConnector; + if (this->recieverPage != NULL) + delete recieverPage; + recieverPage = NULL; + JceConnector = NULL; + this->recieverPage = new QString(); + this->JceConnector = new jceSSLClient(progressBar); + QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); + QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); + emit connectionReadyAfterDisconnection(); } /** @@ -146,17 +146,17 @@ void jceLogin::reMakeConnection() */ int jceLogin::makeFirstVisit() { - QString usr = jceA->getUsername(); - QString psw = jceA->getPassword(); - if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA)))) + QString usr = jceA->getUsername(); + QString psw = jceA->getPassword(); + if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA)))) { - if (!JceConnector->recieveData(*recieverPage,true)) - return jceLogin::ERROR_ON_GETTING_INFO; + if (!JceConnector->recieveData(*recieverPage,true)) + return jceLogin::ERROR_ON_GETTING_INFO; } - else - return jceLogin::ERROR_ON_SEND_REQUEST; + else + return jceLogin::ERROR_ON_SEND_REQUEST; - return true; + return true; } /** * @brief jceLogin::makeSecondVisit making the second validation step of jce student portal login @@ -164,19 +164,19 @@ int jceLogin::makeFirstVisit() */ int jceLogin::makeSecondVisit() { - QString usrid=jceA->getUserID(); - QString pswid=jceA->getHashedPassword(); - if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getSecondValidationStep(*jceA))))) + QString usrid=jceA->getUserID(); + QString pswid=jceA->getHashedPassword(); + if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getSecondValidationStep(*jceA))))) { - if (!(JceConnector->recieveData(*recieverPage,true))) - return jceLogin::ERROR_ON_GETTING_INFO; + if (!(JceConnector->recieveData(*recieverPage,true))) + return jceLogin::ERROR_ON_GETTING_INFO; - return true; + return true; } - else - return jceLogin::ERROR_ON_SEND_REQUEST; + else + return jceLogin::ERROR_ON_SEND_REQUEST; - return true; + return true; } /** * @brief jceLogin::getCalendar according to parameters, we make an HTML request and send it over socket to server @@ -186,17 +186,17 @@ int jceLogin::makeSecondVisit() */ int jceLogin::getCalendar(int year, int semester) { - if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getCalendar(*jceA,year,semester))))) + if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getCalendar(*jceA,year,semester))))) { - if (!(JceConnector->recieveData(*recieverPage,false))) - return jceLogin::ERROR_ON_GETTING_PAGE; - else - return jceLogin::JCE_PAGE_PASSED; + if (!(JceConnector->recieveData(*recieverPage,false))) + return jceLogin::ERROR_ON_GETTING_PAGE; + else + return jceLogin::JCE_PAGE_PASSED; } - else - return jceLogin::ERROR_ON_SEND_REQUEST; + else + return jceLogin::ERROR_ON_SEND_REQUEST; - return true; + return true; } /** @@ -209,17 +209,17 @@ int jceLogin::getCalendar(int year, int semester) */ int jceLogin::getGrades(int fromYear, int toYear, int fromSemester, int toSemester) { - if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getGradesPath(*jceA,fromYear, toYear, fromSemester, toSemester))))) + if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getGradesPath(*jceA,fromYear, toYear, fromSemester, toSemester))))) { - if (!(JceConnector->recieveData(*recieverPage,false))) - return jceLogin::ERROR_ON_GETTING_PAGE; - else - return jceLogin::JCE_PAGE_PASSED; + if (!(JceConnector->recieveData(*recieverPage,false))) + return jceLogin::ERROR_ON_GETTING_PAGE; + else + return jceLogin::JCE_PAGE_PASSED; } - else - return jceLogin::ERROR_ON_SEND_REQUEST; + else + return jceLogin::ERROR_ON_SEND_REQUEST; - return true; + return true; } /** @@ -229,43 +229,43 @@ int jceLogin::getGrades(int fromYear, int toYear, int fromSemester, int toSemest bool jceLogin::checkValidation() { - //finds the hashed password - QString constUserID_TAG = "value=\"-N"; - QString constHassID_TAG = "-A,-N"; - QString hasspass,hassid; - std::size_t hasspass_position1,hasspass_position2; - std::size_t id_position1,id_position2; + //finds the hashed password + QString constUserID_TAG = "value=\"-N"; + QString constHassID_TAG = "-A,-N"; + QString hasspass,hassid; + std::size_t hasspass_position1,hasspass_position2; + std::size_t id_position1,id_position2; - hasspass_position1 = this->recieverPage->toStdString().find(constHassID_TAG.toStdString()); //looking for hasspass index - if (hasspass_position1 == std::string::npos) //didnt find the tag - return false; - else - hasspass_position1 += constHassID_TAG.length(); //skip the index of tag - hasspass_position2 = this->recieverPage->toStdString().find(",-A,-A", hasspass_position1); - //finds the hass pass - if (hasspass_position2 != std::string::npos) //found the hasspass! storing it - hasspass = recieverPage->mid(hasspass_position1,hasspass_position2-hasspass_position1); - else - return false; - //finds the user id - id_position1 = this->recieverPage->toStdString().find(constUserID_TAG.toStdString(), 0); //looking for hassid index - if (id_position1 == std::string::npos) //didnt find the tag - return false; - else - id_position1 += constUserID_TAG.length(); //skip the index of tag - id_position2 = this->recieverPage->toStdString().find(",-A", id_position1); - if (id_position2 != std::string::npos) //found the hassid! storing it - hassid = recieverPage->mid(id_position1,id_position2-id_position1); - else - return false; + hasspass_position1 = this->recieverPage->toStdString().find(constHassID_TAG.toStdString()); //looking for hasspass index + if (hasspass_position1 == std::string::npos) //didnt find the tag + return false; + else + hasspass_position1 += constHassID_TAG.length(); //skip the index of tag + hasspass_position2 = this->recieverPage->toStdString().find(",-A,-A", hasspass_position1); + //finds the hass pass + if (hasspass_position2 != std::string::npos) //found the hasspass! storing it + hasspass = recieverPage->mid(hasspass_position1,hasspass_position2-hasspass_position1); + else + return false; + //finds the user id + id_position1 = this->recieverPage->toStdString().find(constUserID_TAG.toStdString(), 0); //looking for hassid index + if (id_position1 == std::string::npos) //didnt find the tag + return false; + else + id_position1 += constUserID_TAG.length(); //skip the index of tag + id_position2 = this->recieverPage->toStdString().find(",-A", id_position1); + if (id_position2 != std::string::npos) //found the hassid! storing it + hassid = recieverPage->mid(id_position1,id_position2-id_position1); + else + return false; - //setting user information with given data hassid and hasspass - jceA->setHashedPassword(hasspass); - jceA->setUserID(hassid); + //setting user information with given data hassid and hasspass + jceA->setHashedPassword(hasspass); + jceA->setUserID(hassid); - qDebug() << "jceLogin::checkValidation(); Found Hashed: " << hasspass << "And ID: " << hassid; + qDebug() << "jceLogin::checkValidation(); Found Hashed: " << hasspass << "And ID: " << hassid; - return true; + return true; } /** * @brief jceLogin::setLoginFlag @@ -273,7 +273,7 @@ bool jceLogin::checkValidation() */ void jceLogin::setLoginFlag(bool x) { - this->loginFlag = x; + this->loginFlag = x; } /** * @brief jceLogin::isLoginFlag checking if there is a connection, if true - > return if we signed in. otherwise, return not (not connected dough) @@ -281,9 +281,9 @@ void jceLogin::setLoginFlag(bool x) */ bool jceLogin::isLoginFlag() const { - if (checkConnection()) - return this->loginFlag; - return false; + if (checkConnection()) + return this->loginFlag; + return false; } /** @@ -292,27 +292,27 @@ bool jceLogin::isLoginFlag() const */ QString jceLogin::getPage() { - return *recieverPage; + return *recieverPage; } void jceLogin::reValidation() { - qDebug() << Q_FUNC_INFO << "Revalidating user"; + qDebug() << Q_FUNC_INFO << "Revalidating user"; - if (makeFirstVisit() == true) + if (makeFirstVisit() == true) { - if (checkValidation()) + if (checkValidation()) { - if (makeSecondVisit() == true) - qDebug() << Q_FUNC_INFO << "Validated"; - else - qWarning() << Q_FUNC_INFO << "Second visit finished with an error"; + if (makeSecondVisit() == true) + qDebug() << Q_FUNC_INFO << "Validated"; + else + qWarning() << Q_FUNC_INFO << "Second visit finished with an error"; } - else - qDebug() << Q_FUNC_INFO << "checking validation ended with an error"; + else + qDebug() << Q_FUNC_INFO << "checking validation ended with an error"; } - else + else { - qDebug() << Q_FUNC_INFO << "Couldnt Validate User"; + qDebug() << Q_FUNC_INFO << "Couldnt Validate User"; } } diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index 912b47b..44310a8 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -12,57 +12,58 @@ class jceLogin : public QObject { - Q_OBJECT + Q_OBJECT public: - jceLogin(user* username,QProgressBar *progressbarPtr); - ~jceLogin(); + jceLogin(user* username,QProgressBar *progressbarPtr); + ~jceLogin(); - enum jceStatus { - JCE_NOT_CONNECTED, - ERROR_ON_VALIDATION, - ERROR_ON_VALIDATION_USER_BLOCKED, - ERROR_ON_OPEN_SOCKET, - ERROR_ON_SEND_REQUEST, - ERROR_ON_GETTING_INFO, - ERROR_ON_GETTING_PAGE, + enum jceStatus { + JCE_NOT_CONNECTED, + ERROR_ON_VALIDATION, + ERROR_ON_VALIDATION_USER_BLOCKED, + ERROR_ON_OPEN_SOCKET, + ERROR_ON_SEND_REQUEST, + ERROR_ON_GETTING_INFO, + ERROR_ON_GETTING_PAGE, - JCE_START_VALIDATING_PROGRESS, - JCE_VALIDATION_PASSED, - JCE_YOU_ARE_IN, - JCE_PAGE_PASSED - }; + JCE_START_VALIDATING_PROGRESS, + JCE_VALIDATION_PASSED, + JCE_YOU_ARE_IN, + JCE_PAGE_PASSED + }; - int makeConnection(); - void closeAll(); - bool checkConnection() const; - bool isLoginFlag() const; + int makeConnection(); + void closeAll(); - int getCalendar(int year, int semester); - int getGrades(int fromYear, int toYear, int fromSemester, int toSemester); + bool checkConnection() const; + bool isLoginFlag() const; - QString getPage(); + int getCalendar(int year, int semester); + int getGrades(int fromYear, int toYear, int fromSemester, int toSemester); + + QString getPage(); private slots: - void reValidation(); - void reMakeConnection(); + void reValidation(); + void reMakeConnection(); signals: - void connectionReadyAfterDisconnection(); + void connectionReadyAfterDisconnection(); private: - int makeFirstVisit(); - int makeSecondVisit(); - bool checkValidation(); - void setLoginFlag(bool x); + int makeFirstVisit(); + int makeSecondVisit(); + bool checkValidation(); + void setLoginFlag(bool x); - bool loginFlag; - QString * recieverPage; - user * jceA; - jceSSLClient * JceConnector; - QProgressBar *progressBar; + bool loginFlag; + QString * recieverPage; + user * jceA; + jceSSLClient * JceConnector; + QProgressBar *progressBar; }; From da17cc17843ac1a36d836eed283ca636bd182f46 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 6 Oct 2014 19:18:05 +0300 Subject: [PATCH 07/58] login tab to be on flash --- main/mainscreen.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index d7d4f53..52c6a1a 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 2 + 0 false From 63c5ec9cc7995283024a45d69236333f7418874c Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 6 Oct 2014 19:41:55 +0300 Subject: [PATCH 08/58] sorting is by type and not by string! #25 --- main/CourseTab/coursestablemanager.cpp | 305 +++++++++++++------------ 1 file changed, 162 insertions(+), 143 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index bdf7dc8..ce215a7 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -2,49 +2,49 @@ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { - this->gp = NULL; - this->us = usrPtr; - this->courseTBL = ptr; + this->gp = NULL; + this->us = usrPtr; + this->courseTBL = ptr; - /* + /* * Initilizing Table */ - courseTBL->setRowCount(0); - courseTBL->setColumnCount(COURSE_FIELDS); - QStringList mz; - mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); - courseTBL->setHorizontalHeaderLabels(mz); - courseTBL->verticalHeader()->setVisible(false); - courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); - courseTBL->setShowGrid(true); - courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); + courseTBL->setRowCount(0); + courseTBL->setColumnCount(COURSE_FIELDS); + QStringList mz; + mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); + courseTBL->setHorizontalHeaderLabels(mz); + courseTBL->verticalHeader()->setVisible(false); + courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); + courseTBL->setShowGrid(true); + courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); - /* + /* * */ - graph = new gradegraph(NULL,gp); + graph = new gradegraph(NULL,gp); } coursesTableManager::~coursesTableManager() { - courseTBL = NULL; - delete gp; - gp = NULL; + courseTBL = NULL; + delete gp; + gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: *gp->getCourses()) { - if (us->getInfluenceCourseOnly()) + if (us->getInfluenceCourseOnly()) { - if (isCourseInfluence(c)) - addRow(c); - } - else + if (isCourseInfluence(c)) addRow(c); + } + else + addRow(c); } } /** @@ -53,7 +53,7 @@ void coursesTableManager::insertJceCoursesIntoTable() */ void coursesTableManager::setCoursesList(QString &html) { - gp = new GradePage(html); + gp = new GradePage(html); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it @@ -65,81 +65,81 @@ void coursesTableManager::setCoursesList(QString &html) bool coursesTableManager::changes(QString change, int row, int col) { - bool isNumFlag = true; - if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) - return true; + bool isNumFlag = true; + if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) + return true; - int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); - for (gradeCourse *c: *gp->getCourses()) + int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); + for (gradeCourse *c: *gp->getCourses()) { - if (c->getSerialNum() == serialCourse) + if (c->getSerialNum() == serialCourse) { - switch (col) + switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): - c->setCourseNumInList(change.toInt()); - break; + c->setCourseNumInList(change.toInt()); + break; case (gradeCourse::CourseScheme::YEAR): - c->setYear(change.toInt()); - break; + c->setYear(change.toInt()); + break; case (gradeCourse::CourseScheme::SEMESTER): - c->setSemester(change.toInt()); - break; + c->setSemester(change.toInt()); + break; case (gradeCourse::CourseScheme::NAME): - c->setName(change); - break; + c->setName(change); + break; case (gradeCourse::CourseScheme::TYPE): - c->setType(change); - break; + c->setType(change); + break; case (gradeCourse::CourseScheme::POINTS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); - } + } else - c->setPoints(change.toDouble()); + c->setPoints(change.toDouble()); break; - } + } case (gradeCourse::CourseScheme::HOURS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getHours())); - } + } else - c->setHours(change.toDouble()); + c->setHours(change.toDouble()); break; - } + } case (gradeCourse::CourseScheme::GRADE): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } + } else - { + { if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) - c->setGrade(change.toDouble()); + c->setGrade(change.toDouble()); else - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } break; - } + } case (gradeCourse::CourseScheme::ADDITION): - c->setAdditions(change); - break; + c->setAdditions(change); + break; } - break; + break; } } - return isNumFlag; + return isNumFlag; } /** @@ -148,91 +148,110 @@ bool coursesTableManager::changes(QString change, int row, int col) */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { - int i=1,j=1; + int i=1,j=1; - j = 0; - QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; - const gradeCourse * c; - if (courseToAdd != NULL) + j = 0; + QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; + const gradeCourse * c; + if (courseToAdd != NULL) { - c = courseToAdd; - if (!isCourseAlreadyInserted(c->getSerialNum())) + c = courseToAdd; + if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount() + 1); - i = courseTBL->rowCount()-1; + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; - number = new QTableWidgetItem(QString::number(c->getCourseNumInList())); - number->setFlags(number->flags() & ~Qt::ItemIsEditable); - year = new QTableWidgetItem(QString::number(c->getYear())); - year->setFlags(year->flags() & ~Qt::ItemIsEditable); - semester = new QTableWidgetItem(QString::number(c->getSemester())); - semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); - serial = new QTableWidgetItem(QString::number(c->getSerialNum())); - serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); - points = new QTableWidgetItem(QString::number(c->getPoints())); - points->setFlags(points->flags() & ~Qt::ItemIsEditable); - hours = new QTableWidgetItem(QString::number(c->getHours())); - hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); - grade = new QTableWidgetItem(QString::number(c->getGrade())); - name = new QTableWidgetItem(c->getName()); - name->setFlags(name->flags() & ~Qt::ItemIsEditable); - type = new QTableWidgetItem(c->getType()); - type->setFlags(type->flags() & ~Qt::ItemIsEditable); - addition = new QTableWidgetItem(c->getAddidtions()); - courseTBL->setItem(i,j++,number); - courseTBL->setItem(i,j++,year); - courseTBL->setItem(i,j++,semester); - courseTBL->setItem(i,j++,serial); - courseTBL->setItem(i,j++,name); - courseTBL->setItem(i,j++,type); - courseTBL->setItem(i,j++,points); - courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j++,grade); - courseTBL->setItem(i,j,addition); + number = new QTableWidgetItem(); + number->setData(Qt::EditRole, c->getCourseNumInList()); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(); + year->setData(Qt::EditRole,c->getYear()); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); + + semester = new QTableWidgetItem(); + semester->setData(Qt::EditRole,c->getSemester()); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); + + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole,c->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + + name = new QTableWidgetItem(); + name->setData(Qt::EditRole,c->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); + + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, c->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); + + points = new QTableWidgetItem(); + points->setData(Qt::EditRole, c->getPoints()); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); + + hours = new QTableWidgetItem(); + hours->setData(Qt::EditRole, c->getHours()); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); + + grade = new QTableWidgetItem(); + grade->setData(Qt::EditRole,c->getGrade()); + + addition = new QTableWidgetItem(); + addition->setData(Qt::EditRole,c->getAddidtions()); + + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); + courseTBL->setItem(i,j++,serial); + courseTBL->setItem(i,j++,name); + courseTBL->setItem(i,j++,type); + courseTBL->setItem(i,j++,points); + courseTBL->setItem(i,j++,hours); + courseTBL->setItem(i,j++,grade); + courseTBL->setItem(i,j,addition); } } - else + else { - qCritical() << Q_FUNC_INFO << "no course to load!"; + qCritical() << Q_FUNC_INFO << "no course to load!"; } - courseTBL->resizeColumnsToContents(); + courseTBL->resizeColumnsToContents(); } double coursesTableManager::getAvg() { - if (this->gp != NULL) - return gp->getAvg(); - return 0; + if (this->gp != NULL) + return gp->getAvg(); + return 0; } void coursesTableManager::showGraph() { - if (gp != NULL) - this->graph->show(); + if (gp != NULL) + this->graph->show(); } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { - if (ignoreCourseStatus) + if (ignoreCourseStatus) { - int i = 0; - while (i < courseTBL->rowCount()) + int i = 0; + while (i < courseTBL->rowCount()) { - if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) - courseTBL->removeRow(i--); - i++; + if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) + courseTBL->removeRow(i--); + i++; } } - else + else { - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: *gp->getCourses()) { - if (!(isCourseAlreadyInserted(c->getSerialNum()))) - if (c->getPoints() == 0) - addRow(c); + if (!(isCourseAlreadyInserted(c->getSerialNum()))) + if (c->getPoints() == 0) + addRow(c); } } @@ -240,49 +259,49 @@ void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) void coursesTableManager::clearTable() { - if (courseTBL->rowCount() == 0) - return; + if (courseTBL->rowCount() == 0) + return; - int i = 0; //starting point - while (courseTBL->rowCount() > i) + int i = 0; //starting point + while (courseTBL->rowCount() > i) { - gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); - courseTBL->removeRow(i); + gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); + courseTBL->removeRow(i); } - gp = NULL; - courseTBL->repaint(); + gp = NULL; + courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { - QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); - for (gradeCourse *c: *gp->getCourses()) + QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); + for (gradeCourse *c: *gp->getCourses()) { - if (c->getSerialNum() == courseSerial.toDouble()) - return c; + if (c->getSerialNum() == courseSerial.toDouble()) + return c; } - return NULL; + return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { - int i; - for (i = courseTBL->rowCount(); i >= 0; --i) + int i; + for (i = courseTBL->rowCount(); i >= 0; --i) { - if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) + if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { - QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); - if (QString::number(courseID) == courseSerial) - return true; + QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); + if (QString::number(courseID) == courseSerial) + return true; } } - return false; + return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { - if (courseToCheck->getPoints() > 0) - return true; - return false; + if (courseToCheck->getPoints() > 0) + return true; + return false; } From a87c5abb2cdb636ee975fd51574e4f519fce7a55 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Tue, 7 Oct 2014 17:26:11 +0300 Subject: [PATCH 09/58] add graph. fixes more isses --- main/CourseTab/coursestablemanager.cpp | 19 +- main/mainscreen.cpp | 10 + src/jceData/Grades/gradePage.cpp | 253 +++++++++++++++--------- src/jceData/Grades/gradePage.h | 29 +-- src/jceData/Grades/graph/gradegraph.cpp | 144 +++++++++++++- src/jceData/Grades/graph/gradegraph.h | 4 + src/jceData/Grades/graph/gradegraph.ui | 17 +- 7 files changed, 359 insertions(+), 117 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index ce215a7..de8e6dc 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -53,6 +53,8 @@ void coursesTableManager::insertJceCoursesIntoTable() */ void coursesTableManager::setCoursesList(QString &html) { + if (gp != NULL) + gp->~GradePage(); gp = new GradePage(html); } /** @@ -229,7 +231,9 @@ double coursesTableManager::getAvg() void coursesTableManager::showGraph() { if (gp != NULL) - this->graph->show(); + { + this->graph->showGraph(gp); + } } @@ -247,12 +251,13 @@ void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) } else { - for (gradeCourse *c: *gp->getCourses()) - { - if (!(isCourseAlreadyInserted(c->getSerialNum()))) - if (c->getPoints() == 0) - addRow(c); - } + if (this->gp != NULL) + for (gradeCourse *c: *gp->getCourses()) + { + if (!(isCourseAlreadyInserted(c->getSerialNum()))) + if (c->getPoints() == 0) + addRow(c); + } } } diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 0eb638a..eb94e3d 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -172,6 +172,7 @@ void MainScreen::on_ratesButton_clicked() } QApplication::restoreOverrideCursor(); } + bool MainScreen::checkIfValidDates() { bool flag = false; @@ -188,29 +189,35 @@ bool MainScreen::checkIfValidDates() } return flag; } + void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) { qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; this->userLoginSetting->setInfluenceCourseOnly(checked); this->courseTableMgr->influnceCourseChanged(checked); } + void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { ui->spinBoxCoursesFromYear->setValue(arg1); } + void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { ui->spinBoxCoursesToYear->setValue(arg1); } + void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { ui->spinBoxCoursesFromSemester->setValue(arg1%4); } + void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { ui->spinBoxCoursesToSemester->setValue(arg1%4); } + void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) @@ -221,17 +228,20 @@ void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } + void MainScreen::on_clearTableButton_clicked() { qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); courseTableMgr->clearTable(); ui->avgLCD->display(courseTableMgr->getAvg()); } + void MainScreen::on_graphButton_clicked() { courseTableMgr->showGraph(); } + //EVENTS ON CALENDAR TAB void MainScreen::on_getCalendarBtn_clicked() { diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index 8e0c08d..456d19f 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -1,153 +1,226 @@ #include "gradePage.h" +static int maxYear = 0; +static int minYear = 9999; + GradePage::GradePage(QString html) : Page() { - courses = new std::list(); - tempHtml = getString(html); - coursesListInit(tempHtml); + courses = new std::list(); + tempHtml = getString(html); + coursesListInit(tempHtml); } GradePage::~GradePage() { - for(Course* c : *courses) - delete c; - delete courses; + for(Course* c : *courses) + delete c; + delete courses; } void GradePage::removeCourse(QString courseSerialID) { - for(gradeCourse* c : *courses) + for(gradeCourse* c : *courses) { - if (c->getSerialNum() == courseSerialID.toInt()) + if (c->getSerialNum() == courseSerialID.toInt()) { - courses->remove(c); - delete c; - return; + courses->remove(c); + delete c; + return; } } } void GradePage::coursesListInit(QString &linesTokinzedString) { - std::list stringHolder; - QString temp; - gradeCourse* cTemp = NULL; - char* tok; - char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); - tok = strtok(textToTok,"\n"); - while (tok != NULL) //putting every line in a string holder before parsing it + std::list stringHolder; + QString temp; + gradeCourse* cTemp = NULL; + char* tok; + char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); + tok = strtok(textToTok,"\n"); + while (tok != NULL) //putting every line in a string holder before parsing it { - temp = tok; - stringHolder.push_back(temp); - tok = strtok(NULL, "\n"); + temp = tok; + stringHolder.push_back(temp); + tok = strtok(NULL, "\n"); } - for (QString temp: stringHolder) + for (QString temp: stringHolder) { - cTemp = lineToCourse(temp); - if (cTemp != NULL) - courses->push_back(cTemp); + cTemp = lineToCourse(temp); + if (cTemp != NULL) + courses->push_back(cTemp); } } gradeCourse* GradePage::lineToCourse(QString line) { - gradeCourse *tempC = NULL; - QString templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions] - int serial,year,semester,courseNumInList; - double points,hours,grade; - QString name,type, additions; - QString tempS = ""; - int i = 0; - char* tok; - char* cLine = strdup(line.toStdString().c_str()); - tok = strtok(cLine, "\t"); - while(tok != NULL) + gradeCourse *tempC = NULL; + QString templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions] + int serial,year,semester,courseNumInList; + double points,hours,grade; + QString name,type, additions; + QString tempS = ""; + int i = 0; + char* tok; + char* cLine = strdup(line.toStdString().c_str()); + tok = strtok(cLine, "\t"); + while(tok != NULL) { - tempS = tok; + tempS = tok; - if (i == gradeCourse::CourseScheme::SERIAL) //we need to extract the serial manually + if (i == gradeCourse::CourseScheme::SERIAL) //we need to extract the serial manually { - tempS = ""; - char *tokTemp; - tokTemp = tok; - while (!(isdigit((int)*tokTemp))) //getting to serial number starting pointer - tokTemp++; + tempS = ""; + char *tokTemp; + tokTemp = tok; + while (!(isdigit((int)*tokTemp))) //getting to serial number starting pointer + tokTemp++; - while (isdigit((int)*tokTemp)) //serial number + while (isdigit((int)*tokTemp)) //serial number { - tempS += QString(*tokTemp); - tokTemp++; + tempS += QString(*tokTemp); + tokTemp++; } - templinearray[i] = tempS.trimmed(); - templinearray[i+1] = QString(tokTemp).trimmed(); - i +=2; //skipping on serial and course name + templinearray[i] = tempS.trimmed(); + templinearray[i+1] = QString(tokTemp).trimmed(); + i +=2; //skipping on serial and course name } - else + else { - templinearray[i] = tempS.trimmed(); - i++; + templinearray[i] = tempS.trimmed(); + i++; } - if (i == COURSE_FIELDS) - break; - tok=strtok(NULL, "\t"); + if (i == COURSE_FIELDS) + break; + tok=strtok(NULL, "\t"); } - if (templinearray[0] == "") //empty parsing + if (templinearray[0] == "") //empty parsing { - qCritical() << Q_FUNC_INFO << "empty parsing"; - return NULL; + qCritical() << Q_FUNC_INFO << "empty parsing"; + return NULL; } - year = templinearray[gradeCourse::CourseScheme::YEAR].toInt(); - semester = templinearray[gradeCourse::CourseScheme::SEMESTER].toInt(); - courseNumInList = templinearray[gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST].toInt(); - serial = templinearray[gradeCourse::CourseScheme::SERIAL].toInt(); + year = templinearray[gradeCourse::CourseScheme::YEAR].toInt(); + semester = templinearray[gradeCourse::CourseScheme::SEMESTER].toInt(); + courseNumInList = templinearray[gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST].toInt(); + serial = templinearray[gradeCourse::CourseScheme::SERIAL].toInt(); - name = templinearray[gradeCourse::CourseScheme::NAME]; - type = templinearray[gradeCourse::CourseScheme::TYPE]; + name = templinearray[gradeCourse::CourseScheme::NAME]; + type = templinearray[gradeCourse::CourseScheme::TYPE]; - points = templinearray[gradeCourse::CourseScheme::POINTS].toDouble(); - hours = templinearray[gradeCourse::CourseScheme::HOURS].toDouble(); + points = templinearray[gradeCourse::CourseScheme::POINTS].toDouble(); + hours = templinearray[gradeCourse::CourseScheme::HOURS].toDouble(); - if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE])) - grade = templinearray[gradeCourse::CourseScheme::GRADE].toDouble(); - else - grade = NO_GRADE_YET; + if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE])) + grade = templinearray[gradeCourse::CourseScheme::GRADE].toDouble(); + else + grade = NO_GRADE_YET; - additions = templinearray[gradeCourse::CourseScheme::ADDITION]; + additions = templinearray[gradeCourse::CourseScheme::ADDITION]; - tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); - return tempC; + if (year >= maxYear) + maxYear = year; + + if (year <= minYear) + minYear = year; + + tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); + return tempC; } //checking if one of the chars inside grade is not a number bool GradePage::isGradedYet(QString grade) { - if (strlen(grade.toStdString().c_str()) <= 1) + if (strlen(grade.toStdString().c_str()) <= 1) + return false; + + for (char c: grade.toStdString()) + { + if (c == '\0') + break; + if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9 return false; - for (char c: grade.toStdString()) - { - if (c == '\0') - break; - if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9 - return false; - } - return true; + return true; } +/** + * @brief GradePage::getAvg getting avg + * @return - gpa avg of all courses + */ double GradePage::getAvg() { - double avg = 0; - double points = 0; - for(gradeCourse* c : *courses) + double avg = 0; + double points = 0; + for (gradeCourse* c : *courses) { - if ((c->getGrade() != 0)) + if ((c->getGrade() != 0)) { - avg += c->getGrade() * c->getPoints(); - points += c->getPoints(); + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); } } - avg /= points; - return avg; + avg /= points; + return avg; +} +/** + * @brief GradePage::getAvg getting avg of given year + * @param year - year (yyyy) + * @return - gpa avg of given year + */ +double GradePage::getAvg(int year) +{ + double avg = 0; + double points = 0; + for (gradeCourse* c : *courses) + { + if ((c->getGrade() != 0) && (c->getYear() == year)) + { + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); + } + } + if (points != 0) + avg /= points; + else + avg=0; + return avg; +} +/** + * @brief GradePage::getAvg + * @param year - year (yyyy) + * @param semester - semeser (1-3) + * @return -gpa avg of given year in given semester + */ +double GradePage::getAvg(int year, int semester) +{ + double avg = 0; + double points = 0; + for (gradeCourse* c : *courses) + { + if ((c->getGrade() != 0) && (c->getYear() == year) && (c->getSemester() == semester)) + { + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); + } + } + if (points != 0) + avg /= points; + else + avg=0; + return avg; +} +/** + * @brief GradePage::getMinYearInList + * @return the minimal year inside courses list + */ +int GradePage::getMinYearInList() +{ + return minYear; +} + +int GradePage::getMaxYearInList() +{ + return maxYear; } diff --git a/src/jceData/Grades/gradePage.h b/src/jceData/Grades/gradePage.h index ea4ee28..677c0e5 100644 --- a/src/jceData/Grades/gradePage.h +++ b/src/jceData/Grades/gradePage.h @@ -15,25 +15,32 @@ class GradePage : public Page { - + public: - GradePage(QString html); - ~GradePage(); + GradePage(QString html); + ~GradePage(); - void removeCourse(QString courseSerialID); - double getAvg(); + void removeCourse(QString courseSerialID); + double getAvg(); + double getAvg(int year); + double getAvg(int year, int semester); - std::list* getCourses() { return courses; } + int getMinYearInList(); + int getMaxYearInList(); + + + std::list* getCourses() { return courses; } private: - void coursesListInit(QString &linesTokinzedString); - gradeCourse* lineToCourse(QString line); + void coursesListInit(QString &linesTokinzedString); + gradeCourse* lineToCourse(QString line); - bool isGradedYet(QString grade); + bool isGradedYet(QString grade); - std::list* courses; - QString tempHtml; + std::list* courses; + + QString tempHtml; }; diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index f581cd3..b0d114b 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -2,14 +2,148 @@ #include "ui_gradegraph.h" gradegraph::gradegraph(QWidget *parent, GradePage *gpPTR) : - QDialog(parent), - ui(new Ui::gradegraph) + QDialog(parent), + ui(new Ui::gradegraph) { - ui->setupUi(this); - this->gp = gpPTR; + ui->setupUi(this); + this->gp = gpPTR; + +} + +void gradegraph::showGraph(GradePage *gpPTR) +{ + this->gp = gpPTR; + setVisualization(); + setGraphsData(); + this->show(); } gradegraph::~gradegraph() { - delete ui; + delete ui; +} + +void gradegraph::setGraphsData() +{ + int minYearInList = gp->getMinYearInList(); //2012 + int maxYearInList = gp->getMaxYearInList()+1; //2016 + int xRangeForYear = (maxYearInList - minYearInList+2)*3; //6*3=18 + QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),sem(xRangeForYear); + + for (int yearCount=0,i=1; igetAvg(minYearInList+yearCount); + yearlyAvg[i] = lastAvg; + + // add the text label at the top: + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); + textLabel->position->setCoords(i, lastAvg+1.5); // place position at center/top of axis rect + textLabel->setText(QString::number(lastAvg,'g',4)); + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text + yearCount++; + + } + else + { + if (i+4 < xRangeForYear) //semesters + { + double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); + SemesterialAvg[i+4] = avg; + // add the text label at the top: + + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); + textLabel->position->setCoords(i+4, avg+0.5); // place position at center/top of axis rect + textLabel->setText(QString::number(avg,'g',4)); + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text + + + } + + yearlyAvg[i] = 0; + } + } + //yearly + ui->graphwidget->graph(0)->setData(sem,yearlyAvg); + //yearly + ui->graphwidget->graph(1)->setData(sem,SemesterialAvg); +} + +/** + * @brief gradegraph::setvisualization set graph borders text, range and looking + */ +void gradegraph::setVisualization() +{ + ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box + + ui->graphwidget->addGraph(); //yearly and semesterial graphs + ui->graphwidget->addGraph(); + + ui->graphwidget->graph(0)->setName(tr("Yearly Average")); + ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsLine); + ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); + + ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); + ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsLine); + ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); + + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; + + QVector xStrings(0); + for (int year=minYearInList,i = 0; i < xRangeForYear-1; ++i) + { + //set year x axe label to be yyyy A B C yyyy+1 A B C yyyy+2.... + int semesterChar = i%4; + QString tempString; + switch (semesterChar) + { + case 1: + tempString = tr("A"); + xStrings << tempString; + break; + case 2: + tempString = tr("B"); + xStrings << tempString; + break; + case 3: + tempString = tr("C"); + xStrings << tempString; + break; + case 0: + tempString = QString::number(year); + xStrings << tempString; + year++; + break; + + } + } + ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); + ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); + ui->graphwidget->yAxis->setRange(50,100); + ui->graphwidget->yAxis->setTickStep(2); + ui->graphwidget->yAxis->setAutoSubTicks(false); + ui->graphwidget->yAxis->setAutoTickStep(false); + ui->graphwidget->yAxis->setSubTickCount(5); + + + ui->graphwidget->xAxis->setLabel(tr("Years")); + ui->graphwidget->xAxis->setAutoTickLabels(false); + ui->graphwidget->xAxis->setTickVectorLabels(xStrings); + ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); + ui->graphwidget->xAxis->setAutoTickStep(false); + ui->graphwidget->xAxis->setTickStep(1); + ui->graphwidget->xAxis->setAutoSubTicks(false); + ui->graphwidget->xAxis->setSubTickCount(1); + ui->graphwidget->xAxis->setRange(1,xRangeForYear); + + ui->graphwidget->legend->setVisible(true); //show graph name on top right } diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index 649c40e..97195ad 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -15,11 +15,15 @@ class gradegraph : public QDialog public: gradegraph(QWidget *parent = 0, GradePage *gpPTR = 0); + void showGraph(GradePage *gpPTR); ~gradegraph(); private: GradePage *gp; + + void setVisualization(); + void setGraphsData(); Ui::gradegraph *ui; }; diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 75cf324..99691cc 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -6,14 +6,14 @@ 0 0 - 597 - 461 + 624 + 527 Dialog - + @@ -34,7 +34,16 @@ - + + + + 0 + 0 + + + + + From 791bdcc5af2249673e2255ee5551f6b508869068 Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Tue, 7 Oct 2014 23:58:09 +0300 Subject: [PATCH 10/58] Tweaked the progress bar and added debuging msgs ProgressBar will be visible only if the value is NOT 0 or NOT 100. that means, if there is no progress going on, there is no progress bar visible. --- main/CourseTab/coursestablemanager.cpp | 1 + main/mainscreen.cpp | 16 ++++++++ main/mainscreen.h | 2 + main/mainscreen.ui | 2 +- src/jceData/Calendar/calendarDialog.cpp | 2 +- src/jceData/Grades/graph/gradegraph.cpp | 6 +++ src/jceData/Grades/graph/gradegraph.h | 3 ++ src/jceData/Grades/graph/gradegraph.ui | 51 +++++++++++++++++++------ 8 files changed, 69 insertions(+), 14 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index de8e6dc..265a359 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -232,6 +232,7 @@ void coursesTableManager::showGraph() { if (gp != NULL) { + qDebug() << "Graph Dialog Opened. gp != NULL"; this->graph->showGraph(gp); } } diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index eb94e3d..e32ddc3 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -49,6 +49,9 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc ui->statusBar->repaint(); qDebug() << Q_FUNC_INFO << "Ready."; + //set the progress bar to be invisible (It will show only if value !=0 or !=100) + ui->progressBar->setVisible(false); + } MainScreen::~MainScreen() { @@ -238,6 +241,7 @@ void MainScreen::on_clearTableButton_clicked() void MainScreen::on_graphButton_clicked() { + qDebug() << "Show Graph button clicked"; courseTableMgr->showGraph(); } @@ -388,3 +392,15 @@ void MainScreen::on_labelMadeBy_linkActivated(const QString &link) } + +/** + * @brief Every time the value changes this method will be called + * @param value = the value of the progress Bar + */ +void MainScreen::on_progressBar_valueChanged(int value) +{ + if(value == 0 || value == 100) + ui->progressBar->setVisible(false); + else + ui->progressBar->setVisible(true); +} diff --git a/main/mainscreen.h b/main/mainscreen.h index b04691c..62da771 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -69,6 +69,8 @@ private slots: void on_graphButton_clicked(); + void on_progressBar_valueChanged(int value); + private: void checkLocale(); diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 52c6a1a..4f6482c 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -690,7 +690,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 21 + 23 diff --git a/src/jceData/Calendar/calendarDialog.cpp b/src/jceData/Calendar/calendarDialog.cpp index f3bd71c..7a29c13 100644 --- a/src/jceData/Calendar/calendarDialog.cpp +++ b/src/jceData/Calendar/calendarDialog.cpp @@ -1,5 +1,5 @@ #include "calendarDialog.h" -#include "ui_calendardialog.h" +#include "ui_calendarDialog.h" CalendarDialog::CalendarDialog(QWidget *parent) : diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index b0d114b..ad37b57 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -147,3 +147,9 @@ void gradegraph::setVisualization() ui->graphwidget->legend->setVisible(true); //show graph name on top right } + +void gradegraph::on_pushButton_clicked() +{ + qDebug() << "Closed Graph Dialog"; + this->done(0); +} diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index 97195ad..3cde01c 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -18,6 +18,9 @@ public: void showGraph(GradePage *gpPTR); ~gradegraph(); +private slots: + void on_pushButton_clicked(); + private: GradePage *gp; diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 99691cc..78fab3f 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -7,13 +7,13 @@ 0 0 624 - 527 + 531 Dialog - + @@ -34,16 +34,43 @@ - - - - 0 - 0 - - - - - + + + + + + 0 + 0 + + + + + + + + + + + Qt::Horizontal + + + + 88 + 20 + + + + + + + + Close + + + + + + From f3e65503b8c48a3509141efb363cb8d4686e4027 Mon Sep 17 00:00:00 2001 From: liranbg Date: Wed, 8 Oct 2014 00:16:27 +0300 Subject: [PATCH 11/58] adding exam schedule --- jceGrade.pro | 6 +- main/CourseTab/coursestablemanager.cpp | 355 ++++++++++++------------ src/jceData/Calendar/calendarCourse.cpp | 63 +++-- src/jceData/Calendar/calendarCourse.h | 11 +- src/jceData/Calendar/calendarExam.cpp | 5 + src/jceData/Calendar/calendarExam.h | 12 + src/jceData/Calendar/calendarPage.h | 1 - src/jceData/Grades/graph/gradegraph.cpp | 15 +- src/jceData/Grades/graph/gradegraph.h | 2 +- 9 files changed, 250 insertions(+), 220 deletions(-) create mode 100644 src/jceData/Calendar/calendarExam.cpp create mode 100644 src/jceData/Calendar/calendarExam.h diff --git a/jceGrade.pro b/jceGrade.pro index 8839a65..280d5b2 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -53,7 +53,8 @@ HEADERS += \ src/jceData/Calendar/calendarDialog.h \ src/appDatabase/jce_logger.h \ src/jceData/Grades/graph/qcustomplot.h \ - src/jceData/Grades/graph/gradegraph.h + src/jceData/Grades/graph/gradegraph.h \ + src/jceData/Calendar/calendarExam.h SOURCES += \ main/CalendarTab/CalendarManager.cpp \ @@ -76,4 +77,5 @@ SOURCES += \ src/jceData/Calendar/calendarDialog.cpp \ src/appDatabase/jce_logger.cpp \ src/jceData/Grades/graph/qcustomplot.cpp \ - src/jceData/Grades/graph/gradegraph.cpp + src/jceData/Grades/graph/gradegraph.cpp \ + src/jceData/Calendar/calendarExam.cpp diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index de8e6dc..f0dff3a 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -2,49 +2,46 @@ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { - this->gp = NULL; - this->us = usrPtr; - this->courseTBL = ptr; + this->gp = NULL; + this->us = usrPtr; + this->courseTBL = ptr; - /* - * Initilizing Table - */ - courseTBL->setRowCount(0); - courseTBL->setColumnCount(COURSE_FIELDS); - QStringList mz; - mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); - courseTBL->setHorizontalHeaderLabels(mz); - courseTBL->verticalHeader()->setVisible(false); - courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); - courseTBL->setShowGrid(true); - courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); + /* + * Initilizing Table + */ + courseTBL->setRowCount(0); + courseTBL->setColumnCount(COURSE_FIELDS); + QStringList mz; + mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); + courseTBL->setHorizontalHeaderLabels(mz); + courseTBL->verticalHeader()->setVisible(false); + courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); + courseTBL->setShowGrid(true); + courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); - /* - * - */ - graph = new gradegraph(NULL,gp); + graph = new gradegraph(NULL); } coursesTableManager::~coursesTableManager() { - courseTBL = NULL; - delete gp; - gp = NULL; + courseTBL = NULL; + delete gp; + gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: *gp->getCourses()) { - if (us->getInfluenceCourseOnly()) + if (us->getInfluenceCourseOnly()) { - if (isCourseInfluence(c)) - addRow(c); + if (isCourseInfluence(c)) + addRow(c); } - else - addRow(c); + else + addRow(c); } } /** @@ -53,9 +50,9 @@ void coursesTableManager::insertJceCoursesIntoTable() */ void coursesTableManager::setCoursesList(QString &html) { - if (gp != NULL) - gp->~GradePage(); - gp = new GradePage(html); + if (gp != NULL) + gp->~GradePage(); + gp = new GradePage(html); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it @@ -67,81 +64,81 @@ void coursesTableManager::setCoursesList(QString &html) bool coursesTableManager::changes(QString change, int row, int col) { - bool isNumFlag = true; - if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) - return true; + bool isNumFlag = true; + if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) + return true; - int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); - for (gradeCourse *c: *gp->getCourses()) + int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); + for (gradeCourse *c: *gp->getCourses()) { - if (c->getSerialNum() == serialCourse) + if (c->getSerialNum() == serialCourse) { - switch (col) + switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): - c->setCourseNumInList(change.toInt()); - break; + c->setCourseNumInList(change.toInt()); + break; case (gradeCourse::CourseScheme::YEAR): - c->setYear(change.toInt()); - break; + c->setYear(change.toInt()); + break; case (gradeCourse::CourseScheme::SEMESTER): - c->setSemester(change.toInt()); - break; + c->setSemester(change.toInt()); + break; case (gradeCourse::CourseScheme::NAME): - c->setName(change); - break; + c->setName(change); + break; case (gradeCourse::CourseScheme::TYPE): - c->setType(change); - break; + c->setType(change); + break; case (gradeCourse::CourseScheme::POINTS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); - } + } else - c->setPoints(change.toDouble()); + c->setPoints(change.toDouble()); break; - } - case (gradeCourse::CourseScheme::HOURS): - { - change.toDouble(&isNumFlag); - - if (!isNumFlag) - { - courseTBL->item(row,col)->setText(QString::number(c->getHours())); - } - else - c->setHours(change.toDouble()); - break; - } - case (gradeCourse::CourseScheme::GRADE): - { - change.toDouble(&isNumFlag); - - if (!isNumFlag) - { - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } - else - { - if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) - c->setGrade(change.toDouble()); - else - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } - break; - } - case (gradeCourse::CourseScheme::ADDITION): - c->setAdditions(change); - break; } - break; + case (gradeCourse::CourseScheme::HOURS): + { + change.toDouble(&isNumFlag); + + if (!isNumFlag) + { + courseTBL->item(row,col)->setText(QString::number(c->getHours())); + } + else + c->setHours(change.toDouble()); + break; + } + case (gradeCourse::CourseScheme::GRADE): + { + change.toDouble(&isNumFlag); + + if (!isNumFlag) + { + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } + else + { + if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) + c->setGrade(change.toDouble()); + else + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } + break; + } + case (gradeCourse::CourseScheme::ADDITION): + c->setAdditions(change); + break; + } + break; } } - return isNumFlag; + return isNumFlag; } /** @@ -150,163 +147,163 @@ bool coursesTableManager::changes(QString change, int row, int col) */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { - int i=1,j=1; + int i=1,j=1; - j = 0; - QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; - const gradeCourse * c; - if (courseToAdd != NULL) + j = 0; + QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; + const gradeCourse * c; + if (courseToAdd != NULL) { - c = courseToAdd; - if (!isCourseAlreadyInserted(c->getSerialNum())) + c = courseToAdd; + if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount() + 1); - i = courseTBL->rowCount()-1; + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; - number = new QTableWidgetItem(); - number->setData(Qt::EditRole, c->getCourseNumInList()); - number->setFlags(number->flags() & ~Qt::ItemIsEditable); + number = new QTableWidgetItem(); + number->setData(Qt::EditRole, c->getCourseNumInList()); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); - year = new QTableWidgetItem(); - year->setData(Qt::EditRole,c->getYear()); - year->setFlags(year->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(); + year->setData(Qt::EditRole,c->getYear()); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); - semester = new QTableWidgetItem(); - semester->setData(Qt::EditRole,c->getSemester()); - semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); + semester = new QTableWidgetItem(); + semester->setData(Qt::EditRole,c->getSemester()); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); - serial = new QTableWidgetItem(); - serial->setData(Qt::EditRole,c->getSerialNum()); - serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole,c->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); - name = new QTableWidgetItem(); - name->setData(Qt::EditRole,c->getName()); - name->setFlags(name->flags() & ~Qt::ItemIsEditable); + name = new QTableWidgetItem(); + name->setData(Qt::EditRole,c->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); - type = new QTableWidgetItem(); - type->setData(Qt::EditRole, c->getType()); - type->setFlags(type->flags() & ~Qt::ItemIsEditable); + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, c->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); - points = new QTableWidgetItem(); - points->setData(Qt::EditRole, c->getPoints()); - points->setFlags(points->flags() & ~Qt::ItemIsEditable); + points = new QTableWidgetItem(); + points->setData(Qt::EditRole, c->getPoints()); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); - hours = new QTableWidgetItem(); - hours->setData(Qt::EditRole, c->getHours()); - hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); + hours = new QTableWidgetItem(); + hours->setData(Qt::EditRole, c->getHours()); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); - grade = new QTableWidgetItem(); - grade->setData(Qt::EditRole,c->getGrade()); + grade = new QTableWidgetItem(); + grade->setData(Qt::EditRole,c->getGrade()); - addition = new QTableWidgetItem(); - addition->setData(Qt::EditRole,c->getAddidtions()); + addition = new QTableWidgetItem(); + addition->setData(Qt::EditRole,c->getAddidtions()); - courseTBL->setItem(i,j++,number); - courseTBL->setItem(i,j++,year); - courseTBL->setItem(i,j++,semester); - courseTBL->setItem(i,j++,serial); - courseTBL->setItem(i,j++,name); - courseTBL->setItem(i,j++,type); - courseTBL->setItem(i,j++,points); - courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j++,grade); - courseTBL->setItem(i,j,addition); + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); + courseTBL->setItem(i,j++,serial); + courseTBL->setItem(i,j++,name); + courseTBL->setItem(i,j++,type); + courseTBL->setItem(i,j++,points); + courseTBL->setItem(i,j++,hours); + courseTBL->setItem(i,j++,grade); + courseTBL->setItem(i,j,addition); } } - else + else { - qCritical() << Q_FUNC_INFO << "no course to load!"; + qCritical() << Q_FUNC_INFO << "no course to load!"; } - courseTBL->resizeColumnsToContents(); + courseTBL->resizeColumnsToContents(); } double coursesTableManager::getAvg() { - if (this->gp != NULL) - return gp->getAvg(); - return 0; + if (this->gp != NULL) + return gp->getAvg(); + return 0; } void coursesTableManager::showGraph() { - if (gp != NULL) + if (gp != NULL) { - this->graph->showGraph(gp); + this->graph->showGraph(gp); } } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { - if (ignoreCourseStatus) + if (ignoreCourseStatus) { - int i = 0; - while (i < courseTBL->rowCount()) + int i = 0; + while (i < courseTBL->rowCount()) { - if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) - courseTBL->removeRow(i--); - i++; + if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) + courseTBL->removeRow(i--); + i++; } } - else + else { - if (this->gp != NULL) - for (gradeCourse *c: *gp->getCourses()) - { - if (!(isCourseAlreadyInserted(c->getSerialNum()))) - if (c->getPoints() == 0) - addRow(c); - } + if (this->gp != NULL) + for (gradeCourse *c: *gp->getCourses()) + { + if (!(isCourseAlreadyInserted(c->getSerialNum()))) + if (c->getPoints() == 0) + addRow(c); + } } } void coursesTableManager::clearTable() { - if (courseTBL->rowCount() == 0) - return; + if (courseTBL->rowCount() == 0) + return; - int i = 0; //starting point - while (courseTBL->rowCount() > i) + int i = 0; //starting point + while (courseTBL->rowCount() > i) { - gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); - courseTBL->removeRow(i); + gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); + courseTBL->removeRow(i); } - gp = NULL; - courseTBL->repaint(); + gp = NULL; + courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { - QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); - for (gradeCourse *c: *gp->getCourses()) + QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); + for (gradeCourse *c: *gp->getCourses()) { - if (c->getSerialNum() == courseSerial.toDouble()) - return c; + if (c->getSerialNum() == courseSerial.toDouble()) + return c; } - return NULL; + return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { - int i; - for (i = courseTBL->rowCount(); i >= 0; --i) + int i; + for (i = courseTBL->rowCount(); i >= 0; --i) { - if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) + if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { - QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); - if (QString::number(courseID) == courseSerial) - return true; + QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); + if (QString::number(courseID) == courseSerial) + return true; } } - return false; + return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { - if (courseToCheck->getPoints() > 0) - return true; - return false; + if (courseToCheck->getPoints() > 0) + return true; + return false; } diff --git a/src/jceData/Calendar/calendarCourse.cpp b/src/jceData/Calendar/calendarCourse.cpp index 5fec893..8b41f33 100644 --- a/src/jceData/Calendar/calendarCourse.cpp +++ b/src/jceData/Calendar/calendarCourse.cpp @@ -2,48 +2,55 @@ calendarCourse::calendarCourse(int serial, QString name, QString type, QString lecturer, double points, double semesterHours, QString dayAndHour, - QString room) : Course(serial,name, type,points) + QString room, calendarCourse::CourseCalendarType type) : Course(serial,name, type,points) { this->lecturer = lecturer; this->semesterHours = semesterHours; this->room = room; - setDayAndHour(dayAndHour); + setDayAndHour(dayAndHour.type); } /** * @brief calendarCourse::setDayAndHour * given a string of time and day - parsing it into day, hour it begins and hour it ends seperated * @param parse - */ -void calendarCourse::setDayAndHour(QString parse) +void calendarCourse::setDayAndHour(QString parse, calendarCourse::CourseCalendarType type) { - int ctr = 0; - QString temp = ""; - QTime timetemp; - char *tok; - char* textToTok = strdup(parse.toStdString().c_str()); - tok = strtok(textToTok, " -"); - while(tok != NULL) + if (type == calendarCourse::CourseCalendarType::CoursesSchedule) { - temp = tok; - switch (ctr) + int ctr = 0; + QString temp = ""; + QTime timetemp; + char *tok; + char* textToTok = strdup(parse.toStdString().c_str()); + tok = strtok(textToTok, " -"); + while(tok != NULL) { - case 0: //day - setDay(temp); - break; - case 1: //hour it begins - timetemp = QTime::fromString(temp,"hh:mm"); - setHourBegin(timetemp.hour()); - setMinutesBegin(timetemp.minute()); - break; - case 2: //hour it ends - timetemp = QTime::fromString(temp,"hh:mm"); - setHourEnd(timetemp.hour()); - setMinutesEnd(timetemp.minute()); - break; - } + temp = tok; + switch (ctr) + { + case 0: //day + setDay(temp); + break; + case 1: //hour it begins + timetemp = QTime::fromString(temp,"hh:mm"); + setHourBegin(timetemp.hour()); + setMinutesBegin(timetemp.minute()); + break; + case 2: //hour it ends + timetemp = QTime::fromString(temp,"hh:mm"); + setHourEnd(timetemp.hour()); + setMinutesEnd(timetemp.minute()); + break; + } + + ctr++; + tok = strtok(NULL, " -"); + } + } + if (type == calendarCourse::CourseCalendarType::ExamSchedule) + { - ctr++; - tok = strtok(NULL, " -"); } } diff --git a/src/jceData/Calendar/calendarCourse.h b/src/jceData/Calendar/calendarCourse.h index 9659d69..e30838f 100644 --- a/src/jceData/Calendar/calendarCourse.h +++ b/src/jceData/Calendar/calendarCourse.h @@ -9,6 +9,12 @@ class calendarCourse : public Course { public: + enum CourseCalendarType + { + ExamSchedule, + CoursesSchedule + }; + enum CourseScheme { SERIAL, @@ -21,7 +27,8 @@ public: ROOM }; calendarCourse(int serial, QString name, QString type, QString lecturer, - double points, double semesterHours, QString dayAndHour, QString room); + double points, double semesterHours, QString dayAndHour, + QString room, calendarCourse::CourseCalendarType type = calendarCourse::CourseCalendarType::CoursesSchedule); ~calendarCourse(){} int getDay() const; @@ -47,7 +54,7 @@ public: private: - void setDayAndHour(QString parse); + void setDayAndHour(QString parse, CourseCalendarType type); QString lecturer; double semesterHours; diff --git a/src/jceData/Calendar/calendarExam.cpp b/src/jceData/Calendar/calendarExam.cpp new file mode 100644 index 0000000..dfbf567 --- /dev/null +++ b/src/jceData/Calendar/calendarExam.cpp @@ -0,0 +1,5 @@ +#include "calendarExam.h" + +calendarExam::calendarExam() +{ +} diff --git a/src/jceData/Calendar/calendarExam.h b/src/jceData/Calendar/calendarExam.h new file mode 100644 index 0000000..9a8640d --- /dev/null +++ b/src/jceData/Calendar/calendarExam.h @@ -0,0 +1,12 @@ +#ifndef CALENDAREXAM_H +#define CALENDAREXAM_H + +#include "../page.h" + +class calendarExam : public Page +{ +public: + calendarExam(); +}; + +#endif // CALENDAREXAM_H diff --git a/src/jceData/Calendar/calendarPage.h b/src/jceData/Calendar/calendarPage.h index 75de858..d4935bd 100644 --- a/src/jceData/Calendar/calendarPage.h +++ b/src/jceData/Calendar/calendarPage.h @@ -28,7 +28,6 @@ private: QString tempHtml; std::list* courses; - }; #endif // CALENDARPAGE_H diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index b0d114b..59ec562 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -1,12 +1,12 @@ #include "gradegraph.h" #include "ui_gradegraph.h" -gradegraph::gradegraph(QWidget *parent, GradePage *gpPTR) : +gradegraph::gradegraph(QWidget *parent) : QDialog(parent), ui(new Ui::gradegraph) { ui->setupUi(this); - this->gp = gpPTR; + this->gp = NULL; } @@ -16,6 +16,7 @@ void gradegraph::showGraph(GradePage *gpPTR) setVisualization(); setGraphsData(); this->show(); + } gradegraph::~gradegraph() @@ -25,12 +26,12 @@ gradegraph::~gradegraph() void gradegraph::setGraphsData() { - int minYearInList = gp->getMinYearInList(); //2012 - int maxYearInList = gp->getMaxYearInList()+1; //2016 - int xRangeForYear = (maxYearInList - minYearInList+2)*3; //6*3=18 + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),sem(xRangeForYear); - for (int yearCount=0,i=1; igraphwidget->xAxis->setLabel(tr("Years")); ui->graphwidget->xAxis->setAutoTickLabels(false); - ui->graphwidget->xAxis->setTickVectorLabels(xStrings); ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); ui->graphwidget->xAxis->setAutoTickStep(false); ui->graphwidget->xAxis->setTickStep(1); ui->graphwidget->xAxis->setAutoSubTicks(false); ui->graphwidget->xAxis->setSubTickCount(1); + ui->graphwidget->xAxis->setTickVectorLabels(xStrings); ui->graphwidget->xAxis->setRange(1,xRangeForYear); ui->graphwidget->legend->setVisible(true); //show graph name on top right diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index 97195ad..e9e6cd0 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -14,7 +14,7 @@ class gradegraph : public QDialog Q_OBJECT public: - gradegraph(QWidget *parent = 0, GradePage *gpPTR = 0); + gradegraph(QWidget *parent = 0); void showGraph(GradePage *gpPTR); ~gradegraph(); From 1857c66ff17cb1ae443495136223a29db8f98c22 Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Wed, 8 Oct 2014 00:44:39 +0300 Subject: [PATCH 12/58] added feature #26 For now there are 2 colors. red - fail or really low yellow - you might want to try again :) --- main/CourseTab/coursestablemanager.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index 265a359..1f34ee2 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -209,7 +209,24 @@ void coursesTableManager::addRow(const gradeCourse *courseToAdd) courseTBL->setItem(i,j++,type); courseTBL->setItem(i,j++,points); courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j++,grade); + courseTBL->setItem(i,j,grade); + if(c->getGrade() < 55 && c->getGrade() != 0) + { + courseTBL->item(i, j)->setBackground(Qt::darkRed); + courseTBL->item(i,j)->setTextColor(Qt::white); + } + else if(55 <= c->getGrade() && c->getGrade() < 70 ) + { + courseTBL->item(i, j)->setBackground(Qt::darkYellow); + courseTBL->item(i,j)->setTextColor(Qt::white); + } +// else if(70 < c->getGrade() && c->getGrade() <= 80 ) +// courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! +// else if(c->getGrade() > 80) +// courseTBL->item(i, j)->setBackground(Qt::green); + + j++; + courseTBL->setItem(i,j,addition); } From c17c34b63b98760cca50ce8ce5f3856998227a4d Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Wed, 8 Oct 2014 00:51:09 +0300 Subject: [PATCH 13/58] added function names to qDebug from 2 commits ago --- main/CourseTab/coursestablemanager.cpp | 4 ++-- src/jceData/Grades/graph/gradegraph.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index 1f34ee2..cbc24f7 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -233,7 +233,7 @@ void coursesTableManager::addRow(const gradeCourse *courseToAdd) } else { - qCritical() << Q_FUNC_INFO << "no course to load!"; + qCritical() << Q_FUNC_INFO << " no course to load!"; } courseTBL->resizeColumnsToContents(); @@ -249,7 +249,7 @@ void coursesTableManager::showGraph() { if (gp != NULL) { - qDebug() << "Graph Dialog Opened. gp != NULL"; + qDebug() << Q_FUNC_INFO << " Graph Dialog Opened. gp != NULL"; this->graph->showGraph(gp); } } diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index ad37b57..1963b19 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -150,6 +150,6 @@ void gradegraph::setVisualization() void gradegraph::on_pushButton_clicked() { - qDebug() << "Closed Graph Dialog"; + qDebug() << Q_FUNC_INFO << " Closed Graph Dialog"; this->done(0); } From 6d623b78006f1661702395646681255452e38a61 Mon Sep 17 00:00:00 2001 From: liranbg Date: Wed, 8 Oct 2014 07:14:50 +0300 Subject: [PATCH 14/58] added #27. changed directories (overloaded), added some checkings. --- jceGrade.pro | 30 +++-- main/CalendarTab/CalendarManager.cpp | 16 ++- main/CalendarTab/CalendarManager.h | 20 ++- main/LoginTab/loginhandler.cpp | 8 ++ main/LoginTab/loginhandler.h | 1 + main/mainscreen.cpp | 36 +++++- main/mainscreen.h | 2 + main/mainscreen.ui | 11 +- src/jceData/CSV/csv_exporter.h | 4 +- src/jceData/Calendar/Exams/calendarExam.cpp | 116 ++++++++++++++++++ src/jceData/Calendar/Exams/calendarExam.h | 34 +++++ .../Calendar/Exams/calendarExamCourse.cpp | 100 +++++++++++++++ .../Calendar/Exams/calendarExamCourse.h | 70 +++++++++++ src/jceData/Calendar/Exams/examDialog.cpp | 74 +++++++++++ src/jceData/Calendar/Exams/examDialog.h | 27 ++++ src/jceData/Calendar/Exams/examDialog.ui | 86 +++++++++++++ src/jceData/Calendar/calendarExam.cpp | 5 - src/jceData/Calendar/calendarExam.h | 12 -- .../{ => coursesSchedule}/calendarDialog.cpp | 0 .../{ => coursesSchedule}/calendarDialog.h | 0 .../{ => coursesSchedule}/calendarDialog.ui | 0 .../{ => coursesSchedule}/calendarPage.cpp | 19 ++- .../{ => coursesSchedule}/calendarPage.h | 9 +- .../calendarPageCourse.cpp} | 46 +++---- .../calendarPageCourse.h} | 19 ++- .../calendarSchedule.cpp | 4 +- .../{ => coursesSchedule}/calendarSchedule.h | 2 +- src/jceData/Grades/gradeCourse.cpp | 13 +- src/jceData/Grades/gradeCourse.h | 6 +- src/jceData/Grades/graph/gradegraph.cpp | 1 + src/jceData/course.h | 6 +- src/jceSettings/jceLoginHtmlScripts.h | 11 ++ src/jceSettings/jcelogin.cpp | 14 +++ src/jceSettings/jcelogin.h | 1 + 34 files changed, 697 insertions(+), 106 deletions(-) create mode 100644 src/jceData/Calendar/Exams/calendarExam.cpp create mode 100644 src/jceData/Calendar/Exams/calendarExam.h create mode 100644 src/jceData/Calendar/Exams/calendarExamCourse.cpp create mode 100644 src/jceData/Calendar/Exams/calendarExamCourse.h create mode 100644 src/jceData/Calendar/Exams/examDialog.cpp create mode 100644 src/jceData/Calendar/Exams/examDialog.h create mode 100644 src/jceData/Calendar/Exams/examDialog.ui delete mode 100644 src/jceData/Calendar/calendarExam.cpp delete mode 100644 src/jceData/Calendar/calendarExam.h rename src/jceData/Calendar/{ => coursesSchedule}/calendarDialog.cpp (100%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarDialog.h (100%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarDialog.ui (100%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarPage.cpp (83%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarPage.h (76%) rename src/jceData/Calendar/{calendarCourse.cpp => coursesSchedule/calendarPageCourse.cpp} (68%) rename src/jceData/Calendar/{calendarCourse.h => coursesSchedule/calendarPageCourse.h} (75%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarSchedule.cpp (93%) rename src/jceData/Calendar/{ => coursesSchedule}/calendarSchedule.h (87%) diff --git a/jceGrade.pro b/jceGrade.pro index 280d5b2..4ba14b3 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -25,8 +25,9 @@ TRANSLATIONS = jce_en.ts \ FORMS += \ main/mainscreen.ui \ - src/jceData/Calendar/calendarDialog.ui \ - src/jceData/Grades/graph/gradegraph.ui + src/jceData/Grades/graph/gradegraph.ui \ + src/jceData/Calendar/Exams/examDialog.ui \ + src/jceData/Calendar/coursesSchedule/calendarDialog.ui RESOURCES += \ resources/connectionstatus.qrc @@ -38,7 +39,6 @@ HEADERS += \ main/mainscreen.h \ src/appDatabase/savedata.h \ src/jceConnection/jcesslclient.h \ - src/jceData/Calendar/calendarPage.h \ src/jceData/Grades/gradeCourse.h \ src/jceData/Grades/gradePage.h \ src/jceData/course.h \ @@ -46,15 +46,19 @@ HEADERS += \ src/jceSettings/jcelogin.h \ src/jceSettings/jceLoginHtmlScripts.h \ src/jceSettings/user.h \ - src/jceData/Calendar/calendarCourse.h \ - src/jceData/Calendar/calendarSchedule.h \ src/jceData/CSV/csv_exporter.h \ src/appDatabase/simplecrypt.h \ - src/jceData/Calendar/calendarDialog.h \ src/appDatabase/jce_logger.h \ src/jceData/Grades/graph/qcustomplot.h \ src/jceData/Grades/graph/gradegraph.h \ - src/jceData/Calendar/calendarExam.h + src/jceData/Calendar/calendarPageCourse.h \ + src/jceData/Calendar/Exams/examDialog.h \ + src/jceData/Calendar/Exams/calendarExam.h \ + src/jceData/Calendar/Exams/calendarExamCourse.h \ + src/jceData/Calendar/coursesSchedule/calendarDialog.h \ + src/jceData/Calendar/coursesSchedule/calendarPage.h \ + src/jceData/Calendar/coursesSchedule/calendarPageCourse.h \ + src/jceData/Calendar/coursesSchedule/calendarSchedule.h SOURCES += \ main/CalendarTab/CalendarManager.cpp \ @@ -64,18 +68,20 @@ SOURCES += \ main/mainscreen.cpp \ src/appDatabase/savedata.cpp \ src/jceConnection/jcesslclient.cpp \ - src/jceData/Calendar/calendarPage.cpp \ src/jceData/Grades/gradeCourse.cpp \ src/jceData/Grades/gradePage.cpp \ src/jceData/page.cpp \ src/jceSettings/jcelogin.cpp \ src/jceSettings/user.cpp \ - src/jceData/Calendar/calendarCourse.cpp \ - src/jceData/Calendar/calendarSchedule.cpp \ src/jceData/CSV/csv_exporter.cpp \ src/appDatabase/simplecrypt.cpp \ - src/jceData/Calendar/calendarDialog.cpp \ src/appDatabase/jce_logger.cpp \ src/jceData/Grades/graph/qcustomplot.cpp \ src/jceData/Grades/graph/gradegraph.cpp \ - src/jceData/Calendar/calendarExam.cpp + src/jceData/Calendar/Exams/examDialog.cpp \ + src/jceData/Calendar/Exams/calendarExam.cpp \ + src/jceData/Calendar/Exams/calendarExamCourse.cpp \ + src/jceData/Calendar/coursesSchedule/calendarDialog.cpp \ + src/jceData/Calendar/coursesSchedule/calendarPage.cpp \ + src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp \ + src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp diff --git a/main/CalendarTab/CalendarManager.cpp b/main/CalendarTab/CalendarManager.cpp index d6c5041..ac408a3 100644 --- a/main/CalendarTab/CalendarManager.cpp +++ b/main/CalendarTab/CalendarManager.cpp @@ -1,15 +1,25 @@ #include "CalendarManager.h" -CalendarManager::CalendarManager(QGridLayout *ptr) +CalendarManager::CalendarManager(QWidget *parent, QGridLayout *ptr) : QWidget(parent) { - caliSchedPtr = new calendarSchedule(); + caliSchedPtr = new calendarSchedule(this); + examSchePtr = new calendarExam(); ptr->addWidget(caliSchedPtr); - caliDialog = new CalendarDialog(); + caliDialog = new CalendarDialog(this); + examDialogPtr = new examDialog(this,examSchePtr); } void CalendarManager::setCalendar(QString html) { caliSchedPtr->setPage(html); + +} + +void CalendarManager::setExamsSchedule(QString html) +{ + examSchePtr->setPage(html); + examDialogPtr->initializingDataIntoTable(); + examDialogPtr->show(); } void CalendarManager::exportCalendarCSV() //need to add fix to the null pointer bug { diff --git a/main/CalendarTab/CalendarManager.h b/main/CalendarTab/CalendarManager.h index a0ce3b1..182a527 100644 --- a/main/CalendarTab/CalendarManager.h +++ b/main/CalendarTab/CalendarManager.h @@ -1,21 +1,25 @@ #ifndef CALENDARMANAGER_H #define CALENDARMANAGER_H -#include "./src/jceData/Calendar/calendarPage.h" -#include "./src/jceData/Calendar/calendarSchedule.h" +#include "./src/jceData/Calendar/coursesSchedule/calendarPage.h" +#include "./src/jceData/Calendar/coursesSchedule/calendarSchedule.h" +#include "./src/jceData/Calendar/coursesSchedule/calendarDialog.h" #include "./src/jceData/CSV/csv_exporter.h" -#include "./src/jceData/Calendar/calendarDialog.h" + +#include "./src/jceData/Calendar/Exams/calendarExam.h" +#include "./src/jceData/Calendar/Exams/examDialog.h" #include +#include #include #include -class CalendarManager : public QObject +class CalendarManager : public QWidget { Q_OBJECT public: - CalendarManager(QGridLayout *ptr); + CalendarManager(QWidget *parent = 0, QGridLayout *ptr = 0); ~CalendarManager() { delete caliSchedPtr; @@ -23,9 +27,15 @@ public: } void exportCalendarCSV(); void setCalendar(QString html); + void setExamsSchedule(QString html); + void resetTable() { if (caliSchedPtr != NULL) caliSchedPtr->clearTableItems(); } private: + calendarExam * examSchePtr; + examDialog * examDialogPtr; + + calendarSchedule * caliSchedPtr; CalendarDialog * caliDialog; diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 68061d5..c0c70e5 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -146,6 +146,14 @@ int loginHandler::makeCalendarRequest(int year, int semester) else return jceLogin::JCE_NOT_CONNECTED; } + +int loginHandler::makeExamsScheduleRequest(int year, int semester) +{ + if (isLoggedInFlag()) + return jceLog->getExams(year,semester); + else + return jceLogin::JCE_NOT_CONNECTED; +} void loginHandler::setIconConnectionStatus(jceLogin::jceStatus statusDescription) { QPixmap iconPix; diff --git a/main/LoginTab/loginhandler.h b/main/LoginTab/loginhandler.h index 8512ec1..5b7d154 100644 --- a/main/LoginTab/loginhandler.h +++ b/main/LoginTab/loginhandler.h @@ -37,6 +37,7 @@ public: int makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester); int makeCalendarRequest(int year,int semester); + int makeExamsScheduleRequest(int year, int semester); private slots: void readyAfterConnectionLost(); diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index e32ddc3..96e7988 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -31,7 +31,7 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc this->userLoginSetting = new user("",""); this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); - this->calendar = new CalendarManager(ui->calendarGridLayoutMain); + this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); this->data = new SaveData(); //check login File @@ -247,12 +247,42 @@ void MainScreen::on_graphButton_clicked() //EVENTS ON CALENDAR TAB +void MainScreen::on_examsBtn_clicked() +{ + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + int status = 0; + QString page; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) + { + ui->statusBar->showMessage(tr("Getting exams...")); + if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + { + ui->statusBar->showMessage(tr("Done."),1000); + page = loginHandel->getCurrentPageContect(); + calendar->setExamsSchedule(page); + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; + ui->statusBar->showMessage(tr("Done")); + } + else if (status == jceLogin::JCE_NOT_CONNECTED) + { + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + } + else + qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; + } + QApplication::restoreOverrideCursor(); +} void MainScreen::on_getCalendarBtn_clicked() { ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); int status = 0; - QString page; + QString page; QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { @@ -404,3 +434,5 @@ void MainScreen::on_progressBar_valueChanged(int value) else ui->progressBar->setVisible(true); } + + diff --git a/main/mainscreen.h b/main/mainscreen.h index 62da771..3f9a7f9 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -71,6 +71,8 @@ private slots: void on_progressBar_valueChanged(int value); + void on_examsBtn_clicked(); + private: void checkLocale(); diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 4f6482c..be6b6ae 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 0 + 2 false @@ -606,6 +606,13 @@ font-size: 15px; + + + + Show Exams + + + @@ -690,7 +697,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 23 + 22 diff --git a/src/jceData/CSV/csv_exporter.h b/src/jceData/CSV/csv_exporter.h index 52d8dc8..d83ddac 100644 --- a/src/jceData/CSV/csv_exporter.h +++ b/src/jceData/CSV/csv_exporter.h @@ -16,8 +16,8 @@ #include #include -#include "../Calendar/calendarSchedule.h" -#include "../Calendar/calendarDialog.h" +#include "../Calendar/coursesSchedule/calendarSchedule.h" +#include "../Calendar/coursesSchedule/calendarDialog.h" #define CSV_CALENDAR_HEADER "Subject,Start Date,Start Time,End Date,End Time,Description,Location" diff --git a/src/jceData/Calendar/Exams/calendarExam.cpp b/src/jceData/Calendar/Exams/calendarExam.cpp new file mode 100644 index 0000000..70141b1 --- /dev/null +++ b/src/jceData/Calendar/Exams/calendarExam.cpp @@ -0,0 +1,116 @@ +#include "calendarExam.h" + +calendarExam::calendarExam() +{ + exams = NULL; + htmlDataHolderParsed = ""; +} + +/** + * @brief calendarExam::setPage - getting a html page and stripping it into a exams schedule in a list + * @param html - html page with tags + */ +void calendarExam::setPage(QString html) +{ + examsCounter = 0; + if (exams == NULL) + exams = new QList(); + else + exams->clear(); + this->htmlDataHolderParsed = getString(html); + examListInit(htmlDataHolderParsed); +} + +/** + * @brief calendarExam::examListInit spliting the stripped html into lines, and using linetocourse function to make it an object + * @param linesTokinzedString - list of lines, each line has differen exam information + */ +void calendarExam::examListInit(QString &linesTokinzedString) +{ + QString tempToken; + + QStringList holder = linesTokinzedString.split("\n"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) + { + tempToken = (*iterator); + if (!tempToken.isEmpty()) + { + calendarExamCourse *cTemp = lineToCourse(tempToken); + if (cTemp != NULL) + this->exams->push_back(cTemp); + } + } +} + +/** + * @brief calendarExam::lineToCourse getting line of exam with data and make it an object containing data (date, time, course name and etc) + * @param line + * @return + */ +calendarExamCourse *calendarExam::lineToCourse(QString line) +{ + calendarExamCourse *tempC = NULL; + QString templinearray[EXAM_SCHEDULE_FIELDS]; + //SERIAL, NAME, LECTURER, FIELD, TYPE, FIRST_DATE, FIRST_HOUR_BEGIN, SECOND_DATE, SECOND_HOUR_BEGIN + + int serial; + QString name, lecturer, field, type, firstDate, firstHourbegin, secondDate, secondHourbegin; + + QString tempToken; + int i = 0; + QStringList holder = line.split("\t"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) + { + + tempToken = (*iterator); + templinearray[i] = tempToken.trimmed(); + i++; + if (i >= EXAM_SCHEDULE_FIELDS) + break; + } + + if (templinearray[0] == "") //empty parsing + return NULL; + + + serial = templinearray[calendarExamCourse::ExamScheme::SERIAL].toInt(); + name = templinearray[calendarExamCourse::ExamScheme::NAME]; + + lecturer = templinearray[calendarExamCourse::ExamScheme::LECTURER]; + if (lecturer.isEmpty()) + lecturer = LECTURER_DEFAULT_STRING; + + field = templinearray[calendarExamCourse::ExamScheme::FIELD]; + type = templinearray[calendarExamCourse::ExamScheme::TYPE]; + + firstDate = templinearray[calendarExamCourse::ExamScheme::FIRST_DATE]; + if (firstDate.isEmpty()) + return NULL; //can't set a default date to an exam. must be an error + + firstHourbegin = templinearray[calendarExamCourse::ExamScheme::FIRST_HOUR_BEGIN]; + if (firstHourbegin.isEmpty()) + firstHourbegin = HOUR_DEFAULT_STRING; + secondDate = templinearray[calendarExamCourse::ExamScheme::SECOND_DATE]; + if (secondDate.isEmpty()) + { + secondDate = SECOND_DATE_DEFAULT_STRING; + secondHourbegin = HOUR_DEFAULT_STRING; + } + else + { + secondHourbegin = templinearray[calendarExamCourse::ExamScheme::SECOND_HOUR_BEGIN]; + if (secondHourbegin.isEmpty()) + secondHourbegin = HOUR_DEFAULT_STRING; + } + + tempC = new calendarExamCourse(serial,name,lecturer,field,type,firstDate,firstHourbegin,secondDate,secondHourbegin); + examsCounter++; + return tempC; +} +int calendarExam::getExamsCounter() const +{ + return examsCounter; +} + diff --git a/src/jceData/Calendar/Exams/calendarExam.h b/src/jceData/Calendar/Exams/calendarExam.h new file mode 100644 index 0000000..20f5a3f --- /dev/null +++ b/src/jceData/Calendar/Exams/calendarExam.h @@ -0,0 +1,34 @@ +#ifndef CALENDAREXAM_H +#define CALENDAREXAM_H + +#include "../../page.h" +#include "calendarExamCourse.h" + +#include +#include +#include + + +class calendarExam : public Page +{ +public: + calendarExam(); + void setPage(QString html); + + QList* getExams() { return exams; } + int getExamsCounter() const; + + + +private: + + void examListInit(QString &linesTokinzedString); + calendarExamCourse * lineToCourse(QString line); + + QString htmlDataHolderParsed; + QList *exams; + + int examsCounter; //not including madei b +}; + +#endif // CALENDAREXAM_H diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.cpp b/src/jceData/Calendar/Exams/calendarExamCourse.cpp new file mode 100644 index 0000000..7e9859b --- /dev/null +++ b/src/jceData/Calendar/Exams/calendarExamCourse.cpp @@ -0,0 +1,100 @@ +#include "calendarExamCourse.h" + + +calendarExamCourse::calendarExamCourse(int serial, QString name, QString lecturer, QString field, + QString type, QString firstDate, QString firstHourbegin, + QString secondDate, QString secondHourbegin) : Course (serial,name,type) +{ + this->lecturer = lecturer; + this->field = field; + setDate(firstDate,true); + setDate(secondDate,false); + setTime(firstHourbegin,true); + setTime(secondHourbegin,false); + +} +/** + * @brief calendarExamCourse::setDate + * @param date + * @param isFirst if true > first. otherwise > second + */ +void calendarExamCourse::setDate(QString date, bool isFirst) +{ + if (isFirst) + this->firstDate = QDate::fromString(date,"dd/MM/yyyy"); + else + this->secondDate = QDate::fromString(date,"dd/MM/yyyy"); +} +/** + * @brief calendarExamCourse::setTime + * @param time + * @param isFirst if true > first. otherwise > second + */ +void calendarExamCourse::setTime(QString time, bool isFirst) +{ +// qDebug() << "time string is: " << time; + if (isFirst) + this->firstHourbegin = QTime::fromString(time,"hh:mm"); + else + this->secondHourbegin = QTime::fromString(time,"hh:mm"); +} +QTime calendarExamCourse::getSecondHourbegin() const +{ + return secondHourbegin; +} + +void calendarExamCourse::setSecondHourbegin(const QTime &value) +{ + secondHourbegin = value; +} + +QDate calendarExamCourse::getSecondDate() const +{ + return secondDate; +} + +void calendarExamCourse::setSecondDate(const QDate &value) +{ + secondDate = value; +} + +QTime calendarExamCourse::getFirstHourbegin() const +{ + return firstHourbegin; +} + +void calendarExamCourse::setFirstHourbegin(const QTime &value) +{ + firstHourbegin = value; +} + +QDate calendarExamCourse::getFirstDate() const +{ + return firstDate; +} + +void calendarExamCourse::setFirstDate(const QDate &value) +{ + firstDate = value; +} + +QString calendarExamCourse::getField() const +{ + return field; +} + +void calendarExamCourse::setField(const QString &value) +{ + field = value; +} + +QString calendarExamCourse::getLecturer() const +{ + return lecturer; +} + +void calendarExamCourse::setLecturer(const QString &value) +{ + lecturer = value; +} + diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.h b/src/jceData/Calendar/Exams/calendarExamCourse.h new file mode 100644 index 0000000..4127074 --- /dev/null +++ b/src/jceData/Calendar/Exams/calendarExamCourse.h @@ -0,0 +1,70 @@ +#ifndef CALENDAREXAMCOURSE_H +#define CALENDAREXAMCOURSE_H + +#include "../../course.h" + +#include +#include +#include + +#define EXAM_SCHEDULE_FIELDS 9 + +#define LECTURER_DEFAULT_STRING "nullLecturer" +#define HOUR_DEFAULT_STRING "00:00" +#define SECOND_DATE_DEFAULT_STRING "nullSECOND_DATE" + +class calendarExamCourse : public Course +{ + +public: + + enum ExamScheme + { + SERIAL, + NAME, + LECTURER, + FIELD, + TYPE, + FIRST_DATE, + FIRST_HOUR_BEGIN, + SECOND_DATE, + SECOND_HOUR_BEGIN + }; + + calendarExamCourse(int serial, QString name, QString lecturer, QString field, + QString type, QString firstDate, QString firstHourbegin, + QString secondDate, QString secondHourbegin); + + + QString getLecturer() const; + void setLecturer(const QString &value); + + QString getField() const; + void setField(const QString &value); + + QDate getFirstDate() const; + void setFirstDate(const QDate &value); + + QTime getFirstHourbegin() const; + void setFirstHourbegin(const QTime &value); + + QDate getSecondDate() const; + void setSecondDate(const QDate &value); + + QTime getSecondHourbegin() const; + void setSecondHourbegin(const QTime &value); + +private: + + void setDate(QString date, bool isFirst); //isFirst = true > first. otherwise > second + void setTime(QString time, bool isFirst); //isFirst = true > first. otherwise > second + + QString lecturer; + QString field; + QDate firstDate; + QTime firstHourbegin; + QDate secondDate; + QTime secondHourbegin; +}; + +#endif // CALENDAREXAMCOURSE_H diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp new file mode 100644 index 0000000..eb7d076 --- /dev/null +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -0,0 +1,74 @@ +#include "examDialog.h" +#include "ui_examDialog.h" + +examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(parent), + ui(new Ui::examDialog) +{ + ui->setupUi(this); + exams = calSchedPtr; + QStringList headLine; + //SERIAL, NAME, LECTURER, FIELD, TYPE, FIRST_DATE, FIRST_HOUR_BEGIN, SECOND_DATE, SECOND_HOUR_BEGIN + + headLine << tr("Serial") << tr("Course") << tr("Lecturer") << tr("Field") << tr("Type") << tr("First") << tr("Begin") << tr("Second") << tr("Begin"); + + ui->tableWidget->setColumnCount(EXAM_SCHEDULE_FIELDS); + ui->tableWidget->setHorizontalHeaderLabels(headLine); + ui->tableWidget->setLayoutDirection(Qt::LayoutDirection::RightToLeft); + + this->setModal(true); +} + +void examDialog::initializingDataIntoTable() +{ + ui->tableWidget->setRowCount(exams->getExamsCounter()); + int i=0,j=0; + QTableWidgetItem *lecturer,*name,*type; + QTableWidgetItem *serial; + QTableWidgetItem *field; + QDateEdit *firstDate; + QTimeEdit *firstHourbegin; + QDateEdit *secondDate; + QTimeEdit *secondHourbegin; + + for (calendarExamCourse * tempExam: *exams->getExams()) + { + j=0; + lecturer = new QTableWidgetItem(); + lecturer->setData(Qt::EditRole, tempExam->getLecturer()); + name = new QTableWidgetItem(); + name->setData(Qt::EditRole, tempExam->getName()); + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, tempExam->getType()); + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole, tempExam->getSerialNum()); + field = new QTableWidgetItem(); + field->setData(Qt::EditRole, tempExam->getField()); + firstDate = new QDateEdit(); + firstDate->setDate(tempExam->getFirstDate()); + secondDate = new QDateEdit(); + secondDate->setDate(tempExam->getSecondDate()); + firstHourbegin = new QTimeEdit(); + firstHourbegin->setTime(tempExam->getFirstHourbegin()); + secondHourbegin = new QTimeEdit(); + secondHourbegin->setTime(tempExam->getSecondHourbegin()); + + ui->tableWidget->setItem(i,j++,lecturer); + ui->tableWidget->setItem(i,j++,name); + ui->tableWidget->setItem(i,j++,type); + ui->tableWidget->setItem(i,j++,serial); + ui->tableWidget->setItem(i,j++,field); + ui->tableWidget->setCellWidget(i,j++,firstDate); + ui->tableWidget->setCellWidget(i,j++,firstHourbegin); + ui->tableWidget->setCellWidget(i,j++,secondDate); + ui->tableWidget->setCellWidget(i,j++,secondHourbegin); + i++; + } + ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + + +} +examDialog::~examDialog() +{ + delete ui; +} diff --git a/src/jceData/Calendar/Exams/examDialog.h b/src/jceData/Calendar/Exams/examDialog.h new file mode 100644 index 0000000..43d4341 --- /dev/null +++ b/src/jceData/Calendar/Exams/examDialog.h @@ -0,0 +1,27 @@ +#ifndef EXAMDIALOG_H +#define EXAMDIALOG_H + +#include +#include + +#include "calendarExam.h" + +namespace Ui { +class examDialog; +} + +class examDialog : public QDialog +{ + Q_OBJECT + +public: + explicit examDialog(QWidget *parent,calendarExam * calSchedPtr); + void initializingDataIntoTable(); + ~examDialog(); + +private: + Ui::examDialog *ui; + calendarExam * exams; +}; + +#endif // EXAMDIALOG_H diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui new file mode 100644 index 0000000..06fe26e --- /dev/null +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -0,0 +1,86 @@ + + + examDialog + + + + 0 + 0 + 810 + 257 + + + + Dialog + + + + + + + 0 + 0 + + + + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + + + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + examDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + examDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/jceData/Calendar/calendarExam.cpp b/src/jceData/Calendar/calendarExam.cpp deleted file mode 100644 index dfbf567..0000000 --- a/src/jceData/Calendar/calendarExam.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#include "calendarExam.h" - -calendarExam::calendarExam() -{ -} diff --git a/src/jceData/Calendar/calendarExam.h b/src/jceData/Calendar/calendarExam.h deleted file mode 100644 index 9a8640d..0000000 --- a/src/jceData/Calendar/calendarExam.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef CALENDAREXAM_H -#define CALENDAREXAM_H - -#include "../page.h" - -class calendarExam : public Page -{ -public: - calendarExam(); -}; - -#endif // CALENDAREXAM_H diff --git a/src/jceData/Calendar/calendarDialog.cpp b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp similarity index 100% rename from src/jceData/Calendar/calendarDialog.cpp rename to src/jceData/Calendar/coursesSchedule/calendarDialog.cpp diff --git a/src/jceData/Calendar/calendarDialog.h b/src/jceData/Calendar/coursesSchedule/calendarDialog.h similarity index 100% rename from src/jceData/Calendar/calendarDialog.h rename to src/jceData/Calendar/coursesSchedule/calendarDialog.h diff --git a/src/jceData/Calendar/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui similarity index 100% rename from src/jceData/Calendar/calendarDialog.ui rename to src/jceData/Calendar/coursesSchedule/calendarDialog.ui diff --git a/src/jceData/Calendar/calendarPage.cpp b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp similarity index 83% rename from src/jceData/Calendar/calendarPage.cpp rename to src/jceData/Calendar/coursesSchedule/calendarPage.cpp index 0a68e38..8aafa4c 100644 --- a/src/jceData/Calendar/calendarPage.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp @@ -1,10 +1,9 @@ #include "calendarPage.h" -QString CalendarPage::htmlToString() -{ - return tempHtml; -} - +/** + * @brief CalendarPage::setPage getting the html and stripping it into a courses schedule in a list + * @param html + */ void CalendarPage::setPage(QString html) { @@ -13,7 +12,10 @@ void CalendarPage::setPage(QString html) calendarListInit(tempHtml); } - +/** + * @brief CalendarPage::calendarListInit - make an object from each line of course + * @param linesTokinzedString - string contain lines of coureses. each string contain single course information + */ void CalendarPage::calendarListInit(QString &linesTokinzedString) { std::list stringHolder; @@ -36,6 +38,11 @@ void CalendarPage::calendarListInit(QString &linesTokinzedString) } } +/** + * @brief CalendarPage::lineToCourse + * @param line - line of course contain its data and information + * @return calendarcourse object with its information + */ calendarCourse *CalendarPage::lineToCourse(QString line) { diff --git a/src/jceData/Calendar/calendarPage.h b/src/jceData/Calendar/coursesSchedule/calendarPage.h similarity index 76% rename from src/jceData/Calendar/calendarPage.h rename to src/jceData/Calendar/coursesSchedule/calendarPage.h index d4935bd..b4b9077 100644 --- a/src/jceData/Calendar/calendarPage.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.h @@ -1,8 +1,8 @@ #ifndef CALENDARPAGE_H #define CALENDARPAGE_H -#include "../page.h" -#include "calendarCourse.h" +#include "../../page.h" +#include "calendarPageCourse.h" #include #define ROOM_DEFAULT_STRING "nullRoom" @@ -12,18 +12,19 @@ class CalendarPage : public Page { public: - QString htmlToString(); std::list* getCourses() { return courses; } protected: + virtual void setPage(QString html); CalendarPage() { courses = NULL; } private: + void calendarListInit(QString &linesTokinzedString); - calendarCourse* lineToCourse(QString line); + calendarCourse * lineToCourse(QString line); QString tempHtml; std::list* courses; diff --git a/src/jceData/Calendar/calendarCourse.cpp b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp similarity index 68% rename from src/jceData/Calendar/calendarCourse.cpp rename to src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp index 129a46f..a97fbe0 100644 --- a/src/jceData/Calendar/calendarCourse.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp @@ -1,23 +1,22 @@ -#include "calendarCourse.h" +#include "calendarPageCourse.h" calendarCourse::calendarCourse(int serial, QString name, QString type, QString lecturer, double points, double semesterHours, QString dayAndHour, - QString room, calendarCourse::CourseCalendarType courseType) : Course(serial,name, type,points) + QString room) : Course(serial,name, type) { + this->points = points; this->lecturer = lecturer; this->semesterHours = semesterHours; this->room = room; - setDayAndHour(dayAndHour,courseType); + setDayAndHour(dayAndHour); } /** * @brief calendarCourse::setDayAndHour * given a string of time and day - parsing it into day, hour it begins and hour it ends seperated * @param parse - */ -void calendarCourse::setDayAndHour(QString parse, calendarCourse::CourseCalendarType courseType) +void calendarCourse::setDayAndHour(QString parse) { - if (courseType == calendarCourse::CourseCalendarType::CoursesSchedule) - { int ctr = 0; QString temp = ""; QTime timetemp; @@ -47,11 +46,6 @@ void calendarCourse::setDayAndHour(QString parse, calendarCourse::CourseCalendar ctr++; tok = strtok(NULL, " -"); } - } - if (courseType == calendarCourse::CourseCalendarType::ExamSchedule) - { - - } } QString calendarCourse::getLecturer() const @@ -108,26 +102,6 @@ void calendarCourse::setMinutesEnd(int value) { minutesEnd = value; } -/** - * @brief calendarCourse::courseToString - * @return prints the course into string pattern - */ -QString calendarCourse::courseToString() -{ - QString courseText = ""; - courseText += " " + QString::number(this->getSerialNum()); - courseText += " " + this->getName(); - courseText += " " + this->getType(); - courseText += " " + this->lecturer; - courseText += " " + QString::number(this->getPoints()); - courseText += " " + QString::number(this->semesterHours); - courseText += " " + QString::number(this->day); - courseText += " " + QString::number(this->hourBegin) + ":" + QString::number(this->minutesBegin) + "-" + QString::number(this->hourEnd) + ":" + QString::number(this->minutesEnd); - courseText += " " + this->room; - courseText += "\n"; - return courseText; - -} int calendarCourse::getDay() const { return day; @@ -171,3 +145,13 @@ void calendarCourse::setRoom(const QString &value) + +double calendarCourse::getPoints() const +{ + return points; +} + +void calendarCourse::setPoints(double value) +{ + points = value; +} diff --git a/src/jceData/Calendar/calendarCourse.h b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h similarity index 75% rename from src/jceData/Calendar/calendarCourse.h rename to src/jceData/Calendar/coursesSchedule/calendarPageCourse.h index 789d1b2..1a2929b 100644 --- a/src/jceData/Calendar/calendarCourse.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h @@ -1,7 +1,7 @@ #ifndef CALENDARCOURSE_H #define CALENDARCOURSE_H -#include "../course.h" +#include "../../course.h" #include #define CALENDAR_COURSE_FIELDS 8 @@ -9,11 +9,6 @@ class calendarCourse : public Course { public: - enum CourseCalendarType - { - ExamSchedule, - CoursesSchedule - }; enum CourseScheme { @@ -26,9 +21,11 @@ public: DAY_AND_HOURS, ROOM }; + calendarCourse(int serial, QString name, QString type, QString lecturer, double points, double semesterHours, QString dayAndHour, - QString room, calendarCourse::CourseCalendarType courseType = calendarCourse::CourseCalendarType::CoursesSchedule); + QString room); + ~calendarCourse(){} int getDay() const; @@ -39,6 +36,7 @@ public: int getMinutesBegin() const; int getHourEnd() const; int getMinutesEnd() const; + double getPoints() const; void setDay(const QString &value); void setLecturer(const QString &value); @@ -48,14 +46,13 @@ public: void setMinutesBegin(int value); void setHourEnd(int value); void setMinutesEnd(int value); - - QString courseToString(); - + void setPoints(double value); private: - void setDayAndHour(QString parse, CourseCalendarType courseType); + void setDayAndHour(QString parse); + double points; QString lecturer; double semesterHours; int day; diff --git a/src/jceData/Calendar/calendarSchedule.cpp b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp similarity index 93% rename from src/jceData/Calendar/calendarSchedule.cpp rename to src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp index 06e1837..7850984 100644 --- a/src/jceData/Calendar/calendarSchedule.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp @@ -1,6 +1,6 @@ #include "calendarSchedule.h" -calendarSchedule::calendarSchedule() +calendarSchedule::calendarSchedule(QWidget *parent) : QTableWidget(parent) { QStringList days,hours; QTextStream hourString; @@ -22,7 +22,7 @@ calendarSchedule::calendarSchedule() days << QObject::tr("Sunday") << QObject::tr("Monday") << QObject::tr("Tuesday") << QObject::tr("Wednesday") << QObject::tr("Thursday") << QObject::tr("Friday"); setRowCount(endingHour - startingHour + 1); - setColumnCount(6); + setColumnCount(6); //number of days not including saturday ofcourse :) setLayoutDirection(Qt::LayoutDirection::RightToLeft);\ diff --git a/src/jceData/Calendar/calendarSchedule.h b/src/jceData/Calendar/coursesSchedule/calendarSchedule.h similarity index 87% rename from src/jceData/Calendar/calendarSchedule.h rename to src/jceData/Calendar/coursesSchedule/calendarSchedule.h index 14749cd..cf6f948 100644 --- a/src/jceData/Calendar/calendarSchedule.h +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.h @@ -16,7 +16,7 @@ class calendarSchedule : public QTableWidget, public CalendarPage { Q_OBJECT public: - calendarSchedule(); + calendarSchedule(QWidget *parent = 0); ~calendarSchedule() { clearTableItems(); } void setPage(QString html); void clearTableItems(); diff --git a/src/jceData/Grades/gradeCourse.cpp b/src/jceData/Grades/gradeCourse.cpp index 16bca5b..2f9656f 100644 --- a/src/jceData/Grades/gradeCourse.cpp +++ b/src/jceData/Grades/gradeCourse.cpp @@ -1,7 +1,8 @@ #include "gradeCourse.h" -gradeCourse::gradeCourse(int year, int semester, int courseNumInList, int serial, QString name, QString type, double points,double hours, double grade, QString additions) : Course(serial,name,type,points) +gradeCourse::gradeCourse(int year, int semester, int courseNumInList, int serial, QString name, QString type, double points,double hours, double grade, QString additions) : Course(serial,name,type) { + this->points = points; this->hours = hours; this->grade = grade; this->additions = additions; @@ -56,4 +57,14 @@ void gradeCourse::setCourseNumInList(int value) { courseNumInList = value; } +double gradeCourse::getPoints() const +{ + return points; +} + +void gradeCourse::setPoints(double value) +{ + points = value; +} + diff --git a/src/jceData/Grades/gradeCourse.h b/src/jceData/Grades/gradeCourse.h index d62356a..bcdeff6 100644 --- a/src/jceData/Grades/gradeCourse.h +++ b/src/jceData/Grades/gradeCourse.h @@ -41,18 +41,20 @@ public: double getHours() const {return this->hours;} double getGrade() const; QString getAddidtions() const {return this->additions;} + int getCourseNumInList() const; + double getPoints() const; void setHours(double hours); void setGrade(double grade); void setAdditions(QString additions); void setYear(int year); void setSemester(int semester); - - int getCourseNumInList() const; void setCourseNumInList(int value); + void setPoints(double value); private: + double points; double hours; double grade; QString additions; diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 0706efe..27e13a0 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -16,6 +16,7 @@ void gradegraph::showGraph(GradePage *gpPTR) setVisualization(); setGraphsData(); this->show(); + this->setModal(true); //makes it on top of application } diff --git a/src/jceData/course.h b/src/jceData/course.h index 3c90351..b4cdf07 100644 --- a/src/jceData/course.h +++ b/src/jceData/course.h @@ -15,22 +15,19 @@ class Course { public: - Course(int serial,QString name, QString type, double points) { + Course(int serial,QString name, QString type) { this->serialNum = serial; this->name = name; this->type = type; - this->points = points; } virtual ~Course() { } int getSerialNum() const {return this->serialNum;} virtual QString getName() const {return this->name;} virtual QString getType() const {return this->type;} - virtual double getPoints() const {return this->points;} virtual void setName(QString name) { this->name = name;} virtual void setType(QString type){ this->type = type;} - virtual void setPoints(double points){ this->points = points;} private: @@ -38,7 +35,6 @@ private: int serialNum; QString name; QString type; - double points; }; diff --git a/src/jceSettings/jceLoginHtmlScripts.h b/src/jceSettings/jceLoginHtmlScripts.h index 293017b..2eba6c3 100644 --- a/src/jceSettings/jceLoginHtmlScripts.h +++ b/src/jceSettings/jceLoginHtmlScripts.h @@ -84,6 +84,17 @@ public: parameters += "R1C2=" + QString::number(semester) + "&"; return parameters; } + const static QString getExamSchedule(const user &usr,int year, int semester) + { + QString parameters; + parameters = "PRGNAME=HADPASAT_TOCHNIT_BEHINOT&ARGUMENTS=TZ,UNIQ,R1C1,R1C2,R1C3&"; + parameters += "TZ=" + usr.getUserID() + "&"; + parameters += "UNIQ=" + usr.getHashedPassword() + "&"; + parameters += "R1C1=" + QString::number(year) + "&"; + parameters += "R1C2=" + QString::number(semester) + "&"; + parameters += "R1C3=0"; + return parameters; + } }; diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 79e852c..c9c5062 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -199,6 +199,20 @@ int jceLogin::getCalendar(int year, int semester) return true; } +int jceLogin::getExams(int year, int semester) +{ + if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getExamSchedule(*jceA,year,semester))))) + { + if (!(JceConnector->recieveData(*recieverPage,false))) + return jceLogin::ERROR_ON_GETTING_PAGE; + else + return jceLogin::JCE_PAGE_PASSED; + } + else + return jceLogin::ERROR_ON_SEND_REQUEST; + + return true; +} /** * @brief jceLogin::getGrades according to parameters, we make an HTML request and send it over socket to server * @param fromYear - from year diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index 44310a8..66d1ca6 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -40,6 +40,7 @@ public: bool checkConnection() const; bool isLoginFlag() const; + int getExams(int year, int semester); int getCalendar(int year, int semester); int getGrades(int fromYear, int toYear, int fromSemester, int toSemester); From a3995acb0d0a8843fc3a1ffc474c1c7f382de3c6 Mon Sep 17 00:00:00 2001 From: liranbg Date: Thu, 9 Oct 2014 20:22:40 +0300 Subject: [PATCH 15/58] fix lose of information --- src/jceConnection/jcesslclient.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 1e24a92..c293eee 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -210,6 +210,7 @@ void jceSSLClient::readItAll() } this->progressBar->setValue(this->progressBar->value() + 6); packet.append(p); + packet.append("\0"); }while (p.size() > 0); } From 0246b8bcef2e16179af269150427d205c814f425 Mon Sep 17 00:00:00 2001 From: liranbg Date: Thu, 9 Oct 2014 21:17:51 +0300 Subject: [PATCH 16/58] added buffer macro --- src/jceConnection/jcesslclient.cpp | 2 +- src/jceConnection/jcesslclient.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index c293eee..bd25409 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -258,7 +258,7 @@ void jceSSLClient::setDisconnected() void jceSSLClient::setEncrypted() { qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; - setReadBufferSize(10000); + setReadBufferSize(packetSize); setSocketOption(QAbstractSocket::KeepAliveOption,true); flag = true; if (!isConnected()) diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index a6edbed..1b2cec6 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -11,6 +11,7 @@ #include #include +#define packetSize 10000 #define milisTimeOut 4000 class jceSSLClient : public QSslSocket From 01f49ddfc73f093135c4ae81e069e333536fe1ca Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 18:20:33 +0300 Subject: [PATCH 17/58] changing socket engine --- main/mainscreen.ui | 2 +- src/jceConnection/jcesslclient.cpp | 158 ++++++++++-------- src/jceConnection/jcesslclient.h | 74 ++++---- .../Calendar/coursesSchedule/calendarPage.cpp | 77 ++++----- src/jceSettings/jcelogin.cpp | 14 +- 5 files changed, 173 insertions(+), 152 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index be6b6ae..9e32c81 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 2 + 0 false diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index bd25409..b740b42 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -3,7 +3,8 @@ /** * @brief jceSSLClient::jceSSLClient Constructer, setting the signals */ -jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : flag(false), packet(""),networkConf(), reConnection(false) +jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : loggedIAndConnectedFlag(false), readingFlag(false), + reConnectionFlag(false), networkConf(), packet(""), recieveLastPacket(false), packetSizeRecieved(0) { this->progressBar = progressbarPtr; //setting signals @@ -14,8 +15,8 @@ jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : flag(false), packet(" connect(&networkConf,SIGNAL(onlineStateChanged(bool)),this,SLOT(setOnlineState(bool))); //loop event will connect the server, and when it is connected, it will quit - but connection will be open - connect(this, SIGNAL(encrypted()), &loop, SLOT(quit())); - connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loop,SLOT(quit())); + connect(this, SIGNAL(encrypted()), &loginThreadLoop, SLOT(quit())); + connect(this, SIGNAL(error(QAbstractSocket::SocketError)),&loginThreadLoop,SLOT(quit())); } /** @@ -43,7 +44,7 @@ bool jceSSLClient::makeConnect(QString server, int port) qDebug() << Q_FUNC_INFO << "we're online"; - if (reConnection) //reset reconnectiong flag + if (reConnectionFlag) //reset reconnectiong flag { qDebug() << Q_FUNC_INFO << "Making Reconnection"; } @@ -59,12 +60,12 @@ bool jceSSLClient::makeConnect(QString server, int port) qDebug() << Q_FUNC_INFO << "Connection to: " << server << "On Port: " << port; connectToHostEncrypted(server.toStdString().c_str(), port); - loop.exec(); //starting connection, waiting to encryption and then it ends + loginThreadLoop.exec(); //starting connection, waiting to encryption and then it ends qDebug() << Q_FUNC_INFO << "returning the connection status: " << isConnected(); - if (reConnection) + if (reConnectionFlag) { - reConnection = false; + reConnectionFlag = false; emit serverDisconnectedbyRemote(); } return isConnected(); @@ -76,10 +77,10 @@ bool jceSSLClient::makeConnect(QString server, int port) */ bool jceSSLClient::makeDiconnect() { - if (loop.isRunning()) + if (loginThreadLoop.isRunning()) { qWarning() << Q_FUNC_INFO << "Killing connection thread"; - loop.exit(); + loginThreadLoop.exit(); } qDebug() << Q_FUNC_INFO << "disconnecting from host and emitting disconnected()"; this->disconnectFromHost(); //emits disconnected > setDisconnected @@ -117,7 +118,7 @@ bool jceSSLClient::isConnected() } if (!isConnectedToNetwork()) //no link, ethernet\wifi tempFlag = false; - return ((flag) && (tempFlag)); + return ((loggedIAndConnectedFlag) && (tempFlag)); } /** * @brief jceSSLClient::sendData - given string, send it to server @@ -127,11 +128,17 @@ bool jceSSLClient::isConnected() bool jceSSLClient::sendData(QString str) { bool sendDataFlag = false; - + int amount = 0; if (isConnected()) //if connected { - write(str.toStdString().c_str(),str.length()); - if (waitForBytesWritten()) + amount = write(str.toStdString().c_str(),str.length()); + qDebug() << Q_FUNC_INFO << "lenght send: " << str.length() << "lenght recieved: " << amount; + if (amount == -1) + { + qCritical() << Q_FUNC_INFO << "SendData ended with -1"; + sendDataFlag = false; + } + else if (waitForBytesWritten()) sendDataFlag = true; } qDebug() << Q_FUNC_INFO << "Sending Data status is: " << sendDataFlag; @@ -143,42 +150,35 @@ bool jceSSLClient::sendData(QString str) * @param fast true for LOGIN ONLY, false to retrieve all data * @return true if recieved data bigger than zero */ -bool jceSSLClient::recieveData(QString &str, bool fast) +bool jceSSLClient::recieveData(QString *str) { qDebug() << Q_FUNC_INFO << "Data receiving!"; + bool sflag = false; //success on recieving flag + str->clear(); packet = ""; - bool sflag = false; + recieveLastPacket = false; + packetSizeRecieved = 0; //counting packet size + readingFlag = true; //to ignore timeout socket error - if (fast) //fast mode connection, good only for login step!!!! - { - qDebug() << Q_FUNC_INFO << "login step receiving"; - //loop will exit after first read packet. - //meanwhile packet will gain data. good for small amount of data - fast connection! - connect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); - connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); - readerLoop.exec(); - disconnect(this, SIGNAL(readyRead()), &readerLoop, SLOT(quit())); - disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); - } - else - { - qDebug() << Q_FUNC_INFO << "normal receiving"; - //loop will exit after timeout \ full data - connect(this, SIGNAL(packetHasData()), &readerLoop, SLOT(quit())); + timer.setSingleShot(true); + timer.start(milisTimeOut); //if timer is timeout -> it means the connection takes long time - timer.setSingleShot(true); - connect(&timer, SIGNAL(timeout()), &readerLoop, SLOT(quit())); - connect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); - timer.start(5000); - readerLoop.exec(); + connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); //we have something to read + connect(&timer, SIGNAL(timeout()), &readerLoop, SLOT(quit())); //if timer timeout > exiting event - } - str = packet; - qDebug() << Q_FUNC_INFO << "received bytes: " << str.length() ; - if (str.length() > 0) + readerLoop.exec(); + + disconnect(&timer, SIGNAL(timeout()), &readerLoop, SLOT(quit())); + disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); + + str->append(packet); + qDebug() << *str; + + qDebug() << Q_FUNC_INFO << "packet size: " << packetSizeRecieved << "received data lenght: " << str->length(); + if (str->length() > 0) sflag = true; qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; - disconnect(this, SIGNAL(readyRead()), this, SLOT(readItAll())); + readingFlag = false; return sflag; } @@ -187,33 +187,41 @@ bool jceSSLClient::recieveData(QString &str, bool fast) */ void jceSSLClient::readIt() { - QString p; - do - { - p = readAll(); - packet.append(p); - this->progressBar->setValue(this->progressBar->value() + 6); - }while (p.size() > 0); + int packSize = bytesAvailable(); + int doTimes=0; + QByteArray tempPacket; -} -void jceSSLClient::readItAll() -{ - QString p; do { - p = ""; - p = read(bytesAvailable()); - if (p.contains("") == true) - { - //we recieved the end of table. we can stop recieving - timer.setInterval(1000); - } - this->progressBar->setValue(this->progressBar->value() + 6); - packet.append(p); + qDebug() << Q_FUNC_INFO << "packet size" << packSize; + + if (doTimes++ > 0) //for debbuging, checking thread looping times + qDebug() << Q_FUNC_INFO << "do loop" << doTimes; + + waitForReadyRead(100); + tempPacket = read(packSize); + + readerAppendingLocker.lock(); + packetSizeRecieved += packSize; + packet.append(tempPacket); packet.append("\0"); - }while (p.size() > 0); -} + readerAppendingLocker.unlock(); + progressBar->setValue(this->progressBar->value() + 6); + + if (tempPacket.contains("Go_To_system_After_Login.htm") || tempPacket.contains("")) + { + //we have the last packet. (uses only in login first step + recieveLastPacket = true; + timer.setInterval(200); + } + else + { + //just a packet with data + } + + }while ((packSize = bytesAvailable()) > 0); +} void jceSSLClient::setOnlineState(bool isOnline) { qWarning() << Q_FUNC_INFO << "isOnline status change: " << isOnline; @@ -246,8 +254,8 @@ void jceSSLClient::setDisconnected() qDebug() << Q_FUNC_INFO << "connection has been DISCONNECTED"; this->setSocketState(QAbstractSocket::SocketState::UnconnectedState); packet.clear(); - flag = false; - if (reConnection) + loggedIAndConnectedFlag = false; + if (reConnectionFlag) makeConnect(); @@ -260,11 +268,11 @@ void jceSSLClient::setEncrypted() qDebug() << Q_FUNC_INFO << "connection has been ENCRYPTED"; setReadBufferSize(packetSize); setSocketOption(QAbstractSocket::KeepAliveOption,true); - flag = true; + loggedIAndConnectedFlag = true; if (!isConnected()) { qWarning() << Q_FUNC_INFO << "Connection status didnt change! reseting flag to false"; - flag = false; + loggedIAndConnectedFlag = false; } } @@ -291,7 +299,7 @@ void jceSSLClient::showIfErrorMsg() //The remote host closed the connection if (isConnectedToNetwork()) //we can reconnect { - reConnection = true; + reConnectionFlag = true; } else relevantError = true; @@ -402,19 +410,23 @@ void jceSSLClient::checkErrors(QAbstractSocket::SocketError a) qWarning() << Q_FUNC_INFO << "Var Error: " << a; qWarning() << Q_FUNC_INFO << "Error: " << errorString(); } + else if (!readingFlag) + { + qWarning() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; + qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork() << "state is: " << state(); + qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + + } else { - qDebug() << Q_FUNC_INFO << "isConnected?: " << isConnected() << "is timeout?" << timeout; - qWarning() << Q_FUNC_INFO << "isOnline?: " << isConnectedToNetwork(); - qWarning() << Q_FUNC_INFO << "state is: " << state(); - qWarning() << Q_FUNC_INFO << "Var Error: " << a; - qWarning() << Q_FUNC_INFO << "Error: " << errorString(); + //timeout when reading } showIfErrorMsg(); } /** written by KARAN BALKAR * @brief jceSSLClient::isConnectedToNetwork + * * @return */ bool jceSSLClient::isConnectedToNetwork(){ diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index 1b2cec6..e2cfb6d 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -5,54 +5,66 @@ #include #include #include +#include +#include #include #include #include -#include + #include -#define packetSize 10000 -#define milisTimeOut 4000 +#define packetSize 4096 //4k +#define milisTimeOut 5000 //4 seconds class jceSSLClient : public QSslSocket { - Q_OBJECT + Q_OBJECT public: - jceSSLClient(QProgressBar *progressbarPtr); + jceSSLClient(QProgressBar *progressbarPtr); - bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); - bool makeDiconnect(); - bool isConnected(); - bool sendData(QString str); - bool recieveData(QString &str, bool fast); - void showIfErrorMsg(); + bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); + bool makeDiconnect(); + bool isConnected(); + bool sendData(QString str); + bool recieveData(QString *str); + void showIfErrorMsg(); signals: - void serverDisconnectedbyRemote(); - void noInternetLink(); - void socketDisconnected(); - void packetHasData(); + void serverDisconnectedbyRemote(); + void noInternetLink(); + void socketDisconnected(); private slots: - void checkErrors(QAbstractSocket::SocketError a); - void setConnected(); - void setEncrypted(); - void setDisconnected(); - void readIt(); - void readItAll(); - void setOnlineState(bool isOnline); + void checkErrors(QAbstractSocket::SocketError a); + void setConnected(); + void setEncrypted(); + void setDisconnected(); + void readIt(); + void setOnlineState(bool isOnline); private: - bool isConnectedToNetwork(); //checking if online - bool flag; - QString packet; - QEventLoop loop; //handle the connection as thread - QEventLoop readerLoop; - QTimer timer; - QNetworkConfigurationManager networkConf; //checking if online - bool reConnection; //used for remote host disconnecting - QProgressBar *progressBar; // + bool isConnectedToNetwork(); //checking if online + + bool loggedIAndConnectedFlag; + bool readingFlag; + bool reConnectionFlag; //used for remote host disconnecting + + QNetworkConfigurationManager networkConf; //checking if online + + QString packet; + bool recieveLastPacket; + int packetSizeRecieved; + + QEventLoop loginThreadLoop; //handle the connection as thread + QEventLoop readerLoop; + + QMutex readerAppendingLocker; //locking packet when appending + QTimer timer; //uses to check if reading has reached its timeout + + + + QProgressBar *progressBar; //progressbar pointer }; diff --git a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp index 8aafa4c..24bcccb 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp @@ -9,6 +9,7 @@ void CalendarPage::setPage(QString html) courses = new std::list(); tempHtml = getString(html); + qDebug() << "starting .."; calendarListInit(tempHtml); } @@ -18,23 +19,19 @@ void CalendarPage::setPage(QString html) */ void CalendarPage::calendarListInit(QString &linesTokinzedString) { - std::list stringHolder; - QString temp; - calendarCourse * cTemp = NULL; - char* tok; - char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); - tok = strtok(textToTok,"\n"); - while (tok != NULL) + QString tempToken; + + QStringList holder = linesTokinzedString.split("\n"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) { - temp = tok; - stringHolder.push_back(temp); - tok = strtok(NULL, "\n"); - } - for (QString temp: stringHolder) - { - cTemp = lineToCourse(temp); - if (cTemp != NULL) - courses->push_back(cTemp); + tempToken = (*iterator); + if (!tempToken.isEmpty()) + { + calendarCourse *cTemp = lineToCourse(tempToken); + if (cTemp != NULL) + this->courses->push_back(cTemp); + } } } @@ -51,27 +48,27 @@ calendarCourse *CalendarPage::lineToCourse(QString line) int serial; double points,semesterHours; QString name,type, lecturer,dayAndHour,room; - QString tempS = ""; - int i = 0; - char* tok; - char* cLine = strdup(line.toStdString().c_str()); - tok = strtok(cLine, "\t"); - while(tok != NULL) - { - tempS = QString(tok); + QString tempToken; + int i = 0; + QStringList holder = line.split("\t"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) + { + + tempToken = (*iterator); if (i >= 1) //skips on semester character { - templinearray[i-1] = tempS.trimmed(); + templinearray[i] = tempToken.trimmed(); } - i++; - if (i > 8) - break; - tok=strtok(NULL, "\t"); - } + if (i >= CALENDAR_COURSE_FIELDS) + break; + } + if (templinearray[0] == "") //empty parsing - return NULL; + return NULL; + serial = templinearray[calendarCourse::CourseScheme::SERIAL].toInt(); name = templinearray[calendarCourse::CourseScheme::NAME]; @@ -101,16 +98,16 @@ calendarCourse *CalendarPage::lineToCourse(QString line) tempC = new calendarCourse(serial,name,type,lecturer,points,semesterHours,dayAndHour,room); -// qDebug() << "serial is: " << tempC->getSerialNum(); -// qDebug() << tempC->getName(); -// qDebug() << tempC->getType(); -// qDebug() << tempC->getLecturer(); -// qDebug() << tempC->getPoints(); -// qDebug() << tempC->getHourBegin() << ":" << tempC->getMinutesBegin(); -// qDebug() << tempC->getHourEnd() << ":" << tempC->getMinutesEnd(); + qDebug() << "serial is: " << tempC->getSerialNum(); + qDebug() << tempC->getName(); + qDebug() << tempC->getType(); + qDebug() << tempC->getLecturer(); + qDebug() << tempC->getPoints(); + qDebug() << tempC->getHourBegin() << ":" << tempC->getMinutesBegin(); + qDebug() << tempC->getHourEnd() << ":" << tempC->getMinutesEnd(); -// qDebug() << tempC->getDay(); -// qDebug() << tempC->getRoom(); + qDebug() << tempC->getDay(); + qDebug() << tempC->getRoom(); return tempC; } diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index c9c5062..591d472 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -59,7 +59,7 @@ int jceLogin::makeConnection() returnMode = makeSecondVisit(); if (returnMode == true) //siging in the website { - qDebug() << "jceLogin::makeConnection(); Signed in succeesfully"; + qDebug() << Q_FUNC_INFO << "Signed in succeesfully"; status = jceStatus::JCE_YOU_ARE_IN; setLoginFlag(true); } @@ -94,7 +94,7 @@ int jceLogin::makeConnection() status = jceStatus::JCE_NOT_CONNECTED; //we throw status even if we are IN! - qDebug() << "jceLogin::makeConnection(); return status: " << status; + qDebug() << Q_FUNC_INFO << "return status: " << status; return status; } @@ -150,7 +150,7 @@ int jceLogin::makeFirstVisit() QString psw = jceA->getPassword(); if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA)))) { - if (!JceConnector->recieveData(*recieverPage,true)) + if (!JceConnector->recieveData(recieverPage)) return jceLogin::ERROR_ON_GETTING_INFO; } else @@ -168,7 +168,7 @@ int jceLogin::makeSecondVisit() QString pswid=jceA->getHashedPassword(); if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getSecondValidationStep(*jceA))))) { - if (!(JceConnector->recieveData(*recieverPage,true))) + if (!(JceConnector->recieveData(recieverPage))) return jceLogin::ERROR_ON_GETTING_INFO; return true; @@ -188,7 +188,7 @@ int jceLogin::getCalendar(int year, int semester) { if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getCalendar(*jceA,year,semester))))) { - if (!(JceConnector->recieveData(*recieverPage,false))) + if (!(JceConnector->recieveData(recieverPage))) return jceLogin::ERROR_ON_GETTING_PAGE; else return jceLogin::JCE_PAGE_PASSED; @@ -203,7 +203,7 @@ int jceLogin::getExams(int year, int semester) { if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getExamSchedule(*jceA,year,semester))))) { - if (!(JceConnector->recieveData(*recieverPage,false))) + if (!(JceConnector->recieveData(recieverPage))) return jceLogin::ERROR_ON_GETTING_PAGE; else return jceLogin::JCE_PAGE_PASSED; @@ -225,7 +225,7 @@ int jceLogin::getGrades(int fromYear, int toYear, int fromSemester, int toSemest { if ((JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getGradesPath(*jceA,fromYear, toYear, fromSemester, toSemester))))) { - if (!(JceConnector->recieveData(*recieverPage,false))) + if (!(JceConnector->recieveData(recieverPage))) return jceLogin::ERROR_ON_GETTING_PAGE; else return jceLogin::JCE_PAGE_PASSED; From 65c23138e502daf268d013fa6c855da9956c9c92 Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 18:50:07 +0300 Subject: [PATCH 18/58] using qt lists, fixed documentation --- src/jceConnection/jcesslclient.cpp | 27 ++++++++-------- .../Calendar/coursesSchedule/calendarPage.cpp | 31 ++++++++++--------- .../Calendar/coursesSchedule/calendarPage.h | 6 ++-- .../coursesSchedule/calendarPageCourse.cpp | 8 ----- 4 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index b740b42..ac97523 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -145,22 +145,20 @@ bool jceSSLClient::sendData(QString str) return sendDataFlag; } /** - * @brief jceSSLClient::recieveData - * @param str this variable will store the recieved data - * @param fast true for LOGIN ONLY, false to retrieve all data - * @return true if recieved data bigger than zero + * @brief jceSSLClient::recieveData - recieving data through threaded reading and mutex + * @param str - string to fill with data. + * @return true if packet has recieced the last packet -> true, otherwise ->false */ bool jceSSLClient::recieveData(QString *str) { qDebug() << Q_FUNC_INFO << "Data receiving!"; - bool sflag = false; //success on recieving flag str->clear(); packet = ""; recieveLastPacket = false; packetSizeRecieved = 0; //counting packet size readingFlag = true; //to ignore timeout socket error - timer.setSingleShot(true); + timer.setSingleShot(true); //counting just once. timer.start(milisTimeOut); //if timer is timeout -> it means the connection takes long time connect(this, SIGNAL(readyRead()), this, SLOT(readIt())); //we have something to read @@ -172,18 +170,21 @@ bool jceSSLClient::recieveData(QString *str) disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); str->append(packet); - qDebug() << *str; + //qDebug() << *str; //if you want to see the whole packet, unmark me qDebug() << Q_FUNC_INFO << "packet size: " << packetSizeRecieved << "received data lenght: " << str->length(); - if (str->length() > 0) - sflag = true; - qDebug() << Q_FUNC_INFO << "return with flag: " << sflag; - readingFlag = false; - return sflag; + qDebug() << Q_FUNC_INFO << "return with flag: " << recieveLastPacket; + + readingFlag = false; //finished reading session + return recieveLastPacket; //we have the last packet } /** - * @brief jceSSLClient::readIt function to read for fast mode in recieved data + * @brief jceSSLClient::readIt + * this method, called by a thread to read the bytes avilable by the remote server + * each packet we append into the class private var 'packet' (mutexed) + * if we recieve the last packet (see tags below) we set the timer of the calling function to 100msc + * */ void jceSSLClient::readIt() { diff --git a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp index 24bcccb..245912e 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp @@ -6,10 +6,12 @@ */ void CalendarPage::setPage(QString html) { + if (courses == NULL) + courses = new QList(); + else + courses->clear(); - courses = new std::list(); tempHtml = getString(html); - qDebug() << "starting .."; calendarListInit(tempHtml); } @@ -26,6 +28,7 @@ void CalendarPage::calendarListInit(QString &linesTokinzedString) for (iterator = holder.begin(); iterator != holder.end(); ++iterator) { tempToken = (*iterator); + if (!tempToken.isEmpty()) { calendarCourse *cTemp = lineToCourse(tempToken); @@ -55,14 +58,14 @@ calendarCourse *CalendarPage::lineToCourse(QString line) QStringList::iterator iterator; for (iterator = holder.begin(); iterator != holder.end(); ++iterator) { - tempToken = (*iterator); + if (i >= 1) //skips on semester character { - templinearray[i] = tempToken.trimmed(); + templinearray[i-1] = tempToken.trimmed(); } i++; - if (i >= CALENDAR_COURSE_FIELDS) + if (i > CALENDAR_COURSE_FIELDS) break; } @@ -98,16 +101,16 @@ calendarCourse *CalendarPage::lineToCourse(QString line) tempC = new calendarCourse(serial,name,type,lecturer,points,semesterHours,dayAndHour,room); - qDebug() << "serial is: " << tempC->getSerialNum(); - qDebug() << tempC->getName(); - qDebug() << tempC->getType(); - qDebug() << tempC->getLecturer(); - qDebug() << tempC->getPoints(); - qDebug() << tempC->getHourBegin() << ":" << tempC->getMinutesBegin(); - qDebug() << tempC->getHourEnd() << ":" << tempC->getMinutesEnd(); +// qDebug() << "serial is: " << tempC->getSerialNum(); +// qDebug() << tempC->getName(); +// qDebug() << tempC->getType(); +// qDebug() << tempC->getLecturer(); +// qDebug() << tempC->getPoints(); +// qDebug() << tempC->getHourBegin() << ":" << tempC->getMinutesBegin(); +// qDebug() << tempC->getHourEnd() << ":" << tempC->getMinutesEnd(); - qDebug() << tempC->getDay(); - qDebug() << tempC->getRoom(); +// qDebug() << tempC->getDay(); +// qDebug() << tempC->getRoom(); return tempC; } diff --git a/src/jceData/Calendar/coursesSchedule/calendarPage.h b/src/jceData/Calendar/coursesSchedule/calendarPage.h index b4b9077..65d5b0d 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPage.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.h @@ -3,7 +3,7 @@ #include "../../page.h" #include "calendarPageCourse.h" -#include +#include #define ROOM_DEFAULT_STRING "nullRoom" #define LECTURER_DEFAULT_STRING "nullLecturer" @@ -12,7 +12,7 @@ class CalendarPage : public Page { public: - std::list* getCourses() { return courses; } + QList *getCourses() { return courses; } protected: @@ -27,7 +27,7 @@ private: calendarCourse * lineToCourse(QString line); QString tempHtml; - std::list* courses; + QList *courses; }; diff --git a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp index a97fbe0..50735ad 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp @@ -138,14 +138,6 @@ void calendarCourse::setRoom(const QString &value) { room = value; } - - - - - - - - double calendarCourse::getPoints() const { return points; From 054237a66771b3bd424c1075eb8c48381ddb1dc0 Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 20:36:00 +0300 Subject: [PATCH 19/58] using refs, change exam qdate format --- main/CalendarTab/CalendarManager.cpp | 4 ++-- src/jceData/CSV/csv_exporter.cpp | 4 ++-- src/jceData/Calendar/Exams/examDialog.cpp | 7 ++++++- src/jceData/Calendar/Exams/examDialog.ui | 8 ++++---- .../Calendar/coursesSchedule/calendarDialog.h | 11 +++++++++++ .../Calendar/coursesSchedule/calendarPage.cpp | 8 ++------ .../Calendar/coursesSchedule/calendarPage.h | 14 +++++++++++--- .../Calendar/coursesSchedule/calendarPageCourse.h | 11 +++++++++++ .../Calendar/coursesSchedule/calendarSchedule.cpp | 2 +- .../Calendar/coursesSchedule/calendarSchedule.h | 8 ++++++++ 10 files changed, 58 insertions(+), 19 deletions(-) diff --git a/main/CalendarTab/CalendarManager.cpp b/main/CalendarTab/CalendarManager.cpp index ac408a3..ec2816d 100644 --- a/main/CalendarTab/CalendarManager.cpp +++ b/main/CalendarTab/CalendarManager.cpp @@ -21,9 +21,9 @@ void CalendarManager::setExamsSchedule(QString html) examDialogPtr->initializingDataIntoTable(); examDialogPtr->show(); } -void CalendarManager::exportCalendarCSV() //need to add fix to the null pointer bug +void CalendarManager::exportCalendarCSV() { - if (this->caliSchedPtr->getCourses() == NULL) + if (this->caliSchedPtr->getCourses().isEmpty()) return; QMessageBox msgBox; int buttonClicked = caliDialog->exec(); diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index a79385c..aaa01f1 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -23,7 +23,7 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca if ((cal == NULL) || (calSched == NULL)) //pointers checking! return false; - if (calSched->getCourses() == NULL) + if (calSched->getCourses().isEmpty()) return false; qDebug() << Q_FUNC_INFO << "Getting path for csv file from user..."; @@ -53,7 +53,7 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca out << CSV_CALENDAR_HEADER << "\n"; // macro in header file - for (calendarCourse *coursePtr: *(calSched->getCourses())) //main loop - running though all courses + for (calendarCourse *coursePtr: (calSched->getCourses())) //main loop - running though all courses { // Getting course info - store in vars for easy access int day = coursePtr->getDay(); diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp index eb7d076..a51a264 100644 --- a/src/jceData/Calendar/Exams/examDialog.cpp +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -11,6 +11,8 @@ examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(par headLine << tr("Serial") << tr("Course") << tr("Lecturer") << tr("Field") << tr("Type") << tr("First") << tr("Begin") << tr("Second") << tr("Begin"); + ui->tableWidget->verticalHeader()->setVisible(false); + ui->tableWidget->horizontalHeader()->setVisible(false); ui->tableWidget->setColumnCount(EXAM_SCHEDULE_FIELDS); ui->tableWidget->setHorizontalHeaderLabels(headLine); ui->tableWidget->setLayoutDirection(Qt::LayoutDirection::RightToLeft); @@ -29,7 +31,6 @@ void examDialog::initializingDataIntoTable() QTimeEdit *firstHourbegin; QDateEdit *secondDate; QTimeEdit *secondHourbegin; - for (calendarExamCourse * tempExam: *exams->getExams()) { j=0; @@ -44,8 +45,10 @@ void examDialog::initializingDataIntoTable() field = new QTableWidgetItem(); field->setData(Qt::EditRole, tempExam->getField()); firstDate = new QDateEdit(); + firstDate->setDisplayFormat("d/M/yy"); firstDate->setDate(tempExam->getFirstDate()); secondDate = new QDateEdit(); + secondDate->setDisplayFormat("d/M/yy"); secondDate->setDate(tempExam->getSecondDate()); firstHourbegin = new QTimeEdit(); firstHourbegin->setTime(tempExam->getFirstHourbegin()); @@ -66,6 +69,8 @@ void examDialog::initializingDataIntoTable() ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + this->setMinimumHeight(ui->tableWidget->height()); + this->setMinimumWidth(ui->tableWidget->width()); } examDialog::~examDialog() diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index 06fe26e..b35f23b 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -13,8 +13,8 @@ Dialog - - + + @@ -27,10 +27,10 @@ - + - + diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.h b/src/jceData/Calendar/coursesSchedule/calendarDialog.h index 8d26ba0..52ca03f 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.h +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.h @@ -18,6 +18,17 @@ namespace Ui { class CalendarDialog; } +/** + * @brief The CalendarDialog class + * + * This class preseting a Dialog with selection of dates + * The user has to choose between a starting point of semester to the end. + * + * This dialog main goal is to let the user an option to export his CSV + * containing data of his schedule. + * + * Made By Sagi Dayan, sagidayan@gmail.com On 22/09/2014 + */ class CalendarDialog : public QDialog { Q_OBJECT diff --git a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp index 245912e..afc89f6 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPage.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.cpp @@ -6,11 +6,7 @@ */ void CalendarPage::setPage(QString html) { - if (courses == NULL) - courses = new QList(); - else - courses->clear(); - + courses.clear(); tempHtml = getString(html); calendarListInit(tempHtml); @@ -33,7 +29,7 @@ void CalendarPage::calendarListInit(QString &linesTokinzedString) { calendarCourse *cTemp = lineToCourse(tempToken); if (cTemp != NULL) - this->courses->push_back(cTemp); + this->courses.push_back(cTemp); } } } diff --git a/src/jceData/Calendar/coursesSchedule/calendarPage.h b/src/jceData/Calendar/coursesSchedule/calendarPage.h index 65d5b0d..de1cf1e 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPage.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPage.h @@ -8,17 +8,25 @@ #define ROOM_DEFAULT_STRING "nullRoom" #define LECTURER_DEFAULT_STRING "nullLecturer" +/** + * @brief The CalendarPage class + * + * This class generating html string to a list of calendarCourses + * Each item in a list is a course with its information (hour, day, name, serial and etc) + * + * Made By liran ben gida, LiranBG@gmail.com On 31/8/2014 + */ class CalendarPage : public Page { public: - QList *getCourses() { return courses; } + QList getCourses() { return courses; } protected: virtual void setPage(QString html); - CalendarPage() { courses = NULL; } + CalendarPage() { } private: @@ -27,7 +35,7 @@ private: calendarCourse * lineToCourse(QString line); QString tempHtml; - QList *courses; + QList courses; }; diff --git a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h index 1a2929b..9cf4f18 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h @@ -6,6 +6,17 @@ #define CALENDAR_COURSE_FIELDS 8 +/** + * @brief The calendarCourse class + * + * This class holds each scheduled course + * the course scheme can be found below, inside the enum CourseScheme + * + * The class's constructor gets the data and manipulate it into an object + * with its relevant information. + * + * Made By liran ben gida, LiranBG@gmail.com On 31/8/2014 + */ class calendarCourse : public Course { public: diff --git a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp index 7850984..89f6216 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp @@ -59,7 +59,7 @@ void calendarSchedule::insertCourseIntoTable() QString courseString; int currentHour,currentDay,blocksNumber; int row,col; - for (calendarCourse *coursePtr: *getCourses()) + for (calendarCourse *coursePtr: getCourses()) { courseString = ""; currentHour = coursePtr->getHourBegin(); diff --git a/src/jceData/Calendar/coursesSchedule/calendarSchedule.h b/src/jceData/Calendar/coursesSchedule/calendarSchedule.h index cf6f948..ddaa48b 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarSchedule.h +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.h @@ -12,6 +12,14 @@ #define HOURS_END 20 #define ACADEMIN_HOUR 45 +/** + * @brief The calendarSchedule class + * + * This class combining the courses schedule with each course into a table + * setpage -> insertingIntoTable -> showing data + * + * Made By liran ben gida, LiranBG@gmail.com On 31/8/2014 + */ class calendarSchedule : public QTableWidget, public CalendarPage { Q_OBJECT From 8d5385f99e224801682aaae564ff4f5dc1d639cf Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 21:33:08 +0300 Subject: [PATCH 20/58] gradepage documentation, using qlist --- main/CourseTab/coursestablemanager.cpp | 8 +- src/jceData/Calendar/Exams/calendarExam.cpp | 12 +- src/jceData/Calendar/Exams/calendarExam.h | 13 +- .../Calendar/Exams/calendarExamCourse.h | 11 + src/jceData/Calendar/Exams/examDialog.cpp | 13 +- src/jceData/Calendar/Exams/examDialog.h | 10 + .../Calendar/coursesSchedule/calendarDialog.h | 15 +- src/jceData/Grades/gradeCourse.h | 3 - src/jceData/Grades/gradePage.cpp | 267 ++++++++++-------- src/jceData/Grades/gradePage.h | 7 +- 10 files changed, 202 insertions(+), 157 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index 30646e7..da0d613 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -33,7 +33,7 @@ coursesTableManager::~coursesTableManager() */ void coursesTableManager::insertJceCoursesIntoTable() { - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { if (us->getInfluenceCourseOnly()) { @@ -69,7 +69,7 @@ bool coursesTableManager::changes(QString change, int row, int col) return true; int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { if (c->getSerialNum() == serialCourse) { @@ -267,7 +267,7 @@ void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) else { if (this->gp != NULL) - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { if (!(isCourseAlreadyInserted(c->getSerialNum()))) if (c->getPoints() == 0) @@ -295,7 +295,7 @@ void coursesTableManager::clearTable() gradeCourse *coursesTableManager::getCourseByRow(int row) { QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); - for (gradeCourse *c: *gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { if (c->getSerialNum() == courseSerial.toDouble()) return c; diff --git a/src/jceData/Calendar/Exams/calendarExam.cpp b/src/jceData/Calendar/Exams/calendarExam.cpp index 70141b1..31444b5 100644 --- a/src/jceData/Calendar/Exams/calendarExam.cpp +++ b/src/jceData/Calendar/Exams/calendarExam.cpp @@ -2,7 +2,6 @@ calendarExam::calendarExam() { - exams = NULL; htmlDataHolderParsed = ""; } @@ -13,10 +12,7 @@ calendarExam::calendarExam() void calendarExam::setPage(QString html) { examsCounter = 0; - if (exams == NULL) - exams = new QList(); - else - exams->clear(); + exams.clear(); this->htmlDataHolderParsed = getString(html); examListInit(htmlDataHolderParsed); } @@ -38,15 +34,15 @@ void calendarExam::examListInit(QString &linesTokinzedString) { calendarExamCourse *cTemp = lineToCourse(tempToken); if (cTemp != NULL) - this->exams->push_back(cTemp); + this->exams.push_back(cTemp); } } } /** * @brief calendarExam::lineToCourse getting line of exam with data and make it an object containing data (date, time, course name and etc) - * @param line - * @return + * @param line - parsed line with tabs between each relevant data + * @return object of examcourse with its data */ calendarExamCourse *calendarExam::lineToCourse(QString line) { diff --git a/src/jceData/Calendar/Exams/calendarExam.h b/src/jceData/Calendar/Exams/calendarExam.h index 20f5a3f..b538da4 100644 --- a/src/jceData/Calendar/Exams/calendarExam.h +++ b/src/jceData/Calendar/Exams/calendarExam.h @@ -8,14 +8,21 @@ #include #include - +/** + * @brief The calendarExam class + * + * This class generating html string to a list of examcourses + * Each item in a list is a course with its information (hour, day, name, serial and etc) + * + * Made By liran ben gida, LiranBG@gmail.com On 08/10/2014 + */ class calendarExam : public Page { public: calendarExam(); void setPage(QString html); - QList* getExams() { return exams; } + QList getExams() { return exams; } int getExamsCounter() const; @@ -26,7 +33,7 @@ private: calendarExamCourse * lineToCourse(QString line); QString htmlDataHolderParsed; - QList *exams; + QList exams; int examsCounter; //not including madei b }; diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.h b/src/jceData/Calendar/Exams/calendarExamCourse.h index 4127074..12a37b8 100644 --- a/src/jceData/Calendar/Exams/calendarExamCourse.h +++ b/src/jceData/Calendar/Exams/calendarExamCourse.h @@ -13,6 +13,17 @@ #define HOUR_DEFAULT_STRING "00:00" #define SECOND_DATE_DEFAULT_STRING "nullSECOND_DATE" +/** + * @brief The calendarExamCourse class + * + * This class holds each exam course + * the course scheme can be found below, inside the enum ExamScheme + * + * The class's constructor gets the data and manipulate it into an object + * with its relevant information. + * + * Made By liran ben gida, LiranBG@gmail.com On 08/10/2014 + */ class calendarExamCourse : public Course { diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp index a51a264..4c0ae8d 100644 --- a/src/jceData/Calendar/Exams/examDialog.cpp +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -1,6 +1,10 @@ #include "examDialog.h" #include "ui_examDialog.h" - +/** + * @brief examDialog::examDialog + * @param parent + * @param calSchedPtr - list of courses with information about each exam + */ examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(parent), ui(new Ui::examDialog) { @@ -20,6 +24,11 @@ examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(par this->setModal(true); } +/** + * @brief examDialog::initializingDataIntoTable + * + * Inserting each object of exam into the table + */ void examDialog::initializingDataIntoTable() { ui->tableWidget->setRowCount(exams->getExamsCounter()); @@ -31,7 +40,7 @@ void examDialog::initializingDataIntoTable() QTimeEdit *firstHourbegin; QDateEdit *secondDate; QTimeEdit *secondHourbegin; - for (calendarExamCourse * tempExam: *exams->getExams()) + for (calendarExamCourse * tempExam: exams->getExams()) { j=0; lecturer = new QTableWidgetItem(); diff --git a/src/jceData/Calendar/Exams/examDialog.h b/src/jceData/Calendar/Exams/examDialog.h index 43d4341..24aef6b 100644 --- a/src/jceData/Calendar/Exams/examDialog.h +++ b/src/jceData/Calendar/Exams/examDialog.h @@ -10,6 +10,16 @@ namespace Ui { class examDialog; } +/** + * @brief The examDialog class + * + * This class preseting a Dialog with dates, information and time of exams + * + * This dialog main goal is to let the user an option to edit and see the containing data of his exam schedule. + * The user will be able to export the exam schedule into .CSV file through CalendarTab + * + * Made By liran ben gida, LiranBG@gmail.com On 08/10/2014 + */ class examDialog : public QDialog { Q_OBJECT diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.h b/src/jceData/Calendar/coursesSchedule/calendarDialog.h index 52ca03f..1adbe5a 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.h +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.h @@ -1,10 +1,12 @@ /** * JCE Manager (C) * - * This QDialog widget will hold the dates of a Semester, Start and End. + * This QDialog widget hold the dates of a Semester, Start and End. * * this dialog will help the csv_exporter class to export a CSV file that will contain * all the courses within that period of time. + * + * Made By Sagi Dayan, sagidayan@gmail.com On 22/09/2014 */ #ifndef CALENDARDIALOG_H @@ -18,17 +20,6 @@ namespace Ui { class CalendarDialog; } -/** - * @brief The CalendarDialog class - * - * This class preseting a Dialog with selection of dates - * The user has to choose between a starting point of semester to the end. - * - * This dialog main goal is to let the user an option to export his CSV - * containing data of his schedule. - * - * Made By Sagi Dayan, sagidayan@gmail.com On 22/09/2014 - */ class CalendarDialog : public QDialog { Q_OBJECT diff --git a/src/jceData/Grades/gradeCourse.h b/src/jceData/Grades/gradeCourse.h index bcdeff6..12d329b 100644 --- a/src/jceData/Grades/gradeCourse.h +++ b/src/jceData/Grades/gradeCourse.h @@ -8,9 +8,6 @@ * LiranBG@gmail.com */ #include "../course.h" -#include -#include -#include #define COURSE_FIELDS 10 #define NO_GRADE_YET 101; diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index 456d19f..f63be27 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -5,165 +5,185 @@ static int minYear = 9999; GradePage::GradePage(QString html) : Page() { - courses = new std::list(); - tempHtml = getString(html); - coursesListInit(tempHtml); - + tempHtml = getString(html); + coursesListInit(tempHtml); } GradePage::~GradePage() { - for(Course* c : *courses) - delete c; - delete courses; + for (Course* c : courses) + delete c; } +/** + * @brief GradePage::removeCourse + * @param courseSerialID - course ID to remove + */ void GradePage::removeCourse(QString courseSerialID) { - for(gradeCourse* c : *courses) + for(gradeCourse* c : courses) { - if (c->getSerialNum() == courseSerialID.toInt()) + if (c->getSerialNum() == courseSerialID.toInt()) { - courses->remove(c); - delete c; - return; + courses.removeAll(c); + delete c; + return; } } } + +/** + * @brief GradePage::coursesListInit + * using lineToCourse function, its making a list of gradeCourse object from a given string of information + * @param linesTokinzedString list of courses, tokenized by lines. containing data of each course + */ void GradePage::coursesListInit(QString &linesTokinzedString) { - std::list stringHolder; - QString temp; - gradeCourse* cTemp = NULL; - char* tok; - char* textToTok = strdup(linesTokinzedString.toStdString().c_str()); - tok = strtok(textToTok,"\n"); - while (tok != NULL) //putting every line in a string holder before parsing it + QString tempToken; + + QStringList holder = linesTokinzedString.split("\n"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) { - temp = tok; - stringHolder.push_back(temp); - tok = strtok(NULL, "\n"); - } - for (QString temp: stringHolder) - { - cTemp = lineToCourse(temp); - if (cTemp != NULL) - courses->push_back(cTemp); + tempToken = (*iterator); + if ((!tempToken.isEmpty()) && (tempToken.length() > 1)) + { + gradeCourse *cTemp = lineToCourse(tempToken); + if (cTemp != NULL) + this->courses.push_back(cTemp); + } } } + +/** + * @brief GradePage::lineToCourse + * making an object of gradepage with the given information from string + * @param line - lines tokenized by tabs containing each course information (year, serial, name, points and etc..) + * @return + */ gradeCourse* GradePage::lineToCourse(QString line) { - gradeCourse *tempC = NULL; - QString templinearray[COURSE_FIELDS];//[serial,name,type,points,hours,grade,additions] - int serial,year,semester,courseNumInList; - double points,hours,grade; - QString name,type, additions; - QString tempS = ""; - int i = 0; - char* tok; - char* cLine = strdup(line.toStdString().c_str()); - tok = strtok(cLine, "\t"); - while(tok != NULL) + gradeCourse *tempC = NULL; + QString templinearray[COURSE_FIELDS];//[year,semester,numInList,serial,name,type,points,hours,grade,additions] + int serial,year,semester,courseNumInList; + double points,hours,grade; + QString name,type, additions; + + QString tempToken; + int i = 0; + QStringList holder = line.split("\t"); + QStringList::iterator iterator; + for (iterator = holder.begin(); iterator != holder.end(); ++iterator) { - tempS = tok; - if (i == gradeCourse::CourseScheme::SERIAL) //we need to extract the serial manually + tempToken = (*iterator); + tempToken = tempToken.trimmed(); + //we are checking it because in GPA, serial and course name are mixed + if (i == gradeCourse::CourseScheme::SERIAL) { - tempS = ""; - char *tokTemp; - tokTemp = tok; - while (!(isdigit((int)*tokTemp))) //getting to serial number starting pointer - tokTemp++; + QString tempDataOfSerialCourseName; - while (isdigit((int)*tokTemp)) //serial number + //getting serial + QStringList secHolder = tempToken.split(" "); + QStringList::iterator secIterator = secHolder.begin(); + tempDataOfSerialCourseName = *secIterator; + templinearray[i] = tempDataOfSerialCourseName.trimmed(); + //getting course name; + ++secIterator; + tempDataOfSerialCourseName.clear(); + while (secIterator != secHolder.end()) { - tempS += QString(*tokTemp); - tokTemp++; + tempDataOfSerialCourseName.append(*secIterator + " "); + secIterator++; } - templinearray[i] = tempS.trimmed(); - templinearray[i+1] = QString(tokTemp).trimmed(); - i +=2; //skipping on serial and course name + templinearray[++i] = tempDataOfSerialCourseName.trimmed(); } - else + else { - templinearray[i] = tempS.trimmed(); - i++; + templinearray[i] = tempToken; } - if (i == COURSE_FIELDS) - break; - tok=strtok(NULL, "\t"); + i++; + if (i >= COURSE_FIELDS) + break; } - if (templinearray[0] == "") //empty parsing + + if (templinearray[0] == "") //empty parsing { - qCritical() << Q_FUNC_INFO << "empty parsing"; - return NULL; + qCritical() << Q_FUNC_INFO << "empty parsing"; + return NULL; } - year = templinearray[gradeCourse::CourseScheme::YEAR].toInt(); - semester = templinearray[gradeCourse::CourseScheme::SEMESTER].toInt(); - courseNumInList = templinearray[gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST].toInt(); - serial = templinearray[gradeCourse::CourseScheme::SERIAL].toInt(); + year = templinearray[gradeCourse::CourseScheme::YEAR].toInt(); + semester = templinearray[gradeCourse::CourseScheme::SEMESTER].toInt(); + courseNumInList = templinearray[gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST].toInt(); + serial = templinearray[gradeCourse::CourseScheme::SERIAL].toInt(); - name = templinearray[gradeCourse::CourseScheme::NAME]; - type = templinearray[gradeCourse::CourseScheme::TYPE]; + name = templinearray[gradeCourse::CourseScheme::NAME]; + type = templinearray[gradeCourse::CourseScheme::TYPE]; - points = templinearray[gradeCourse::CourseScheme::POINTS].toDouble(); - hours = templinearray[gradeCourse::CourseScheme::HOURS].toDouble(); + points = templinearray[gradeCourse::CourseScheme::POINTS].toDouble(); + hours = templinearray[gradeCourse::CourseScheme::HOURS].toDouble(); - if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE])) - grade = templinearray[gradeCourse::CourseScheme::GRADE].toDouble(); - else - grade = NO_GRADE_YET; + if (isGradedYet(templinearray[gradeCourse::CourseScheme::GRADE])) + grade = templinearray[gradeCourse::CourseScheme::GRADE].toDouble(); + else + grade = NO_GRADE_YET; - additions = templinearray[gradeCourse::CourseScheme::ADDITION]; + additions = templinearray[gradeCourse::CourseScheme::ADDITION]; - if (year >= maxYear) - maxYear = year; + if (year >= maxYear) + maxYear = year; - if (year <= minYear) - minYear = year; + if (year <= minYear) + minYear = year; - tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); - return tempC; + tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); + return tempC; } -//checking if one of the chars inside grade is not a number +/** + * @brief GradePage::isGradedYet checking if one of the chars inside grade is not a number + * @param grade + * @return if has bee graded or not + */ bool GradePage::isGradedYet(QString grade) { - if (strlen(grade.toStdString().c_str()) <= 1) - return false; - - for (char c: grade.toStdString()) - { - if (c == '\0') - break; - if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9 + if (strlen(grade.toStdString().c_str()) <= 1) return false; + for (char c: grade.toStdString()) + { + if (c == '\0') + break; + if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9 + return false; + } - return true; + return true; } + /** * @brief GradePage::getAvg getting avg * @return - gpa avg of all courses */ double GradePage::getAvg() { - double avg = 0; - double points = 0; - for (gradeCourse* c : *courses) + double avg = 0; + double points = 0; + for (gradeCourse* c : courses) { - if ((c->getGrade() != 0)) + if ((c->getGrade() != 0)) { - avg += c->getGrade() * c->getPoints(); - points += c->getPoints(); + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); } } - avg /= points; - return avg; + avg /= points; + return avg; } + /** * @brief GradePage::getAvg getting avg of given year * @param year - year (yyyy) @@ -171,56 +191,59 @@ double GradePage::getAvg() */ double GradePage::getAvg(int year) { - double avg = 0; - double points = 0; - for (gradeCourse* c : *courses) + double avg = 0; + double points = 0; + for (gradeCourse* c : courses) { - if ((c->getGrade() != 0) && (c->getYear() == year)) + if ((c->getGrade() != 0) && (c->getYear() == year)) { - avg += c->getGrade() * c->getPoints(); - points += c->getPoints(); + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); } } - if (points != 0) - avg /= points; - else - avg=0; - return avg; + if (points != 0) + avg /= points; + else + avg=0; + return avg; } + /** * @brief GradePage::getAvg * @param year - year (yyyy) * @param semester - semeser (1-3) * @return -gpa avg of given year in given semester */ + double GradePage::getAvg(int year, int semester) { - double avg = 0; - double points = 0; - for (gradeCourse* c : *courses) + double avg = 0; + double points = 0; + for (gradeCourse* c : courses) { - if ((c->getGrade() != 0) && (c->getYear() == year) && (c->getSemester() == semester)) + if ((c->getGrade() != 0) && (c->getYear() == year) && (c->getSemester() == semester)) { - avg += c->getGrade() * c->getPoints(); - points += c->getPoints(); + avg += c->getGrade() * c->getPoints(); + points += c->getPoints(); } } - if (points != 0) - avg /= points; - else - avg=0; - return avg; + if (points != 0) + avg /= points; + else + avg=0; + return avg; } + /** * @brief GradePage::getMinYearInList * @return the minimal year inside courses list */ int GradePage::getMinYearInList() { - return minYear; + return minYear; } int GradePage::getMaxYearInList() { - return maxYear; + return maxYear; } diff --git a/src/jceData/Grades/gradePage.h b/src/jceData/Grades/gradePage.h index 677c0e5..c94c428 100644 --- a/src/jceData/Grades/gradePage.h +++ b/src/jceData/Grades/gradePage.h @@ -11,7 +11,7 @@ #include "../page.h" #include "../Grades/gradeCourse.h" -#include +#include class GradePage : public Page { @@ -21,6 +21,7 @@ public: ~GradePage(); void removeCourse(QString courseSerialID); + double getAvg(); double getAvg(int year); double getAvg(int year, int semester); @@ -29,7 +30,7 @@ public: int getMaxYearInList(); - std::list* getCourses() { return courses; } + QList getCourses() { return courses; } private: @@ -38,7 +39,7 @@ private: bool isGradedYet(QString grade); - std::list* courses; + QList courses; QString tempHtml; From 96751b69458e3f32cbbd1e6129d47795fe9a9fe5 Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 21:47:30 +0300 Subject: [PATCH 21/58] documentation --- src/jceData/CSV/csv_exporter.cpp | 4 +- src/jceData/Calendar/Exams/calendarExam.cpp | 18 +- .../Calendar/Exams/calendarExamCourse.h | 4 +- src/jceData/Grades/gradeCourse.cpp | 1 + src/jceData/Grades/gradeCourse.h | 23 ++- src/jceData/Grades/gradePage.h | 39 ++-- src/jceData/Grades/graph/gradegraph.cpp | 182 +++++++++--------- 7 files changed, 145 insertions(+), 126 deletions(-) diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index aaa01f1..96545f4 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -150,7 +150,7 @@ QString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM QString start; start.append(QString::number(startH)); start.append(":00"); -// start.append(QString::number(startM)); + // start.append(QString::number(startM)); start.append(":00"); QString end; @@ -172,7 +172,7 @@ QString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM description.append("טרם נקבע מיקום"); else { - description.append(" ב"); + description.append(" ב"); description.append(room); } diff --git a/src/jceData/Calendar/Exams/calendarExam.cpp b/src/jceData/Calendar/Exams/calendarExam.cpp index 31444b5..39b19b9 100644 --- a/src/jceData/Calendar/Exams/calendarExam.cpp +++ b/src/jceData/Calendar/Exams/calendarExam.cpp @@ -71,24 +71,24 @@ calendarExamCourse *calendarExam::lineToCourse(QString line) return NULL; - serial = templinearray[calendarExamCourse::ExamScheme::SERIAL].toInt(); - name = templinearray[calendarExamCourse::ExamScheme::NAME]; + serial = templinearray[calendarExamCourse::CourseScheme::SERIAL].toInt(); + name = templinearray[calendarExamCourse::CourseScheme::NAME]; - lecturer = templinearray[calendarExamCourse::ExamScheme::LECTURER]; + lecturer = templinearray[calendarExamCourse::CourseScheme::LECTURER]; if (lecturer.isEmpty()) lecturer = LECTURER_DEFAULT_STRING; - field = templinearray[calendarExamCourse::ExamScheme::FIELD]; - type = templinearray[calendarExamCourse::ExamScheme::TYPE]; + field = templinearray[calendarExamCourse::CourseScheme::FIELD]; + type = templinearray[calendarExamCourse::CourseScheme::TYPE]; - firstDate = templinearray[calendarExamCourse::ExamScheme::FIRST_DATE]; + firstDate = templinearray[calendarExamCourse::CourseScheme::FIRST_DATE]; if (firstDate.isEmpty()) return NULL; //can't set a default date to an exam. must be an error - firstHourbegin = templinearray[calendarExamCourse::ExamScheme::FIRST_HOUR_BEGIN]; + firstHourbegin = templinearray[calendarExamCourse::CourseScheme::FIRST_HOUR_BEGIN]; if (firstHourbegin.isEmpty()) firstHourbegin = HOUR_DEFAULT_STRING; - secondDate = templinearray[calendarExamCourse::ExamScheme::SECOND_DATE]; + secondDate = templinearray[calendarExamCourse::CourseScheme::SECOND_DATE]; if (secondDate.isEmpty()) { secondDate = SECOND_DATE_DEFAULT_STRING; @@ -96,7 +96,7 @@ calendarExamCourse *calendarExam::lineToCourse(QString line) } else { - secondHourbegin = templinearray[calendarExamCourse::ExamScheme::SECOND_HOUR_BEGIN]; + secondHourbegin = templinearray[calendarExamCourse::CourseScheme::SECOND_HOUR_BEGIN]; if (secondHourbegin.isEmpty()) secondHourbegin = HOUR_DEFAULT_STRING; } diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.h b/src/jceData/Calendar/Exams/calendarExamCourse.h index 12a37b8..8cb3776 100644 --- a/src/jceData/Calendar/Exams/calendarExamCourse.h +++ b/src/jceData/Calendar/Exams/calendarExamCourse.h @@ -17,7 +17,7 @@ * @brief The calendarExamCourse class * * This class holds each exam course - * the course scheme can be found below, inside the enum ExamScheme + * the course scheme can be found below, inside the enum CourseScheme * * The class's constructor gets the data and manipulate it into an object * with its relevant information. @@ -29,7 +29,7 @@ class calendarExamCourse : public Course public: - enum ExamScheme + enum CourseScheme { SERIAL, NAME, diff --git a/src/jceData/Grades/gradeCourse.cpp b/src/jceData/Grades/gradeCourse.cpp index 2f9656f..13b1a8c 100644 --- a/src/jceData/Grades/gradeCourse.cpp +++ b/src/jceData/Grades/gradeCourse.cpp @@ -15,6 +15,7 @@ gradeCourse::~gradeCourse() { } + double gradeCourse::getGrade() const { double noGrade = NO_GRADE_YET; diff --git a/src/jceData/Grades/gradeCourse.h b/src/jceData/Grades/gradeCourse.h index 12d329b..8bd67e4 100644 --- a/src/jceData/Grades/gradeCourse.h +++ b/src/jceData/Grades/gradeCourse.h @@ -1,18 +1,25 @@ #ifndef GRADE_COURSE_H #define GRADE_COURSE_H -/* This Code Made By Sagi Dayan - * SagiDayan@gmail.com - * - * Minor changes has been made by Liran Ben Gida - * LiranBG@gmail.com -*/ #include "../course.h" -#define COURSE_FIELDS 10 +#define COURSE_FIELDS 10 #define NO_GRADE_YET 101; - +/** + * @brief The gradeCourse class + * + * This class holds a list of course in GPA + * the course scheme can be found below, inside the enum CourseScheme + * + * The class's constructor gets the data and manipulate it into an object + * with its relevant information. + * + * Made By: + * Sagi Dayan, SagiDayan@gmail.com + * Liran Ben Gida, LiranBG@gmail.com + * On 31/8/2014 + */ class gradeCourse : public Course { public: diff --git a/src/jceData/Grades/gradePage.h b/src/jceData/Grades/gradePage.h index c94c428..727c82d 100644 --- a/src/jceData/Grades/gradePage.h +++ b/src/jceData/Grades/gradePage.h @@ -13,35 +13,46 @@ #include +/** + * @brief The GradePage class + * + * This class generating html string to a list of gradeCourse + * Each item in a list is a course with its information (grade, points, name, serial and etc) + * + * Made By: + * Sagi Dayan, SagiDayan@gmail.com + * Liran Ben Gida, LiranBG@gmail.com + * On 31/8/2014 + */ class GradePage : public Page { public: - GradePage(QString html); - ~GradePage(); + GradePage(QString html); + ~GradePage(); - void removeCourse(QString courseSerialID); + void removeCourse(QString courseSerialID); - double getAvg(); - double getAvg(int year); - double getAvg(int year, int semester); + double getAvg(); + double getAvg(int year); + double getAvg(int year, int semester); - int getMinYearInList(); - int getMaxYearInList(); + int getMinYearInList(); + int getMaxYearInList(); - QList getCourses() { return courses; } + QList getCourses() { return courses; } private: - void coursesListInit(QString &linesTokinzedString); - gradeCourse* lineToCourse(QString line); + void coursesListInit(QString &linesTokinzedString); + gradeCourse* lineToCourse(QString line); - bool isGradedYet(QString grade); + bool isGradedYet(QString grade); - QList courses; + QList courses; - QString tempHtml; + QString tempHtml; }; diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 235dd49..70ffcc3 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -2,80 +2,80 @@ #include "ui_gradegraph.h" gradegraph::gradegraph(QWidget *parent) : - QDialog(parent), - ui(new Ui::gradegraph) + QDialog(parent), + ui(new Ui::gradegraph) { - ui->setupUi(this); - this->gp = NULL; + ui->setupUi(this); + this->gp = NULL; } void gradegraph::showGraph(GradePage *gpPTR) { - this->gp = gpPTR; - setVisualization(); - setGraphsData(); - this->show(); - this->setModal(true); //makes it on top of application + this->gp = gpPTR; + setVisualization(); + setGraphsData(); + this->show(); + this->setModal(true); //makes it on top of application } gradegraph::~gradegraph() { - delete ui; + delete ui; } void gradegraph::setGraphsData() { - int minYearInList = gp->getMinYearInList(); - int maxYearInList = gp->getMaxYearInList()+1; - int xRangeForYear = (maxYearInList - minYearInList+2)*3; - QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),sem(xRangeForYear); + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; + QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),sem(xRangeForYear); - for (int yearCount=0,i=1; igetAvg(minYearInList+yearCount); - yearlyAvg[i] = lastAvg; + lastAvg = gp->getAvg(minYearInList+yearCount); + yearlyAvg[i] = lastAvg; - // add the text label at the top: - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); - textLabel->position->setCoords(i, lastAvg+1.5); // place position at center/top of axis rect - textLabel->setText(QString::number(lastAvg,'g',4)); - textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger - textLabel->setPen(QPen(Qt::black)); // show black border around text - yearCount++; + // add the text label at the top: + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); + textLabel->position->setCoords(i, lastAvg+1.5); // place position at center/top of axis rect + textLabel->setText(QString::number(lastAvg,'g',4)); + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text + yearCount++; } - else + else { - if (i+4 < xRangeForYear) //semesters + if (i+4 < xRangeForYear) //semesters { - double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); - SemesterialAvg[i+4] = avg; - // add the text label at the top: + double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); + SemesterialAvg[i+4] = avg; + // add the text label at the top: - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); - textLabel->position->setCoords(i+4, avg+0.5); // place position at center/top of axis rect - textLabel->setText(QString::number(avg,'g',4)); - textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger - textLabel->setPen(QPen(Qt::black)); // show black border around text + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); + textLabel->position->setCoords(i+4, avg+0.5); // place position at center/top of axis rect + textLabel->setText(QString::number(avg,'g',4)); + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text } - yearlyAvg[i] = 0; + yearlyAvg[i] = 0; } } - //yearly - ui->graphwidget->graph(0)->setData(sem,yearlyAvg); - //yearly - ui->graphwidget->graph(1)->setData(sem,SemesterialAvg); + //yearly + ui->graphwidget->graph(0)->setData(sem,yearlyAvg); + //yearly + ui->graphwidget->graph(1)->setData(sem,SemesterialAvg); } /** @@ -83,71 +83,71 @@ void gradegraph::setGraphsData() */ void gradegraph::setVisualization() { - ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box + ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box - ui->graphwidget->addGraph(); //yearly and semesterial graphs - ui->graphwidget->addGraph(); + ui->graphwidget->addGraph(); //yearly and semesterial graphs + ui->graphwidget->addGraph(); - ui->graphwidget->graph(0)->setName(tr("Yearly Average")); - ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsLine); - ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); + ui->graphwidget->graph(0)->setName(tr("Yearly Average")); + ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsLine); + ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); - ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); - ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsLine); - ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); + ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); + ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsLine); + ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); - int minYearInList = gp->getMinYearInList(); - int maxYearInList = gp->getMaxYearInList()+1; - int xRangeForYear = (maxYearInList - minYearInList+2)*3; + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; - QVector xStrings(0); - for (int year=minYearInList,i = 0; i < xRangeForYear-1; ++i) + QVector xStrings(0); + for (int year=minYearInList,i = 0; i < xRangeForYear-1; ++i) { - //set year x axe label to be yyyy A B C yyyy+1 A B C yyyy+2.... - int semesterChar = i%4; - QString tempString; - switch (semesterChar) + //set year x axe label to be yyyy A B C yyyy+1 A B C yyyy+2.... + int semesterChar = i%4; + QString tempString; + switch (semesterChar) { case 1: - tempString = tr("A"); - xStrings << tempString; - break; + tempString = tr("A"); + xStrings << tempString; + break; case 2: - tempString = tr("B"); - xStrings << tempString; - break; + tempString = tr("B"); + xStrings << tempString; + break; case 3: - tempString = tr("C"); - xStrings << tempString; - break; + tempString = tr("C"); + xStrings << tempString; + break; case 0: - tempString = QString::number(year); - xStrings << tempString; - year++; - break; + tempString = QString::number(year); + xStrings << tempString; + year++; + break; } } - ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); - ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); - ui->graphwidget->yAxis->setRange(50,100); - ui->graphwidget->yAxis->setTickStep(2); - ui->graphwidget->yAxis->setAutoSubTicks(false); - ui->graphwidget->yAxis->setAutoTickStep(false); - ui->graphwidget->yAxis->setSubTickCount(5); + ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); + ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); + ui->graphwidget->yAxis->setRange(50,100); + ui->graphwidget->yAxis->setTickStep(2); + ui->graphwidget->yAxis->setAutoSubTicks(false); + ui->graphwidget->yAxis->setAutoTickStep(false); + ui->graphwidget->yAxis->setSubTickCount(5); - ui->graphwidget->xAxis->setLabel(tr("Years")); - ui->graphwidget->xAxis->setAutoTickLabels(false); - ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); - ui->graphwidget->xAxis->setAutoTickStep(false); - ui->graphwidget->xAxis->setTickStep(1); - ui->graphwidget->xAxis->setAutoSubTicks(false); - ui->graphwidget->xAxis->setSubTickCount(1); + ui->graphwidget->xAxis->setLabel(tr("Years")); + ui->graphwidget->xAxis->setAutoTickLabels(false); + ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); + ui->graphwidget->xAxis->setAutoTickStep(false); + ui->graphwidget->xAxis->setTickStep(1); + ui->graphwidget->xAxis->setAutoSubTicks(false); + ui->graphwidget->xAxis->setSubTickCount(1); ui->graphwidget->xAxis->setTickVectorLabels(xStrings); - ui->graphwidget->xAxis->setRange(1,xRangeForYear); + ui->graphwidget->xAxis->setRange(1,xRangeForYear); - ui->graphwidget->legend->setVisible(true); //show graph name on top right + ui->graphwidget->legend->setVisible(true); //show graph name on top right } void gradegraph::on_pushButton_clicked() From e828cdd9d326fe85599c888c6ffac960df887560 Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 21:51:14 +0300 Subject: [PATCH 22/58] documentation --- src/jceData/course.h | 11 ++++++++++- src/jceData/page.h | 11 +++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/jceData/course.h b/src/jceData/course.h index b4cdf07..c2508d0 100644 --- a/src/jceData/course.h +++ b/src/jceData/course.h @@ -10,7 +10,16 @@ #include #include - +/** + * @brief The Course class + * + * This class is a prototype of a basic course structure + * + * Made By: + * Sagi Dayan, SagiDayan@gmail.com + * Liran Ben Gida, LiranBG@gmail.com + * On 31/8/2014 + */ class Course { public: diff --git a/src/jceData/page.h b/src/jceData/page.h index d43543a..eb444f1 100644 --- a/src/jceData/page.h +++ b/src/jceData/page.h @@ -1,12 +1,6 @@ #ifndef PAGE_H #define PAGE_H -/* This Code Made By Sagi Dayan - * SagiDayan@gmail.com - * - * Changes have been made by Liran Ben Gida - * LiranBG@gmail.com -*/ #include #include @@ -14,6 +8,11 @@ * @brief The Page class * parsing given page - strip and clean html tags * use only with JCE + * + * Made By: + * Sagi Dayan, SagiDayan@gmail.com + * Liran Ben Gida, LiranBG@gmail.com + * On 31/8/2014 */ class Page { From 3d826864d213b2b4278480e9d07a006b0168610a Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 21:53:19 +0300 Subject: [PATCH 23/58] less information on debug. no need each packet size --- src/jceConnection/jcesslclient.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index ac97523..2eec393 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -194,7 +194,7 @@ void jceSSLClient::readIt() do { - qDebug() << Q_FUNC_INFO << "packet size" << packSize; +// qDebug() << Q_FUNC_INFO << "packet size" << packSize; if (doTimes++ > 0) //for debbuging, checking thread looping times qDebug() << Q_FUNC_INFO << "do loop" << doTimes; From b1957f7f56db535bfe9ca66328d3acc9e00810cc Mon Sep 17 00:00:00 2001 From: liranbg Date: Fri, 10 Oct 2014 22:24:19 +0300 Subject: [PATCH 24/58] calendar tooltip --- .../coursesSchedule/calendarPageCourse.cpp | 19 +++++++++++++++++++ .../coursesSchedule/calendarPageCourse.h | 4 +++- .../coursesSchedule/calendarSchedule.cpp | 1 + 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp index 50735ad..b6b7fe8 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp @@ -147,3 +147,22 @@ void calendarCourse::setPoints(double value) { points = value; } + +double points; +QString lecturer; +double semesterHours; +int day; +int hourBegin; +int minutesBegin; +int hourEnd; +int minutesEnd; +QString room; + +QString calendarCourse::toString() +{ + QTime begin,end; + begin.setHMS(hourBegin,minutesBegin,0); + end.setHMS(hourEnd,minutesEnd,0); + return QString("%1 %2 %3\n%4 %5\n%6 - %7").arg(QString::number(this->getSerialNum()),this->getName(),QString::number(this->points),this->getLecturer(),this->getRoom(), + begin.toString("hh:mm"),end.toString(("hh:mm"))); +} diff --git a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h index 9cf4f18..35fb2d9 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h +++ b/src/jceData/Calendar/coursesSchedule/calendarPageCourse.h @@ -47,7 +47,7 @@ public: int getMinutesBegin() const; int getHourEnd() const; int getMinutesEnd() const; - double getPoints() const; + double getPoints() const; void setDay(const QString &value); void setLecturer(const QString &value); @@ -59,6 +59,8 @@ public: void setMinutesEnd(int value); void setPoints(double value); + QString toString(); + private: void setDayAndHour(QString parse); diff --git a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp index 89f6216..38d6bdc 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp @@ -83,6 +83,7 @@ void calendarSchedule::insertCourseIntoTable() item = new QTableWidgetItem(courseString); + item->setToolTip(coursePtr->toString()); if (this->takeItem(row,col) != NULL) delete this->takeItem(row,col); this->setItem(row,col,item); From c7d76d99ac612bf0675ccd4ccf131022f3b68296 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Sat, 11 Oct 2014 17:58:11 +0300 Subject: [PATCH 25/58] changed gpa ui --- main/mainscreen.ui | 541 +++++++++++++++-------- src/jceData/Calendar/Exams/examDialog.ui | 6 + 2 files changed, 365 insertions(+), 182 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 9e32c81..4e24066 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -48,8 +48,8 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r - - + + true @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 0 + 1 false @@ -316,13 +316,350 @@ font-size: 15px; GPA - + - - - 0 - - + + + + + 5 + + + 0 + + + + + Qt::Horizontal + + + QSizePolicy::Expanding + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + #frameFrom { + border-width: 1px; + border-style: inset; + border-color: black; +} + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 1 + + + 0 + + + 0 + + + 0 + + + 0 + + + 1 + + + + + + + + 0 + 0 + + + + + + + Year: + + + + + + + 2008 + + + 2015 + + + 2011 + + + + + + + + 0 + 0 + + + + + + + Semester: + + + + + + + 1 + + + 999 + + + + + + + + + + 0 + 0 + + + + + + + <html><head/><body><p align="center">From</p></body></html> + + + + + + + + + + + 0 + 0 + + + + #frameTo { + border-width: 1px; + border-style: inset; + border-color: black; +} + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 1 + + + 0 + + + 0 + + + 0 + + + 0 + + + 1 + + + + + QLayout::SetDefaultConstraint + + + + + + 0 + 0 + + + + + + + Year: + + + + + + + 2008 + + + 2016 + + + 2015 + + + + + + + + 0 + 0 + + + + + + + Semester: + + + + + + + 1 + + + 999 + + + 3 + + + + + + + + + + 0 + 0 + + + + + + + <html><head/><body><p align="center">To</p></body></html> + + + + + + + + + + + 0 + 0 + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 5 + + + 0 + + + 0 + + + 0 + + + 9 + + + 0 + + + + + true + + + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> + + + Get GPA + + + + + + + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> + + + Clear Table + + + + + + + + + + + 0 + 0 + + + + Only Main Courses + + + + + + @@ -341,36 +678,9 @@ font-size: 15px; - - - - - - - - true - - - <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> - - - Add - - - - - - - <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> - - - Clear - - - - - - + + + Qt::Horizontal @@ -383,23 +693,23 @@ font-size: 15px; - - - + + + Graph View - + Average: - + @@ -428,143 +738,13 @@ font-size: 15px; - - - - - - Only Main Courses - - - - - - - - 0 - 0 - - - - From - - - - - - - Year: - - - - - - - 2008 - - - 2015 - - - 2011 - - - - - - - Semester: - - - - - - - 1 - - - 999 - - - - - - - Qt::Horizontal - - - QSizePolicy::Minimum - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - To - - - - - - - Year: - - - - - - - 2008 - - - 2016 - - - 2015 - - - - - - - Semester - - - - - - - 1 - - - 999 - - - 3 - - - - - - Calendar + Schedule @@ -602,7 +782,7 @@ font-size: 15px; - Get Calendar + Get Schedule @@ -643,14 +823,14 @@ font-size: 15px; - + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - + @@ -697,7 +877,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 22 + 21 @@ -780,17 +960,14 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: keepLogin loginButton tabWidget - checkBoxCoursesInfluence spinBoxCoursesFromYear spinBoxCoursesFromSemester spinBoxCoursesToYear spinBoxCoursesToSemester - ratesButton coursesTable spinBoxYear spinBoxSemester getCalendarBtn - clearTableButton exportToCVSBtn diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index b35f23b..c43802d 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -10,6 +10,12 @@ 257 + + + 0 + 0 + + Dialog From 60fa80aa5cd5804a6f9a3367fd75eb17ad681673 Mon Sep 17 00:00:00 2001 From: liranbg Date: Sun, 12 Oct 2014 05:52:07 +0300 Subject: [PATCH 26/58] interface, schedule&exam --- main/CalendarTab/CalendarManager.cpp | 4 + main/CalendarTab/CalendarManager.h | 2 +- main/CourseTab/coursestablemanager.cpp | 118 ++-- main/LoginTab/loginhandler.cpp | 2 +- main/mainscreen.cpp | 78 ++- main/mainscreen.h | 40 +- main/mainscreen.ui | 554 ++++++++++-------- src/jceConnection/jcesslclient.cpp | 2 +- src/jceData/Calendar/Exams/examDialog.cpp | 157 ++++- src/jceData/Calendar/Exams/examDialog.h | 13 +- src/jceData/Calendar/Exams/examDialog.ui | 13 +- .../coursesSchedule/calendarDialog.cpp | 1 + .../coursesSchedule/calendarDialog.ui | 344 ++++++----- 13 files changed, 761 insertions(+), 567 deletions(-) diff --git a/main/CalendarTab/CalendarManager.cpp b/main/CalendarTab/CalendarManager.cpp index ec2816d..403143c 100644 --- a/main/CalendarTab/CalendarManager.cpp +++ b/main/CalendarTab/CalendarManager.cpp @@ -19,6 +19,10 @@ void CalendarManager::setExamsSchedule(QString html) { examSchePtr->setPage(html); examDialogPtr->initializingDataIntoTable(); +} + +void CalendarManager::showExamDialog() +{ examDialogPtr->show(); } void CalendarManager::exportCalendarCSV() diff --git a/main/CalendarTab/CalendarManager.h b/main/CalendarTab/CalendarManager.h index 182a527..e45430c 100644 --- a/main/CalendarTab/CalendarManager.h +++ b/main/CalendarTab/CalendarManager.h @@ -28,7 +28,7 @@ public: void exportCalendarCSV(); void setCalendar(QString html); void setExamsSchedule(QString html); - + void showExamDialog(); void resetTable() { if (caliSchedPtr != NULL) caliSchedPtr->clearTableItems(); } private: diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index da0d613..c60fa74 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -157,82 +157,84 @@ void coursesTableManager::addRow(const gradeCourse *courseToAdd) c = courseToAdd; if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount() + 1); - i = courseTBL->rowCount()-1; + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; - number = new QTableWidgetItem(); - number->setData(Qt::EditRole, c->getCourseNumInList()); - number->setFlags(number->flags() & ~Qt::ItemIsEditable); + number = new QTableWidgetItem(); + number->setData(Qt::EditRole, c->getCourseNumInList()); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); - year = new QTableWidgetItem(); - year->setData(Qt::EditRole,c->getYear()); - year->setFlags(year->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(); + year->setData(Qt::EditRole,c->getYear()); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); - semester = new QTableWidgetItem(); - semester->setData(Qt::EditRole,c->getSemester()); - semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); + semester = new QTableWidgetItem(); + semester->setData(Qt::EditRole,c->getSemester()); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); - serial = new QTableWidgetItem(); - serial->setData(Qt::EditRole,c->getSerialNum()); - serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole,c->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); - name = new QTableWidgetItem(); - name->setData(Qt::EditRole,c->getName()); - name->setFlags(name->flags() & ~Qt::ItemIsEditable); + name = new QTableWidgetItem(); + name->setData(Qt::EditRole,c->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); - type = new QTableWidgetItem(); - type->setData(Qt::EditRole, c->getType()); - type->setFlags(type->flags() & ~Qt::ItemIsEditable); + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, c->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); - points = new QTableWidgetItem(); - points->setData(Qt::EditRole, c->getPoints()); - points->setFlags(points->flags() & ~Qt::ItemIsEditable); + points = new QTableWidgetItem(); + points->setData(Qt::EditRole, c->getPoints()); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); - hours = new QTableWidgetItem(); - hours->setData(Qt::EditRole, c->getHours()); - hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); + hours = new QTableWidgetItem(); + hours->setData(Qt::EditRole, c->getHours()); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); - grade = new QTableWidgetItem(); - grade->setData(Qt::EditRole,c->getGrade()); + grade = new QTableWidgetItem(); + grade->setData(Qt::EditRole,c->getGrade()); - addition = new QTableWidgetItem(); - addition->setData(Qt::EditRole,c->getAddidtions()); + addition = new QTableWidgetItem(); + addition->setData(Qt::EditRole,c->getAddidtions()); - courseTBL->setItem(i,j++,number); - courseTBL->setItem(i,j++,year); - courseTBL->setItem(i,j++,semester); - courseTBL->setItem(i,j++,serial); - courseTBL->setItem(i,j++,name); - courseTBL->setItem(i,j++,type); - courseTBL->setItem(i,j++,points); - courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j,grade); - if(c->getGrade() < 55 && c->getGrade() != 0) - { - courseTBL->item(i, j)->setBackground(Qt::darkRed); - courseTBL->item(i,j)->setTextColor(Qt::white); - } - else if(55 <= c->getGrade() && c->getGrade() < 70 ) - { - courseTBL->item(i, j)->setBackground(Qt::darkYellow); - courseTBL->item(i,j)->setTextColor(Qt::white); - } -// else if(70 < c->getGrade() && c->getGrade() <= 80 ) -// courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! -// else if(c->getGrade() > 80) -// courseTBL->item(i, j)->setBackground(Qt::green); + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); + courseTBL->setItem(i,j++,serial); + courseTBL->setItem(i,j++,name); + courseTBL->setItem(i,j++,type); + courseTBL->setItem(i,j++,points); + courseTBL->setItem(i,j++,hours); + courseTBL->setItem(i,j,grade); + if(c->getGrade() < 55 && c->getGrade() != 0) + { + courseTBL->item(i, j)->setBackground(Qt::darkRed); + courseTBL->item(i,j)->setTextColor(Qt::white); + } + else if(55 <= c->getGrade() && c->getGrade() < 70 ) + { + courseTBL->item(i, j)->setBackground(Qt::darkYellow); + courseTBL->item(i,j)->setTextColor(Qt::white); + } + // else if(70 < c->getGrade() && c->getGrade() <= 80 ) + // courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! + // else if(c->getGrade() > 80) + // courseTBL->item(i, j)->setBackground(Qt::green); - j++; + j++; - courseTBL->setItem(i,j,addition); + courseTBL->setItem(i,j,addition); } } else { - qCritical() << Q_FUNC_INFO << " no course to load!"; + qCritical() << Q_FUNC_INFO << " no course to load!"; } + courseTBL->resizeColumnsToContents(); + courseTBL->resizeRowsToContents(); } double coursesTableManager::getAvg() @@ -246,8 +248,8 @@ void coursesTableManager::showGraph() { if (gp != NULL) { - qDebug() << Q_FUNC_INFO << " Graph Dialog Opened. gp != NULL"; - this->graph->showGraph(gp); + qDebug() << Q_FUNC_INFO << " Graph Dialog Opened. gp != NULL"; + this->graph->showGraph(gp); } } diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index c0c70e5..84b22d1 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -129,7 +129,7 @@ QString loginHandler::getCurrentPageContect() if (isLoggedInFlag()) parse.setText(jceLog->getPage()); else - throw jceLogin::ERROR_ON_GETTING_INFO; + return ""; return parse.toPlainText(); } int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester) diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 96e7988..67ad197 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -175,7 +175,6 @@ void MainScreen::on_ratesButton_clicked() } QApplication::restoreOverrideCursor(); } - bool MainScreen::checkIfValidDates() { bool flag = false; @@ -199,28 +198,23 @@ void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) this->userLoginSetting->setInfluenceCourseOnly(checked); this->courseTableMgr->influnceCourseChanged(checked); } - void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { ui->spinBoxCoursesFromYear->setValue(arg1); } - void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { ui->spinBoxCoursesToYear->setValue(arg1); } - void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { ui->spinBoxCoursesFromSemester->setValue(arg1%4); } - void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { ui->spinBoxCoursesToSemester->setValue(arg1%4); } - void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) @@ -231,7 +225,6 @@ void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } - void MainScreen::on_clearTableButton_clicked() { qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); @@ -248,6 +241,11 @@ void MainScreen::on_graphButton_clicked() //EVENTS ON CALENDAR TAB void MainScreen::on_examsBtn_clicked() +{ + calendar->showExamDialog(); + +} +void MainScreen::on_getCalendarBtn_clicked() { ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); @@ -256,45 +254,38 @@ void MainScreen::on_examsBtn_clicked() QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting exams...")); - if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting schedule...")); + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - ui->statusBar->showMessage(tr("Done."),1000); + calendar->resetTable(); + ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); page = loginHandel->getCurrentPageContect(); - calendar->setExamsSchedule(page); - ui->progressBar->setValue(100); - qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; - ui->statusBar->showMessage(tr("Done")); - } - else if (status == jceLogin::JCE_NOT_CONNECTED) - { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - } - else - qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; - } - QApplication::restoreOverrideCursor(); -} -void MainScreen::on_getCalendarBtn_clicked() -{ - ui->progressBar->setValue(0); - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QString page; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) - { - ui->statusBar->showMessage(tr("Getting schedule...")); - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + calendar->setCalendar(page); + + qDebug() << Q_FUNC_INFO << "calendar is loaded"; + + //auto getting exam + if (loginHandel->isLoggedInFlag()) { - calendar->resetTable(); - ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); - page = loginHandel->getCurrentPageContect(); - calendar->setCalendar(page); + ui->statusBar->showMessage(tr("Getting exams...")); + if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + { + ui->statusBar->showMessage(tr("Done."),1000); + page = loginHandel->getCurrentPageContect(); + calendar->setExamsSchedule(page); + qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; + } + else if (status == jceLogin::JCE_NOT_CONNECTED) + { + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + } + else + qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; + + ui->progressBar->setValue(100); - qDebug() << Q_FUNC_INFO << "calendar is loaded"; ui->statusBar->showMessage(tr("Done")); } else if (status == jceLogin::JCE_NOT_CONNECTED) @@ -306,7 +297,8 @@ void MainScreen::on_getCalendarBtn_clicked() else qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } - QApplication::restoreOverrideCursor(); + } + QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { diff --git a/main/mainscreen.h b/main/mainscreen.h index 3f9a7f9..116c957 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -27,56 +27,42 @@ public: private slots: - void on_ratesButton_clicked(); - + //Login Tab slots void on_loginButton_clicked(); - + void on_keepLogin_clicked(); void on_usrnmLineEdit_editingFinished(); - void on_actionCredits_triggered(); - + //GPA Tab slots + void on_ratesButton_clicked(); + void on_graphButton_clicked(); void on_clearTableButton_clicked(); - - void on_actionExit_triggered(); - void on_coursesTable_itemChanged(QTableWidgetItem *item); - - void on_keepLogin_clicked(); - - void on_actionHow_To_triggered(); - - void on_getCalendarBtn_clicked(); - void on_checkBoxCoursesInfluence_toggled(bool checked); + //Schedule Tab slots + void on_getCalendarBtn_clicked(); + void on_examsBtn_clicked(); void on_exportToCVSBtn_clicked(); + //Menubar slots + void on_actionCredits_triggered(); + void on_actionExit_triggered(); + void on_actionHow_To_triggered(); void on_actionHebrew_triggered(); - void on_actionEnglish_triggered(); - void on_actionOS_Default_triggered(); + //Main screen general slots void on_spinBoxCoursesFromSemester_valueChanged(int arg1); - void on_spinBoxCoursesFromYear_valueChanged(int arg1); - void on_spinBoxCoursesToYear_valueChanged(int arg1); - void on_spinBoxCoursesToSemester_valueChanged(int arg1); - void on_labelMadeBy_linkActivated(const QString &link); - - void on_graphButton_clicked(); - void on_progressBar_valueChanged(int value); - void on_examsBtn_clicked(); - private: void checkLocale(); - bool checkIfValidDates(); Ui::MainScreen *ui; diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 4e24066..997f0a2 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -48,7 +48,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r - + @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 1 + 0 false @@ -119,7 +119,6 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r #LoginFrame { border: 3px solid rgb(160, 165, 170); border-radius: 40px; - } #loginButton { color: white; @@ -327,21 +326,290 @@ font-size: 15px; 0 - - - - Qt::Horizontal + + + + + 0 + 0 + - - QSizePolicy::Expanding + + #frameTo { + border: 1px solids; + border-style: inset; + border-color: black; + border-radius: 10px; +} - - - 40 - 20 - + + QFrame::StyledPanel - + + QFrame::Raised + + + + 1 + + + 0 + + + 0 + + + 0 + + + 0 + + + 1 + + + + + QLayout::SetDefaultConstraint + + + + + + 0 + 0 + + + + + + + Semester: + + + + + + + 1 + + + 999 + + + 3 + + + + + + + + 0 + 0 + + + + + + + Year: + + + + + + + 2008 + + + 2016 + + + 2015 + + + + + + + + + + 0 + 0 + + + + + + + <html><head/><body><p align="center">To</p></body></html> + + + + + + + + + + + 0 + 0 + + + + #frameBtns { + border: 0px solids; +} + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 5 + + + 0 + + + 0 + + + 0 + + + 9 + + + 0 + + + + + 0 + + + 0 + + + + + 0 + + + -1 + + + + + + 0 + 0 + + + + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> + + + Clear Table + + + + + + + true + + + + 0 + 0 + + + + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> + + + Get GPA + + + false + + + false + + + false + + + + + + + + + #frameMainCourses { + border: 0px solids; +} + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Only Main Courses + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + @@ -353,9 +621,10 @@ font-size: 15px; #frameFrom { - border-width: 1px; + border: 1px solids; border-style: inset; border-color: black; + border-radius: 10px; } @@ -461,223 +730,8 @@ font-size: 15px; - - - - - 0 - 0 - - - - #frameTo { - border-width: 1px; - border-style: inset; - border-color: black; -} - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 1 - - - 0 - - - 0 - - - 0 - - - 0 - - - 1 - - - - - QLayout::SetDefaultConstraint - - - - - - 0 - 0 - - - - - - - Year: - - - - - - - 2008 - - - 2016 - - - 2015 - - - - - - - - 0 - 0 - - - - - - - Semester: - - - - - - - 1 - - - 999 - - - 3 - - - - - - - - - - 0 - 0 - - - - - - - <html><head/><body><p align="center">To</p></body></html> - - - - - - - - - - - 0 - 0 - - - - QFrame::StyledPanel - - - QFrame::Raised - - - - 5 - - - 0 - - - 0 - - - 0 - - - 9 - - - 0 - - - - - true - - - <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> - - - Get GPA - - - - - - - <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> - - - Clear Table - - - - - - - - - - - 0 - 0 - - - - Only Main Courses - - - - - - - - 0 - 0 - - - - Qt::RightToLeft - - - QAbstractItemView::SingleSelection - - - true - - - @@ -738,6 +792,25 @@ font-size: 15px; + + + + + 0 + 0 + + + + Qt::RightToLeft + + + QAbstractItemView::SingleSelection + + + true + + + @@ -782,7 +855,7 @@ font-size: 15px; - Get Schedule + Get Schedule && Exam @@ -823,13 +896,6 @@ font-size: 15px; - - - - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - - - @@ -869,6 +935,13 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: + + + + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> + + + @@ -877,7 +950,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 21 + 22 @@ -968,7 +1041,6 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: spinBoxYear spinBoxSemester getCalendarBtn - exportToCVSBtn diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 2eec393..deb03cd 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -170,7 +170,7 @@ bool jceSSLClient::recieveData(QString *str) disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); str->append(packet); - //qDebug() << *str; //if you want to see the whole packet, unmark me +// qDebug() << *str; //if you want to see the whole packet, unmark me qDebug() << Q_FUNC_INFO << "packet size: " << packetSizeRecieved << "received data lenght: " << str->length(); qDebug() << Q_FUNC_INFO << "return with flag: " << recieveLastPacket; diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp index 4c0ae8d..1a1b84f 100644 --- a/src/jceData/Calendar/Exams/examDialog.cpp +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -13,15 +13,21 @@ examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(par QStringList headLine; //SERIAL, NAME, LECTURER, FIELD, TYPE, FIRST_DATE, FIRST_HOUR_BEGIN, SECOND_DATE, SECOND_HOUR_BEGIN - headLine << tr("Serial") << tr("Course") << tr("Lecturer") << tr("Field") << tr("Type") << tr("First") << tr("Begin") << tr("Second") << tr("Begin"); + headLine << tr("Serial") << tr("Course") << tr("Lecturer") << tr("Field") << tr("Type") << tr("Exam 1 Date") << tr("Starting Hour") << tr("Exam 2 Date") << tr("Starting Hour"); ui->tableWidget->verticalHeader()->setVisible(false); - ui->tableWidget->horizontalHeader()->setVisible(false); + ui->tableWidget->horizontalHeader()->setVisible(true); ui->tableWidget->setColumnCount(EXAM_SCHEDULE_FIELDS); ui->tableWidget->setHorizontalHeaderLabels(headLine); ui->tableWidget->setLayoutDirection(Qt::LayoutDirection::RightToLeft); + ui->tableWidget->setSortingEnabled(false); - this->setModal(true); + this->setModal(true); //always on top + + ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Interactive); + + connect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(upgradeExamsTime(QTableWidgetItem*))); } /** @@ -31,58 +37,151 @@ examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(par */ void examDialog::initializingDataIntoTable() { + disconnect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(upgradeExamsTime(QTableWidgetItem*))); ui->tableWidget->setRowCount(exams->getExamsCounter()); int i=0,j=0; + int year,month,day; //for constructin qdate by setdate QTableWidgetItem *lecturer,*name,*type; QTableWidgetItem *serial; QTableWidgetItem *field; - QDateEdit *firstDate; - QTimeEdit *firstHourbegin; - QDateEdit *secondDate; - QTimeEdit *secondHourbegin; + QTableWidgetItem *firstDate; + QTableWidgetItem *firstHourbegin; + QTableWidgetItem *secondDate; + QTableWidgetItem *secondHourbegin; for (calendarExamCourse * tempExam: exams->getExams()) { j=0; + lecturer = new QTableWidgetItem(); lecturer->setData(Qt::EditRole, tempExam->getLecturer()); + lecturer->setFlags(lecturer->flags() & ~Qt::ItemIsEditable); + name = new QTableWidgetItem(); name->setData(Qt::EditRole, tempExam->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); + type = new QTableWidgetItem(); type->setData(Qt::EditRole, tempExam->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); + serial = new QTableWidgetItem(); serial->setData(Qt::EditRole, tempExam->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + field = new QTableWidgetItem(); field->setData(Qt::EditRole, tempExam->getField()); - firstDate = new QDateEdit(); - firstDate->setDisplayFormat("d/M/yy"); - firstDate->setDate(tempExam->getFirstDate()); - secondDate = new QDateEdit(); - secondDate->setDisplayFormat("d/M/yy"); - secondDate->setDate(tempExam->getSecondDate()); - firstHourbegin = new QTimeEdit(); - firstHourbegin->setTime(tempExam->getFirstHourbegin()); - secondHourbegin = new QTimeEdit(); - secondHourbegin->setTime(tempExam->getSecondHourbegin()); + field->setFlags(field->flags() & ~Qt::ItemIsEditable); + + firstDate = new QTableWidgetItem(); + tempExam->getFirstDate().getDate(&year,&month,&day); + firstDate->setData(Qt::EditRole, QDate(year,month,day).toString("d/M/yy")); + firstDate->setFlags(firstDate->flags() & ~Qt::ItemIsEditable); + + secondDate = new QTableWidgetItem(); + tempExam->getSecondDate().getDate(&year,&month,&day); + secondDate->setData(Qt::EditRole, QDate(year,month,day).toString("d/M/yy")); + secondDate->setFlags(secondDate->flags() & ~Qt::ItemIsEditable); + + firstHourbegin = new QTableWidgetItem(); + firstHourbegin->setData(Qt::EditRole, QTime(tempExam->getFirstHourbegin().hour(),tempExam->getFirstHourbegin().minute()).toString("hh:mm")); + + secondHourbegin = new QTableWidgetItem(); + secondHourbegin->setData(Qt::EditRole, QTime(tempExam->getSecondHourbegin().hour(),tempExam->getSecondHourbegin().minute()).toString("hh:mm")); + - ui->tableWidget->setItem(i,j++,lecturer); - ui->tableWidget->setItem(i,j++,name); - ui->tableWidget->setItem(i,j++,type); ui->tableWidget->setItem(i,j++,serial); + ui->tableWidget->setItem(i,j++,name); + ui->tableWidget->setItem(i,j++,lecturer); ui->tableWidget->setItem(i,j++,field); - ui->tableWidget->setCellWidget(i,j++,firstDate); - ui->tableWidget->setCellWidget(i,j++,firstHourbegin); - ui->tableWidget->setCellWidget(i,j++,secondDate); - ui->tableWidget->setCellWidget(i,j++,secondHourbegin); + ui->tableWidget->setItem(i,j++,type); + ui->tableWidget->setItem(i,j++,firstDate); + ui->tableWidget->setItem(i,j++,firstHourbegin); + ui->tableWidget->setItem(i,j++,secondDate); + ui->tableWidget->setItem(i,j++,secondHourbegin); i++; } - ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - - this->setMinimumHeight(ui->tableWidget->height()); - this->setMinimumWidth(ui->tableWidget->width()); + resetGeo(); + connect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(upgradeExamsTime(QTableWidgetItem*))); } examDialog::~examDialog() { delete ui; } + +/** + * @brief examDialog::upgradeExamsTime + * gets an item and check if its value is valid by time. + * currently we allow only modification of time + * + * @param item - tablewidet from ui->tablewidet. + * @return true if has been changed. false otherwise + */ +bool examDialog::upgradeExamsTime(QTableWidgetItem *item) +{ + QString text; + int row,col; + text = item->text(); + row = item->row(); + col = item->column(); + if (ui->tableWidget->item(row,calendarExamCourse::CourseScheme::SERIAL) == NULL) + return true; + + int serialCourse = ui->tableWidget->item(row,calendarExamCourse::CourseScheme::SERIAL)->text().toInt(); + for (calendarExamCourse * tempExam: exams->getExams()) + { + if (tempExam->getSerialNum() == serialCourse) + { + if (QTime::fromString(text).isValid()) + { + if (col == calendarExamCourse::CourseScheme::FIRST_HOUR_BEGIN) + tempExam->setFirstHourbegin(QTime::fromString(text)); + else if (col == calendarExamCourse::CourseScheme::SECOND_HOUR_BEGIN) + tempExam->setSecondHourbegin(QTime::fromString(text)); + else + qCritical() << Q_FUNC_INFO; //is doesnt need to get here. we allow modifications only at hours + return true; + } + else + { + if (col == calendarExamCourse::CourseScheme::FIRST_HOUR_BEGIN) + ui->tableWidget->item(row,col)->setData(Qt::EditRole, QTime(tempExam->getFirstHourbegin().hour(),tempExam->getFirstHourbegin().minute()).toString("hh:mm")); + else if (col == calendarExamCourse::CourseScheme::SECOND_HOUR_BEGIN) + ui->tableWidget->item(row,col)->setData(Qt::EditRole, QTime(tempExam->getSecondHourbegin().hour(),tempExam->getSecondHourbegin().minute()).toString("hh:mm")); + else + qCritical() << Q_FUNC_INFO; //is doesnt need to get here. we allow modifications only at hours + qWarning() << Q_FUNC_INFO << "missmatch data"; + QMessageBox::critical(this,tr("Error"),tr("Missmatching data.\nFormat: hh:mm\nIn Example: 08:25 or 12:05")); + return false; + } + } + } + return false; +} + +/** + * @brief examDialog::resetGeo + * Resizes Dialog according to widgets and table content + */ +void examDialog::resetGeo() +{ + + ui->tableWidget->resizeColumnsToContents(); + ui->tableWidget->resizeRowsToContents(); + + int mWidth=0,mHeight=0; + mHeight += ui->tableWidget->horizontalHeader()->height() + 4; + for (int i=0,j=0; i < ui->tableWidget->rowCount() && j < ui->tableWidget->columnCount();++i,++j) + { + mWidth += ui->tableWidget->columnWidth(j); + mHeight += ui->tableWidget->rowHeight(i) + 4; + + } + mHeight += ui->buttonBox->height() + 4; + mHeight += ui->labelHeader->height() + 4; + + + this->setMinimumHeight(mHeight); +// this->setMaximumHeight(mHeight); + +} diff --git a/src/jceData/Calendar/Exams/examDialog.h b/src/jceData/Calendar/Exams/examDialog.h index 24aef6b..04bc9d3 100644 --- a/src/jceData/Calendar/Exams/examDialog.h +++ b/src/jceData/Calendar/Exams/examDialog.h @@ -2,8 +2,10 @@ #define EXAMDIALOG_H #include -#include - +#include +#include +#include +#include #include "calendarExam.h" namespace Ui { @@ -29,7 +31,14 @@ public: void initializingDataIntoTable(); ~examDialog(); +private slots: + + bool upgradeExamsTime(QTableWidgetItem* item); + private: + + void resetGeo(); + Ui::examDialog *ui; calendarExam * exams; }; diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index c43802d..53829eb 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -7,7 +7,7 @@ 0 0 810 - 257 + 273 @@ -21,7 +21,7 @@ - + 0 @@ -34,7 +34,14 @@ - + + + + 0 + 0 + + + diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp index 7a29c13..bf36e36 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp @@ -70,6 +70,7 @@ void CalendarDialog::on_calEnd_selectionChanged() { changeLabeStatusIcon(false); ui->lbl_status->setText(tr("The end of the semester can NOT be equal or before the semester begin.")); + this->isOK = false; } else diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui index f78317d..863d278 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui @@ -6,177 +6,199 @@ 0 0 - 631 - 281 + 610 + 310 - + 0 0 + + + 0 + 0 + + Dates Dialog - - - - 10 - 10 - 613 - 263 - - - - - - - <body><p><span style=" font-size:9pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p> - - - - - - - - - - - - - Semester Starts At: - - - - - - - Semester Ends At: - - - - - - - - - - - - - - Qt::ImhNone - - - - 2014 - 10 - 26 - - - - - 2000 - 9 - 14 - - - - - 2080 - 12 - 31 - - - - true - - - QCalendarWidget::NoVerticalHeader - - - - - - - - 2015 - 2 - 1 - - - - - 2000 - 9 - 14 - - - - - 2080 - 12 - 31 - - - - true - - - QCalendarWidget::NoVerticalHeader - - - - - - - - - - - - - - - - - - - - <b>Please chose your dates correctly</b> - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - + + + + + + + <html><head/><body><p align="center"><span style=" font-size:14pt; font-weight:600;">Schedule Exportation</span></p></body></html> + + + + + + + + + + + <html><head/><body><p align="center">Semester Starts At:</p></body></html> + + + + + + + + 0 + 0 + + + + Qt::ImhNone + + + + 2014 + 10 + 26 + + + + + 2000 + 9 + 14 + + + + + 2080 + 12 + 31 + + + + true + + + QCalendarWidget::NoVerticalHeader + + + + + + + + + + + <html><head/><body><p align="center">Semester Ends At:</p></body></html> + + + + + + + + 0 + 0 + + + + + 2015 + 2 + 1 + + + + + 2000 + 9 + 14 + + + + + 2080 + 12 + 31 + + + + true + + + QCalendarWidget::NoVerticalHeader + + + + + + + + + + + <html><head/><body><p align="center"><span style=" font-size:12pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p></body></html> + + + + + + + + + + + + + + + + <b>Please chose your dates correctly</b> + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Include Exams + + + true + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + From bec16503b700f911065519833208146f42065e65 Mon Sep 17 00:00:00 2001 From: liranbg Date: Sun, 12 Oct 2014 07:03:34 +0300 Subject: [PATCH 27/58] Using TO-DO plugin in QT. --- main/CourseTab/coursestablemanager.cpp | 5 ++++- main/main.cpp | 2 ++ main/mainscreen.cpp | 2 +- src/appDatabase/jce_logger.cpp | 2 +- src/jceData/Calendar/Exams/examDialog.cpp | 3 +++ src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp | 4 +++- src/jceData/Grades/graph/gradegraph.cpp | 5 ++++- src/jceData/Grades/graph/qcustomplot.cpp | 2 +- 8 files changed, 19 insertions(+), 6 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index c60fa74..f49bf87 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -1,5 +1,8 @@ #include "coursestablemanager.h" - +/* + * TODO: revert gpa to origin + * + */ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { this->gp = NULL; diff --git a/main/main.cpp b/main/main.cpp index a57848e..8901e01 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -5,6 +5,8 @@ #include "../src/appDatabase/savedata.h" #include "../src/appDatabase/jce_logger.h" +//TODO: Project todo list +//update translation, update site spelling, release notes, update help int main(int argc, char *argv[]) { #ifdef QT_DEBUG // Incase QtCreator is in Debug mode all qDebug messages will go to terminal diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 67ad197..45d3390 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -1,6 +1,6 @@ #include "mainscreen.h" #include "ui_mainscreen.h" - +//TODO: busy flag to aboid overload request MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) { diff --git a/src/appDatabase/jce_logger.cpp b/src/appDatabase/jce_logger.cpp index 41e3f6a..ca0ab24 100644 --- a/src/appDatabase/jce_logger.cpp +++ b/src/appDatabase/jce_logger.cpp @@ -8,7 +8,7 @@ * Message types cam be: * * - DEBUG - * - WARNING + * - WARNINGS * - CRITICAL * - FATAL * diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp index 1a1b84f..2214363 100644 --- a/src/jceData/Calendar/Exams/examDialog.cpp +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -1,5 +1,8 @@ #include "examDialog.h" #include "ui_examDialog.h" +/* + *TODO: exam revert, add to csv exportation, dialog size + */ /** * @brief examDialog::examDialog * @param parent diff --git a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp index 38d6bdc..6017097 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp @@ -1,5 +1,7 @@ #include "calendarSchedule.h" - +/* + * BUG: fix resizing when showing error on dates validation + */ calendarSchedule::calendarSchedule(QWidget *parent) : QTableWidget(parent) { QStringList days,hours; diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 70ffcc3..836e548 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -1,6 +1,9 @@ #include "gradegraph.h" #include "ui_gradegraph.h" - +/* + * TODO: make graph understandable + * BUG: graph bug when theres small range of years + */ gradegraph::gradegraph(QWidget *parent) : QDialog(parent), ui(new Ui::gradegraph) diff --git a/src/jceData/Grades/graph/qcustomplot.cpp b/src/jceData/Grades/graph/qcustomplot.cpp index ad267b6..042f1c7 100644 --- a/src/jceData/Grades/graph/qcustomplot.cpp +++ b/src/jceData/Grades/graph/qcustomplot.cpp @@ -14088,7 +14088,7 @@ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) QList maps = colorMaps(); QCPRange newRange; bool haveRange = false; - int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) + int sign = 0; // should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) if (mDataScaleType == QCPAxis::stLogarithmic) sign = (mDataRange.upper < 0 ? -1 : 1); for (int i=0; i Date: Sun, 12 Oct 2014 16:48:42 +0300 Subject: [PATCH 28/58] graph view, parent pointer to table --- main/CourseTab/coursestablemanager.cpp | 347 ++++++++-------- main/mainscreen.cpp | 513 ++++++++++++------------ main/mainscreen.ui | 7 +- src/jceData/Grades/graph/gradegraph.cpp | 237 ++++++----- src/jceData/Grades/graph/gradegraph.h | 5 + src/jceData/Grades/graph/gradegraph.ui | 12 +- 6 files changed, 593 insertions(+), 528 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index f49bf87..6c7404c 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -5,46 +5,46 @@ */ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { - this->gp = NULL; - this->us = usrPtr; - this->courseTBL = ptr; + this->gp = NULL; + this->us = usrPtr; + this->courseTBL = ptr; - /* + /* * Initilizing Table */ - courseTBL->setRowCount(0); - courseTBL->setColumnCount(COURSE_FIELDS); - QStringList mz; - mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); - courseTBL->setHorizontalHeaderLabels(mz); - courseTBL->verticalHeader()->setVisible(false); - courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); - courseTBL->setShowGrid(true); - courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); + courseTBL->setRowCount(0); + courseTBL->setColumnCount(COURSE_FIELDS); + QStringList mz; + mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); + courseTBL->setHorizontalHeaderLabels(mz); + courseTBL->verticalHeader()->setVisible(false); + courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); + courseTBL->setShowGrid(true); + courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); - graph = new gradegraph(NULL); + graph = new gradegraph(ptr); } coursesTableManager::~coursesTableManager() { - courseTBL = NULL; - delete gp; - gp = NULL; + courseTBL = NULL; + delete gp; + gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { - for (gradeCourse *c: gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { - if (us->getInfluenceCourseOnly()) + if (us->getInfluenceCourseOnly()) { - if (isCourseInfluence(c)) - addRow(c); - } - else + if (isCourseInfluence(c)) addRow(c); + } + else + addRow(c); } } /** @@ -53,9 +53,9 @@ void coursesTableManager::insertJceCoursesIntoTable() */ void coursesTableManager::setCoursesList(QString &html) { - if (gp != NULL) - gp->~GradePage(); - gp = new GradePage(html); + if (gp != NULL) + gp->~GradePage(); + gp = new GradePage(html); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it @@ -67,81 +67,81 @@ void coursesTableManager::setCoursesList(QString &html) bool coursesTableManager::changes(QString change, int row, int col) { - bool isNumFlag = true; - if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) - return true; + bool isNumFlag = true; + if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) + return true; - int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); - for (gradeCourse *c: gp->getCourses()) + int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); + for (gradeCourse *c: gp->getCourses()) { - if (c->getSerialNum() == serialCourse) + if (c->getSerialNum() == serialCourse) { - switch (col) + switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): - c->setCourseNumInList(change.toInt()); - break; + c->setCourseNumInList(change.toInt()); + break; case (gradeCourse::CourseScheme::YEAR): - c->setYear(change.toInt()); - break; + c->setYear(change.toInt()); + break; case (gradeCourse::CourseScheme::SEMESTER): - c->setSemester(change.toInt()); - break; + c->setSemester(change.toInt()); + break; case (gradeCourse::CourseScheme::NAME): - c->setName(change); - break; + c->setName(change); + break; case (gradeCourse::CourseScheme::TYPE): - c->setType(change); - break; + c->setType(change); + break; case (gradeCourse::CourseScheme::POINTS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); - } + } else - c->setPoints(change.toDouble()); + c->setPoints(change.toDouble()); break; - } + } case (gradeCourse::CourseScheme::HOURS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getHours())); - } + } else - c->setHours(change.toDouble()); + c->setHours(change.toDouble()); break; - } + } case (gradeCourse::CourseScheme::GRADE): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } + } else - { + { if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) - c->setGrade(change.toDouble()); + c->setGrade(change.toDouble()); else - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } break; - } + } case (gradeCourse::CourseScheme::ADDITION): - c->setAdditions(change); - break; + c->setAdditions(change); + break; } - break; + break; } } - return isNumFlag; + return isNumFlag; } /** @@ -150,183 +150,190 @@ bool coursesTableManager::changes(QString change, int row, int col) */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { - int i=1,j=1; + int i=1,j=1; - j = 0; - QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; - const gradeCourse * c; - if (courseToAdd != NULL) + j = 0; + QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; + const gradeCourse * c; + if (courseToAdd != NULL) { - c = courseToAdd; - if (!isCourseAlreadyInserted(c->getSerialNum())) + c = courseToAdd; + if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount() + 1); - i = courseTBL->rowCount()-1; + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; - number = new QTableWidgetItem(); - number->setData(Qt::EditRole, c->getCourseNumInList()); - number->setFlags(number->flags() & ~Qt::ItemIsEditable); + number = new QTableWidgetItem(); + number->setData(Qt::EditRole, c->getCourseNumInList()); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); - year = new QTableWidgetItem(); - year->setData(Qt::EditRole,c->getYear()); - year->setFlags(year->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(); + year->setData(Qt::EditRole,c->getYear()); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); - semester = new QTableWidgetItem(); - semester->setData(Qt::EditRole,c->getSemester()); - semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); + semester = new QTableWidgetItem(); + semester->setData(Qt::EditRole,c->getSemester()); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); - serial = new QTableWidgetItem(); - serial->setData(Qt::EditRole,c->getSerialNum()); - serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole,c->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); - name = new QTableWidgetItem(); - name->setData(Qt::EditRole,c->getName()); - name->setFlags(name->flags() & ~Qt::ItemIsEditable); + name = new QTableWidgetItem(); + name->setData(Qt::EditRole,c->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); - type = new QTableWidgetItem(); - type->setData(Qt::EditRole, c->getType()); - type->setFlags(type->flags() & ~Qt::ItemIsEditable); + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, c->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); - points = new QTableWidgetItem(); - points->setData(Qt::EditRole, c->getPoints()); - points->setFlags(points->flags() & ~Qt::ItemIsEditable); + points = new QTableWidgetItem(); + points->setData(Qt::EditRole, c->getPoints()); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); - hours = new QTableWidgetItem(); - hours->setData(Qt::EditRole, c->getHours()); - hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); + hours = new QTableWidgetItem(); + hours->setData(Qt::EditRole, c->getHours()); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); - grade = new QTableWidgetItem(); - grade->setData(Qt::EditRole,c->getGrade()); + grade = new QTableWidgetItem(); + // grade->setData(Qt::EditRole,c->getGrade()); //BUG good for sorting, the problem is when you edit -> the cell indicator disappear + grade->setText(QString::number(c->getGrade())); - addition = new QTableWidgetItem(); - addition->setData(Qt::EditRole,c->getAddidtions()); + addition = new QTableWidgetItem(); + addition->setData(Qt::EditRole,c->getAddidtions()); - courseTBL->setItem(i,j++,number); - courseTBL->setItem(i,j++,year); - courseTBL->setItem(i,j++,semester); - courseTBL->setItem(i,j++,serial); - courseTBL->setItem(i,j++,name); - courseTBL->setItem(i,j++,type); - courseTBL->setItem(i,j++,points); - courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j,grade); - if(c->getGrade() < 55 && c->getGrade() != 0) + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); + courseTBL->setItem(i,j++,serial); + courseTBL->setItem(i,j++,name); + courseTBL->setItem(i,j++,type); + courseTBL->setItem(i,j++,points); + courseTBL->setItem(i,j++,hours); + courseTBL->setItem(i,j,grade); + + //FIXME : make it a function, add it when cell has changed + if(c->getGrade() < 55 && c->getGrade() != 0) { - courseTBL->item(i, j)->setBackground(Qt::darkRed); - courseTBL->item(i,j)->setTextColor(Qt::white); + courseTBL->item(i, j)->setBackground(Qt::darkRed); + courseTBL->item(i,j)->setTextColor(Qt::white); } - else if(55 <= c->getGrade() && c->getGrade() < 70 ) + else if(55 <= c->getGrade() && c->getGrade() < 70 ) { - courseTBL->item(i, j)->setBackground(Qt::darkYellow); - courseTBL->item(i,j)->setTextColor(Qt::white); + courseTBL->item(i, j)->setBackground(Qt::darkYellow); + courseTBL->item(i,j)->setTextColor(Qt::white); } - // else if(70 < c->getGrade() && c->getGrade() <= 80 ) - // courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! - // else if(c->getGrade() > 80) - // courseTBL->item(i, j)->setBackground(Qt::green); + // else if(70 < c->getGrade() && c->getGrade() <= 80 ) + // courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! + // else if(c->getGrade() > 80) + // courseTBL->item(i, j)->setBackground(Qt::green); - j++; + j++; - courseTBL->setItem(i,j,addition); + courseTBL->setItem(i,j,addition); } } - else + else { - qCritical() << Q_FUNC_INFO << " no course to load!"; + qCritical() << Q_FUNC_INFO << " no course to load!"; } - courseTBL->resizeColumnsToContents(); - courseTBL->resizeRowsToContents(); + courseTBL->resizeColumnsToContents(); + courseTBL->resizeRowsToContents(); } double coursesTableManager::getAvg() { - if (this->gp != NULL) - return gp->getAvg(); - return 0; + if (this->gp != NULL) + return gp->getAvg(); + return 0; } void coursesTableManager::showGraph() { - if (gp != NULL) + qDebug() << Q_FUNC_INFO; + if (gp != NULL) { - qDebug() << Q_FUNC_INFO << " Graph Dialog Opened. gp != NULL"; - this->graph->showGraph(gp); + this->graph->showGraph(gp); + } + else + { + qWarning() << Q_FUNC_INFO << "open with null grade page"; } } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { - if (ignoreCourseStatus) + if (ignoreCourseStatus) { - int i = 0; - while (i < courseTBL->rowCount()) + int i = 0; + while (i < courseTBL->rowCount()) { - if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) - courseTBL->removeRow(i--); - i++; + if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) + courseTBL->removeRow(i--); + i++; } } - else + else { - if (this->gp != NULL) - for (gradeCourse *c: gp->getCourses()) - { - if (!(isCourseAlreadyInserted(c->getSerialNum()))) - if (c->getPoints() == 0) - addRow(c); - } + if (this->gp != NULL) + for (gradeCourse *c: gp->getCourses()) + { + if (!(isCourseAlreadyInserted(c->getSerialNum()))) + if (c->getPoints() == 0) + addRow(c); + } } } void coursesTableManager::clearTable() { - if (courseTBL->rowCount() == 0) - return; + if (courseTBL->rowCount() == 0) + return; - int i = 0; //starting point - while (courseTBL->rowCount() > i) + int i = 0; //starting point + while (courseTBL->rowCount() > i) { - gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); - courseTBL->removeRow(i); + gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); + courseTBL->removeRow(i); } - gp = NULL; - courseTBL->repaint(); + gp = NULL; + courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { - QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); - for (gradeCourse *c: gp->getCourses()) + QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); + for (gradeCourse *c: gp->getCourses()) { - if (c->getSerialNum() == courseSerial.toDouble()) - return c; + if (c->getSerialNum() == courseSerial.toDouble()) + return c; } - return NULL; + return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { - int i; - for (i = courseTBL->rowCount(); i >= 0; --i) + int i; + for (i = courseTBL->rowCount(); i >= 0; --i) { - if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) + if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { - QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); - if (QString::number(courseID) == courseSerial) - return true; + QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); + if (QString::number(courseID) == courseSerial) + return true; } } - return false; + return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { - if (courseToCheck->getPoints() > 0) - return true; - return false; + if (courseToCheck->getPoints() > 0) + return true; + return false; } diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 45d3390..b344918 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -1,416 +1,417 @@ #include "mainscreen.h" #include "ui_mainscreen.h" -//TODO: busy flag to aboid overload request +//TODO: busy flag to avoid overload request MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) { - ui->setupUi(this); + ui->setupUi(this); - ui->labelMadeBy->setOpenExternalLinks(true); + ui->labelMadeBy->setOpenExternalLinks(true); - //Login Tab - iconPix.load(":/icons/iconX.png"); - ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - ui->labelUsrInputStatus->setPixmap(iconPix); - ui->labelPswInputStatus->setPixmap(iconPix); + //Login Tab + iconPix.load(":/icons/iconX.png"); + ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); + ui->labelUsrInputStatus->setPixmap(iconPix); + ui->labelPswInputStatus->setPixmap(iconPix); - //StatusBar & progressbar - ui->progressBar->setFixedHeight(STATUS_ICON_HEIGH); - ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); - ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH+5); - ui->statusBar->showMessage(tr("Ready")); + //StatusBar & progressbar + ui->progressBar->setFixedHeight(STATUS_ICON_HEIGH); + ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); + ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH+5); + ui->statusBar->showMessage(tr("Ready")); - //GPA Tab - ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); + //GPA Tab + ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); - //Pointer allocating - qDebug() << Q_FUNC_INFO << "Allocating pointers"; - this->userLoginSetting = new user("",""); - this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); - this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); - this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); - this->data = new SaveData(); + //Pointer allocating + qDebug() << Q_FUNC_INFO << "Allocating pointers"; + this->userLoginSetting = new user("",""); + this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); + this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); + this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); + this->data = new SaveData(); - //check login File - if (data->isSaved()) + //check login File + if (data->isSaved()) { - qDebug() << Q_FUNC_INFO << "Loading data from file"; - ui->usrnmLineEdit->setText(data->getUsername()); - ui->pswdLineEdit->setText(data->getPassword()); - ui->keepLogin->setChecked(true); + qDebug() << Q_FUNC_INFO << "Loading data from file"; + ui->usrnmLineEdit->setText(data->getUsername()); + ui->pswdLineEdit->setText(data->getPassword()); + ui->keepLogin->setChecked(true); } - //language - qDebug() << Q_FUNC_INFO << "Checking locale"; - checkLocale(); - ui->statusBar->repaint(); - qDebug() << Q_FUNC_INFO << "Ready."; + //language + qDebug() << Q_FUNC_INFO << "Checking locale"; + checkLocale(); + ui->statusBar->repaint(); + qDebug() << Q_FUNC_INFO << "Ready."; - //set the progress bar to be invisible (It will show only if value !=0 or !=100) - ui->progressBar->setVisible(false); + //set the progress bar to be invisible (It will show only if value !=0 or !=100) + ui->progressBar->setVisible(false); } MainScreen::~MainScreen() { - delete calendar; - delete courseTableMgr; - delete userLoginSetting; - delete loginHandel; - delete data; - delete ui; + delete calendar; + delete courseTableMgr; + delete userLoginSetting; + delete loginHandel; + delete data; + delete ui; } //EVENTS ON LOGIN TAB void MainScreen::on_loginButton_clicked() { - ui->progressBar->setValue(0); - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) { - if (ui->usrnmLineEdit->text().isEmpty()) + if (ui->usrnmLineEdit->text().isEmpty()) { - ui->labelUsrInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "username input is empty"; + ui->labelUsrInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "username input is empty"; } - else - ui->labelUsrInputStatus->setVisible(false); - if (ui->pswdLineEdit->text().isEmpty()) - { - ui->labelPswInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "password input is empty"; - } - else - ui->labelPswInputStatus->setVisible(false); - return; - } - else - { + else ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - } - qDebug() << Q_FUNC_INFO << "login session start"; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) - { - ui->progressBar->setValue(100); - qDebug() << Q_FUNC_INFO << "login session end with true"; - ui->pswdLineEdit->setDisabled(true); - ui->usrnmLineEdit->setDisabled(true); - if (ui->keepLogin->isChecked()) + if (ui->pswdLineEdit->text().isEmpty()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + ui->labelPswInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "password input is empty"; + } + else + ui->labelPswInputStatus->setVisible(false); + return; + } + else + { + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); + } + qDebug() << Q_FUNC_INFO << "login session start"; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) + { + ui->progressBar->setValue(100); + qDebug() << Q_FUNC_INFO << "login session end with true"; + ui->pswdLineEdit->setDisabled(true); + ui->usrnmLineEdit->setDisabled(true); + if (ui->keepLogin->isChecked()) + { + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } } - else + else { - qDebug() << Q_FUNC_INFO << "login session end with false"; - ui->pswdLineEdit->setDisabled(false); - ui->usrnmLineEdit->setDisabled(false); + qDebug() << Q_FUNC_INFO << "login session end with false"; + ui->pswdLineEdit->setDisabled(false); + ui->usrnmLineEdit->setDisabled(false); } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_keepLogin_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (ui->keepLogin->isChecked()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } - else - data->reset(); + else + data->reset(); } void MainScreen::on_usrnmLineEdit_editingFinished() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); } //EVENTS ON GPA TAB void MainScreen::on_ratesButton_clicked() { - ui->progressBar->setValue(0); - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (!checkIfValidDates()) + + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (!checkIfValidDates()) { - qWarning() << Q_FUNC_INFO << "Invalid dates! return"; - QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); - return; + qWarning() << Q_FUNC_INFO << "Invalid dates! return"; + QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); + return; } - QString pageString; - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + QString pageString; + int status = 0; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting grades...")); - if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), - ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), - ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting grades...")); + if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), + ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), + ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - qDebug() << Q_FUNC_INFO << "grade page is ready"; - ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); - pageString = loginHandel->getCurrentPageContect(); - courseTableMgr->setCoursesList(pageString); - courseTableMgr->insertJceCoursesIntoTable(); - ui->progressBar->setValue(100); - ui->statusBar->showMessage(tr("Done")); + qDebug() << Q_FUNC_INFO << "grade page is ready"; + ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); + pageString = loginHandel->getCurrentPageContect(); + courseTableMgr->setCoursesList(pageString); + courseTableMgr->insertJceCoursesIntoTable(); + ui->progressBar->setValue(100); + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else + else { - qCritical() << Q_FUNC_INFO << "grade get ended with" << status; + qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } bool MainScreen::checkIfValidDates() { - bool flag = false; - if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) + bool flag = false; + if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) { - //doesnt matter what is the semester, its valid! + //doesnt matter what is the semester, its valid! + flag = true; + } + else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) + { + //semester from must be equal or less than to semester + if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) flag = true; } - else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) - { - //semester from must be equal or less than to semester - if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) - flag = true; - } - return flag; + return flag; } void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) { - qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; - this->userLoginSetting->setInfluenceCourseOnly(checked); - this->courseTableMgr->influnceCourseChanged(checked); + qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; + this->userLoginSetting->setInfluenceCourseOnly(checked); + this->courseTableMgr->influnceCourseChanged(checked); } void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { - ui->spinBoxCoursesFromYear->setValue(arg1); + ui->spinBoxCoursesFromYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { - ui->spinBoxCoursesToYear->setValue(arg1); + ui->spinBoxCoursesToYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { - ui->spinBoxCoursesFromSemester->setValue(arg1%4); + ui->spinBoxCoursesFromSemester->setValue(arg1%4); } void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { - ui->spinBoxCoursesToSemester->setValue(arg1%4); + ui->spinBoxCoursesToSemester->setValue(arg1%4); } void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { - if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) - ui->avgLCD->display(courseTableMgr->getAvg()); - else + if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) + ui->avgLCD->display(courseTableMgr->getAvg()); + else { - qWarning() << Q_FUNC_INFO << "missmatch data"; - QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); + qWarning() << Q_FUNC_INFO << "missmatch data"; + QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } void MainScreen::on_clearTableButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - courseTableMgr->clearTable(); - ui->avgLCD->display(courseTableMgr->getAvg()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + courseTableMgr->clearTable(); + ui->avgLCD->display(courseTableMgr->getAvg()); } void MainScreen::on_graphButton_clicked() { - qDebug() << "Show Graph button clicked"; - courseTableMgr->showGraph(); + qDebug() << Q_FUNC_INFO; + courseTableMgr->showGraph(); } //EVENTS ON CALENDAR TAB void MainScreen::on_examsBtn_clicked() { - calendar->showExamDialog(); + calendar->showExamDialog(); } void MainScreen::on_getCalendarBtn_clicked() { - ui->progressBar->setValue(0); - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QString page; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + ui->progressBar->setValue(0); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + int status = 0; + QString page; + QApplication::setOverrideCursor(Qt::WaitCursor); + if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting schedule...")); - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting schedule...")); + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - calendar->resetTable(); - ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); - page = loginHandel->getCurrentPageContect(); - calendar->setCalendar(page); + calendar->resetTable(); + ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); + page = loginHandel->getCurrentPageContect(); + calendar->setCalendar(page); - qDebug() << Q_FUNC_INFO << "calendar is loaded"; + qDebug() << Q_FUNC_INFO << "calendar is loaded"; - //auto getting exam - if (loginHandel->isLoggedInFlag()) + //auto getting exam + if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting exams...")); - if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + ui->statusBar->showMessage(tr("Getting exams...")); + if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - ui->statusBar->showMessage(tr("Done."),1000); - page = loginHandel->getCurrentPageContect(); - calendar->setExamsSchedule(page); - qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; + ui->statusBar->showMessage(tr("Done."),1000); + page = loginHandel->getCurrentPageContect(); + calendar->setExamsSchedule(page); + qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else - qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; + else + qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; - ui->progressBar->setValue(100); - ui->statusBar->showMessage(tr("Done")); + ui->progressBar->setValue(100); + ui->statusBar->showMessage(tr("Done")); } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); } - else - qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; + else + qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } } - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (loginHandel->isLoggedInFlag()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (loginHandel->isLoggedInFlag()) { - this->calendar->exportCalendarCSV(); + this->calendar->exportCalendarCSV(); } } //EVENTS ON MENU BAR void MainScreen::on_actionCredits_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::about(this, "About", - "Jce Manager v1.0.0

                  " - +tr("License:")+ - "
                  GNU LESSER GENERAL PUBLIC LICENSE V2.1
                  " - +"
                  "+ - "JceManager Repository"+ - "

                  " - +tr("Powered By: ")+ - " Jce Connection

                  " - +tr("Developed By")+ - ":" - ); + qDebug() << Q_FUNC_INFO; + QMessageBox::about(this, "About", + "Jce Manager v1.0.0

                  " + +tr("License:")+ + "
                  GNU LESSER GENERAL PUBLIC LICENSE V2.1
                  " + +"
                  "+ + "JceManager Repository"+ + "

                  " + +tr("Powered By: ")+ + " Jce Connection

                  " + +tr("Developed By")+ + ":" + ); } void MainScreen::on_actionExit_triggered() { - qDebug() << Q_FUNC_INFO; - exit(0); + qDebug() << Q_FUNC_INFO; + exit(0); } void MainScreen::on_actionHow_To_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::information(this,"How To", - "" - +tr("Help Guide")+ - "
                    " - +tr("
                  • Login:
                    • Type your username and password and click Login.
                    • Once you are connected, you will see a green ball in the right buttom panel.
                  • ") - +tr("
                  • Getting GPA sheet
                    • Click on GPA Tab
                    • Select your dates and click on Add
                  • ") - +tr("
                  • Average Changing
                    • Change one of your grade and see the average in the buttom panel changing.
                  • ") - +tr("
                  • Getting Calendar
                    • Click on Calendar Tab
                    • Select your dates and click on Get Calendar
                  • ") - +tr("
                  • For exporting your calendar to a .CSV file:
                    • Do previous step and continue to next step
                    • Click on Export to CSV
                    • Select your dates and click OK
                    • Once you're Done, go on your calendar and import your csv file
                    • ")+ - "

                      " - +tr("For more information, please visit us at: Jce Manager site")); + qDebug() << Q_FUNC_INFO; + QMessageBox::information(this,"How To", + "" + +tr("Help Guide")+ + "
                        " + +tr("
                      • Login:
                        • Type your username and password and click Login.
                        • Once you are connected, you will see a green ball in the right buttom panel.
                      • ") + +tr("
                      • Getting GPA sheet
                        • Click on GPA Tab
                        • Select your dates and click on Add
                      • ") + +tr("
                      • Average Changing
                        • Change one of your grade and see the average in the buttom panel changing.
                      • ") + +tr("
                      • Getting Calendar
                        • Click on Calendar Tab
                        • Select your dates and click on Get Calendar
                      • ") + +tr("
                      • For exporting your calendar to a .CSV file:
                        • Do previous step and continue to next step
                        • Click on Export to CSV
                        • Select your dates and click OK
                        • Once you're Done, go on your calendar and import your csv file
                        • ")+ + "

                          " + +tr("For more information, please visit us at: Jce Manager site")); } void MainScreen::on_actionHebrew_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionEnglish->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; - data->setLocal("he"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionEnglish->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; + data->setLocal("he"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionHebrew->setChecked(true); + else + ui->actionHebrew->setChecked(true); } void MainScreen::on_actionEnglish_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to English"; - data->setLocal("en"); - QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to English"; + data->setLocal("en"); + QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionEnglish->setChecked(true); + else + ui->actionEnglish->setChecked(true); } void MainScreen::on_actionOS_Default_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionEnglish->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; - data->setLocal("default"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionEnglish->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; + data->setLocal("default"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionOS_Default->setChecked(true); + else + ui->actionOS_Default->setChecked(true); } void MainScreen::checkLocale() { - if(data->getLocal() == "en") + if(data->getLocal() == "en") { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(true); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(true); }else if(data->getLocal() == "he"){ - ui->actionHebrew->setChecked(true); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(true); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(false); }else{ - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(true); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(true); + ui->actionEnglish->setChecked(false); } } void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { - qDebug() << Q_FUNC_INFO << "link: " << link; + qDebug() << Q_FUNC_INFO << "link: " << link; } @@ -421,10 +422,10 @@ void MainScreen::on_labelMadeBy_linkActivated(const QString &link) */ void MainScreen::on_progressBar_valueChanged(int value) { - if(value == 0 || value == 100) - ui->progressBar->setVisible(false); - else - ui->progressBar->setVisible(true); + if(value == 0 || value == 100) + ui->progressBar->setVisible(false); + else + ui->progressBar->setVisible(true); } diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 997f0a2..cbbdf32 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -503,7 +503,7 @@ font-size: 15px; 0 - -1 + 6 @@ -809,6 +809,9 @@ font-size: 15px; true + + true + @@ -950,7 +953,7 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 0 0 1133 - 22 + 21 diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 836e548..24e63f9 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -4,81 +4,113 @@ * TODO: make graph understandable * BUG: graph bug when theres small range of years */ -gradegraph::gradegraph(QWidget *parent) : - QDialog(parent), - ui(new Ui::gradegraph) +gradegraph::gradegraph(QWidget *parent) : QDialog(parent), ui(new Ui::gradegraph) { - ui->setupUi(this); - this->gp = NULL; + ui->setupUi(this); + this->setModal(true); //makes it on top of application + this->gp = NULL; } void gradegraph::showGraph(GradePage *gpPTR) { - this->gp = gpPTR; - setVisualization(); - setGraphsData(); - this->show(); - this->setModal(true); //makes it on top of application + qDebug() << Q_FUNC_INFO; + this->gp = gpPTR; + clearGraph(); + + setVisualization(); + setGraphsData(); + + ui->graphwidget->replot(); + + this->show(); } gradegraph::~gradegraph() { - delete ui; + delete ui; } void gradegraph::setGraphsData() { - int minYearInList = gp->getMinYearInList(); - int maxYearInList = gp->getMaxYearInList()+1; - int xRangeForYear = (maxYearInList - minYearInList+2)*3; - QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),sem(xRangeForYear); + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; + QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),indicatorX(xRangeForYear); - for (int yearCount=0,i=1; igetAvg(minYearInList+yearCount); - yearlyAvg[i] = lastAvg; - // add the text label at the top: - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); - textLabel->position->setCoords(i, lastAvg+1.5); // place position at center/top of axis rect - textLabel->setText(QString::number(lastAvg,'g',4)); - textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger - textLabel->setPen(QPen(Qt::black)); // show black border around text - yearCount++; + indicatorX[i] = i; + if (i%4==1) //years + { + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); + + double lastAvg = gp->getAvg(minYearInList+yearCount); + + if (lastAvg > 0) + { + // add the text label at the top: + if (lastAvg <= MIN_GRADE) //will be below the graph + { + textLabel->position->setCoords(i, MIN_GRADE+5); // place position at center/top of axis rect + textLabel->setText(QString::number(lastAvg,'g',4) + "<= Min Grade (" + QString::number(MIN_GRADE) + ")"); + } + else + { + textLabel->position->setCoords(i, lastAvg+1.5); // place position at center/top of axis rect + textLabel->setText(QString::number(lastAvg,'g',4)); + } + } + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text + + yearlyAvg[i] = lastAvg; + yearCount++; } - else + else { - if (i+4 < xRangeForYear) //semesters + if (i+4 < xRangeForYear) //semesters { - double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); - SemesterialAvg[i+4] = avg; - // add the text label at the top: + QCPItemText *textLabel = new QCPItemText(ui->graphwidget); + ui->graphwidget->addItem(textLabel); - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); - textLabel->position->setCoords(i+4, avg+0.5); // place position at center/top of axis rect - textLabel->setText(QString::number(avg,'g',4)); - textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger - textLabel->setPen(QPen(Qt::black)); // show black border around text + //qDebug() << "year: " << minYearInList+yearCount << "sem " << (i-1)%4; + double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); + //qDebug() << "avg: " << avg; + if (avg > 0) + { + // add the text label at the top: + if (avg <= MIN_GRADE) //will be below the graph + { + textLabel->position->setCoords(i+4, MIN_GRADE+1.5); // place position at center/top of axis rect + textLabel->setText(QString::number(avg,'g',4) + "<= Min Grade (" + QString::number(MIN_GRADE) + ")"); + } + else + { + textLabel->position->setCoords(i+4, avg+1.5); // place position at center/top of axis rect + textLabel->setText(QString::number(avg,'g',4)); + } + + textLabel->setFont(QFont(font().family(), 8)); // make font a bit larger + textLabel->setPen(QPen(Qt::black)); // show black border around text + + SemesterialAvg[i+4] = avg; + } } - yearlyAvg[i] = 0; + yearlyAvg[i] = 0; } } - //yearly - ui->graphwidget->graph(0)->setData(sem,yearlyAvg); - //yearly - ui->graphwidget->graph(1)->setData(sem,SemesterialAvg); + //yearly + ui->graphwidget->graph(0)->setData(indicatorX,yearlyAvg); + //yearly + ui->graphwidget->graph(1)->setData(indicatorX,SemesterialAvg); } /** @@ -86,75 +118,86 @@ void gradegraph::setGraphsData() */ void gradegraph::setVisualization() { - ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box + ui->graphwidget->setBackground(QBrush(Qt::white)); + ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box - ui->graphwidget->addGraph(); //yearly and semesterial graphs - ui->graphwidget->addGraph(); + ui->graphwidget->addGraph(); //yearly and semesterial graphs + ui->graphwidget->addGraph(); - ui->graphwidget->graph(0)->setName(tr("Yearly Average")); - ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsLine); - ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); + ui->graphwidget->graph(0)->setName(tr("Yearly Average")); + ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); + ui->graphwidget->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::blue, 7)); + ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsImpulse ); - ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); - ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsLine); - ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); + ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); + ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsStepLeft); + ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); + ui->graphwidget->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::red, 7)); - int minYearInList = gp->getMinYearInList(); - int maxYearInList = gp->getMaxYearInList()+1; - int xRangeForYear = (maxYearInList - minYearInList+2)*3; - QVector xStrings(0); - for (int year=minYearInList,i = 0; i < xRangeForYear-1; ++i) + int minYearInList = gp->getMinYearInList(); + int maxYearInList = gp->getMaxYearInList()+1; + int xRangeForYear = (maxYearInList - minYearInList+2)*3; + + QVector xStrings(0); + for (int year=minYearInList,i = 0; i < xRangeForYear-1; ++i) { - //set year x axe label to be yyyy A B C yyyy+1 A B C yyyy+2.... - int semesterChar = i%4; - QString tempString; - switch (semesterChar) + //set year x axe label to be yyyy A B C yyyy+1 A B C yyyy+2.... + int semesterChar = i%4; + QString tempString; + switch (semesterChar) { case 1: - tempString = tr("A"); - xStrings << tempString; - break; + tempString = tr("A"); + xStrings << tempString; + break; case 2: - tempString = tr("B"); - xStrings << tempString; - break; + tempString = tr("B"); + xStrings << tempString; + break; case 3: - tempString = tr("C"); - xStrings << tempString; - break; + tempString = tr("C"); + xStrings << tempString; + break; case 0: - tempString = QString::number(year); - xStrings << tempString; - year++; - break; + tempString = QString::number(year); + xStrings << tempString; + year++; + break; } } - ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); - ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); - ui->graphwidget->yAxis->setRange(50,100); - ui->graphwidget->yAxis->setTickStep(2); - ui->graphwidget->yAxis->setAutoSubTicks(false); - ui->graphwidget->yAxis->setAutoTickStep(false); - ui->graphwidget->yAxis->setSubTickCount(5); + ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); + ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); + ui->graphwidget->yAxis->setRange(MIN_GRADE,MAX_GRADE); + ui->graphwidget->yAxis->setTickStep(2); + ui->graphwidget->yAxis->setAutoSubTicks(false); + ui->graphwidget->yAxis->setAutoTickStep(false); + ui->graphwidget->yAxis->setSubTickCount(5); - ui->graphwidget->xAxis->setLabel(tr("Years")); - ui->graphwidget->xAxis->setAutoTickLabels(false); - ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); - ui->graphwidget->xAxis->setAutoTickStep(false); - ui->graphwidget->xAxis->setTickStep(1); - ui->graphwidget->xAxis->setAutoSubTicks(false); - ui->graphwidget->xAxis->setSubTickCount(1); - ui->graphwidget->xAxis->setTickVectorLabels(xStrings); - ui->graphwidget->xAxis->setRange(1,xRangeForYear); + ui->graphwidget->xAxis->setLabel(tr("Years")); + ui->graphwidget->xAxis->setAutoTickLabels(false); + ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); + ui->graphwidget->xAxis->setAutoTickStep(false); + ui->graphwidget->xAxis->setTickStep(1); + ui->graphwidget->xAxis->setAutoSubTicks(false); + ui->graphwidget->xAxis->setSubTickCount(0); + ui->graphwidget->xAxis->setTickVectorLabels(xStrings); + ui->graphwidget->xAxis->setRange(1,xRangeForYear); - ui->graphwidget->legend->setVisible(true); //show graph name on top right + ui->graphwidget->legend->setVisible(true); //show graph name on top right +} +void gradegraph::clearGraph() +{ + int itemDeleted,graphs,plots; + itemDeleted = ui->graphwidget->clearItems(); + graphs = ui->graphwidget->clearGraphs(); + plots = ui->graphwidget->clearPlottables(); + qDebug() << Q_FUNC_INFO << "items:" << itemDeleted << "graphs" << graphs << "plots:" << plots; } - void gradegraph::on_pushButton_clicked() { - qDebug() << Q_FUNC_INFO << " Closed Graph Dialog"; - this->done(0); + qDebug() << Q_FUNC_INFO << " Closed Graph Dialog"; + this->done(0); } diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index 0f510bd..b5324fe 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -9,6 +9,9 @@ namespace Ui { class gradegraph; } +#define MIN_GRADE 50 +#define MAX_GRADE 100 + class gradegraph : public QDialog { Q_OBJECT @@ -27,6 +30,8 @@ private: void setVisualization(); void setGraphsData(); + void clearGraph(); + Ui::gradegraph *ui; }; diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 78fab3f..5744652 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -11,7 +11,11 @@ - Dialog + GPA Graph View + + + + :/icons/icon.ico:/icons/icon.ico @@ -29,7 +33,7 @@ - <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">Graph View</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">GPA Graph View</span></p></body></html> @@ -82,6 +86,8 @@ 1 - + + + From 1032c32013240dcc77ccf2ad46d8e3f544b90943 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Sun, 12 Oct 2014 22:19:43 +0300 Subject: [PATCH 29/58] jcestatusbar widget --- jceGrade.pro | 6 +- main/LoginTab/loginhandler.cpp | 46 ++--------- main/LoginTab/loginhandler.h | 12 +-- main/jceWidgets/jcestatusbar.cpp | 118 +++++++++++++++++++++++++++++ main/jceWidgets/jcestatusbar.h | 51 +++++++++++++ main/mainscreen.cpp | 55 +++++--------- main/mainscreen.h | 7 +- main/mainscreen.ui | 53 ------------- src/jceConnection/jcesslclient.cpp | 4 +- src/jceConnection/jcesslclient.h | 6 +- src/jceSettings/jcelogin.cpp | 2 +- src/jceSettings/jcelogin.h | 7 +- 12 files changed, 217 insertions(+), 150 deletions(-) create mode 100644 main/jceWidgets/jcestatusbar.cpp create mode 100644 main/jceWidgets/jcestatusbar.h diff --git a/jceGrade.pro b/jceGrade.pro index 4ba14b3..43f07ed 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -58,7 +58,8 @@ HEADERS += \ src/jceData/Calendar/coursesSchedule/calendarDialog.h \ src/jceData/Calendar/coursesSchedule/calendarPage.h \ src/jceData/Calendar/coursesSchedule/calendarPageCourse.h \ - src/jceData/Calendar/coursesSchedule/calendarSchedule.h + src/jceData/Calendar/coursesSchedule/calendarSchedule.h \ + main/jceWidgets/jcestatusbar.h SOURCES += \ main/CalendarTab/CalendarManager.cpp \ @@ -84,4 +85,5 @@ SOURCES += \ src/jceData/Calendar/coursesSchedule/calendarDialog.cpp \ src/jceData/Calendar/coursesSchedule/calendarPage.cpp \ src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp \ - src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp + src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp \ + main/jceWidgets/jcestatusbar.cpp diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 84b22d1..8e5a8f4 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -1,24 +1,17 @@ #include "loginhandler.h" -loginHandler::loginHandler(user *ptr, QStatusBar *statusBarPtr,QPushButton *loginButtonPtr,QProgressBar *progressbarPtr): logggedInFlag(false) +loginHandler::loginHandler(user *ptr, QPushButton *loginButtonPtr, jceStatusBar *progressbarPtr): logggedInFlag(false) { this->loginButtonPtr = loginButtonPtr; - this->progressBar = progressbarPtr; + this->statusBar = progressbarPtr; - //statusBar - statusBar = statusBarPtr; - iconButtomStatusLabel = new QLabel(statusBarPtr); - iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); - //display progressbar and then ball icon. - statusBar->addPermanentWidget(progressBar,0); - statusBar->addPermanentWidget(iconButtomStatusLabel,0); - setIconConnectionStatus(jceLogin::jceStatus::JCE_NOT_CONNECTED); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); //user settings userPtr = ptr; - this->jceLog = new jceLogin(userPtr,progressBar); + this->jceLog = new jceLogin(userPtr,statusBar); QObject::connect(this->jceLog,SIGNAL(connectionReadyAfterDisconnection()),this,SLOT(readyAfterConnectionLost())); } @@ -31,14 +24,14 @@ bool loginHandler::login(QString username,QString password) logout(); return false; } - setIconConnectionStatus(jceLogin::jceStatus::JCE_START_VALIDATING_PROGRESS); + statusBar->setIconConnectionStatus(jceStatusBar::Connecting); userPtr->setUsername(username); userPtr->setPassword(password); if (makeConnection() == true) { - setIconConnectionStatus(jceLogin::jceStatus::JCE_YOU_ARE_IN); + statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); loginButtonPtr->setText(QObject::tr("Logout")); return isLoggedInFlag(); } @@ -52,7 +45,7 @@ bool loginHandler::login(QString username,QString password) void loginHandler::logout() { loginButtonPtr->setText(QObject::tr("Login")); - setIconConnectionStatus(jceLogin::jceStatus::JCE_NOT_CONNECTED); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); jceLog->closeAll(); logggedInFlag = false; } @@ -154,32 +147,7 @@ int loginHandler::makeExamsScheduleRequest(int year, int semester) else return jceLogin::JCE_NOT_CONNECTED; } -void loginHandler::setIconConnectionStatus(jceLogin::jceStatus statusDescription) -{ - QPixmap iconPix; - switch (statusDescription) - { - case jceLogin::jceStatus::JCE_START_VALIDATING_PROGRESS: - iconPix.load(":/icons/blueStatusIcon.png"); - statusBar->showMessage(tr("Connecting...")); - break; - case jceLogin::jceStatus::JCE_YOU_ARE_IN: - iconPix.load(":/icons/greenStatusIcon.png"); - statusBar->showMessage(tr("Connected")); - break; - case jceLogin::jceStatus::JCE_NOT_CONNECTED: - iconPix.load(":/icons/redStatusIcon.png"); - statusBar->showMessage(tr("Disconnected")); - break; - default: - iconPix.load(":/icons/redStatusIcon.png"); - statusBar->showMessage(tr("Ready.")); - break; - } - iconButtomStatusLabel->setPixmap(iconPix); - this->statusBar->repaint(); -} void loginHandler::popMessage(QString message,bool addInfo) { if (addInfo) diff --git a/main/LoginTab/loginhandler.h b/main/LoginTab/loginhandler.h index 5b7d154..6b13fbf 100644 --- a/main/LoginTab/loginhandler.h +++ b/main/LoginTab/loginhandler.h @@ -6,28 +6,25 @@ #include #include #include -#include -#include #include #include "./src/jceSettings/jcelogin.h" #include "./src/appDatabase/savedata.h" +#include "./main/jceWidgets/jcestatusbar.h" class loginHandler : public QObject { Q_OBJECT public: - loginHandler(user *ptr, QStatusBar *statusBarPtr, QPushButton *loginButtonPtr, QProgressBar *progressbarPtr); + loginHandler(user *ptr, QPushButton *loginButtonPtr, jceStatusBar *progressbarPtr); ~loginHandler() { - delete iconButtomStatusLabel; delete jceLog; } bool login(QString username,QString password); void logout(); - void setIconConnectionStatus(jceLogin::jceStatus statusDescription); bool makeConnection(); @@ -50,10 +47,9 @@ private: jceLogin * jceLog; user * userPtr; - QStatusBar *statusBar; - QLabel *iconButtomStatusLabel; + jceStatusBar *statusBar; + QPushButton *loginButtonPtr; - QProgressBar *progressBar; }; diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp new file mode 100644 index 0000000..9444776 --- /dev/null +++ b/main/jceWidgets/jcestatusbar.cpp @@ -0,0 +1,118 @@ +#include "jcestatusbar.h" + +jceStatusBar::jceStatusBar(QWidget *parent) : + QStatusBar(parent) +{ + + this->setStyleSheet("QStatusBar::item { border: 0px solid black };"); + this->setFixedHeight(STATUS_ICON_HEIGH+5); + this->showMessage(tr("Ready")); + + + //Icon + iconButtomStatusLabel = new QLabel(this); + iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); + + //ProgressBar + progressBar = new QProgressBar(this); + connect(progressBar,SIGNAL(valueChanged(int)),this,SLOT(setProgressValue(int))); + connect(this,SIGNAL(progressHasPacket(int)),this,SLOT(addValueToProgressBar(int))); + + progressBar->setFixedWidth(120); + progressBar->setFixedHeight(STATUS_ICON_HEIGH); + progressBar->setStyleSheet("#progressBar::horizontal {" + "border: 1px solid gray;" + "border-radius: 3px;" + "background: transparent;" + "padding: 1px;" + "}" + "#progressBar::chunk:horizontal {" + "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 1 white);" + "}"); + progressBar->setRange(0,100); + progressBar->setValue(0); + progressBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + progressBar->setTextVisible(true); + progressBar->setFormat("%p%"); + + + addPermanentWidget(progressBar,0); + addPermanentWidget(iconButtomStatusLabel,0); + +} + +void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) +{ + QPixmap iconPix; + switch (update) + { + case jceProgressStatus::Disconnected: + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Disconnected")); + break; + case jceProgressStatus::Ready: + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Ready.")); + break; + case jceProgressStatus::Connecting: + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Connecting...")); + break; + case jceProgressStatus::Sending: + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Sending.")); + break; + case jceProgressStatus::Recieving: + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Recieving.")); + break; + case jceProgressStatus::Inserting: + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Inserting.")); + break; + case jceProgressStatus::LoggedIn: + setProgressValue(100); + iconPix.load(":/icons/greenStatusIcon.png"); + showMessage(tr("LoggedIn.")); + break; + case jceProgressStatus::Done: + setProgressValue(100); + iconPix.load(":/icons/greenStatusIcon.png"); + showMessage(tr("Done.")); + break; + case jceProgressStatus::Connected: + setProgressValue(100); + iconPix.load(":/icons/greenStatusIcon.png"); + showMessage(tr("Connected")); + break; + } + iconButtomStatusLabel->setPixmap(iconPix); + + repaint(); + +} +/** +* @brief Every time the value changes this method will be called +* @param value = the value of the progress Bar +*/ +void jceStatusBar::setProgressValue(int value) +{ + + if (value == 0) + { + progressBar->setVisible(false); + progressBar->setValue(0); + } + else + { + progressBar->setValue(value); + progressBar->setVisible(true); + } + +} + +void jceStatusBar::addValueToProgressBar(int value) +{ + progressBar->setValue(progressBar->value() + value); + +} diff --git a/main/jceWidgets/jcestatusbar.h b/main/jceWidgets/jcestatusbar.h new file mode 100644 index 0000000..69d7b3f --- /dev/null +++ b/main/jceWidgets/jcestatusbar.h @@ -0,0 +1,51 @@ +#ifndef JCESTATUSBAR_H +#define JCESTATUSBAR_H + + + +#include +#include +#include + +#define STATUS_ICON_HEIGH 35 + +class jceStatusBar : public QStatusBar +{ + Q_OBJECT +public: + + enum jceProgressStatus + { + Ready, + Disconnected, + Connecting, + Connected, + LoggedIn, + Sending, + Recieving, + Inserting, + Done + }; + + jceStatusBar(QWidget *parent = 0); + + void setIconConnectionStatus(jceProgressStatus update); + + +signals: + void progressHasPacket(int num); + +public slots: + void setProgressValue(int val); + +private slots: + void addValueToProgressBar(int value); + +private: + + + QProgressBar * progressBar; + QLabel *iconButtomStatusLabel; +}; + +#endif // JCESTATUSBAR_H diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index b344918..065ac52 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -6,6 +6,8 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc { ui->setupUi(this); + + ui->labelMadeBy->setOpenExternalLinks(true); //Login Tab @@ -16,12 +18,9 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc ui->labelUsrInputStatus->setPixmap(iconPix); ui->labelPswInputStatus->setPixmap(iconPix); - - //StatusBar & progressbar - ui->progressBar->setFixedHeight(STATUS_ICON_HEIGH); - ui->statusBar->setStyleSheet("QStatusBar::item { border: 0px solid black };"); - ui->statusBar->setFixedHeight(STATUS_ICON_HEIGH+5); - ui->statusBar->showMessage(tr("Ready")); + //StatusBar + statusBar = new jceStatusBar(this); + this->setStatusBar(statusBar); //GPA Tab ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); @@ -30,7 +29,7 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc qDebug() << Q_FUNC_INFO << "Allocating pointers"; this->userLoginSetting = new user("",""); this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); - this->loginHandel = new loginHandler(userLoginSetting,ui->statusBar,ui->loginButton,ui->progressBar); + this->loginHandel = new loginHandler(userLoginSetting, ui->loginButton, statusBar); this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); this->data = new SaveData(); @@ -46,12 +45,8 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc //language qDebug() << Q_FUNC_INFO << "Checking locale"; checkLocale(); - ui->statusBar->repaint(); qDebug() << Q_FUNC_INFO << "Ready."; - //set the progress bar to be invisible (It will show only if value !=0 or !=100) - ui->progressBar->setVisible(false); - } MainScreen::~MainScreen() { @@ -66,7 +61,6 @@ MainScreen::~MainScreen() //EVENTS ON LOGIN TAB void MainScreen::on_loginButton_clicked() { - ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) { @@ -95,7 +89,6 @@ void MainScreen::on_loginButton_clicked() QApplication::setOverrideCursor(Qt::WaitCursor); if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) { - ui->progressBar->setValue(100); qDebug() << Q_FUNC_INFO << "login session end with true"; ui->pswdLineEdit->setDisabled(true); ui->usrnmLineEdit->setDisabled(true); @@ -137,7 +130,7 @@ void MainScreen::on_usrnmLineEdit_editingFinished() void MainScreen::on_ratesButton_clicked() { - ui->progressBar->setValue(0); +// ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); if (!checkIfValidDates()) { @@ -150,18 +143,18 @@ void MainScreen::on_ratesButton_clicked() QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting grades...")); +// ui->statusBar->showMessage(tr("Getting grades...")); if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) { qDebug() << Q_FUNC_INFO << "grade page is ready"; - ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); +// ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); pageString = loginHandel->getCurrentPageContect(); courseTableMgr->setCoursesList(pageString); courseTableMgr->insertJceCoursesIntoTable(); - ui->progressBar->setValue(100); - ui->statusBar->showMessage(tr("Done")); +// ui->progressBar->setValue(100); +// ui->statusBar->showMessage(tr("Done")); } else if (status == jceLogin::JCE_NOT_CONNECTED) { @@ -248,18 +241,18 @@ void MainScreen::on_examsBtn_clicked() } void MainScreen::on_getCalendarBtn_clicked() { - ui->progressBar->setValue(0); +// ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); int status = 0; QString page; QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting schedule...")); +// ui->statusBar->showMessage(tr("Getting schedule...")); if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { calendar->resetTable(); - ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); +// ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); page = loginHandel->getCurrentPageContect(); calendar->setCalendar(page); @@ -268,10 +261,10 @@ void MainScreen::on_getCalendarBtn_clicked() //auto getting exam if (loginHandel->isLoggedInFlag()) { - ui->statusBar->showMessage(tr("Getting exams...")); +// ui->statusBar->showMessage(tr("Getting exams...")); if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - ui->statusBar->showMessage(tr("Done."),1000); +// ui->statusBar->showMessage(tr("Done."),1000); page = loginHandel->getCurrentPageContect(); calendar->setExamsSchedule(page); qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; @@ -286,8 +279,8 @@ void MainScreen::on_getCalendarBtn_clicked() qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; - ui->progressBar->setValue(100); - ui->statusBar->showMessage(tr("Done")); +// ui->progressBar->setValue(100); +// ui->statusBar->showMessage(tr("Done")); } else if (status == jceLogin::JCE_NOT_CONNECTED) { @@ -416,16 +409,4 @@ void MainScreen::on_labelMadeBy_linkActivated(const QString &link) } -/** - * @brief Every time the value changes this method will be called - * @param value = the value of the progress Bar - */ -void MainScreen::on_progressBar_valueChanged(int value) -{ - if(value == 0 || value == 100) - ui->progressBar->setVisible(false); - else - ui->progressBar->setVisible(true); -} - diff --git a/main/mainscreen.h b/main/mainscreen.h index 116c957..59e40b5 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -10,9 +10,10 @@ #include "./CourseTab/coursestablemanager.h" #include "./LoginTab/loginhandler.h" #include "./CalendarTab/CalendarManager.h" +#include "./jceWidgets/jceStatusBar.h" + -#define STATUS_ICON_HEIGH 35 namespace Ui { class MainScreen; } @@ -58,7 +59,7 @@ private slots: void on_spinBoxCoursesToYear_valueChanged(int arg1); void on_spinBoxCoursesToSemester_valueChanged(int arg1); void on_labelMadeBy_linkActivated(const QString &link); - void on_progressBar_valueChanged(int value); +// void on_progressBar_valueChanged(int value); private: @@ -75,6 +76,8 @@ private: coursesTableManager *courseTableMgr; loginHandler *loginHandel; + jceStatusBar *statusBar; + }; #endif // MAINSCREEN_H diff --git a/main/mainscreen.ui b/main/mainscreen.ui index cbbdf32..767a49a 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -899,45 +899,6 @@ font-size: 15px; - - - - - 0 - 0 - - - - #progressBar::horizontal { -border: 1px solid gray; -border-radius: 3px; -background: transparent; -padding: 1px; -} -#progressBar::chunk:horizontal { -background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 1 white); -} - - - 0 - - - Qt::AlignCenter - - - true - - - Qt::Horizontal - - - false - - - QProgressBar::TopToBottom - - - @@ -975,20 +936,6 @@ background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: - - - - 0 - 0 - - - - - 16777215 - 50 - - - Credits diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index deb03cd..2906b8f 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -3,7 +3,7 @@ /** * @brief jceSSLClient::jceSSLClient Constructer, setting the signals */ -jceSSLClient::jceSSLClient(QProgressBar *progressbarPtr) : loggedIAndConnectedFlag(false), readingFlag(false), +jceSSLClient::jceSSLClient(jceStatusBar *progressbarPtr) : loggedIAndConnectedFlag(false), readingFlag(false), reConnectionFlag(false), networkConf(), packet(""), recieveLastPacket(false), packetSizeRecieved(0) { this->progressBar = progressbarPtr; @@ -208,7 +208,7 @@ void jceSSLClient::readIt() packet.append("\0"); readerAppendingLocker.unlock(); - progressBar->setValue(this->progressBar->value() + 6); + emit progressBar->progressHasPacket(6); if (tempPacket.contains("Go_To_system_After_Login.htm") || tempPacket.contains("")) { diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index e2cfb6d..8f77372 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -11,7 +11,7 @@ #include #include -#include +#include "./main/jceWidgets/jcestatusbar.h" #define packetSize 4096 //4k #define milisTimeOut 5000 //4 seconds @@ -20,7 +20,7 @@ class jceSSLClient : public QSslSocket { Q_OBJECT public: - jceSSLClient(QProgressBar *progressbarPtr); + jceSSLClient(jceStatusBar *progressbarPtr); bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); bool makeDiconnect(); @@ -64,7 +64,7 @@ private: - QProgressBar *progressBar; //progressbar pointer + jceStatusBar *progressBar; //progressbar pointer }; diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 591d472..656823a 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -4,7 +4,7 @@ * @brief jceLogin::jceLogin * @param username pointer to allocated user settings */ -jceLogin::jceLogin(user* username, QProgressBar *progressbarPtr) +jceLogin::jceLogin(user* username, jceStatusBar *progressbarPtr) { this->progressBar = progressbarPtr; this->recieverPage = new QString(); diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index 66d1ca6..507bc3a 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -1,12 +1,13 @@ #ifndef JCELOGIN_H #define JCELOGIN_H + #include "./src/jceConnection/jcesslclient.h" #include "./src/jceSettings/user.h" #include "jceLoginHtmlScripts.h" + #include -#include #include @@ -15,7 +16,7 @@ class jceLogin : public QObject Q_OBJECT public: - jceLogin(user* username,QProgressBar *progressbarPtr); + jceLogin(user* username,jceStatusBar *progressbarPtr); ~jceLogin(); enum jceStatus { @@ -64,7 +65,7 @@ private: QString * recieverPage; user * jceA; jceSSLClient * JceConnector; - QProgressBar *progressBar; + jceStatusBar *progressBar; }; From 71d5e9b8b331ac716a2fee1f72e3f2d84118e8fd Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 01:14:26 +0300 Subject: [PATCH 30/58] update statusbar --- main/LoginTab/loginhandler.cpp | 14 ++++++++++-- main/jceWidgets/jcestatusbar.cpp | 36 +++++++++++++++++++----------- main/jceWidgets/jcestatusbar.h | 5 +++-- main/mainscreen.cpp | 30 ++++++++----------------- main/mainscreen.ui | 19 +++++++++------- src/jceConnection/jcesslclient.cpp | 8 ++++--- src/jceConnection/jcesslclient.h | 4 ++-- src/jceSettings/jcelogin.cpp | 17 +++++++++----- src/jceSettings/jcelogin.h | 4 ++-- 9 files changed, 79 insertions(+), 58 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 8e5a8f4..6b7c2ac 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -24,19 +24,18 @@ bool loginHandler::login(QString username,QString password) logout(); return false; } - statusBar->setIconConnectionStatus(jceStatusBar::Connecting); userPtr->setUsername(username); userPtr->setPassword(password); if (makeConnection() == true) { - statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); loginButtonPtr->setText(QObject::tr("Logout")); return isLoggedInFlag(); } else { + logout(); return false; } @@ -101,6 +100,7 @@ void loginHandler::readyAfterConnectionLost() { qWarning() << Q_FUNC_INFO; setLoginFlag(false); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); login(userPtr->getUsername(),userPtr->getPassword()); } @@ -128,22 +128,32 @@ QString loginHandler::getCurrentPageContect() int loginHandler::makeGradeRequest(int fromYear, int toYear, int fromSemester, int toSemester) { if (isLoggedInFlag()) + { + statusBar->setIconConnectionStatus(jceStatusBar::Sending); return jceLog->getGrades(fromYear, toYear, fromSemester, toSemester); + } else return jceLogin::JCE_NOT_CONNECTED; } int loginHandler::makeCalendarRequest(int year, int semester) { if (isLoggedInFlag()) + { + statusBar->setIconConnectionStatus(jceStatusBar::Sending); return jceLog->getCalendar(year,semester); + } else return jceLogin::JCE_NOT_CONNECTED; } int loginHandler::makeExamsScheduleRequest(int year, int semester) { + if (isLoggedInFlag()) + { + statusBar->setIconConnectionStatus(jceStatusBar::Sending); return jceLog->getExams(year,semester); + } else return jceLogin::JCE_NOT_CONNECTED; } diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index 9444776..59fe9d7 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -3,8 +3,7 @@ jceStatusBar::jceStatusBar(QWidget *parent) : QStatusBar(parent) { - - this->setStyleSheet("QStatusBar::item { border: 0px solid black };"); + this->setStyleSheet("QStatusBar { border: 0px solid black };"); this->setFixedHeight(STATUS_ICON_HEIGH+5); this->showMessage(tr("Ready")); @@ -20,20 +19,21 @@ jceStatusBar::jceStatusBar(QWidget *parent) : progressBar->setFixedWidth(120); progressBar->setFixedHeight(STATUS_ICON_HEIGH); - progressBar->setStyleSheet("#progressBar::horizontal {" + progressBar->setStyleSheet("QProgressBar {" "border: 1px solid gray;" "border-radius: 3px;" "background: transparent;" "padding: 1px;" "}" - "#progressBar::chunk:horizontal {" - "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 green, stop: 1 white);" + "QProgressBar::chunk {" + "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 #b4e391 , stop: 1 #61c419);" "}"); progressBar->setRange(0,100); progressBar->setValue(0); - progressBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + progressBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); progressBar->setTextVisible(true); progressBar->setFormat("%p%"); + progressBar->setOrientation(Qt::Horizontal); addPermanentWidget(progressBar,0); @@ -46,39 +46,50 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) QPixmap iconPix; switch (update) { + case jceProgressStatus::ERROR: + setProgressValue(0); + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Error")); + break; case jceProgressStatus::Disconnected: + setProgressValue(0); iconPix.load(":/icons/redStatusIcon.png"); showMessage(tr("Disconnected")); break; case jceProgressStatus::Ready: + setProgressValue(100); iconPix.load(":/icons/redStatusIcon.png"); - showMessage(tr("Ready.")); + showMessage(tr("Ready")); break; case jceProgressStatus::Connecting: + setProgressValue(5); iconPix.load(":/icons/blueStatusIcon.png"); showMessage(tr("Connecting...")); break; case jceProgressStatus::Sending: + setProgressValue(10); iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Sending.")); + showMessage(tr("Sending...")); break; case jceProgressStatus::Recieving: + setProgressValue(15); iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Recieving.")); + showMessage(tr("Recieving...")); break; case jceProgressStatus::Inserting: + setProgressValue(80); iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Inserting.")); + showMessage(tr("Inserting")); break; case jceProgressStatus::LoggedIn: setProgressValue(100); iconPix.load(":/icons/greenStatusIcon.png"); - showMessage(tr("LoggedIn.")); + showMessage(tr("Logged In.")); break; case jceProgressStatus::Done: setProgressValue(100); iconPix.load(":/icons/greenStatusIcon.png"); - showMessage(tr("Done.")); + showMessage(tr("Done")); break; case jceProgressStatus::Connected: setProgressValue(100); @@ -97,7 +108,6 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) */ void jceStatusBar::setProgressValue(int value) { - if (value == 0) { progressBar->setVisible(false); diff --git a/main/jceWidgets/jcestatusbar.h b/main/jceWidgets/jcestatusbar.h index 69d7b3f..bfff49e 100644 --- a/main/jceWidgets/jcestatusbar.h +++ b/main/jceWidgets/jcestatusbar.h @@ -2,7 +2,7 @@ #define JCESTATUSBAR_H - +#include #include #include #include @@ -24,7 +24,8 @@ public: Sending, Recieving, Inserting, - Done + Done, + ERROR }; jceStatusBar(QWidget *parent = 0); diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 065ac52..05cbe62 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -6,10 +6,6 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc { ui->setupUi(this); - - - ui->labelMadeBy->setOpenExternalLinks(true); - //Login Tab iconPix.load(":/icons/iconX.png"); ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); @@ -129,8 +125,6 @@ void MainScreen::on_usrnmLineEdit_editingFinished() //EVENTS ON GPA TAB void MainScreen::on_ratesButton_clicked() { - -// ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); if (!checkIfValidDates()) { @@ -143,27 +137,28 @@ void MainScreen::on_ratesButton_clicked() QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { -// ui->statusBar->showMessage(tr("Getting grades...")); + statusBar->setIconConnectionStatus(jceStatusBar::Ready); if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) { qDebug() << Q_FUNC_INFO << "grade page is ready"; -// ui->statusBar->showMessage(tr("Done. Inserting data into table..."),1000); + statusBar->setIconConnectionStatus(jceStatusBar::Inserting); pageString = loginHandel->getCurrentPageContect(); courseTableMgr->setCoursesList(pageString); courseTableMgr->insertJceCoursesIntoTable(); -// ui->progressBar->setValue(100); -// ui->statusBar->showMessage(tr("Done")); + statusBar->setIconConnectionStatus(jceStatusBar::Done); } else if (status == jceLogin::JCE_NOT_CONNECTED) { qWarning() << Q_FUNC_INFO << "not connected"; QApplication::restoreOverrideCursor(); QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); } else { + statusBar->setIconConnectionStatus(jceStatusBar::ERROR); qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } } @@ -241,18 +236,16 @@ void MainScreen::on_examsBtn_clicked() } void MainScreen::on_getCalendarBtn_clicked() { -// ui->progressBar->setValue(0); qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); int status = 0; QString page; QApplication::setOverrideCursor(Qt::WaitCursor); if (loginHandel->isLoggedInFlag()) { -// ui->statusBar->showMessage(tr("Getting schedule...")); if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { + statusBar->setIconConnectionStatus(jceStatusBar::Inserting); calendar->resetTable(); -// ui->statusBar->showMessage(tr("Done. Inserting schdule into table..."),1000); page = loginHandel->getCurrentPageContect(); calendar->setCalendar(page); @@ -261,32 +254,29 @@ void MainScreen::on_getCalendarBtn_clicked() //auto getting exam if (loginHandel->isLoggedInFlag()) { -// ui->statusBar->showMessage(tr("Getting exams...")); if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { -// ui->statusBar->showMessage(tr("Done."),1000); page = loginHandel->getCurrentPageContect(); calendar->setExamsSchedule(page); qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; + statusBar->setIconConnectionStatus(jceStatusBar::Done); } else if (status == jceLogin::JCE_NOT_CONNECTED) { qWarning() << Q_FUNC_INFO << "not connected"; QApplication::restoreOverrideCursor(); QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); } else qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; - - -// ui->progressBar->setValue(100); -// ui->statusBar->showMessage(tr("Done")); } else if (status == jceLogin::JCE_NOT_CONNECTED) { qWarning() << Q_FUNC_INFO << "not connected"; QApplication::restoreOverrideCursor(); QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); } else qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; @@ -405,8 +395,6 @@ void MainScreen::checkLocale() void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { qDebug() << Q_FUNC_INFO << "link: " << link; - - } diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 767a49a..d0884ab 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -49,6 +49,16 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r + + + + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> + + + true + + + @@ -899,13 +909,6 @@ font-size: 15px; - - - - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - - - @@ -914,7 +917,7 @@ font-size: 15px; 0 0 1133 - 21 + 22 diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 2906b8f..b3e4579 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -3,10 +3,10 @@ /** * @brief jceSSLClient::jceSSLClient Constructer, setting the signals */ -jceSSLClient::jceSSLClient(jceStatusBar *progressbarPtr) : loggedIAndConnectedFlag(false), readingFlag(false), +jceSSLClient::jceSSLClient(jceStatusBar *statusBar) : loggedIAndConnectedFlag(false), readingFlag(false), reConnectionFlag(false), networkConf(), packet(""), recieveLastPacket(false), packetSizeRecieved(0) { - this->progressBar = progressbarPtr; + this->statusBar = statusBar; //setting signals connect(this,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(checkErrors(QAbstractSocket::SocketError))); connect(this,SIGNAL(connected()),this,SLOT(setConnected())); @@ -131,6 +131,7 @@ bool jceSSLClient::sendData(QString str) int amount = 0; if (isConnected()) //if connected { + statusBar->setIconConnectionStatus(jceStatusBar::Sending); amount = write(str.toStdString().c_str(),str.length()); qDebug() << Q_FUNC_INFO << "lenght send: " << str.length() << "lenght recieved: " << amount; if (amount == -1) @@ -151,6 +152,7 @@ bool jceSSLClient::sendData(QString str) */ bool jceSSLClient::recieveData(QString *str) { + statusBar->setIconConnectionStatus(jceStatusBar::Recieving); qDebug() << Q_FUNC_INFO << "Data receiving!"; str->clear(); packet = ""; @@ -208,7 +210,7 @@ void jceSSLClient::readIt() packet.append("\0"); readerAppendingLocker.unlock(); - emit progressBar->progressHasPacket(6); + emit statusBar->progressHasPacket(10); if (tempPacket.contains("Go_To_system_After_Login.htm") || tempPacket.contains("")) { diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index 8f77372..1f2471c 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -20,7 +20,7 @@ class jceSSLClient : public QSslSocket { Q_OBJECT public: - jceSSLClient(jceStatusBar *progressbarPtr); + jceSSLClient(jceStatusBar *statusBar); bool makeConnect(QString server = "yedion.jce.ac.il", int port = 443); bool makeDiconnect(); @@ -64,7 +64,7 @@ private: - jceStatusBar *progressBar; //progressbar pointer + jceStatusBar *statusBar; //progressbar pointer }; diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 656823a..013afe6 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -4,12 +4,12 @@ * @brief jceLogin::jceLogin * @param username pointer to allocated user settings */ -jceLogin::jceLogin(user* username, jceStatusBar *progressbarPtr) +jceLogin::jceLogin(user* username, jceStatusBar *statusBar) { - this->progressBar = progressbarPtr; + this->statusBar = statusBar; this->recieverPage = new QString(); this->jceA = username; - this->JceConnector = new jceSSLClient(progressBar); + this->JceConnector = new jceSSLClient(statusBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); } @@ -28,7 +28,7 @@ jceLogin::~jceLogin() */ int jceLogin::makeConnection() { - qDebug() << "jceLogin::makeConnection(); connection to be make"; + qDebug() << Q_FUNC_INFO << "connection to be make"; if (this->recieverPage == NULL) this->recieverPage = new QString(); @@ -40,6 +40,7 @@ int jceLogin::makeConnection() if (returnMode == false) { + statusBar->setIconConnectionStatus(jceStatusBar::Connecting); if (JceConnector->makeConnect(dst_host,dst_port) == false) //couldnt make a connection return jceStatus::ERROR_ON_OPEN_SOCKET; else @@ -48,6 +49,7 @@ int jceLogin::makeConnection() if (returnMode == true) //connected to host { + statusBar->setIconConnectionStatus(jceStatusBar::Connected); returnMode = makeFirstVisit(); if (returnMode == true) //requst and send first validation { @@ -62,6 +64,7 @@ int jceLogin::makeConnection() qDebug() << Q_FUNC_INFO << "Signed in succeesfully"; status = jceStatus::JCE_YOU_ARE_IN; setLoginFlag(true); + statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); } else if (returnMode == jceLogin::ERROR_ON_GETTING_INFO) { @@ -93,6 +96,8 @@ int jceLogin::makeConnection() else status = jceStatus::JCE_NOT_CONNECTED; + if (status != jceStatus::JCE_YOU_ARE_IN) + statusBar->setIconConnectionStatus(jceStatusBar::ERROR); //we throw status even if we are IN! qDebug() << Q_FUNC_INFO << "return status: " << status; return status; @@ -114,6 +119,7 @@ bool jceLogin::checkConnection() const */ void jceLogin::closeAll() { + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); this->JceConnector->makeDiconnect(); if ((this->recieverPage != NULL) && (!this->recieverPage->isEmpty())) { @@ -134,7 +140,7 @@ void jceLogin::reMakeConnection() recieverPage = NULL; JceConnector = NULL; this->recieverPage = new QString(); - this->JceConnector = new jceSSLClient(progressBar); + this->JceConnector = new jceSSLClient(statusBar); QObject::connect(JceConnector,SIGNAL(serverDisconnectedbyRemote()),this,SLOT(reValidation())); QObject::connect(JceConnector,SIGNAL(noInternetLink()),this,SLOT(reMakeConnection())); emit connectionReadyAfterDisconnection(); @@ -148,6 +154,7 @@ int jceLogin::makeFirstVisit() { QString usr = jceA->getUsername(); QString psw = jceA->getPassword(); + if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA)))) { if (!JceConnector->recieveData(recieverPage)) diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index 507bc3a..a0443d6 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -16,7 +16,7 @@ class jceLogin : public QObject Q_OBJECT public: - jceLogin(user* username,jceStatusBar *progressbarPtr); + jceLogin(user* username, jceStatusBar *statusBar); ~jceLogin(); enum jceStatus { @@ -65,7 +65,7 @@ private: QString * recieverPage; user * jceA; jceSSLClient * JceConnector; - jceStatusBar *progressBar; + jceStatusBar *statusBar; }; From cde830dac7eb36502b6498e8bb0e2467b5ce3b19 Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 01:43:08 +0300 Subject: [PATCH 31/58] added busy flag into mainscreen --- main/mainscreen.cpp | 541 +++++++++++++++++++++++--------------------- main/mainscreen.h | 6 + 2 files changed, 290 insertions(+), 257 deletions(-) diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 05cbe62..8529604 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -4,397 +4,424 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) { - ui->setupUi(this); + ui->setupUi(this); + this->isBlocked = false; + //Login Tab + iconPix.load(":/icons/iconX.png"); + ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); + ui->labelUsrInputStatus->setPixmap(iconPix); + ui->labelPswInputStatus->setPixmap(iconPix); - //Login Tab - iconPix.load(":/icons/iconX.png"); - ui->pswdLineEdit->setEchoMode((QLineEdit::Password)); - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - ui->labelUsrInputStatus->setPixmap(iconPix); - ui->labelPswInputStatus->setPixmap(iconPix); + //StatusBar + statusBar = new jceStatusBar(this); + this->setStatusBar(statusBar); - //StatusBar - statusBar = new jceStatusBar(this); - this->setStatusBar(statusBar); + //GPA Tab + ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); - //GPA Tab - ui->avgLCD->setPalette(QPalette(QPalette::WindowText,Qt::blue)); + //Pointer allocating + qDebug() << Q_FUNC_INFO << "Allocating pointers"; + this->userLoginSetting = new user("",""); + this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); + this->loginHandel = new loginHandler(userLoginSetting, ui->loginButton, statusBar); + this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); + this->data = new SaveData(); - //Pointer allocating - qDebug() << Q_FUNC_INFO << "Allocating pointers"; - this->userLoginSetting = new user("",""); - this->courseTableMgr = new coursesTableManager(ui->coursesTable,userLoginSetting); - this->loginHandel = new loginHandler(userLoginSetting, ui->loginButton, statusBar); - this->calendar = new CalendarManager(this,ui->calendarGridLayoutMain); - this->data = new SaveData(); - - //check login File - if (data->isSaved()) + //check login File + if (data->isSaved()) { - qDebug() << Q_FUNC_INFO << "Loading data from file"; - ui->usrnmLineEdit->setText(data->getUsername()); - ui->pswdLineEdit->setText(data->getPassword()); - ui->keepLogin->setChecked(true); + qDebug() << Q_FUNC_INFO << "Loading data from file"; + ui->usrnmLineEdit->setText(data->getUsername()); + ui->pswdLineEdit->setText(data->getPassword()); + ui->keepLogin->setChecked(true); } - //language - qDebug() << Q_FUNC_INFO << "Checking locale"; - checkLocale(); - qDebug() << Q_FUNC_INFO << "Ready."; + //language + qDebug() << Q_FUNC_INFO << "Checking locale"; + checkLocale(); + qDebug() << Q_FUNC_INFO << "Ready."; } MainScreen::~MainScreen() { - delete calendar; - delete courseTableMgr; - delete userLoginSetting; - delete loginHandel; - delete data; - delete ui; + delete calendar; + delete courseTableMgr; + delete userLoginSetting; + delete loginHandel; + delete data; + delete ui; } //EVENTS ON LOGIN TAB void MainScreen::on_loginButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) + if (!isBusy()) { - if (ui->usrnmLineEdit->text().isEmpty()) + lock(); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if ((ui->usrnmLineEdit->text().isEmpty()) || (ui->pswdLineEdit->text().isEmpty())) { - ui->labelUsrInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "username input is empty"; + if (ui->usrnmLineEdit->text().isEmpty()) + { + ui->labelUsrInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "username input is empty"; + } + else + ui->labelUsrInputStatus->setVisible(false); + if (ui->pswdLineEdit->text().isEmpty()) + { + ui->labelPswInputStatus->setVisible(true); + qDebug() << Q_FUNC_INFO << "password input is empty"; + } + else + ui->labelPswInputStatus->setVisible(false); + return; } - else - ui->labelUsrInputStatus->setVisible(false); - if (ui->pswdLineEdit->text().isEmpty()) + else { - ui->labelPswInputStatus->setVisible(true); - qDebug() << Q_FUNC_INFO << "password input is empty"; + ui->labelUsrInputStatus->setVisible(false); + ui->labelPswInputStatus->setVisible(false); } - else - ui->labelPswInputStatus->setVisible(false); - return; - } - else - { - ui->labelUsrInputStatus->setVisible(false); - ui->labelPswInputStatus->setVisible(false); - } - qDebug() << Q_FUNC_INFO << "login session start"; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) - { - qDebug() << Q_FUNC_INFO << "login session end with true"; - ui->pswdLineEdit->setDisabled(true); - ui->usrnmLineEdit->setDisabled(true); - if (ui->keepLogin->isChecked()) + qDebug() << Q_FUNC_INFO << "login session start"; + if (this->loginHandel->login(ui->usrnmLineEdit->text(),ui->pswdLineEdit->text()) == true) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "login session end with true"; + ui->pswdLineEdit->setDisabled(true); + ui->usrnmLineEdit->setDisabled(true); + if (ui->keepLogin->isChecked()) + { + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); + } } - } - else - { - qDebug() << Q_FUNC_INFO << "login session end with false"; - ui->pswdLineEdit->setDisabled(false); - ui->usrnmLineEdit->setDisabled(false); + else + { + qDebug() << Q_FUNC_INFO << "login session end with false"; + ui->pswdLineEdit->setDisabled(false); + ui->usrnmLineEdit->setDisabled(false); + } + unlock(); } - QApplication::restoreOverrideCursor(); + + } void MainScreen::on_keepLogin_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (ui->keepLogin->isChecked()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (ui->keepLogin->isChecked()) { - qDebug() << Q_FUNC_INFO << "saving data"; - data->setUsername(ui->usrnmLineEdit->text()); - data->setPassword(ui->pswdLineEdit->text()); + qDebug() << Q_FUNC_INFO << "saving data"; + data->setUsername(ui->usrnmLineEdit->text()); + data->setPassword(ui->pswdLineEdit->text()); } - else - data->reset(); + else + data->reset(); } void MainScreen::on_usrnmLineEdit_editingFinished() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); } //EVENTS ON GPA TAB void MainScreen::on_ratesButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (!checkIfValidDates()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (!isBusy()) { - qWarning() << Q_FUNC_INFO << "Invalid dates! return"; - QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); - return; + lock(); + if (!checkIfValidDates()) + { + qWarning() << Q_FUNC_INFO << "Invalid dates! return"; + QMessageBox::critical(this,tr("Error"),tr("Invalid Dates.\nMake Sure everything is correct and try again")); + return; + } + QString pageString; + int status = 0; + if (loginHandel->isLoggedInFlag()) + { + statusBar->setIconConnectionStatus(jceStatusBar::Ready); + if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), + ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), + ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) + { + qDebug() << Q_FUNC_INFO << "grade page is ready"; + statusBar->setIconConnectionStatus(jceStatusBar::Inserting); + pageString = loginHandel->getCurrentPageContect(); + courseTableMgr->setCoursesList(pageString); + courseTableMgr->insertJceCoursesIntoTable(); + statusBar->setIconConnectionStatus(jceStatusBar::Done); + } + else if (status == jceLogin::JCE_NOT_CONNECTED) + { + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); + } + else + { + statusBar->setIconConnectionStatus(jceStatusBar::ERROR); + qCritical() << Q_FUNC_INFO << "grade get ended with" << status; + } + } + unlock(); } - QString pageString; - int status = 0; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) - { - statusBar->setIconConnectionStatus(jceStatusBar::Ready); - if ((status = loginHandel->makeGradeRequest(ui->spinBoxCoursesFromYear->value(), - ui->spinBoxCoursesToYear->value(),ui->spinBoxCoursesFromSemester->value(), - ui->spinBoxCoursesToSemester->value())) == jceLogin::JCE_PAGE_PASSED) - { - qDebug() << Q_FUNC_INFO << "grade page is ready"; - statusBar->setIconConnectionStatus(jceStatusBar::Inserting); - pageString = loginHandel->getCurrentPageContect(); - courseTableMgr->setCoursesList(pageString); - courseTableMgr->insertJceCoursesIntoTable(); - statusBar->setIconConnectionStatus(jceStatusBar::Done); - } - else if (status == jceLogin::JCE_NOT_CONNECTED) - { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); - } - else - { - statusBar->setIconConnectionStatus(jceStatusBar::ERROR); - qCritical() << Q_FUNC_INFO << "grade get ended with" << status; - } - } - QApplication::restoreOverrideCursor(); } bool MainScreen::checkIfValidDates() { - bool flag = false; - if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) + bool flag = false; + if (ui->spinBoxCoursesFromYear->value() < ui->spinBoxCoursesToYear->value()) { - //doesnt matter what is the semester, its valid! - flag = true; - } - else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) - { - //semester from must be equal or less than to semester - if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + //doesnt matter what is the semester, its valid! flag = true; } - return flag; + else if ((ui->spinBoxCoursesFromYear->value() == ui->spinBoxCoursesToYear->value())) + { + //semester from must be equal or less than to semester + if (ui->spinBoxCoursesFromSemester->value() <= ui->spinBoxCoursesToSemester->value()) + flag = true; + } + return flag; } void MainScreen::on_checkBoxCoursesInfluence_toggled(bool checked) { - qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; - this->userLoginSetting->setInfluenceCourseOnly(checked); - this->courseTableMgr->influnceCourseChanged(checked); + qDebug() << Q_FUNC_INFO << "only main courses toggeled" << checked; + this->userLoginSetting->setInfluenceCourseOnly(checked); + this->courseTableMgr->influnceCourseChanged(checked); } void MainScreen::on_spinBoxCoursesFromYear_valueChanged(int arg1) { - ui->spinBoxCoursesFromYear->setValue(arg1); + ui->spinBoxCoursesFromYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesToYear_valueChanged(int arg1) { - ui->spinBoxCoursesToYear->setValue(arg1); + ui->spinBoxCoursesToYear->setValue(arg1); } void MainScreen::on_spinBoxCoursesFromSemester_valueChanged(int arg1) { - ui->spinBoxCoursesFromSemester->setValue(arg1%4); + ui->spinBoxCoursesFromSemester->setValue(arg1%4); } void MainScreen::on_spinBoxCoursesToSemester_valueChanged(int arg1) { - ui->spinBoxCoursesToSemester->setValue(arg1%4); + ui->spinBoxCoursesToSemester->setValue(arg1%4); } void MainScreen::on_coursesTable_itemChanged(QTableWidgetItem *item) { - if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) - ui->avgLCD->display(courseTableMgr->getAvg()); - else + if (this->courseTableMgr->changes(item->text(),item->row(),item->column())) + ui->avgLCD->display(courseTableMgr->getAvg()); + else { - qWarning() << Q_FUNC_INFO << "missmatch data"; - QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); + qWarning() << Q_FUNC_INFO << "missmatch data"; + QMessageBox::critical(this,tr("Error"),tr("Missmatching data")); } } void MainScreen::on_clearTableButton_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - courseTableMgr->clearTable(); - ui->avgLCD->display(courseTableMgr->getAvg()); + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + courseTableMgr->clearTable(); + ui->avgLCD->display(courseTableMgr->getAvg()); } void MainScreen::on_graphButton_clicked() { - qDebug() << Q_FUNC_INFO; - courseTableMgr->showGraph(); + qDebug() << Q_FUNC_INFO; + courseTableMgr->showGraph(); } //EVENTS ON CALENDAR TAB void MainScreen::on_examsBtn_clicked() { - calendar->showExamDialog(); - + calendar->showExamDialog(); } void MainScreen::on_getCalendarBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - int status = 0; - QString page; - QApplication::setOverrideCursor(Qt::WaitCursor); - if (loginHandel->isLoggedInFlag()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (!isBusy()) { - if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + lock(); + int status = 0; + QString page; + if (loginHandel->isLoggedInFlag()) { - statusBar->setIconConnectionStatus(jceStatusBar::Inserting); - calendar->resetTable(); - page = loginHandel->getCurrentPageContect(); - calendar->setCalendar(page); - - qDebug() << Q_FUNC_INFO << "calendar is loaded"; - - //auto getting exam - if (loginHandel->isLoggedInFlag()) + if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { - if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + statusBar->setIconConnectionStatus(jceStatusBar::Inserting); + calendar->resetTable(); + page = loginHandel->getCurrentPageContect(); + calendar->setCalendar(page); + + qDebug() << Q_FUNC_INFO << "calendar is loaded"; + + //auto getting exam + if (loginHandel->isLoggedInFlag()) { - page = loginHandel->getCurrentPageContect(); - calendar->setExamsSchedule(page); - qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; - statusBar->setIconConnectionStatus(jceStatusBar::Done); + if ((status = loginHandel->makeExamsScheduleRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) + { + page = loginHandel->getCurrentPageContect(); + calendar->setExamsSchedule(page); + qDebug() << Q_FUNC_INFO << "exams schedule is loaded"; + statusBar->setIconConnectionStatus(jceStatusBar::Done); + } + else if (status == jceLogin::JCE_NOT_CONNECTED) + { + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); + } + else + qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; } - else if (status == jceLogin::JCE_NOT_CONNECTED) + else if (status == jceLogin::JCE_NOT_CONNECTED) { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); + qWarning() << Q_FUNC_INFO << "not connected"; + QApplication::restoreOverrideCursor(); + QMessageBox::critical(this,tr("Error"),tr("Not Connected")); + statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); } - else - qCritical() << Q_FUNC_INFO << "exams request get ended with" << status; + else + qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } - else if (status == jceLogin::JCE_NOT_CONNECTED) - { - qWarning() << Q_FUNC_INFO << "not connected"; - QApplication::restoreOverrideCursor(); - QMessageBox::critical(this,tr("Error"),tr("Not Connected")); - statusBar->setIconConnectionStatus(jceStatusBar::Disconnected); - } - else - qCritical() << Q_FUNC_INFO << "calendar get ended with" << status; } + unlock(); } - QApplication::restoreOverrideCursor(); } void MainScreen::on_exportToCVSBtn_clicked() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); - if (loginHandel->isLoggedInFlag()) + qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); + if (loginHandel->isLoggedInFlag()) { - this->calendar->exportCalendarCSV(); + this->calendar->exportCalendarCSV(); } } //EVENTS ON MENU BAR void MainScreen::on_actionCredits_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::about(this, "About", - "Jce Manager v1.0.0

                          " - +tr("License:")+ - "
                          GNU LESSER GENERAL PUBLIC LICENSE V2.1
                          " - +"
                          "+ - "JceManager Repository"+ - "

                          " - +tr("Powered By: ")+ - " Jce Connection

                          " - +tr("Developed By")+ - ":" - ); + qDebug() << Q_FUNC_INFO; + QMessageBox::about(this, "About", + "Jce Manager v1.0.0

                          " + +tr("License:")+ + "
                          GNU LESSER GENERAL PUBLIC LICENSE V2.1
                          " + +"
                          "+ + "JceManager Repository"+ + "

                          " + +tr("Powered By: ")+ + " Jce Connection

                          " + +tr("Developed By")+ + ":" + ); } void MainScreen::on_actionExit_triggered() { - qDebug() << Q_FUNC_INFO; - exit(0); + qDebug() << Q_FUNC_INFO; + exit(0); } void MainScreen::on_actionHow_To_triggered() { - qDebug() << Q_FUNC_INFO; - QMessageBox::information(this,"How To", - "" - +tr("Help Guide")+ - "
                            " - +tr("
                          • Login:
                            • Type your username and password and click Login.
                            • Once you are connected, you will see a green ball in the right buttom panel.
                          • ") - +tr("
                          • Getting GPA sheet
                            • Click on GPA Tab
                            • Select your dates and click on Add
                          • ") - +tr("
                          • Average Changing
                            • Change one of your grade and see the average in the buttom panel changing.
                          • ") - +tr("
                          • Getting Calendar
                            • Click on Calendar Tab
                            • Select your dates and click on Get Calendar
                          • ") - +tr("
                          • For exporting your calendar to a .CSV file:
                            • Do previous step and continue to next step
                            • Click on Export to CSV
                            • Select your dates and click OK
                            • Once you're Done, go on your calendar and import your csv file
                            • ")+ - "

                              " - +tr("For more information, please visit us at: Jce Manager site")); + qDebug() << Q_FUNC_INFO; + QMessageBox::information(this,"How To", + "" + +tr("Help Guide")+ + "
                                " + +tr("
                              • Login:
                                • Type your username and password and click Login.
                                • Once you are connected, you will see a green ball in the right buttom panel.
                              • ") + +tr("
                              • Getting GPA sheet
                                • Click on GPA Tab
                                • Select your dates and click on Add
                              • ") + +tr("
                              • Average Changing
                                • Change one of your grade and see the average in the buttom panel changing.
                              • ") + +tr("
                              • Getting Calendar
                                • Click on Calendar Tab
                                • Select your dates and click on Get Calendar
                              • ") + +tr("
                              • For exporting your calendar to a .CSV file:
                                • Do previous step and continue to next step
                                • Click on Export to CSV
                                • Select your dates and click OK
                                • Once you're Done, go on your calendar and import your csv file
                                • ")+ + "

                                  " + +tr("For more information, please visit us at: Jce Manager site")); } void MainScreen::on_actionHebrew_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionEnglish->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; - data->setLocal("he"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionEnglish->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; + data->setLocal("he"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionHebrew->setChecked(true); + else + ui->actionHebrew->setChecked(true); } void MainScreen::on_actionEnglish_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to English"; - data->setLocal("en"); - QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to English"; + data->setLocal("en"); + QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionEnglish->setChecked(true); + else + ui->actionEnglish->setChecked(true); } void MainScreen::on_actionOS_Default_triggered() { - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) + qDebug() << Q_FUNC_INFO; + if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) { - ui->actionHebrew->setChecked(false); - ui->actionEnglish->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; - data->setLocal("default"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + ui->actionHebrew->setChecked(false); + ui->actionEnglish->setChecked(false); + qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; + data->setLocal("default"); + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); } - else - ui->actionOS_Default->setChecked(true); + else + ui->actionOS_Default->setChecked(true); } void MainScreen::checkLocale() { - if(data->getLocal() == "en") + if(data->getLocal() == "en") { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(true); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(true); }else if(data->getLocal() == "he"){ - ui->actionHebrew->setChecked(true); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(true); + ui->actionOS_Default->setChecked(false); + ui->actionEnglish->setChecked(false); }else{ - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(true); - ui->actionEnglish->setChecked(false); + ui->actionHebrew->setChecked(false); + ui->actionOS_Default->setChecked(true); + ui->actionEnglish->setChecked(false); } } +//MAIN SCREEN void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { - qDebug() << Q_FUNC_INFO << "link: " << link; + qDebug() << Q_FUNC_INFO << "link: " << link; +} +/** + * @brief MainScreen::lock + * turn isblocked into true to avoid multiple requests and to cause errors + */ +void MainScreen::lock() +{ + QApplication::setOverrideCursor(Qt::WaitCursor); + this->isBlocked = true; +} +void MainScreen::unlock() +{ + QApplication::restoreOverrideCursor(); + this->isBlocked = false; +} +bool MainScreen::isBusy() +{ + return this->isBlocked; } - - diff --git a/main/mainscreen.h b/main/mainscreen.h index 59e40b5..73066b6 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -66,8 +66,14 @@ private: void checkLocale(); bool checkIfValidDates(); + bool isBusy(); + void lock(); + void unlock(); + Ui::MainScreen *ui; + bool isBlocked; + QPixmap iconPix; user *userLoginSetting; SaveData *data; From a33939c93b34556605cd96fc4dda6b9ab69c83cd Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 01:59:57 +0300 Subject: [PATCH 32/58] add .csv to exportation, fix progressbar --- main/CourseTab/coursestablemanager.cpp | 4 +++- main/jceWidgets/jcestatusbar.cpp | 8 +++++--- main/mainscreen.cpp | 2 +- src/jceData/CSV/csv_exporter.cpp | 6 +++--- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index 6c7404c..a0853c3 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -196,7 +196,9 @@ void coursesTableManager::addRow(const gradeCourse *courseToAdd) hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); grade = new QTableWidgetItem(); - // grade->setData(Qt::EditRole,c->getGrade()); //BUG good for sorting, the problem is when you edit -> the cell indicator disappear + //grade->setData(Qt::EditRole,c->getGrade()); + //BUG QT bug + //good for sorting, the problem is when you edit -> the cell indicator disappear grade->setText(QString::number(c->getGrade())); addition = new QTableWidgetItem(); diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index 59fe9d7..45c978d 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -57,7 +57,7 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) showMessage(tr("Disconnected")); break; case jceProgressStatus::Ready: - setProgressValue(100); + setProgressValue(0); iconPix.load(":/icons/redStatusIcon.png"); showMessage(tr("Ready")); break; @@ -67,12 +67,14 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) showMessage(tr("Connecting...")); break; case jceProgressStatus::Sending: - setProgressValue(10); + if (progressBar->value() < 10) + setProgressValue(10); iconPix.load(":/icons/blueStatusIcon.png"); showMessage(tr("Sending...")); break; case jceProgressStatus::Recieving: - setProgressValue(15); + if (progressBar->value() < 15) + setProgressValue(15); iconPix.load(":/icons/blueStatusIcon.png"); showMessage(tr("Recieving...")); break; diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 8529604..c457b1f 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -1,6 +1,5 @@ #include "mainscreen.h" #include "ui_mainscreen.h" -//TODO: busy flag to avoid overload request MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainScreen) { @@ -251,6 +250,7 @@ void MainScreen::on_getCalendarBtn_clicked() QString page; if (loginHandel->isLoggedInFlag()) { + statusBar->setIconConnectionStatus(jceStatusBar::Ready); if ((status = loginHandel->makeCalendarRequest(ui->spinBoxYear->value(),ui->spinBoxSemester->value())) == jceLogin::JCE_PAGE_PASSED) { statusBar->setIconConnectionStatus(jceStatusBar::Inserting); diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index 96545f4..f1843c8 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -110,11 +110,11 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca */ QString CSV_Exporter::getFileFath() { - QString fileName = QFileDialog::getSaveFileName(); + QString fileName = QFileDialog::getSaveFileName(NULL, + QObject::tr("JceManager Save Schedule Dialog"), "", + QObject::tr("CSV Files (*.csv);;All Files (*)")); if (fileName == "") return NULL; - if (!fileName.contains(".csv", Qt::CaseInsensitive)) - fileName.append(".csv"); return fileName; } From 10f53aa3f3df1d757d7708856242a9b98225fa9d Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 04:31:36 +0300 Subject: [PATCH 33/58] gpa grade gradient, cleartable on get gpa --- main/CourseTab/coursestablemanager.cpp | 418 ++++++++++++------------ main/CourseTab/coursestablemanager.h | 10 +- main/LoginTab/loginhandler.cpp | 2 +- main/mainscreen.cpp | 4 +- src/jceConnection/jcesslclient.cpp | 2 +- src/jceData/Grades/gradePage.cpp | 9 +- src/jceData/Grades/graph/gradegraph.cpp | 8 +- src/jceSettings/jcelogin.cpp | 3 + 8 files changed, 237 insertions(+), 219 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index a0853c3..b778e8b 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -5,46 +5,46 @@ */ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { - this->gp = NULL; - this->us = usrPtr; - this->courseTBL = ptr; + this->gp = NULL; + this->us = usrPtr; + this->courseTBL = ptr; - /* + /* * Initilizing Table */ - courseTBL->setRowCount(0); - courseTBL->setColumnCount(COURSE_FIELDS); - QStringList mz; - mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); - courseTBL->setHorizontalHeaderLabels(mz); - courseTBL->verticalHeader()->setVisible(false); - courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); - courseTBL->setShowGrid(true); - courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); + courseTBL->setRowCount(0); + courseTBL->setColumnCount(COURSE_FIELDS); + QStringList mz; + mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); + courseTBL->setHorizontalHeaderLabels(mz); + courseTBL->verticalHeader()->setVisible(false); + courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); + courseTBL->setShowGrid(true); + courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); - graph = new gradegraph(ptr); + graph = new gradegraph(ptr); } coursesTableManager::~coursesTableManager() { - courseTBL = NULL; - delete gp; - gp = NULL; + courseTBL = NULL; + delete gp; + gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { - for (gradeCourse *c: gp->getCourses()) + for (gradeCourse *c: gp->getCourses()) { - if (us->getInfluenceCourseOnly()) + if (us->getInfluenceCourseOnly()) { - if (isCourseInfluence(c)) - addRow(c); + if (isCourseInfluence(c)) + addRow(c); } - else - addRow(c); + else + addRow(c); } } /** @@ -53,9 +53,9 @@ void coursesTableManager::insertJceCoursesIntoTable() */ void coursesTableManager::setCoursesList(QString &html) { - if (gp != NULL) - gp->~GradePage(); - gp = new GradePage(html); + clearTable(); + gp = new GradePage(html); + insertJceCoursesIntoTable(); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it @@ -67,81 +67,85 @@ void coursesTableManager::setCoursesList(QString &html) bool coursesTableManager::changes(QString change, int row, int col) { - bool isNumFlag = true; - if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) - return true; + bool isNumFlag = true; + if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) + return true; - int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); - for (gradeCourse *c: gp->getCourses()) + int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); + for (gradeCourse *c: gp->getCourses()) { - if (c->getSerialNum() == serialCourse) + if (c->getSerialNum() == serialCourse) { - switch (col) + switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): - c->setCourseNumInList(change.toInt()); - break; + c->setCourseNumInList(change.toInt()); + break; case (gradeCourse::CourseScheme::YEAR): - c->setYear(change.toInt()); - break; + c->setYear(change.toInt()); + break; case (gradeCourse::CourseScheme::SEMESTER): - c->setSemester(change.toInt()); - break; + c->setSemester(change.toInt()); + break; case (gradeCourse::CourseScheme::NAME): - c->setName(change); - break; + c->setName(change); + break; case (gradeCourse::CourseScheme::TYPE): - c->setType(change); - break; + c->setType(change); + break; case (gradeCourse::CourseScheme::POINTS): - { + { change.toDouble(&isNumFlag); if (!isNumFlag) - { + { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); - } + } else - c->setPoints(change.toDouble()); + c->setPoints(change.toDouble()); break; - } - case (gradeCourse::CourseScheme::HOURS): - { - change.toDouble(&isNumFlag); - - if (!isNumFlag) - { - courseTBL->item(row,col)->setText(QString::number(c->getHours())); - } - else - c->setHours(change.toDouble()); - break; - } - case (gradeCourse::CourseScheme::GRADE): - { - change.toDouble(&isNumFlag); - - if (!isNumFlag) - { - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } - else - { - if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) - c->setGrade(change.toDouble()); - else - courseTBL->item(row,col)->setText(QString::number(c->getGrade())); - } - break; - } - case (gradeCourse::CourseScheme::ADDITION): - c->setAdditions(change); - break; } - break; + case (gradeCourse::CourseScheme::HOURS): + { + change.toDouble(&isNumFlag); + + if (!isNumFlag) + { + courseTBL->item(row,col)->setText(QString::number(c->getHours())); + } + else + c->setHours(change.toDouble()); + break; + } + case (gradeCourse::CourseScheme::GRADE): + { + + change.toDouble(&isNumFlag); + + if (!isNumFlag) //not a number + { + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } + else + { + if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) + { + c->setGrade(change.toDouble()); + colorTheGrade(row); + } + else + courseTBL->item(row,col)->setText(QString::number(c->getGrade())); + } + break; + } + case (gradeCourse::CourseScheme::ADDITION): + c->setAdditions(change); + break; + } + break; } } - return isNumFlag; + return isNumFlag; } /** @@ -150,192 +154,202 @@ bool coursesTableManager::changes(QString change, int row, int col) */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { - int i=1,j=1; + int i=1,j=1; - j = 0; - QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; - const gradeCourse * c; - if (courseToAdd != NULL) + j = 0; + QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; + const gradeCourse * c; + if (courseToAdd != NULL) { - c = courseToAdd; - if (!isCourseAlreadyInserted(c->getSerialNum())) + c = courseToAdd; + if (!isCourseAlreadyInserted(c->getSerialNum())) { - courseTBL->setRowCount(courseTBL->rowCount() + 1); - i = courseTBL->rowCount()-1; + courseTBL->setRowCount(courseTBL->rowCount() + 1); + i = courseTBL->rowCount()-1; - number = new QTableWidgetItem(); - number->setData(Qt::EditRole, c->getCourseNumInList()); - number->setFlags(number->flags() & ~Qt::ItemIsEditable); + number = new QTableWidgetItem(); + number->setData(Qt::EditRole, c->getCourseNumInList()); + number->setFlags(number->flags() & ~Qt::ItemIsEditable); - year = new QTableWidgetItem(); - year->setData(Qt::EditRole,c->getYear()); - year->setFlags(year->flags() & ~Qt::ItemIsEditable); + year = new QTableWidgetItem(); + year->setData(Qt::EditRole,c->getYear()); + year->setFlags(year->flags() & ~Qt::ItemIsEditable); - semester = new QTableWidgetItem(); - semester->setData(Qt::EditRole,c->getSemester()); - semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); + semester = new QTableWidgetItem(); + semester->setData(Qt::EditRole,c->getSemester()); + semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); - serial = new QTableWidgetItem(); - serial->setData(Qt::EditRole,c->getSerialNum()); - serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); + serial = new QTableWidgetItem(); + serial->setData(Qt::EditRole,c->getSerialNum()); + serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); - name = new QTableWidgetItem(); - name->setData(Qt::EditRole,c->getName()); - name->setFlags(name->flags() & ~Qt::ItemIsEditable); + name = new QTableWidgetItem(); + name->setData(Qt::EditRole,c->getName()); + name->setFlags(name->flags() & ~Qt::ItemIsEditable); - type = new QTableWidgetItem(); - type->setData(Qt::EditRole, c->getType()); - type->setFlags(type->flags() & ~Qt::ItemIsEditable); + type = new QTableWidgetItem(); + type->setData(Qt::EditRole, c->getType()); + type->setFlags(type->flags() & ~Qt::ItemIsEditable); - points = new QTableWidgetItem(); - points->setData(Qt::EditRole, c->getPoints()); - points->setFlags(points->flags() & ~Qt::ItemIsEditable); + points = new QTableWidgetItem(); + points->setData(Qt::EditRole, c->getPoints()); + points->setFlags(points->flags() & ~Qt::ItemIsEditable); - hours = new QTableWidgetItem(); - hours->setData(Qt::EditRole, c->getHours()); - hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); + hours = new QTableWidgetItem(); + hours->setData(Qt::EditRole, c->getHours()); + hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); - grade = new QTableWidgetItem(); - //grade->setData(Qt::EditRole,c->getGrade()); - //BUG QT bug - //good for sorting, the problem is when you edit -> the cell indicator disappear - grade->setText(QString::number(c->getGrade())); + grade = new QTableWidgetItem(); + //grade->setData(Qt::EditRole,c->getGrade()); + //BUG QT bug + //good for sorting, the problem is when you edit -> the cell indicator disappear + grade->setText(QString::number(c->getGrade())); - addition = new QTableWidgetItem(); - addition->setData(Qt::EditRole,c->getAddidtions()); + addition = new QTableWidgetItem(); + addition->setData(Qt::EditRole,c->getAddidtions()); - courseTBL->setItem(i,j++,number); - courseTBL->setItem(i,j++,year); - courseTBL->setItem(i,j++,semester); - courseTBL->setItem(i,j++,serial); - courseTBL->setItem(i,j++,name); - courseTBL->setItem(i,j++,type); - courseTBL->setItem(i,j++,points); - courseTBL->setItem(i,j++,hours); - courseTBL->setItem(i,j,grade); + courseTBL->setItem(i,j++,number); + courseTBL->setItem(i,j++,year); + courseTBL->setItem(i,j++,semester); + courseTBL->setItem(i,j++,serial); + courseTBL->setItem(i,j++,name); + courseTBL->setItem(i,j++,type); + courseTBL->setItem(i,j++,points); + courseTBL->setItem(i,j++,hours); + courseTBL->setItem(i,j++,grade); + courseTBL->setItem(i,j,addition); - //FIXME : make it a function, add it when cell has changed - if(c->getGrade() < 55 && c->getGrade() != 0) - { - courseTBL->item(i, j)->setBackground(Qt::darkRed); - courseTBL->item(i,j)->setTextColor(Qt::white); - } - else if(55 <= c->getGrade() && c->getGrade() < 70 ) - { - courseTBL->item(i, j)->setBackground(Qt::darkYellow); - courseTBL->item(i,j)->setTextColor(Qt::white); - } - // else if(70 < c->getGrade() && c->getGrade() <= 80 ) - // courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! - // else if(c->getGrade() > 80) - // courseTBL->item(i, j)->setBackground(Qt::green); - - j++; - - courseTBL->setItem(i,j,addition); + colorTheGrade(i); } } - else + else { - qCritical() << Q_FUNC_INFO << " no course to load!"; + qCritical() << Q_FUNC_INFO << " no course to load!"; } - courseTBL->resizeColumnsToContents(); - courseTBL->resizeRowsToContents(); + courseTBL->resizeColumnsToContents(); + courseTBL->resizeRowsToContents(); } double coursesTableManager::getAvg() { - if (this->gp != NULL) - return gp->getAvg(); - return 0; + if (this->gp != NULL) + return gp->getAvg(); + return 0; } -void coursesTableManager::showGraph() +bool coursesTableManager::showGraph() { - qDebug() << Q_FUNC_INFO; - if (gp != NULL) + qDebug() << Q_FUNC_INFO; + if (gp != NULL) { - this->graph->showGraph(gp); - } - else - { - qWarning() << Q_FUNC_INFO << "open with null grade page"; + this->graph->showGraph(gp); + return true; } + qWarning() << Q_FUNC_INFO << "open with null grade page"; + return false; } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { - if (ignoreCourseStatus) + if (ignoreCourseStatus) { - int i = 0; - while (i < courseTBL->rowCount()) + int i = 0; + while (i < courseTBL->rowCount()) { - if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) - courseTBL->removeRow(i--); - i++; + if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) + courseTBL->removeRow(i--); + i++; } } - else + else { - if (this->gp != NULL) - for (gradeCourse *c: gp->getCourses()) - { - if (!(isCourseAlreadyInserted(c->getSerialNum()))) - if (c->getPoints() == 0) - addRow(c); - } + if (this->gp != NULL) + for (gradeCourse *c: gp->getCourses()) + { + if (!(isCourseAlreadyInserted(c->getSerialNum()))) + if (c->getPoints() == 0) + addRow(c); + } } } void coursesTableManager::clearTable() { - if (courseTBL->rowCount() == 0) - return; + if (courseTBL->rowCount() == 0) + return; - int i = 0; //starting point - while (courseTBL->rowCount() > i) + int i = 0; //starting point + while (courseTBL->rowCount() > i) { - gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); - courseTBL->removeRow(i); + if (gp != NULL) + gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); + courseTBL->removeRow(i); } - gp = NULL; - courseTBL->repaint(); + if (gp != NULL) + delete gp; + gp = NULL; + courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { - QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); - for (gradeCourse *c: gp->getCourses()) + QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); + for (gradeCourse *c: gp->getCourses()) { - if (c->getSerialNum() == courseSerial.toDouble()) - return c; + if (c->getSerialNum() == courseSerial.toDouble()) + return c; } - return NULL; + return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { - int i; - for (i = courseTBL->rowCount(); i >= 0; --i) + int i; + for (i = courseTBL->rowCount(); i >= 0; --i) { - if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) + if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { - QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); - if (QString::number(courseID) == courseSerial) - return true; + QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); + if (QString::number(courseID) == courseSerial) + return true; } } - return false; + return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { - if (courseToCheck->getPoints() > 0) - return true; - return false; + if (courseToCheck->getPoints() > 0) + return true; + return false; + +} +/** + * @brief coursesTableManager::colorTheGrade - color the course grade + * @param rowIndex - course's row index + */ +void coursesTableManager::colorTheGrade(int rowIndex) +{ + gradeCourse * temp = getCourseByRow(rowIndex); + if (temp != NULL) + { + if (temp->getGrade() != 0) + { + float green,red, blue = 0; + float grade = ((float)temp->getGrade()); + + green = qRound(grade * 255 / 100); + red = qRound((255 * (100 - grade) / 100)); + blue = 0; + //higher the grade -> the greener it is + courseTBL->item(rowIndex,gradeCourse::CourseScheme::GRADE)->setBackground(QColor(red,green,blue)); + courseTBL->item(rowIndex,gradeCourse::CourseScheme::GRADE)->setTextColor(Qt::black); + } + + } } diff --git a/main/CourseTab/coursestablemanager.h b/main/CourseTab/coursestablemanager.h index d7d1021..bf72c42 100644 --- a/main/CourseTab/coursestablemanager.h +++ b/main/CourseTab/coursestablemanager.h @@ -2,17 +2,13 @@ #define COURSESTABLEMANAGER_H -#include -#include -#include +#include #include #include #include #include #include -#include - #include "./src/jceData/Grades/graph/gradegraph.h" #include "./src/jceData/Grades/gradePage.h" #include "./src/jceSettings/user.h" @@ -28,7 +24,7 @@ public: void addRow(const gradeCourse * courseToAdd = 0); double getAvg(); - void showGraph(); + bool showGraph(); void influnceCourseChanged(bool status); void clearTable(); @@ -42,6 +38,8 @@ private: gradeCourse * getCourseByRow(int row); bool isCourseAlreadyInserted(double courseID); bool isCourseInfluence(const gradeCourse *courseToCheck); + + void colorTheGrade(int rowIndex); }; #endif // COURSESTABLEMANAGER_H diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index 6b7c2ac..be98d0a 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -59,6 +59,7 @@ bool loginHandler::makeConnection() { case jceLogin::JCE_YOU_ARE_IN: { + statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); logggedInFlag = true; return logggedInFlag; } @@ -145,7 +146,6 @@ int loginHandler::makeCalendarRequest(int year, int semester) else return jceLogin::JCE_NOT_CONNECTED; } - int loginHandler::makeExamsScheduleRequest(int year, int semester) { diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index c457b1f..e6c435b 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -152,7 +152,6 @@ void MainScreen::on_ratesButton_clicked() statusBar->setIconConnectionStatus(jceStatusBar::Inserting); pageString = loginHandel->getCurrentPageContect(); courseTableMgr->setCoursesList(pageString); - courseTableMgr->insertJceCoursesIntoTable(); statusBar->setIconConnectionStatus(jceStatusBar::Done); } else if (status == jceLogin::JCE_NOT_CONNECTED) @@ -231,7 +230,8 @@ void MainScreen::on_clearTableButton_clicked() void MainScreen::on_graphButton_clicked() { qDebug() << Q_FUNC_INFO; - courseTableMgr->showGraph(); + if (!courseTableMgr->showGraph()) + QMessageBox::critical(this,tr("Error"),tr("You must to load GPA first\nClick on 'Get GPA'")); } diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index b3e4579..4c72f16 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -172,7 +172,7 @@ bool jceSSLClient::recieveData(QString *str) disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); str->append(packet); -// qDebug() << *str; //if you want to see the whole packet, unmark me + qDebug() << *str; //if you want to see the whole packet, unmark me qDebug() << Q_FUNC_INFO << "packet size: " << packetSizeRecieved << "received data lenght: " << str->length(); qDebug() << Q_FUNC_INFO << "return with flag: " << recieveLastPacket; diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index f63be27..47e4307 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -135,8 +135,10 @@ gradeCourse* GradePage::lineToCourse(QString line) if (year >= maxYear) maxYear = year; - if (year <= minYear) + if ((year <= minYear) && (points > 0)) //not graded yet isnt influced year! + { minYear = year; + } tempC = new gradeCourse(year,semester,courseNumInList,serial,name,type,points,hours,grade,additions); return tempC; @@ -152,11 +154,12 @@ bool GradePage::isGradedYet(QString grade) if (strlen(grade.toStdString().c_str()) <= 1) return false; - for (char c: grade.toStdString()) + for (QChar c: grade) { if (c == '\0') break; - if (((!isdigit((int)c)) && (!isspace((int)c)))) //48 = 0, 57 = 9 + + if (((!c.isDigit()) && (!c.isSpace()))) //48 = 0, 57 = 9 return false; } diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 24e63f9..025ea3a 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -17,7 +17,8 @@ void gradegraph::showGraph(GradePage *gpPTR) qDebug() << Q_FUNC_INFO; this->gp = gpPTR; - clearGraph(); + if (ui->graphwidget->graphCount() > 0) + clearGraph(); setVisualization(); setGraphsData(); @@ -34,7 +35,7 @@ gradegraph::~gradegraph() void gradegraph::setGraphsData() { - int minYearInList = gp->getMinYearInList(); + int minYearInList = gp->getMinYearInList()-1; int maxYearInList = gp->getMaxYearInList()+1; int xRangeForYear = (maxYearInList - minYearInList+2)*3; QVector SemesterialAvg(xRangeForYear),yearlyAvg(xRangeForYear),indicatorX(xRangeForYear); @@ -134,8 +135,7 @@ void gradegraph::setVisualization() ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); ui->graphwidget->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::red, 7)); - - int minYearInList = gp->getMinYearInList(); + int minYearInList = gp->getMinYearInList()-1; int maxYearInList = gp->getMaxYearInList()+1; int xRangeForYear = (maxYearInList - minYearInList+2)*3; diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 013afe6..9774bbf 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -325,7 +325,10 @@ void jceLogin::reValidation() if (checkValidation()) { if (makeSecondVisit() == true) + { + statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); qDebug() << Q_FUNC_INFO << "Validated"; + } else qWarning() << Q_FUNC_INFO << "Second visit finished with an error"; } From ae7d20bedae82de56c76748c772a24223c453765 Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 05:12:00 +0300 Subject: [PATCH 34/58] add revert button in gpa tab --- main/CourseTab/coursestablemanager.cpp | 34 +++++++++++++++++++++++++ main/CourseTab/coursestablemanager.h | 3 +++ main/mainscreen.cpp | 11 ++++++++ main/mainscreen.h | 2 ++ main/mainscreen.ui | 19 +++++++++++--- src/jceConnection/jcesslclient.cpp | 2 +- src/jceData/Grades/gradeCourse.cpp | 11 ++++++++ src/jceData/Grades/gradeCourse.h | 1 + src/jceData/Grades/gradePage.cpp | 8 ++++++ src/jceData/Grades/gradePage.h | 1 + src/jceData/Grades/graph/gradegraph.cpp | 4 --- 11 files changed, 88 insertions(+), 8 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index b778e8b..2270f3f 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -6,6 +6,7 @@ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { this->gp = NULL; + this->gpCpy = NULL; this->us = usrPtr; this->courseTBL = ptr; @@ -29,6 +30,8 @@ coursesTableManager::~coursesTableManager() { courseTBL = NULL; delete gp; + delete gpCpy; + gpCpy = NULL; gp = NULL; } /** @@ -55,6 +58,7 @@ void coursesTableManager::setCoursesList(QString &html) { clearTable(); gp = new GradePage(html); + this->gpCpy = new GradePage(*gp); insertJceCoursesIntoTable(); } /** @@ -294,6 +298,36 @@ void coursesTableManager::clearTable() gp = NULL; courseTBL->repaint(); } +/** + * @brief coursesTableManager::revertChanges + * + * restored data from the copy of grade page + * TODO: revert-> make it efficient + */ +void coursesTableManager::revertChanges() +{ + if (courseTBL->rowCount() <= 0) + return; + if (this->gpCpy == NULL) + return; + if (this->gp == NULL) + return; + + for (int i = 0; i < courseTBL->rowCount(); ++i) + { + gradeCourse * temp = getCourseByRow(i); + for (gradeCourse * notChangedCourse: gpCpy->getCourses()) + { + if ((temp->getGrade() != notChangedCourse->getGrade()) && + (temp->getSerialNum() == notChangedCourse->getSerialNum())) + { + courseTBL->item(i,gradeCourse::CourseScheme::GRADE)->setText(QString::number(notChangedCourse->getGrade())); + + } + } + } + +} gradeCourse *coursesTableManager::getCourseByRow(int row) { diff --git a/main/CourseTab/coursestablemanager.h b/main/CourseTab/coursestablemanager.h index bf72c42..41e8713 100644 --- a/main/CourseTab/coursestablemanager.h +++ b/main/CourseTab/coursestablemanager.h @@ -29,10 +29,13 @@ public: void influnceCourseChanged(bool status); void clearTable(); + void revertChanges(); + private: gradegraph *graph; QTableWidget *courseTBL; GradePage *gp; + GradePage *gpCpy; user *us; gradeCourse * getCourseByRow(int row); diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index e6c435b..39eb484 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -233,6 +233,16 @@ void MainScreen::on_graphButton_clicked() if (!courseTableMgr->showGraph()) QMessageBox::critical(this,tr("Error"),tr("You must to load GPA first\nClick on 'Get GPA'")); } +void MainScreen::on_revertBtn_clicked() +{ + qDebug() << Q_FUNC_INFO; + if (!isBusy()) + { + lock(); + courseTableMgr->revertChanges(); + unlock(); + } +} //EVENTS ON CALENDAR TAB @@ -425,3 +435,4 @@ bool MainScreen::isBusy() { return this->isBlocked; } + diff --git a/main/mainscreen.h b/main/mainscreen.h index 73066b6..cc3b63e 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -61,6 +61,8 @@ private slots: void on_labelMadeBy_linkActivated(const QString &link); // void on_progressBar_valueChanged(int value); + void on_revertBtn_clicked(); + private: void checkLocale(); diff --git a/main/mainscreen.ui b/main/mainscreen.ui index d0884ab..ace596d 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -508,14 +508,14 @@ font-size: 15px; 0 - + 0 6 - + @@ -523,6 +523,12 @@ font-size: 15px; 0 + + + 16777215 + 35 + + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> @@ -537,7 +543,7 @@ font-size: 15px; true - + 0 0 @@ -559,6 +565,13 @@ font-size: 15px; + + + + Revert Changes + + + diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index 4c72f16..b3e4579 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -172,7 +172,7 @@ bool jceSSLClient::recieveData(QString *str) disconnect(this, SIGNAL(readyRead()), this, SLOT(readIt())); str->append(packet); - qDebug() << *str; //if you want to see the whole packet, unmark me +// qDebug() << *str; //if you want to see the whole packet, unmark me qDebug() << Q_FUNC_INFO << "packet size: " << packetSizeRecieved << "received data lenght: " << str->length(); qDebug() << Q_FUNC_INFO << "return with flag: " << recieveLastPacket; diff --git a/src/jceData/Grades/gradeCourse.cpp b/src/jceData/Grades/gradeCourse.cpp index 13b1a8c..d280102 100644 --- a/src/jceData/Grades/gradeCourse.cpp +++ b/src/jceData/Grades/gradeCourse.cpp @@ -11,6 +11,17 @@ gradeCourse::gradeCourse(int year, int semester, int courseNumInList, int serial this->courseNumInList = courseNumInList; } +gradeCourse::gradeCourse(gradeCourse &other) : Course(other.getSerialNum(),other.getName(),other.getType()) +{ + this->points = other.points; + this->hours = other.hours; + this->grade = other.grade; + this->additions = other.additions; + this->year = other.year; + this->semester = other.semester; + this->courseNumInList = other.courseNumInList; +} + gradeCourse::~gradeCourse() { diff --git a/src/jceData/Grades/gradeCourse.h b/src/jceData/Grades/gradeCourse.h index 8bd67e4..9884571 100644 --- a/src/jceData/Grades/gradeCourse.h +++ b/src/jceData/Grades/gradeCourse.h @@ -38,6 +38,7 @@ public: }; gradeCourse(int year, int semester, int courseNumInList, int serial, QString name, QString type, double points,double hours, double grade, QString additions); + gradeCourse(gradeCourse &other); ~gradeCourse(); int getYear() const { return this->year; } diff --git a/src/jceData/Grades/gradePage.cpp b/src/jceData/Grades/gradePage.cpp index 47e4307..f5703b7 100644 --- a/src/jceData/Grades/gradePage.cpp +++ b/src/jceData/Grades/gradePage.cpp @@ -8,6 +8,14 @@ GradePage::GradePage(QString html) : Page() tempHtml = getString(html); coursesListInit(tempHtml); } + +GradePage::GradePage(GradePage &other) +{ + for(gradeCourse* c : other.getCourses()) + { + courses.push_back(new gradeCourse(*c)); + } +} GradePage::~GradePage() { for (Course* c : courses) diff --git a/src/jceData/Grades/gradePage.h b/src/jceData/Grades/gradePage.h index 727c82d..741f757 100644 --- a/src/jceData/Grades/gradePage.h +++ b/src/jceData/Grades/gradePage.h @@ -29,6 +29,7 @@ class GradePage : public Page public: GradePage(QString html); + GradePage(GradePage &other); ~GradePage(); void removeCourse(QString courseSerialID); diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index 025ea3a..a1ad338 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -1,9 +1,5 @@ #include "gradegraph.h" #include "ui_gradegraph.h" -/* - * TODO: make graph understandable - * BUG: graph bug when theres small range of years - */ gradegraph::gradegraph(QWidget *parent) : QDialog(parent), ui(new Ui::gradegraph) { ui->setupUi(this); From 6cafe6dc7030f42951d24d69898048bf4c9e91b4 Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 06:17:57 +0300 Subject: [PATCH 35/58] added exam revert --- main/CourseTab/coursestablemanager.cpp | 6 +- src/jceData/CSV/csv_exporter.cpp | 4 +- src/jceData/Calendar/Exams/calendarExam.cpp | 15 ++ src/jceData/Calendar/Exams/calendarExam.h | 1 + .../Calendar/Exams/calendarExamCourse.cpp | 13 ++ .../Calendar/Exams/calendarExamCourse.h | 1 + src/jceData/Calendar/Exams/examDialog.cpp | 69 ++++++- src/jceData/Calendar/Exams/examDialog.h | 10 +- src/jceData/Calendar/Exams/examDialog.ui | 174 +++++++++++------- 9 files changed, 210 insertions(+), 83 deletions(-) diff --git a/main/CourseTab/coursestablemanager.cpp b/main/CourseTab/coursestablemanager.cpp index 2270f3f..60ef490 100644 --- a/main/CourseTab/coursestablemanager.cpp +++ b/main/CourseTab/coursestablemanager.cpp @@ -1,8 +1,4 @@ #include "coursestablemanager.h" -/* - * TODO: revert gpa to origin - * - */ coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { this->gp = NULL; @@ -322,7 +318,7 @@ void coursesTableManager::revertChanges() (temp->getSerialNum() == notChangedCourse->getSerialNum())) { courseTBL->item(i,gradeCourse::CourseScheme::GRADE)->setText(QString::number(notChangedCourse->getGrade())); - + break; } } } diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index f1843c8..7f22f69 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -2,8 +2,8 @@ /* * - * Class doc can be bound in csv_exporter.h - * + * Class doc can be found in csv_exporter.h + * TODO: add exam exportation */ CSV_Exporter::CSV_Exporter() { diff --git a/src/jceData/Calendar/Exams/calendarExam.cpp b/src/jceData/Calendar/Exams/calendarExam.cpp index 39b19b9..79d866f 100644 --- a/src/jceData/Calendar/Exams/calendarExam.cpp +++ b/src/jceData/Calendar/Exams/calendarExam.cpp @@ -4,6 +4,21 @@ calendarExam::calendarExam() { htmlDataHolderParsed = ""; } +/** + * @brief calendarExam::calendarExam + * copy constructor + * @param other + */ +calendarExam::calendarExam(calendarExam &other) +{ + examsCounter = 0; + exams.clear(); + for (calendarExamCourse * tempExam: other.getExams()) + { + this->exams.push_back(new calendarExamCourse(*tempExam)); + examsCounter++; + } +} /** * @brief calendarExam::setPage - getting a html page and stripping it into a exams schedule in a list diff --git a/src/jceData/Calendar/Exams/calendarExam.h b/src/jceData/Calendar/Exams/calendarExam.h index b538da4..dd43e46 100644 --- a/src/jceData/Calendar/Exams/calendarExam.h +++ b/src/jceData/Calendar/Exams/calendarExam.h @@ -20,6 +20,7 @@ class calendarExam : public Page { public: calendarExam(); + calendarExam(calendarExam &other); void setPage(QString html); QList getExams() { return exams; } diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.cpp b/src/jceData/Calendar/Exams/calendarExamCourse.cpp index 7e9859b..b613fd0 100644 --- a/src/jceData/Calendar/Exams/calendarExamCourse.cpp +++ b/src/jceData/Calendar/Exams/calendarExamCourse.cpp @@ -12,6 +12,19 @@ calendarExamCourse::calendarExamCourse(int serial, QString name, QString lecture setTime(firstHourbegin,true); setTime(secondHourbegin,false); +} + +calendarExamCourse::calendarExamCourse(calendarExamCourse &other) + :Course (other.getSerialNum(),other.getName(),other.getType()) +{ + this->lecturer = other.lecturer; + this->field = other.field; + this->firstDate = other.getFirstDate(); + this->firstHourbegin = other.firstHourbegin; + this->secondDate = other.secondDate; + this->secondHourbegin = other.secondHourbegin; + + } /** * @brief calendarExamCourse::setDate diff --git a/src/jceData/Calendar/Exams/calendarExamCourse.h b/src/jceData/Calendar/Exams/calendarExamCourse.h index 8cb3776..3512627 100644 --- a/src/jceData/Calendar/Exams/calendarExamCourse.h +++ b/src/jceData/Calendar/Exams/calendarExamCourse.h @@ -45,6 +45,7 @@ public: calendarExamCourse(int serial, QString name, QString lecturer, QString field, QString type, QString firstDate, QString firstHourbegin, QString secondDate, QString secondHourbegin); + calendarExamCourse(calendarExamCourse &other); QString getLecturer() const; diff --git a/src/jceData/Calendar/Exams/examDialog.cpp b/src/jceData/Calendar/Exams/examDialog.cpp index 2214363..c95cbbe 100644 --- a/src/jceData/Calendar/Exams/examDialog.cpp +++ b/src/jceData/Calendar/Exams/examDialog.cpp @@ -1,18 +1,17 @@ #include "examDialog.h" #include "ui_examDialog.h" -/* - *TODO: exam revert, add to csv exportation, dialog size - */ /** * @brief examDialog::examDialog * @param parent * @param calSchedPtr - list of courses with information about each exam */ -examDialog::examDialog(QWidget *parent, calendarExam *calSchedPtr) : QDialog(parent), +examDialog::examDialog(QWidget *parent, calendarExam *calExamPtr) : QDialog(parent), ui(new Ui::examDialog) { ui->setupUi(this); - exams = calSchedPtr; + exams = calExamPtr; + this->examsCpy = NULL; + QStringList headLine; //SERIAL, NAME, LECTURER, FIELD, TYPE, FIRST_DATE, FIRST_HOUR_BEGIN, SECOND_DATE, SECOND_HOUR_BEGIN @@ -42,6 +41,8 @@ void examDialog::initializingDataIntoTable() { disconnect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(upgradeExamsTime(QTableWidgetItem*))); ui->tableWidget->setRowCount(exams->getExamsCounter()); + this->examsCpy = new calendarExam(*exams); + int i=0,j=0; int year,month,day; //for constructin qdate by setdate QTableWidgetItem *lecturer,*name,*type; @@ -180,11 +181,65 @@ void examDialog::resetGeo() mHeight += ui->tableWidget->rowHeight(i) + 4; } - mHeight += ui->buttonBox->height() + 4; + mHeight += ui->frameBtns->height() + 30; mHeight += ui->labelHeader->height() + 4; this->setMinimumHeight(mHeight); -// this->setMaximumHeight(mHeight); } + +void examDialog::on_pushButtonOk_clicked() +{ + qDebug() << Q_FUNC_INFO; + this->hide(); +} + +void examDialog::on_pushButtonRevert_clicked() +{ + qDebug() << Q_FUNC_INFO; + + if (ui->tableWidget->rowCount() <= 0) + return; + if (this->exams == NULL) + return; + if (this->examsCpy == NULL) + return; + for (int i = 0; i < ui->tableWidget->rowCount(); ++i) + { + calendarExamCourse * temp = getExamByRow(i); + for (calendarExamCourse * notChangedCourse: examsCpy->getExams()) + { + if (temp->getSerialNum() == notChangedCourse->getSerialNum()) + { + if (temp->getFirstHourbegin() != notChangedCourse->getFirstHourbegin()) + { + ui->tableWidget->item(i,calendarExamCourse::CourseScheme::FIRST_HOUR_BEGIN)->setData(Qt::EditRole, QTime(notChangedCourse->getFirstHourbegin().hour(),notChangedCourse->getFirstHourbegin().minute()).toString("hh:mm")); + } + if (temp->getSecondHourbegin() != notChangedCourse->getSecondHourbegin()) + { + ui->tableWidget->item(i,calendarExamCourse::CourseScheme::SECOND_HOUR_BEGIN)->setData(Qt::EditRole, QTime(notChangedCourse->getSecondHourbegin().hour(),notChangedCourse->getSecondHourbegin().minute()).toString("hh:mm")); + } + break; //done with course. go to next row + } + } + } + +} + +calendarExamCourse *examDialog::getExamByRow(int row) +{ + int serialNum = ui->tableWidget->item(row,calendarExamCourse::CourseScheme::SERIAL)->text().toInt(); + for (calendarExamCourse * temp : exams->getExams()) + { + if (serialNum == temp->getSerialNum()) + return temp; + } + return NULL; +} + +void examDialog::on_pushButtonCancel_clicked() +{ + on_pushButtonRevert_clicked(); //make revert to discard all changes + this->hide(); +} diff --git a/src/jceData/Calendar/Exams/examDialog.h b/src/jceData/Calendar/Exams/examDialog.h index 04bc9d3..cf1160a 100644 --- a/src/jceData/Calendar/Exams/examDialog.h +++ b/src/jceData/Calendar/Exams/examDialog.h @@ -27,7 +27,7 @@ class examDialog : public QDialog Q_OBJECT public: - explicit examDialog(QWidget *parent,calendarExam * calSchedPtr); + explicit examDialog(QWidget *parent, calendarExam * calExamPtr); void initializingDataIntoTable(); ~examDialog(); @@ -35,12 +35,20 @@ private slots: bool upgradeExamsTime(QTableWidgetItem* item); + void on_pushButtonOk_clicked(); + + void on_pushButtonRevert_clicked(); + + void on_pushButtonCancel_clicked(); + private: + calendarExamCourse *getExamByRow(int row); void resetGeo(); Ui::examDialog *ui; calendarExam * exams; + calendarExam * examsCpy; }; #endif // EXAMDIALOG_H diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index 53829eb..981b1c8 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -19,81 +19,119 @@ Dialog - + - - - - 0 - 0 - + + + #frameAll { + border: 0px solids; +} - - <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + + QFrame::StyledPanel - - - - - - - 0 - 0 - - - - - - - - - 0 - 0 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + QFrame::Raised + + + + + #frameBtns { + border: 0px solids; +} + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 0 + + + + + + + <html><head/><body><p>Revert changes</p></body></html> + + + Revert + + + + + + + <html><head/><body><p>Discard and hide</p></body></html> + + + Cancel + + + + + + + <html><head/><body><p>Save and hide</p></body></html> + + + Ok + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + pushButtonRevert + + horizontalSpacer + + + + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + + + + - - - buttonBox - accepted() - examDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - examDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - + From cb696906f4903619f294196d8b15287cf3f8ef4a Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 06:29:46 +0300 Subject: [PATCH 36/58] fixed progress bar on login session --- main/LoginTab/loginhandler.cpp | 1 - main/jceWidgets/jcestatusbar.cpp | 173 ++++++++++++++++--------------- 2 files changed, 87 insertions(+), 87 deletions(-) diff --git a/main/LoginTab/loginhandler.cpp b/main/LoginTab/loginhandler.cpp index be98d0a..c1f0108 100644 --- a/main/LoginTab/loginhandler.cpp +++ b/main/LoginTab/loginhandler.cpp @@ -59,7 +59,6 @@ bool loginHandler::makeConnection() { case jceLogin::JCE_YOU_ARE_IN: { - statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); logggedInFlag = true; return logggedInFlag; } diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index 45c978d..0127f2c 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -1,107 +1,108 @@ #include "jcestatusbar.h" jceStatusBar::jceStatusBar(QWidget *parent) : - QStatusBar(parent) + QStatusBar(parent) { - this->setStyleSheet("QStatusBar { border: 0px solid black };"); - this->setFixedHeight(STATUS_ICON_HEIGH+5); - this->showMessage(tr("Ready")); + this->setStyleSheet("QStatusBar { border: 0px solid black };"); + this->setFixedHeight(STATUS_ICON_HEIGH+5); + this->showMessage(tr("Ready")); - //Icon - iconButtomStatusLabel = new QLabel(this); - iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); + //Icon + iconButtomStatusLabel = new QLabel(this); + iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); - //ProgressBar - progressBar = new QProgressBar(this); - connect(progressBar,SIGNAL(valueChanged(int)),this,SLOT(setProgressValue(int))); - connect(this,SIGNAL(progressHasPacket(int)),this,SLOT(addValueToProgressBar(int))); + //ProgressBar + progressBar = new QProgressBar(this); + connect(progressBar,SIGNAL(valueChanged(int)),this,SLOT(setProgressValue(int))); + connect(this,SIGNAL(progressHasPacket(int)),this,SLOT(addValueToProgressBar(int))); - progressBar->setFixedWidth(120); - progressBar->setFixedHeight(STATUS_ICON_HEIGH); - progressBar->setStyleSheet("QProgressBar {" - "border: 1px solid gray;" - "border-radius: 3px;" - "background: transparent;" - "padding: 1px;" - "}" - "QProgressBar::chunk {" - "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 #b4e391 , stop: 1 #61c419);" - "}"); - progressBar->setRange(0,100); - progressBar->setValue(0); - progressBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); - progressBar->setTextVisible(true); - progressBar->setFormat("%p%"); - progressBar->setOrientation(Qt::Horizontal); + progressBar->setFixedWidth(120); + progressBar->setFixedHeight(STATUS_ICON_HEIGH); + progressBar->setStyleSheet("QProgressBar {" + "border: 1px solid gray;" + "border-radius: 3px;" + "background: transparent;" + "padding: 1px;" + "}" + "QProgressBar::chunk {" + "background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 0.5, stop: 0 #b4e391 , stop: 1 #61c419);" + "}"); + progressBar->setRange(0,100); + progressBar->setValue(0); + progressBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + progressBar->setTextVisible(true); + progressBar->setFormat("%p%"); + progressBar->setOrientation(Qt::Horizontal); - addPermanentWidget(progressBar,0); - addPermanentWidget(iconButtomStatusLabel,0); + addPermanentWidget(progressBar,0); + addPermanentWidget(iconButtomStatusLabel,0); } void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) { - QPixmap iconPix; - switch (update) + QPixmap iconPix; + switch (update) { case jceProgressStatus::ERROR: - setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); - showMessage(tr("Error")); - break; + setProgressValue(0); + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Error")); + break; case jceProgressStatus::Disconnected: - setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); - showMessage(tr("Disconnected")); - break; + setProgressValue(0); + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Disconnected")); + break; case jceProgressStatus::Ready: - setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); - showMessage(tr("Ready")); - break; + setProgressValue(0); + iconPix.load(":/icons/redStatusIcon.png"); + showMessage(tr("Ready")); + break; case jceProgressStatus::Connecting: - setProgressValue(5); - iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Connecting...")); - break; + setProgressValue(5); + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Connecting...")); + break; case jceProgressStatus::Sending: - if (progressBar->value() < 10) - setProgressValue(10); - iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Sending...")); - break; + if (progressBar->value() < 10) + setProgressValue(10); + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Sending...")); + break; case jceProgressStatus::Recieving: - if (progressBar->value() < 15) + if (progressBar->value() < 15) setProgressValue(15); - iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Recieving...")); - break; - case jceProgressStatus::Inserting: - setProgressValue(80); - iconPix.load(":/icons/blueStatusIcon.png"); - showMessage(tr("Inserting")); - break; - case jceProgressStatus::LoggedIn: - setProgressValue(100); - iconPix.load(":/icons/greenStatusIcon.png"); - showMessage(tr("Logged In.")); - break; - case jceProgressStatus::Done: - setProgressValue(100); - iconPix.load(":/icons/greenStatusIcon.png"); - showMessage(tr("Done")); - break; + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Recieving...")); + break; case jceProgressStatus::Connected: - setProgressValue(100); - iconPix.load(":/icons/greenStatusIcon.png"); - showMessage(tr("Connected")); - break; - } - iconButtomStatusLabel->setPixmap(iconPix); + setProgressValue(30); + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Connected")); + break; + case jceProgressStatus::Inserting: + setProgressValue(80); + iconPix.load(":/icons/blueStatusIcon.png"); + showMessage(tr("Inserting")); + break; + case jceProgressStatus::LoggedIn: + setProgressValue(100); + iconPix.load(":/icons/greenStatusIcon.png"); + showMessage(tr("Logged In.")); + break; + case jceProgressStatus::Done: + setProgressValue(100); + iconPix.load(":/icons/greenStatusIcon.png"); + showMessage(tr("Done")); + break; - repaint(); + } + iconButtomStatusLabel->setPixmap(iconPix); + + repaint(); } /** @@ -110,21 +111,21 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) */ void jceStatusBar::setProgressValue(int value) { - if (value == 0) + if (value == 0) { - progressBar->setVisible(false); - progressBar->setValue(0); + progressBar->setVisible(false); + progressBar->setValue(0); } - else + else { - progressBar->setValue(value); - progressBar->setVisible(true); + progressBar->setValue(value); + progressBar->setVisible(true); } } void jceStatusBar::addValueToProgressBar(int value) { - progressBar->setValue(progressBar->value() + value); + progressBar->setValue(progressBar->value() + value); } From 773679374b4ce18f60e0192911273c7d0bf76ac8 Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 06:49:10 +0300 Subject: [PATCH 37/58] fixed resizing calendar dialog --- main/mainscreen.ui | 2 +- .../Calendar/coursesSchedule/calendarDialog.cpp | 6 ++++-- .../Calendar/coursesSchedule/calendarDialog.ui | 13 +++++++++++-- .../Calendar/coursesSchedule/calendarSchedule.cpp | 3 --- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index ace596d..a768d0a 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -74,7 +74,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 0 + 1 false diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp index bf36e36..cd9984f 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp @@ -43,12 +43,14 @@ void CalendarDialog::on_calStart_selectionChanged() { if(ui->calStart->selectedDate() >= ui->calEnd->selectedDate()) //User input is invalid { + changeLabeStatusIcon(false); - ui->lbl_status->setText(tr("The end of the semester can NOT be equal or before the semester begin.")); + ui->lbl_status->setText(tr("Invalid dates interval")); this->isOK = false; } else // input is valid { + this->resize(610,310); changeLabeStatusIcon(true); ui->lbl_status->setText(tr("Looks fine, Click \"OK\"")); this->isOK = true; @@ -69,7 +71,7 @@ void CalendarDialog::on_calEnd_selectionChanged() if(ui->calStart->selectedDate() >= ui->calEnd->selectedDate()) { changeLabeStatusIcon(false); - ui->lbl_status->setText(tr("The end of the semester can NOT be equal or before the semester begin.")); + ui->lbl_status->setText(tr("Invalid dates interval")); this->isOK = false; } diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui index 863d278..cf08792 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui @@ -6,12 +6,12 @@ 0 0 - 610 + 609 310 - + 0 0 @@ -156,6 +156,15 @@ + + + 0 + 0 + + + + + <b>Please chose your dates correctly</b> diff --git a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp index 6017097..99afda7 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp @@ -1,7 +1,4 @@ #include "calendarSchedule.h" -/* - * BUG: fix resizing when showing error on dates validation - */ calendarSchedule::calendarSchedule(QWidget *parent) : QTableWidget(parent) { QStringList days,hours; From 2cd9ea4f8d9d772b6af4a95976064965090609a5 Mon Sep 17 00:00:00 2001 From: liranbg Date: Mon, 13 Oct 2014 06:50:11 +0300 Subject: [PATCH 38/58] login tab on open --- main/mainscreen.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index a768d0a..ace596d 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -74,7 +74,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 1 + 0 false From e48ae9d43c075cb9f66b01611dbc31971d1165f9 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 16:00:58 +0300 Subject: [PATCH 39/58] fixed win compilation error --- main/jceWidgets/jcestatusbar.cpp | 2 +- main/jceWidgets/jcestatusbar.h | 7 ++++--- main/mainscreen.cpp | 2 +- src/jceSettings/jcelogin.cpp | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index 0127f2c..e4f060b 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -46,7 +46,7 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) QPixmap iconPix; switch (update) { - case jceProgressStatus::ERROR: + case jceProgressStatus::Error: setProgressValue(0); iconPix.load(":/icons/redStatusIcon.png"); showMessage(tr("Error")); diff --git a/main/jceWidgets/jcestatusbar.h b/main/jceWidgets/jcestatusbar.h index bfff49e..226980c 100644 --- a/main/jceWidgets/jcestatusbar.h +++ b/main/jceWidgets/jcestatusbar.h @@ -12,6 +12,7 @@ class jceStatusBar : public QStatusBar { Q_OBJECT + public: enum jceProgressStatus @@ -25,7 +26,7 @@ public: Recieving, Inserting, Done, - ERROR + Error }; jceStatusBar(QWidget *parent = 0); @@ -45,8 +46,8 @@ private slots: private: - QProgressBar * progressBar; - QLabel *iconButtomStatusLabel; + QProgressBar * progressBar; + QLabel *iconButtomStatusLabel; }; #endif // JCESTATUSBAR_H diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 39eb484..6a98d5b 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -163,7 +163,7 @@ void MainScreen::on_ratesButton_clicked() } else { - statusBar->setIconConnectionStatus(jceStatusBar::ERROR); + statusBar->setIconConnectionStatus(jceStatusBar::Error); qCritical() << Q_FUNC_INFO << "grade get ended with" << status; } } diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 9774bbf..8bdad6f 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -97,7 +97,7 @@ int jceLogin::makeConnection() status = jceStatus::JCE_NOT_CONNECTED; if (status != jceStatus::JCE_YOU_ARE_IN) - statusBar->setIconConnectionStatus(jceStatusBar::ERROR); + statusBar->setIconConnectionStatus(jceStatusBar::Error); //we throw status even if we are IN! qDebug() << Q_FUNC_INFO << "return status: " << status; return status; From 2209923153d4bef375b15e777c2f47db955648f0 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 17:11:57 +0300 Subject: [PATCH 40/58] locale, statusbar locale: english as default statusbar: progressbar dissappear at 100% --- main/jceWidgets/jcestatusbar.cpp | 2 +- main/main.cpp | 13 +++++++------ src/appDatabase/savedata.cpp | 6 +++--- src/jceSettings/jcelogin.cpp | 3 --- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index e4f060b..4c7a741 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -111,7 +111,7 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) */ void jceStatusBar::setProgressValue(int value) { - if (value == 0) + if (value == 0 || value == 100) { progressBar->setVisible(false); progressBar->setValue(0); diff --git a/main/main.cpp b/main/main.cpp index 8901e01..7e82ce7 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -7,6 +7,7 @@ //TODO: Project todo list //update translation, update site spelling, release notes, update help +//BUG: fix locale on windows int main(int argc, char *argv[]) { #ifdef QT_DEBUG // Incase QtCreator is in Debug mode all qDebug messages will go to terminal @@ -24,17 +25,17 @@ int main(int argc, char *argv[]) SaveData data; loco = data.getLocal(); //Loading Local (From Settings file (SaveData.cpp) - if(loco == "default") + if(loco == "en") { - QString locale = QLocale::system().name(); - translator.load("jce_"+locale , a.applicationDirPath()); - qDebug() << Q_FUNC_INFO << "Local : Default Local Loaded"; + translator.load("jce_" + loco , a.applicationDirPath()); + qDebug() << Q_FUNC_INFO << "Locale : English Local Loaded"; }else if(loco == "he"){ - translator.load("jce_he" , a.applicationDirPath()); + translator.load("jce_" + loco , a.applicationDirPath()); qDebug() << Q_FUNC_INFO << "Local : Hebrew Local Loaded"; }else{ translator.load("jce_en" , a.applicationDirPath()); - qDebug() << Q_FUNC_INFO << "Local : English Local Loaded"; + data.reset(); + qCritical() << Q_FUNC_INFO << "save data corrupted, rested file."; } a.installTranslator(&translator); //Setting local a.setApplicationVersion(APP_VERSION); diff --git a/src/appDatabase/savedata.cpp b/src/appDatabase/savedata.cpp index bb0e439..dee5476 100644 --- a/src/appDatabase/savedata.cpp +++ b/src/appDatabase/savedata.cpp @@ -88,7 +88,7 @@ void SaveData::setCal(QString cal) */ void SaveData::setLocal(QString local) { - DB.insert("local", local); + DB.insert("locale", local); save(); } @@ -116,7 +116,7 @@ QString SaveData::getPassword() */ QString SaveData::getLocal() { - return DB.value("local"); + return DB.value("locale"); } /** @@ -160,7 +160,7 @@ void SaveData::createDB() { DB.insert("username", ""); DB.insert("password", ""); - DB.insert("local", "default"); + DB.insert("locale", "en"); DB.insert("calendar", ""); } diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 8bdad6f..7819b46 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -152,9 +152,6 @@ void jceLogin::reMakeConnection() */ int jceLogin::makeFirstVisit() { - QString usr = jceA->getUsername(); - QString psw = jceA->getPassword(); - if (JceConnector->sendData(jceLoginHtmlScripts::makeRequest(jceLoginHtmlScripts::getFirstValidationStep(*jceA)))) { if (!JceConnector->recieveData(recieverPage)) From cc9aa67c873f1cf663b4f9596570d60ab9ecdb38 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 17:35:55 +0300 Subject: [PATCH 41/58] update translations --- jce_en.qm | Bin 19316 -> 24660 bytes jce_en.ts | 561 ++++++++++++++++------- jce_he.qm | Bin 11404 -> 16714 bytes jce_he.ts | 561 ++++++++++++++++------- main/main.cpp | 3 +- src/jceData/Calendar/Exams/examDialog.ui | 13 +- 6 files changed, 808 insertions(+), 330 deletions(-) diff --git a/jce_en.qm b/jce_en.qm index 1aa73791285d128f24905abd49d33dfc8a4cf2d9..2d167f62eaa8303d8f1f680827dcb17c5f519c16 100644 GIT binary patch delta 5200 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 delta 1730 zcmZ`)Yfw~W7=F&~Ik1mC$mWn*`3#4g*I z7aGhTo}tVO4w;Ubsj)LEQyFQK*TM!HwIoR$f0%`4nuC_T3rg6GKfe9G@BN89}w3CSUvr)_LIO~sG+$XTxlMVsss1l1t9iEaNQzMyd9wfp@3{1##ZkILRye``yYVsMEaRz zfW3q=|D=^bWD+XgchLOz@SLQFbuAT2I*m$~1fuaOrhiANhLFH>!xc&EJfbq_GDP`)=l0WfRjC+}<`M@!|sGik3*W2b+b0~p`* zv*!ojro!#)RXr(BYiEDmc#H~^uy@<&3dZea?`7)9;)h(`wXeyE1Dv^x@F`ch@_rI( ze#k9eQU&DNxTb4_E4jRmu}4%8R?9>|6dFpwOv`3n)J` zPt}}BPWZ<-RIU4OlZ92Pb`u43n^j#sJ`%89tvX8a@!9H%WBI_0bL#pDJIRSz>d!aP zBP;gsQ`1!RSX+3*zA7p(hPP&)C!Q00$JtnVbiMose(HE)J>OMHjS2Vou9^rSv6ugh z@e+O|f4o@*KOzojH0e{RV82G}KLTX!(lo80yG&;_t9Mf33w4^-E>aF?_NU6|l^1Bb ztJhQE>)P;WD=>9Ht1B)h2O6}+J%bd_(0cvx^cY_XTb=t3kdPj>W&Un*u0HI7fSRoeVOH-6l(!5ZI z#PE8lMQxF;@N>8{7~qi3s3N87%CJ~PP+$m+F*b3j==F&nVMe3VD;RwRlocZ%#-_!O z;Kq*NY(Bfk_ZX@7uR}E!Lxe!15l))jsHb1wqo|kSOKEs1BEmx_3t=au04pjfSAc`! z!R#h1qZ1dc-9xxwynbjMJbwyb?IVIkXdu$e5xwT>#iAfKIt6#V;G?DYahnV6je@nZ zT5!;D(=xkDaC>N7@AimK;vC|lhQ`dGg#m+RmO79TGlz``fstBtj#QBwoldDKp*%4h zrXlUa9@ya-fhbIN7wNEjr0=y6F)G5jsISoo&g2q@j{^@9DwyP`;7y?jW^%zz-WiY; z+>bD_W{-PmkWDHT(z5ih5TB21c$xy - + CalendarDialog - + Dates Dialog Dialog Dates Dialog - - <body><p><span style=" font-size:9pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p> - <body><p><span style=" font-size:9pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p> + + <html><head/><body><p align="center"><span style=" font-size:14pt; font-weight:600;">Schedule Exportation</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:14pt; font-weight:600;">Schedule Exportation</span></p></body></html> - - Semester Starts At: - <b>Semester Starts At: + + <html><head/><body><p align="center">Semester Starts At:</p></body></html> + <html><head/><body><p align="center">Semester Starts At:</p></body></html> - - Semester Ends At: - <b>Semester Ends At: + + <html><head/><body><p align="center">Semester Ends At:</p></body></html> + <html><head/><body><p align="center">Semester Ends At:</p></body></html> - + + <html><head/><body><p align="center"><span style=" font-size:12pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:12pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p></body></html> + + + + Include Exams + Include Exams + + + <b>Please chose your dates correctly</b> <b>Please chose your dates correctly</b> - - - The end of the semester can NOT be equal or before the semester begin. - The end of the semester can NOT be equal or before the semester begin. + + + Invalid dates interval + Invalid dates interval - - + + Looks fine, Click "OK" + Looks fine, Click "OK" + + + Looks ok, Press OK Looks ok, Press OK @@ -50,250 +64,266 @@ JCE Manager - - + + Login Login - + Keep login Keep login - + Username Username - + Password Password - + GPA GPA - + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> - - Add - Add - - - + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> - - Clear - Clear - - - + Average: Average: - + Only Main Courses Only Main Courses - - From - <b>From</b> - - - - + + Year: Year: - + + Semester: Semester: - - To - <b>To</b> - - - - Semester - Semester - - - - Calendar - Calendar - - - - Get Calendar - Get Calendar - - - + Export to CSV Export to .CSV - + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="right">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - + + <html><head/><body><p align="center">To</p></body></html> + <html><head/><body><p align="center">To</p></body></html> + + + + Clear Table + Clear Table + + + + Get GPA + Get GPA + + + + Revert Changes + Revert Changes + + + + <html><head/><body><p align="center">From</p></body></html> + <html><head/><body><p align="center">From</p></body></html> + + + + Graph View + Graph View + + + + Schedule + Schedule + + + + Get Schedule && Exam + Get Schedule && Exam + + + + Show Exams + Show Exams + + + &File &File - + Language Language - + Credits Credits - + Exit Exit - + Hebrew עברית - + English English - + OS Default OS Default - + How To How To - - Ready - Ready - - - - - - + + + + + + Error Error - + Invalid Dates. Make Sure everything is correct and try again Invalid dates. Make sure everything is correct and try again - - + + + Not Connected Not Connected - + Missmatching data Missmatching Data - + License: License: - + Powered By: powered by: Powered By: - + Developed By Developed By - + Help Guide Guide Help Guide - + Liran Liran Ben Gida - + + You must to load GPA first +Click on 'Get GPA' + You must to load GPA first +Click on 'Get GPA' + + + Sagi Sagi Dayan - + <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> - + <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> - + <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> - + <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> - + <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> - + <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> - - + + Settings Settings - - - + + + Your settings will take effect next time you start the program Your settings will take effect next time you start the program @@ -301,20 +331,15 @@ Make Sure everything is correct and try again QObject - + Exported Successfuly! Exported Successfuly! - + Dates not valid Invalid Dates - - - Code - Code - Name @@ -346,195 +371,215 @@ Make Sure everything is correct and try again Additions - + + Number + Number + + + + Year + Year + + + + Semester + Semester + + + + Serial + Serial + + + Logout Logout - + Login Login - + Please Check Your Username & Password Please Check Your Username & Password - + You have been <b>BLOCKED</b> by JCE, please try in a couple of minutes. You have been blocked by JCE, please try in a couple of minutes. You have been <b>blocked</b> by JCE, please try in a couple of minutes. - + Please Check Your Internet Connection. Please Check Your Internet Connection. - + Receive Request Timeout. Receive Request Timeout. - + Send Request Timeout. Send Request Timeout. - + If this message appear without reason, please contact me at liranbg@gmail.com If this message appear without reason, please contact me at liranbg@gmail.com - + Error Error - + Sunday Sunday - + Monday Monday - + Tuesday Thesday - + Wednesday Wednesday - + Thursday Thursday - + Friday Friday - + ConnectionRefusedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + RemoteHostClosedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + HostNotFoundError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketAccessError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketTimeoutError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + NetworkError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslHandshakeFailedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslInternalError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslInvalidUserDataError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + DatagramTooLargeError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + OperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + AddressInUseError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketAddressNotAvailableError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnsupportedSocketOperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyAuthenticationRequiredError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionRefusedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnfinishedSocketOperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionClosedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionTimeoutError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyNotFoundError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyProtocolError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + TemporaryError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnknownSocketError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD @@ -545,28 +590,220 @@ Exporting Failed Unable to open or create the file. Exporting Failed + + + JceManager Save Schedule Dialog + JceManager Save Schedule Dialog + + + + CSV Files (*.csv);;All Files (*) + CSV Files (*.csv);;All Files (*) + - loginHandler + examDialog - - Connecting... - Connecting... + + Exam Dialog + Dialog + Exam Dialog - - Connected - Connected + + <html><head/><body><p>Revert changes</p></body></html> + <html><head/><body><p>Revert changes</p></body></html> - + + Revert + Revert + + + + <html><head/><body><p>Discard and hide</p></body></html> + <html><head/><body><p>Discard and hide</p></body></html> + + + + Cancel + Cancel + + + + <html><head/><body><p>Save and hide</p></body></html> + <html><head/><body><p>Save and hide</p></body></html> + + + + Ok + Ok + + + + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + + + + Serial + Serial + + + + Course + Course + + + + Lecturer + Lecturer + + + + Field + Field + + + + Type + Type + + + + Exam 1 Date + Exam 1 Date + + + + Starting Hour + Starting Hour + + + + Exam 2 Date + Exam 2 Date + + + + Error + Error + + + + Missmatching data. +Format: hh:mm +In Example: 08:25 or 12:05 + Missmatching data. +Format: hh:mm +In Example: 08:25 or 12:05 + + + + gradegraph + + + GPA Graph View + GPA Graph View + + + + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">GPA Graph View</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">GPA Graph View</span></p></body></html> + + + + Close + Close + + + + Yearly Average + Yearly Average + + + + Semesterial Average + Semesterial Average + + + + A + A + + + + B + B + + + + C + Summer + + + + AVG Grade + Grade Axis + + + + Years + Year Axis + + + + jceStatusBar + + + + Ready + Ready + + + + Error + Error + + + Disconnected Disconnected - - Ready. - Ready. + + Connecting... + Connecting... + + + + Sending... + Sending... + + + + Recieving... + Recieving... + + + + Connected + Connected + + + + Inserting + Inserting + + + + Logged In. + Logged In. + + + + Done + Done diff --git a/jce_he.qm b/jce_he.qm index 71711a31506927e704f3018df9fbf4863928575d..b69d71aefd911e176fc503535c44b82b971abe1d 100644 GIT binary patch delta 5253 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 delta 1848 zcmZ`)drVVz6h61TzqYiuAmF3&CGPROQCnf+tpoO3wGWGYOkiWCHNzGh~O(=50x`&u4>Ec>JV-E)5DeBb%L zbDMT-In<&Q~vke5tC~tom0L`PPwuSO{f+%D;6_krOo2f{#l}O`5MWq1HQk>_U_0&P+lazzsPWP7L~}P#$EC9%YT{l+48vt<4t9ME)1;!3v@Mfyl`it3^GiKHegm1tI_ zr2X?RFt|*b;sqR`U7Dk;Lq1-*>Rl@wVAA8kTB0bMwBuO=20bM0eg(1DB|hz|MBp8= z^EXD`2XQ2SM}x_Ahxy+=Y6n3Z|GXY6n5pOg)cYac!IJL&fVvTum4kX+B+DIi51P!@ zy;TS$ds)?8)J3}3+spx_KeH`Q!mz5(*zV0|Q8&y!e!c_)nb|dqGKlu#GzEl+bm5BOY#p?bcB5j}I z$n85svyUj+w&xSk2VS|ZIt=i)S4pQ8b*Ww#Gtd{9?bTm%g-9N+Oiw|7m_=EuhZA<6 zN6OtTPeE`^`Dq3czJbctP8$GKD&=|PgKet3_GDO?sahM_46Dzn&NSd9i#Q`Jn5)Fg z`l?_!Q3z|Rg#7p$xK9uodjj#&H42C9P^?W9S_>ddOG0bubewC1Z@6mIUlV?+Rg#_j zQ`PEu3qY8yHV?L8vSxMFJJ_Y}ih4&g8l#lz-L06MNZk@8L4J$+T=6~-pY)zKJ0FfE zd;6uQqrcBPy>kS4@~*ZAL-A3c9Sipo1y%YSSa}4_-SoM5FdBpJTTc}2F9qOIGKjtW z9!?N-0m-5vNy#OPiwyHcU)c;hbCHe>G8enYt}`c|2Urj5Vh`DUJU{T<_8`}X3K#1k zJ+eKlAKwp|6LkZu*At-wxgo?u?1rbe3$Y6bgYFwjqVx;P2akH>GH4J@alnU<29E0pC7~PZpLMam{zD4E@ z=4zYSs>`e}RqGbpQh>BHauflzQ!xghzYGg@uqIQEs8z{zg^2gk+S zihJRd(}M-K5IH@*JizIMdpbDg_V^y6ZjW!Sadx+#q@U1`RlLruGgp{&mbE$?9;?SC z>DL%5bom9vx-#5XZ8VnaELJ?PwOGwl3(L%JuCLHTx#Omgr*yb91-wRynVgva4(pj< zk}fux#G&w+;{4zQ@pO2IBEwh?Vxv_|@SZ+HhW*`}RLwHV%|)%DmBKQ!O*cmG;rJsYj~AQL zgT#&Dnd0TRQ1RFBO)=Ur&SBOKl>g_I6k9y3`y - + CalendarDialog - + Dates Dialog Dialog בחירת תאריכים - - <body><p><span style=" font-size:9pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p> - <body><p><span style=" font-size:9pt; font-weight:600;">התאריכים הנל נלקחו מהאתר של המכללה. הם תואמים את סמסטר א לשנת 2015.</span></p> + + <html><head/><body><p align="center"><span style=" font-size:14pt; font-weight:600;">Schedule Exportation</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:14pt; font-weight:600;">ייצוא מערכת שעות</span></p></body></html> - - Semester Starts At: - <b> הסמסטר מתחיל ב: + + <html><head/><body><p align="center">Semester Starts At:</p></body></html> + <html><head/><body><p align="center">תחילת סמסטר:</p></body></html> - - Semester Ends At: - <b>הסמסטר נגמר ב: + + <html><head/><body><p align="center">Semester Ends At:</p></body></html> + <html><head/><body><p align="center">סוף סמסטר:</p></body></html> - + + <html><head/><body><p align="center"><span style=" font-size:12pt; font-weight:600;">The dates were chosen according to JCE General Academic Calendar for the first semester</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:12pt; font-weight:600;">התאריכים הנ"ל נבחרו לפי המידע המוצג בתחנת המידע לסמסטר א' 2015</span></p></body></html> + + + + Include Exams + צרף לוח מבחנים + + + <b>Please chose your dates correctly</b> <b>אנא בחר את הנתונים המתאימים</b> - - - The end of the semester can NOT be equal or before the semester begin. - סוף הסמסטר לא יכול להיות שווה או קודם לתחילתו. + + + Invalid dates interval + שגיאה במרווח זמנים - - + + Looks fine, Click "OK" + נראה טוב, לחץ על המשך + + + Looks ok, Press OK נראה טוב, לחץ על המשך @@ -50,250 +64,266 @@ JCE Manager - - + + Login התחבר - + Keep login שמור פרטים - + Username שם משתמש - + Password סיסמה - + GPA גליון ציונים - + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">ציונים הצג</span></p></body></html> - - Add - הוספה - - - + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">טבלה נקהe</span></p></body></html> - - Clear - נקה - - - + Average: ממוצע: - + Only Main Courses הצג קורסים משמעותיים בלבד - - From - <b>מסמסטר</b> - - - - + + Year: שנה: - + + Semester: סמסטר: - - To - <b>עד סמסטר</b> - - - - Semester - סמסטר - - - - Calendar - מערכת שעות - - - - Get Calendar - הצג מערכת - - - + Export to CSV .CSV ייצא אל קובץ - + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="right">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="center">נוצר ע"י: <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - + + <html><head/><body><p align="center">To</p></body></html> + <html><head/><body><p align="center">סוף סמסטר</p></body></html> + + + + Clear Table + נקה טבלה + + + + Get GPA + קבל גליון ציונים + + + + Revert Changes + שחזר שינויים + + + + <html><head/><body><p align="center">From</p></body></html> + <html><head/><body><p align="center">תחילת סמסטר</p></body></html> + + + + Graph View + הצג גרף + + + + Schedule + מערכת שעות + + + + Get Schedule && Exam + קבל מערכת שעות && לוח מבחנים + + + + Show Exams + הצג מבחנים + + + &File &קובץ - + Language שפה - + Credits קרדיט - + Exit יציאה - + Hebrew עברית - + English English - + OS Default ברירת מחדל - + How To עזרה - - Ready - מוכן - - - - - - + + + + + + Error שגיאה - + Invalid Dates. Make Sure everything is correct and try again תאריכים לא חוקיים. אנא בדוק שהנתונים שהוזנו נכונים ונסה מחדשה - - + + + Not Connected לא מחובר - + Missmatching data שגיאה בהכנסת נתונים - + License: רישיון: - + Powered By: powered by: מנוע: - + Developed By - + Help Guide Guide תפריט עזרה - + Liran לירן בן גידה - + + You must to load GPA first +Click on 'Get GPA' + עליך לטעון את מערכת השעות קודם. +לחץ על 'קבל מערכת שעות && לוח מבחנים' + + + Sagi שגיא דיין - + <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> <br><li>התחברות: <ul><li>הזן את שם המשתמש והסיסמה ולחץ על התחבר</li><li>בגמר ההתחברות תראה בכדור ירוק בשורת המצב. המשמעות שהינך מחובר לאתר</li></ul></li> - + <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> <br><li>קבלת גליון ציונים<ul><li>לחץ על לשונית הציונים</li><li>בחר את טווח התאריכים הרצויים ולחץ על הוספה</li></ul></li> - + <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> <br><li>שינוי ממוצע<ul><li>שנה את אחד הציונים שלך בקורס והממוצע ישתנה בהתאם.</li></ul></li> - + <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> <br><li>קבלת שעות מערכת<ul><li>לחץ על לשונית שעות מערכת</li><li>בחר את השנה והסמסטר ולחץ על הצג מערכת</li></ul></li> - + <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> <br><li>על מנת לייצא לקובץ CSV<ul><li>בצע את השלב הקודם ואז</li><li> לחץ על ייצוא לCSV</li><li>בחר את התאריכים המתאימים ולחץ אישור</li><li>לאחר השלמת הפעולה תוכל לייבא את המערכת שעות</li></li> - + <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> <b>לעוד מידע: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> - - + + Settings הגדרות - - - + + + Your settings will take effect next time you start the program ההגדרות שלך ייכנסו לתוקפן בפעם הבאה שתפעיל את התוכנה @@ -301,20 +331,15 @@ Make Sure everything is correct and try again QObject - + Exported Successfuly! הייצוא הושלם! - + Dates not valid תאריכים לא חוקיים - - - Code - קוד קורס - Name @@ -346,195 +371,215 @@ Make Sure everything is correct and try again תוספת - + + Number + מספר + + + + Year + שנה + + + + Semester + סמסטר + + + + Serial + סידורי + + + Logout התנתק - + Login התחבר - + Please Check Your Username & Password אנא בדוק את שם המשתמש והסיסמה שלך - + You have been <b>BLOCKED</b> by JCE, please try in a couple of minutes. You have been blocked by JCE, please try in a couple of minutes. אתה <b>נחסמת</b> על ידי האתר. אנא נסה מאוחר יותר. - + Please Check Your Internet Connection. בדוק את החיבור שלך לאינטרנט. - + Receive Request Timeout. בקשת קבלה נכשלה. - + Send Request Timeout. בקשת שליחה נכשלה. - + If this message appear without reason, please contact me at liranbg@gmail.com אם הודעה זו חוזרת על עצמה ללא סיבה. אנא פנה אל המפתח במייל liranbg@gmail.com - + Error שגיאה - + Sunday ראשון - + Monday שני - + Tuesday שלישי - + Wednesday רביעי - + Thursday חמישי - + Friday שישי - + ConnectionRefusedError - + RemoteHostClosedError - + HostNotFoundError - + SocketAccessError - + SocketTimeoutError - + NetworkError - + SslHandshakeFailedError - + SslInternalError - + SslInvalidUserDataError - + DatagramTooLargeError - + OperationError - + AddressInUseError - + SocketAddressNotAvailableError - + UnsupportedSocketOperationError - + ProxyAuthenticationRequiredError - + ProxyConnectionRefusedError - + UnfinishedSocketOperationError - + ProxyConnectionClosedError - + ProxyConnectionTimeoutError - + ProxyNotFoundError - + ProxyProtocolError - + TemporaryError - + UnknownSocketError @@ -545,28 +590,220 @@ Exporting Failed לא ניתן ליצור את הקובץ. היצוא נכשל + + + JceManager Save Schedule Dialog + JceManager שמירת מערכת שעות + + + + CSV Files (*.csv);;All Files (*) + CSV Files (*.csv);;All Files (*) + - loginHandler + examDialog - - Connecting... - מתחבר... + + Exam Dialog + Dialog + מבחנים - - Connected - מחובר + + <html><head/><body><p>Revert changes</p></body></html> + <html><head/><body><p>בטל שינויים</p></body></html> - + + Revert + בטל שינויים + + + + <html><head/><body><p>Discard and hide</p></body></html> + <html><head/><body><p>בטל שינויים וצא</p></body></html> + + + + Cancel + ביטול + + + + <html><head/><body><p>Save and hide</p></body></html> + <html><head/><body><p>שמור וצא</p></body></html> + + + + Ok + אישור + + + + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:14pt;">לוח בחינות</span></p></body></html> + + + + Serial + סידורי + + + + Course + קורס + + + + Lecturer + מרצה + + + + Field + חוג + + + + Type + סוג + + + + Exam 1 Date + תאריך מועד א' + + + + Starting Hour + תחילת מבחן + + + + Exam 2 Date + תאריך מועד ב' + + + + Error + שגיאה + + + + Missmatching data. +Format: hh:mm +In Example: 08:25 or 12:05 + מידע מוטעה. +הפורמט הינו hh:mm +לדוגמה: 08:25 או 12:05 + + + + gradegraph + + + GPA Graph View + גרף ציונים + + + + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">GPA Graph View</span></p></body></html> + <html><head/><body><p align="center"><span style=" font-size:18pt; font-weight:600;">גרף ציונים</span></p></body></html> + + + + Close + סגור + + + + Yearly Average + ממוצע שנתי + + + + Semesterial Average + ממוצע סמסטריאלי + + + + A + א' + + + + B + ב' + + + + C + קיץ + + + + AVG Grade + ציר ציון + + + + Years + ציר שנים + + + + jceStatusBar + + + + Ready + מוכן + + + + Error + שגיאה + + + Disconnected מנותק - - Ready. - מוכן. + + Connecting... + מתחבר... + + + + Sending... + שולח... + + + + Recieving... + מקבל... + + + + Connected + מחובר + + + + Inserting + מכניס נתונים + + + + Logged In. + מחובר לאתר. + + + + Done + בוצע diff --git a/main/main.cpp b/main/main.cpp index 7e82ce7..3af9c9e 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -7,7 +7,6 @@ //TODO: Project todo list //update translation, update site spelling, release notes, update help -//BUG: fix locale on windows int main(int argc, char *argv[]) { #ifdef QT_DEBUG // Incase QtCreator is in Debug mode all qDebug messages will go to terminal @@ -35,7 +34,7 @@ int main(int argc, char *argv[]) }else{ translator.load("jce_en" , a.applicationDirPath()); data.reset(); - qCritical() << Q_FUNC_INFO << "save data corrupted, rested file."; + qCritical() << Q_FUNC_INFO << "save data corrupted, reset file."; } a.installTranslator(&translator); //Setting local a.setApplicationVersion(APP_VERSION); diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index 981b1c8..21f6260 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -7,7 +7,7 @@ 0 0 810 - 273 + 306 @@ -17,7 +17,11 @@ - Dialog + Exam Dialog + + + + :/icons/icon.ico:/icons/icon.ico @@ -99,7 +103,6 @@ - pushButtonRevert horizontalSpacer @@ -132,6 +135,8 @@ - + + + From 34ae9f016fe9fbd81f39c534d151c3ffd1e63f41 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 17:43:28 +0300 Subject: [PATCH 42/58] exam ui fix --- src/jceData/Calendar/Exams/examDialog.ui | 75 +++++++++++------------- 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index 21f6260..aa07e3d 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -51,60 +51,51 @@ QFrame::Raised - - - 0 - - - - - - - <html><head/><body><p>Revert changes</p></body></html> - - - Revert - - - - - - - <html><head/><body><p>Discard and hide</p></body></html> - - - Cancel - - - - - - - <html><head/><body><p>Save and hide</p></body></html> - - - Ok - - - - - - + + Qt::Horizontal - 40 + 510 20 + + + + <html><head/><body><p>Revert changes</p></body></html> + + + Revert + + + + + + + <html><head/><body><p>Discard and hide</p></body></html> + + + Cancel + + + + + + + <html><head/><body><p>Save and hide</p></body></html> + + + Ok + + + - - horizontalSpacer From 4807821ece58fe0ecd0102a8953e1b29b7a42f9b Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 17:54:23 +0300 Subject: [PATCH 43/58] hebrew tr update --- jce_he.qm | Bin 16714 -> 23078 bytes jce_he.ts | 24 ++++++++++++------------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/jce_he.qm b/jce_he.qm index b69d71aefd911e176fc503535c44b82b971abe1d..9a00e7a309e153d73eabe1edb47c64b5244d3746 100644 GIT binary patch literal 23078 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 delta 1402 zcmXw2ZBSHY7(I9Iy}Nsty$ccrh$!E%urA8N3M(mrpvbl+$c!oIOfxj;qyeS_WUg9@ zreQ)%Y8HbdDW9fEWu7jXRnsYl}33wcHw5MK)UgUi6UHpt(W z0pnL`*7+6W2Wx?3W$W@dZ$=Q@+h1bVY|X}cH0$Wo?Bp?UKa2rV&%#sN0>s|JtXCU= zxM?Udt^&drp{Vp<+7`{m4PfqF*S6zHn*rT}BQbz7rrfs8EOnLT@fklUhhRxt^A#K2Qa zy+F!2(WS6az#K8RojPTFFU~a8Gw~g9!JCzAv_mYfCBu|aV%3vGllWQqSn8K79tmB} zdx#Xf@9rSeaboZD^s6sQ0duHS$OdWZ!4$wgNy=$D0qA<9ZTZIl$7-pyivv2^q)S8I zjg<7XG}!tHC#sjOg;1jSe(C16Gh{GEy4To7yFpIe+Xv{c%eDcL7rIzZyK$Ovikvr- z`SEFT!IfcU^5of=4n)SuCF#R;eDW)csa#^GTyZ0igH*^XWFKIaZFPn_-%R9HMI+~KMR|@*-S-`1yPRd;UdSz};B^&lCul>e2=b*AB;sTfL zkxHyu}Qesh?0ubFIbO#z;=o3dOSz`Dm&Z66Cfo!rnU27Al= zgm7+BX1bs0)E(;5>E}Mfsq8=by&T!fr*Xh<|9R3&z3q2w2Ore<*=GOsj1PRloY_`L z+W(mIM_Kqdx0pQ>E-^mbT$V(c4B6)9i(#}a=3U-wvi#26K8tl?J~p?P29dsC{#sZD zcq59;XRA%zm||5;ba0h-sbyC>IOZ>EMU9gVw~ zUi2o__r?He*QuRuf%lSX2?*tYiItYXtSr(`v&2L)UMja_Zl-+B8p|?oI2YxSzkcu* z5-`#2KmYY5Osw%=m-;Rc)#1OhWFIdq)xWFBO2*NPC{Km&2kB0T^q8OTa`FW J6}m5~{{dO2z1#o* diff --git a/jce_he.ts b/jce_he.ts index 4ab35c4..91c5e32 100644 --- a/jce_he.ts +++ b/jce_he.ts @@ -259,7 +259,7 @@ Make Sure everything is correct and try again Developed By - + פותח ע"י @@ -471,7 +471,7 @@ If this message appear without reason, please contact me at liranbg@gmail.com ConnectionRefusedError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -481,7 +481,7 @@ If this message appear without reason, please contact me at liranbg@gmail.com HostNotFoundError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -496,7 +496,7 @@ If this message appear without reason, please contact me at liranbg@gmail.com NetworkError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -516,17 +516,17 @@ If this message appear without reason, please contact me at liranbg@gmail.com DatagramTooLargeError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) OperationError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) AddressInUseError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -541,12 +541,12 @@ If this message appear without reason, please contact me at liranbg@gmail.com ProxyAuthenticationRequiredError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) ProxyConnectionRefusedError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -556,17 +556,17 @@ If this message appear without reason, please contact me at liranbg@gmail.com ProxyConnectionClosedError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) ProxyConnectionTimeoutError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) ProxyNotFoundError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) From 8e4c339517bd18f156957501a23a3e0273a2c782 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Mon, 13 Oct 2014 17:55:01 +0300 Subject: [PATCH 44/58] hebrew tr update --- jce_he.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/jce_he.ts b/jce_he.ts index 91c5e32..0d3844e 100644 --- a/jce_he.ts +++ b/jce_he.ts @@ -476,7 +476,7 @@ If this message appear without reason, please contact me at liranbg@gmail.com RemoteHostClosedError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -486,12 +486,12 @@ If this message appear without reason, please contact me at liranbg@gmail.com SocketAccessError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) SocketTimeoutError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -501,17 +501,17 @@ If this message appear without reason, please contact me at liranbg@gmail.com SslHandshakeFailedError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) SslInternalError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) SslInvalidUserDataError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -531,12 +531,12 @@ If this message appear without reason, please contact me at liranbg@gmail.com SocketAddressNotAvailableError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) UnsupportedSocketOperationError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -551,7 +551,7 @@ If this message appear without reason, please contact me at liranbg@gmail.com UnfinishedSocketOperationError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) @@ -566,22 +566,22 @@ If this message appear without reason, please contact me at liranbg@gmail.com ProxyNotFoundError - הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) ProxyProtocolError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) TemporaryError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) UnknownSocketError - + הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) From d6c1e7e5d6894985b0a82f96a31cff668a7b89cb Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Mon, 13 Oct 2014 18:22:31 +0300 Subject: [PATCH 45/58] Added exams to the export - if user chooses to Tested on linux - works well! :wink: --- main/CalendarTab/CalendarManager.cpp | 2 +- main/mainscreen.h | 2 +- src/jceData/CSV/csv_exporter.cpp | 61 +++++++++++++++++-- src/jceData/CSV/csv_exporter.h | 3 +- .../coursesSchedule/calendarDialog.cpp | 4 ++ .../Calendar/coursesSchedule/calendarDialog.h | 1 + .../coursesSchedule/calendarDialog.ui | 4 +- 7 files changed, 66 insertions(+), 11 deletions(-) diff --git a/main/CalendarTab/CalendarManager.cpp b/main/CalendarTab/CalendarManager.cpp index 403143c..a763fc2 100644 --- a/main/CalendarTab/CalendarManager.cpp +++ b/main/CalendarTab/CalendarManager.cpp @@ -36,7 +36,7 @@ void CalendarManager::exportCalendarCSV() //calDialog.getStartDate(),calDialog.getEndDate() if (caliDialog->ok()) { - if (CSV_Exporter::exportCalendar(caliSchedPtr, caliDialog)) + if (CSV_Exporter::exportCalendar(caliSchedPtr, caliDialog, examSchePtr)) { msgBox.setIcon(QMessageBox::Information); msgBox.setText(QObject::tr("Exported Successfuly!")); diff --git a/main/mainscreen.h b/main/mainscreen.h index cc3b63e..b01f990 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -10,7 +10,7 @@ #include "./CourseTab/coursestablemanager.h" #include "./LoginTab/loginhandler.h" #include "./CalendarTab/CalendarManager.h" -#include "./jceWidgets/jceStatusBar.h" +#include "./jceWidgets/jcestatusbar.h" diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index 7f22f69..0eca597 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -3,7 +3,6 @@ /* * * Class doc can be found in csv_exporter.h - * TODO: add exam exportation */ CSV_Exporter::CSV_Exporter() { @@ -18,7 +17,7 @@ CSV_Exporter::CSV_Exporter() * @param cal - The Calendar dialog witch holdes the starting date and the eand date. * @return - True if *all* went well, false if something on the way went wrong. */ -bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *cal) +bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *cal, calendarExam *exams) { if ((cal == NULL) || (calSched == NULL)) //pointers checking! return false; @@ -97,6 +96,36 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca out.flush(); } + if(cal->isExams()) //Export Exams as well + { + qDebug() << "Exporting Exams!"; + for(calendarExamCourse* exam:exams->getExams()) + { + QTime startH = exam->getFirstHourbegin(); + QTime endH = startH.addSecs(60*60*3);//add 3 hours + QString type = "מבחן א"; + QString name = exam->getName(); + QDate date = exam->getFirstDate(); + QString line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), "", "", type); + if(line != NULL) + out << line << char(0x0A); + else + qWarning() << Q_FUNC_INFO << "CSV : Got A NULL in Line! in function: " << Q_FUNC_INFO; + //=============== + // Second Date + //=============== + startH = exam->getSecondHourbegin(); + endH = startH.addSecs(60*60*3);//add 3 hours + date = exam->getSecondDate(); + type = "מבחן ב"; + line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), "", "", type); + if(line != NULL) + out << line << char(0x0A); + else + qWarning() << Q_FUNC_INFO << "CSV : Got A NULL in Line! in function: " << Q_FUNC_INFO; + } + out.flush(); + } file.close(); qDebug() << Q_FUNC_INFO << "CSV : Exported Successfully"; @@ -115,6 +144,10 @@ QString CSV_Exporter::getFileFath() QObject::tr("CSV Files (*.csv);;All Files (*)")); if (fileName == "") return NULL; + + //IMPORTENT! ADD CSV EXTENTION + if(!fileName.contains(".csv") && !fileName.contains(".CSV")) + fileName.append(".csv"); return fileName; } @@ -149,20 +182,32 @@ QString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM QString start; start.append(QString::number(startH)); - start.append(":00"); - // start.append(QString::number(startM)); + if(startM != 0) + { + start.append(":"); + start.append(QString::number(startM)); + } + else + start.append(":00"); start.append(":00"); QString end; end.append(QString::number(endH)); - end.append(":"); - end.append(QString::number(endM)); + if(endM != 0) + { + end.append(":"); + end.append(QString::number(endM)); + } + else + end.append(":00"); end.append(":00"); QString description = "\"מרצה "; if (lecturer == LECTURER_DEFAULT_STRING) description.append("טרם נקבע מרצה או מתרגל"); + else if(lecturer == "") + description = ""; else description.append(lecturer); @@ -176,6 +221,9 @@ QString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM description.append(room); } + if(room == "") + description = "\"\Good Luck!\n"; + description.append("\n Created with JCE Manager.\""); //Create the Fucking Line @@ -237,3 +285,4 @@ void CSV_Exporter::changeDayNumberFromQtToNormal(int *QtDay) } return; //Done. } + diff --git a/src/jceData/CSV/csv_exporter.h b/src/jceData/CSV/csv_exporter.h index d83ddac..886448e 100644 --- a/src/jceData/CSV/csv_exporter.h +++ b/src/jceData/CSV/csv_exporter.h @@ -18,6 +18,7 @@ #include "../Calendar/coursesSchedule/calendarSchedule.h" #include "../Calendar/coursesSchedule/calendarDialog.h" +#include "../Calendar/Exams/calendarExam.h" #define CSV_CALENDAR_HEADER "Subject,Start Date,Start Time,End Date,End Time,Description,Location" @@ -26,7 +27,7 @@ class CSV_Exporter { public: CSV_Exporter(); - static bool exportCalendar(calendarSchedule* calSched, CalendarDialog *cal); + static bool exportCalendar(calendarSchedule* calSched, CalendarDialog *cal, calendarExam* exams); private: diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp index cd9984f..0daa0fd 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.cpp @@ -96,3 +96,7 @@ void CalendarDialog::changeLabeStatusIcon(bool goodOrBad) iconPixStatus.load(":/icons/iconX.png"); this->ui->labelIconStatus->setPixmap(iconPixStatus); } + +bool CalendarDialog::isExams(){ + return ui->isExam->isChecked(); +} diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.h b/src/jceData/Calendar/coursesSchedule/calendarDialog.h index 1adbe5a..40c187e 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.h +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.h @@ -30,6 +30,7 @@ public: QDate getStartDate(); QDate getEndDate(); bool ok(); + bool isExams(); private slots: void on_calStart_selectionChanged(); diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui index cf08792..8ca5dda 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui @@ -6,7 +6,7 @@ 0 0 - 609 + 830 310 @@ -184,7 +184,7 @@ - + Include Exams From dd5f4fa9e9ab7366746285eb8dc86267ca54bf8b Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Mon, 13 Oct 2014 21:13:17 +0300 Subject: [PATCH 46/58] Changed the type of exams in exporter --- src/jceData/CSV/csv_exporter.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index 0eca597..96adf43 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -103,7 +103,7 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca { QTime startH = exam->getFirstHourbegin(); QTime endH = startH.addSecs(60*60*3);//add 3 hours - QString type = "מבחן א"; + QString type = "מועד א"; QString name = exam->getName(); QDate date = exam->getFirstDate(); QString line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), "", "", type); @@ -117,7 +117,7 @@ bool CSV_Exporter::exportCalendar(calendarSchedule *calSched, CalendarDialog *ca startH = exam->getSecondHourbegin(); endH = startH.addSecs(60*60*3);//add 3 hours date = exam->getSecondDate(); - type = "מבחן ב"; + type = "מועד ב"; line = makeLine(name, &date, startH.hour(), startH.minute(), endH.hour(), endH.minute(), "", "", type); if(line != NULL) out << line << char(0x0A); @@ -157,7 +157,7 @@ QString CSV_Exporter::getFileFath() * @param name * @param date * @param startH - * @param startM - Not used at the moment. + * @param startM * @param endH * @param endM * @param lecturer From d2d6495030b4391c9a246f69c460517496ff793a Mon Sep 17 00:00:00 2001 From: liranbg Date: Tue, 14 Oct 2014 02:45:11 +0300 Subject: [PATCH 47/58] dockwidget instead of menu --- jceGrade.pro | 1 + main/main.cpp | 10 +- main/mainscreen.cpp | 218 +++++++++++--------- main/mainscreen.h | 18 +- main/mainscreen.ui | 363 ++++++++++++++++++++++++++++++--- resources/connectionstatus.qrc | 4 + resources/flags/il.png | Bin 0 -> 3506 bytes resources/flags/us.png | Bin 0 -> 4202 bytes resources/help.png | Bin 0 -> 4700 bytes resources/il.png | Bin 0 -> 3506 bytes resources/team.png | Bin 0 -> 2350 bytes resources/us.png | Bin 0 -> 4202 bytes src/appDatabase/savedata.cpp | 12 +- src/appDatabase/savedata.h | 6 +- 14 files changed, 481 insertions(+), 151 deletions(-) create mode 100644 resources/flags/il.png create mode 100644 resources/flags/us.png create mode 100644 resources/help.png create mode 100644 resources/il.png create mode 100644 resources/team.png create mode 100644 resources/us.png diff --git a/jceGrade.pro b/jceGrade.pro index 43f07ed..85eecfd 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -87,3 +87,4 @@ SOURCES += \ src/jceData/Calendar/coursesSchedule/calendarPageCourse.cpp \ src/jceData/Calendar/coursesSchedule/calendarSchedule.cpp \ main/jceWidgets/jcestatusbar.cpp + diff --git a/main/main.cpp b/main/main.cpp index 3af9c9e..e1f2b01 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -20,16 +20,14 @@ int main(int argc, char *argv[]) QApplication a(argc, argv); QTranslator translator; - QString loco; SaveData data; - loco = data.getLocal(); //Loading Local (From Settings file (SaveData.cpp) - if(loco == "en") + if(data.getLocale() == "en") { - translator.load("jce_" + loco , a.applicationDirPath()); + translator.load("jce_" + data.getLocale() , a.applicationDirPath()); qDebug() << Q_FUNC_INFO << "Locale : English Local Loaded"; - }else if(loco == "he"){ - translator.load("jce_" + loco , a.applicationDirPath()); + }else if(data.getLocale() == "he"){ + translator.load("jce_" + data.getLocale() , a.applicationDirPath()); qDebug() << Q_FUNC_INFO << "Local : Hebrew Local Loaded"; }else{ translator.load("jce_en" , a.applicationDirPath()); diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 6a98d5b..884d9b5 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -45,6 +45,7 @@ MainScreen::MainScreen(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSc } MainScreen::~MainScreen() { + delete statusBar; delete calendar; delete courseTableMgr; delete userLoginSetting; @@ -122,7 +123,6 @@ void MainScreen::on_keepLogin_clicked() } void MainScreen::on_usrnmLineEdit_editingFinished() { - qDebug() << Q_FUNC_INFO << "in: " << ui->tabWidget->currentWidget()->objectName(); ui->usrnmLineEdit->setText(ui->usrnmLineEdit->text().toLower()); } @@ -244,7 +244,6 @@ void MainScreen::on_revertBtn_clicked() } } - //EVENTS ON CALENDAR TAB void MainScreen::on_examsBtn_clicked() { @@ -314,104 +313,48 @@ void MainScreen::on_exportToCVSBtn_clicked() } } //EVENTS ON MENU BAR -void MainScreen::on_actionCredits_triggered() -{ - qDebug() << Q_FUNC_INFO; - QMessageBox::about(this, "About", - "Jce Manager v1.0.0

                                  " - +tr("License:")+ - "
                                  GNU LESSER GENERAL PUBLIC LICENSE V2.1
                                  " - +"
                                  "+ - "JceManager Repository"+ - "

                                  " - +tr("Powered By: ")+ - " Jce Connection

                                  " - +tr("Developed By")+ - ":" - ); -} -void MainScreen::on_actionExit_triggered() -{ - qDebug() << Q_FUNC_INFO; - exit(0); -} -void MainScreen::on_actionHow_To_triggered() -{ - qDebug() << Q_FUNC_INFO; - QMessageBox::information(this,"How To", - "" - +tr("Help Guide")+ - "
                                    " - +tr("
                                  • Login:
                                    • Type your username and password and click Login.
                                    • Once you are connected, you will see a green ball in the right buttom panel.
                                  • ") - +tr("
                                  • Getting GPA sheet
                                    • Click on GPA Tab
                                    • Select your dates and click on Add
                                  • ") - +tr("
                                  • Average Changing
                                    • Change one of your grade and see the average in the buttom panel changing.
                                  • ") - +tr("
                                  • Getting Calendar
                                    • Click on Calendar Tab
                                    • Select your dates and click on Get Calendar
                                  • ") - +tr("
                                  • For exporting your calendar to a .CSV file:
                                    • Do previous step and continue to next step
                                    • Click on Export to CSV
                                    • Select your dates and click OK
                                    • Once you're Done, go on your calendar and import your csv file
                                    • ")+ - "

                                      " - +tr("For more information, please visit us at: Jce Manager site")); -} -void MainScreen::on_actionHebrew_triggered() -{ - qDebug() << Q_FUNC_INFO; - if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) - { - ui->actionEnglish->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; - data->setLocal("he"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); - } - else - ui->actionHebrew->setChecked(true); -} -void MainScreen::on_actionEnglish_triggered() -{ - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) - { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to English"; - data->setLocal("en"); - QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); - } - else - ui->actionEnglish->setChecked(true); -} -void MainScreen::on_actionOS_Default_triggered() -{ - qDebug() << Q_FUNC_INFO; - if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) - { - ui->actionHebrew->setChecked(false); - ui->actionEnglish->setChecked(false); - qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; - data->setLocal("default"); - QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); - } - else - ui->actionOS_Default->setChecked(true); -} -void MainScreen::checkLocale() -{ - if(data->getLocal() == "en") - { - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(true); - }else if(data->getLocal() == "he"){ - ui->actionHebrew->setChecked(true); - ui->actionOS_Default->setChecked(false); - ui->actionEnglish->setChecked(false); - }else{ - ui->actionHebrew->setChecked(false); - ui->actionOS_Default->setChecked(true); - ui->actionEnglish->setChecked(false); - } -} - +//void MainScreen::on_actionHebrew_triggered() +//{ +// qDebug() << Q_FUNC_INFO; +// if (ui->actionEnglish->isChecked() || ui->actionOS_Default->isChecked()) +// { +// ui->actionEnglish->setChecked(false); +// ui->actionOS_Default->setChecked(false); +// qDebug() << Q_FUNC_INFO << "Changed Language to hebrew"; +// data->setLocal("he"); +// QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); +// } +// else +// ui->actionHebrew->setChecked(true); +//} +//void MainScreen::on_actionEnglish_triggered() +//{ +// qDebug() << Q_FUNC_INFO; +// if (ui->actionHebrew->isChecked() || ui->actionOS_Default->isChecked()) +// { +// ui->actionHebrew->setChecked(false); +// ui->actionOS_Default->setChecked(false); +// qDebug() << Q_FUNC_INFO << "Changed Language to English"; +// data->setLocal("en"); +// QMessageBox::information(this,"Settings",tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); +// } +// else +// ui->actionEnglish->setChecked(true); +//} +//void MainScreen::on_actionOS_Default_triggered() +//{ +// qDebug() << Q_FUNC_INFO; +// if (ui->actionHebrew->isChecked() || ui->actionEnglish->isChecked()) +// { +// ui->actionHebrew->setChecked(false); +// ui->actionEnglish->setChecked(false); +// qDebug() << Q_FUNC_INFO << "Changed Language to OS Default"; +// data->setLocal("default"); +// +// } +// else +// ui->actionOS_Default->setChecked(true); +//} //MAIN SCREEN void MainScreen::on_labelMadeBy_linkActivated(const QString &link) { @@ -436,3 +379,78 @@ bool MainScreen::isBusy() return this->isBlocked; } + +void MainScreen::on_langButton_clicked() +{ + qDebug() << Q_FUNC_INFO; + if (data->getLocale() == "en") + { + qDebug() << Q_FUNC_INFO << "Changed lang to he"; + data->setLocale("he"); + + }else if(data->getLocale() == "he"){ + qDebug() << Q_FUNC_INFO << "Changed lang to en"; + data->setLocale("en"); + }else{ + qCritical() << Q_FUNC_INFO << "currupted data. reset to en"; + data->reset(); + data->setLocale("en"); + } + checkLocale(); + + + QMessageBox::information(this,tr("Settings"),tr("Your settings will take effect next time you start the program"),QMessageBox::Ok); + +} + +void MainScreen::on_creditButton_clicked() +{ + qDebug() << Q_FUNC_INFO; + QMessageBox::about(this, "About", + "Jce Manager v1.0.0

                                      " + +tr("License:")+ + "
                                      GNU LESSER GENERAL PUBLIC LICENSE V2.1
                                      " + +"
                                      "+ + "JceManager Repository"+ + "

                                      " + +tr("Powered By: ")+ + " Jce Connection

                                      " + +tr("Developed By")+ + ":" + ); +} + +void MainScreen::on_howtoButton_clicked() +{ + qDebug() << Q_FUNC_INFO; + QMessageBox::information(this,"How To", + "" + +tr("Help Guide")+ + "
                                        " + +tr("
                                      • Login:
                                        • Type your username and password and click Login.
                                        • Once you are connected, you will see a green ball in the right buttom panel.
                                      • ") + +tr("
                                      • Getting GPA sheet
                                        • Click on GPA Tab
                                        • Select your dates and click on Add
                                      • ") + +tr("
                                      • Average Changing
                                        • Change one of your grade and see the average in the buttom panel changing.
                                      • ") + +tr("
                                      • Getting Calendar
                                        • Click on Calendar Tab
                                        • Select your dates and click on Get Calendar
                                      • ") + +tr("
                                      • For exporting your calendar to a .CSV file:
                                        • Do previous step and continue to next step
                                        • Click on Export to CSV
                                        • Select your dates and click OK
                                        • Once you're Done, go on your calendar and import your csv file
                                        • ")+ + "

                                          " + +tr("For more information, please visit us at: Jce Manager site")); +} + +void MainScreen::checkLocale() +{ + qDebug() << Q_FUNC_INFO; + if (data->getLocale() == "en") + { + ui->langButton->setIcon(QIcon(":/icons/us.png")); + + }else if(data->getLocale() == "he"){ + ui->langButton->setIcon(QIcon(":/icons/il.png")); + }else{ + qCritical() << Q_FUNC_INFO << "currupted data. reset eng"; + data->reset(); + ui->langButton->setIcon(QIcon(":/icons/us.png")); + + } +} diff --git a/main/mainscreen.h b/main/mainscreen.h index b01f990..49d5f70 100644 --- a/main/mainscreen.h +++ b/main/mainscreen.h @@ -36,6 +36,7 @@ private slots: //GPA Tab slots void on_ratesButton_clicked(); void on_graphButton_clicked(); + void on_revertBtn_clicked(); void on_clearTableButton_clicked(); void on_coursesTable_itemChanged(QTableWidgetItem *item); void on_checkBoxCoursesInfluence_toggled(bool checked); @@ -45,26 +46,21 @@ private slots: void on_examsBtn_clicked(); void on_exportToCVSBtn_clicked(); - //Menubar slots - void on_actionCredits_triggered(); - void on_actionExit_triggered(); - void on_actionHow_To_triggered(); - void on_actionHebrew_triggered(); - void on_actionEnglish_triggered(); - void on_actionOS_Default_triggered(); - //Main screen general slots void on_spinBoxCoursesFromSemester_valueChanged(int arg1); void on_spinBoxCoursesFromYear_valueChanged(int arg1); void on_spinBoxCoursesToYear_valueChanged(int arg1); void on_spinBoxCoursesToSemester_valueChanged(int arg1); void on_labelMadeBy_linkActivated(const QString &link); -// void on_progressBar_valueChanged(int value); - void on_revertBtn_clicked(); + //Setting dock + void on_langButton_clicked(); + + void on_creditButton_clicked(); + + void on_howtoButton_clicked(); private: - void checkLocale(); bool checkIfValidDates(); diff --git a/main/mainscreen.ui b/main/mainscreen.ui index ace596d..c323a3f 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -6,7 +6,7 @@ 0 0 - 1133 + 1137 623 @@ -924,33 +924,346 @@ font-size: 15px; - - - - 0 - 0 - 1133 - 22 - + + + + 0 + 0 + - - - &File + + Settings + + + Qt::LeftToRight + + + #dockWidgetContents { +background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, +stop:0 rgba(180, 231, 224, 255), +stop:1 rgba(195, 231, 224, 218)); +} + + + + false + + + QDockWidget::DockWidgetMovable + + + + + + 4 + + + + + 0 + 0 + - - - Language - - - - - - - - - + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + QFrame::NoFrame + + + QFrame::Plain + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + false + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/us.png:/icons/us.png + + + + 48 + 48 + + + + false + + + + + + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + + + + QFrame::NoFrame + + + QFrame::Raised + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/help.png:/icons/help.png + + + + 40 + 36 + + + + + + + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + QFrame::NoFrame + + + QFrame::Plain + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/team.png:/icons/team.png + + + + 36 + 36 + + + + + + + + - diff --git a/resources/connectionstatus.qrc b/resources/connectionstatus.qrc index 6023c12..ee4dc40 100644 --- a/resources/connectionstatus.qrc +++ b/resources/connectionstatus.qrc @@ -6,5 +6,9 @@ icon.ico iconX.png iconV.png + il.png + us.png + help.png + team.png diff --git a/resources/flags/il.png b/resources/flags/il.png new file mode 100644 index 0000000000000000000000000000000000000000..c6a0396b47193fd3376c96a8b3b3e9d0d56cbddb GIT binary patch literal 3506 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 literal 0 HcmV?d00001 diff --git a/resources/help.png b/resources/help.png new file mode 100644 index 0000000000000000000000000000000000000000..78a47665df184cb6cd2e07f5577d5c2d0b443bb8 GIT binary patch literal 4700 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 Unn;o*SpWb407*qoM6N<$f_$c0qW}N^ literal 0 HcmV?d00001 diff --git a/resources/us.png b/resources/us.png new file mode 100644 index 0000000000000000000000000000000000000000..96a8e9c1c8a2dd09493725ccef10d098aebd765d GIT binary patch literal 4202 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 literal 0 HcmV?d00001 diff --git a/src/appDatabase/savedata.cpp b/src/appDatabase/savedata.cpp index dee5476..03b2a5e 100644 --- a/src/appDatabase/savedata.cpp +++ b/src/appDatabase/savedata.cpp @@ -39,7 +39,7 @@ bool SaveData::isSaved() * # username * # password * # calendar - * # local + * # locale */ void SaveData::reset() { @@ -82,11 +82,11 @@ void SaveData::setCal(QString cal) } /** - * @brief gest a local and saves it into the QMap. + * @brief gest a locale and saves it into the QMap. * QMap then is saved to the file. - * @param local - QString (he, en, default) + * @param locale - QString (he, en) */ -void SaveData::setLocal(QString local) +void SaveData::setLocale(QString local) { DB.insert("locale", local); save(); @@ -112,9 +112,9 @@ QString SaveData::getPassword() /** * @brief read from file - * @return local + * @return locale */ -QString SaveData::getLocal() +QString SaveData::getLocale() { return DB.value("locale"); } diff --git a/src/appDatabase/savedata.h b/src/appDatabase/savedata.h index 2c94119..0d30eae 100644 --- a/src/appDatabase/savedata.h +++ b/src/appDatabase/savedata.h @@ -12,7 +12,7 @@ * Keys: * "username" * "password" - * "local" + * "locale" * "calendar" * * Note that the password will be encrypted using the SimpleCrypt class! @@ -40,11 +40,11 @@ public: void setUsername(QString username); void setPassword(QString password); void setCal(QString cal); - void setLocal(QString local); + void setLocale(QString locale); QString getUsername(); QString getPassword(); QString getCal(); - QString getLocal(); + QString getLocale(); private: QMap DB; From 2829f66e9cdc8c2823747f804ff6ac9e780222c2 Mon Sep 17 00:00:00 2001 From: liranbg Date: Tue, 14 Oct 2014 03:20:10 +0300 Subject: [PATCH 48/58] widget instead of dock --- main/mainscreen.ui | 775 ++++++++++++++++++++++----------------------- 1 file changed, 384 insertions(+), 391 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index c323a3f..0971feb 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -50,16 +50,6 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r - - - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - - - true - - - - true @@ -183,12 +173,21 @@ font-size: 15px; 0 + + login + Login + + false + + + true + @@ -922,388 +921,372 @@ font-size: 15px; + + + + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> + + + true + + + + + + + + 0 + 0 + + + + + 16777215 + 52 + + + + + QLayout::SetMinimumSize + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + Team Credit + + + QFrame::NoFrame + + + QFrame::Plain + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + Team Credit + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/team.png:/icons/team.png + + + + 36 + 36 + + + + + + + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + Language + + + QFrame::NoFrame + + + QFrame::Plain + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + Language + + + false + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/us.png:/icons/us.png + + + + 48 + 48 + + + + false + + + + + + + + + + + 0 + 0 + + + + + 48 + 48 + + + + + 48 + 48 + + + + Help + + + + + + QFrame::NoFrame + + + QFrame::Raised + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 50 + 50 + + + + + 50 + 50 + + + + Help + + + QPushButton { +color: white; +border-radius: 16px; +padding: 1px; +padding-left: 1px; +padding-right: 1px; +min-width: 48px; +max-width: 48px; +min-height: 48px; +max-height: 48px; +} + + + + + + + :/icons/help.png:/icons/help.png + + + + 40 + 36 + + + + + + + + + frameLanguage + frameTeam + frameHelp + + - - - - 0 - 0 - - - - Settings - - - Qt::LeftToRight - - - #dockWidgetContents { -background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, -stop:0 rgba(180, 231, 224, 255), -stop:1 rgba(195, 231, 224, 218)); -} - - - - false - - - QDockWidget::DockWidgetMovable - - - - - - 4 - - - - - 0 - 0 - - - - - - - - 0 - 0 - - - - - 48 - 48 - - - - - 48 - 48 - - - - QFrame::NoFrame - - - QFrame::Plain - - - 0 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - - 50 - 50 - - - - - 50 - 50 - - - - false - - - QPushButton { -color: white; -border-radius: 16px; -padding: 1px; -padding-left: 1px; -padding-right: 1px; -min-width: 48px; -max-width: 48px; -min-height: 48px; -max-height: 48px; -} - - - - - - - :/icons/us.png:/icons/us.png - - - - 48 - 48 - - - - false - - - - - - - - - - - 0 - 0 - - - - - 48 - 48 - - - - - 48 - 48 - - - - - - - QFrame::NoFrame - - - QFrame::Raised - - - 0 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - - 50 - 50 - - - - - 50 - 50 - - - - QPushButton { -color: white; -border-radius: 16px; -padding: 1px; -padding-left: 1px; -padding-right: 1px; -min-width: 48px; -max-width: 48px; -min-height: 48px; -max-height: 48px; -} - - - - - - - :/icons/help.png:/icons/help.png - - - - 40 - 36 - - - - - - - - - - - - 0 - 0 - - - - - 48 - 48 - - - - - 48 - 48 - - - - QFrame::NoFrame - - - QFrame::Plain - - - 0 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - - 50 - 50 - - - - - 50 - 50 - - - - QPushButton { -color: white; -border-radius: 16px; -padding: 1px; -padding-left: 1px; -padding-right: 1px; -min-width: 48px; -max-width: 48px; -min-height: 48px; -max-height: 48px; -} - - - - - - - :/icons/team.png:/icons/team.png - - - - 36 - 36 - - - - - - - - - - - - - Credits - - - - - Exit - - - - - true - - - Hebrew - - - - - true - - - English - - - - - true - - - OS Default - - - - - How To - - @@ -1311,15 +1294,25 @@ max-height: 48px; pswdLineEdit keepLogin loginButton - tabWidget spinBoxCoursesFromYear spinBoxCoursesFromSemester spinBoxCoursesToYear spinBoxCoursesToSemester + ratesButton + revertBtn + clearTableButton + checkBoxCoursesInfluence coursesTable + graphButton spinBoxYear spinBoxSemester getCalendarBtn + examsBtn + exportToCVSBtn + langButton + creditButton + howtoButton + tabWidget From 7a0a6dcff42dcaad0598b87fc547a4cae9933412 Mon Sep 17 00:00:00 2001 From: liranbg Date: Tue, 14 Oct 2014 03:33:10 +0300 Subject: [PATCH 49/58] fix end of packet --- src/jceConnection/jcesslclient.cpp | 6 +++++- src/jceConnection/jcesslclient.h | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/jceConnection/jcesslclient.cpp b/src/jceConnection/jcesslclient.cpp index b3e4579..57efebc 100644 --- a/src/jceConnection/jcesslclient.cpp +++ b/src/jceConnection/jcesslclient.cpp @@ -212,7 +212,11 @@ void jceSSLClient::readIt() emit statusBar->progressHasPacket(10); - if (tempPacket.contains("Go_To_system_After_Login.htm") || tempPacket.contains("")) + if ((tempPacket.mid(tempPacket.length()-7,7) == ".HTM-->") + || (tempPacket.mid(tempPacket.length()-7,7) == ".htm-->") + || tempPacket.contains("") + ) + { //we have the last packet. (uses only in login first step recieveLastPacket = true; diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index 1f2471c..740764c 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -1,7 +1,7 @@ #ifndef JCESSLCLIENT_H #define JCESSLCLIENT_H -#include +#include #include #include #include From 052104c5a303c5cfc1bb2ad2724ab5786bb6149d Mon Sep 17 00:00:00 2001 From: liranbg Date: Tue, 14 Oct 2014 06:47:15 +0300 Subject: [PATCH 50/58] new connection icons! :) --- jceGrade.pro | 2 +- main/jceWidgets/jcestatusbar.cpp | 47 ++++++++++++++++++++++--------- main/jceWidgets/jcestatusbar.h | 3 +- resources/blueStatusIcon.png | Bin 1990 -> 0 bytes resources/busy.png | Bin 0 -> 5475 bytes resources/connected.png | Bin 0 -> 4992 bytes resources/connectionstatus.qrc | 6 ++-- resources/disconnected.png | Bin 0 -> 4569 bytes resources/greenStatusIcon.png | Bin 1879 -> 0 bytes resources/redStatusIcon.png | Bin 1699 -> 0 bytes 10 files changed, 39 insertions(+), 19 deletions(-) delete mode 100644 resources/blueStatusIcon.png create mode 100644 resources/busy.png create mode 100644 resources/connected.png create mode 100644 resources/disconnected.png delete mode 100644 resources/greenStatusIcon.png delete mode 100644 resources/redStatusIcon.png diff --git a/jceGrade.pro b/jceGrade.pro index 85eecfd..3da80c6 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -7,6 +7,7 @@ QT += core gui network widgets printsupport CONFIG += qt c++11 +#CONFIG-=app_bundle TARGET = jceManager VERSION = 1.0.0 @@ -51,7 +52,6 @@ HEADERS += \ src/appDatabase/jce_logger.h \ src/jceData/Grades/graph/qcustomplot.h \ src/jceData/Grades/graph/gradegraph.h \ - src/jceData/Calendar/calendarPageCourse.h \ src/jceData/Calendar/Exams/examDialog.h \ src/jceData/Calendar/Exams/calendarExam.h \ src/jceData/Calendar/Exams/calendarExamCourse.h \ diff --git a/main/jceWidgets/jcestatusbar.cpp b/main/jceWidgets/jcestatusbar.cpp index 4c7a741..26dddf3 100644 --- a/main/jceWidgets/jcestatusbar.cpp +++ b/main/jceWidgets/jcestatusbar.cpp @@ -3,13 +3,32 @@ jceStatusBar::jceStatusBar(QWidget *parent) : QStatusBar(parent) { - this->setStyleSheet("QStatusBar { border: 0px solid black };"); - this->setFixedHeight(STATUS_ICON_HEIGH+5); + this->setFixedHeight(STATUS_ICON_HEIGH+30); this->showMessage(tr("Ready")); - - + this->setStyleSheet("QStatusBar {" + "border: 0px solid black;" + "background: rgba(255, 255, 255, 255);" + "padding: 3px;" + "padding-left: 1px;" + "padding-right: 1px;" + "min-height: 50px;" + "max-height: 50px;" + "}"); //Icon iconButtomStatusLabel = new QLabel(this); + iconButtomStatusLabel->setStyleSheet("QLabel {" + "border: 0px solid black" + "border-radius: 16px;" + "padding: 1px;" + "padding-left: 1px;" + "padding-right: 1px;" + "min-width: 48px;" + "max-width: 48px;" + "min-height: 48px;" + "max-height: 48px;" + "}"); + iconButtomStatusLabel->setMaximumHeight(STATUS_ICON_HEIGH+2); + iconButtomStatusLabel->setMinimumHeight(STATUS_ICON_HEIGH+2); iconButtomStatusLabel->setAlignment(Qt::AlignHCenter); //ProgressBar @@ -48,54 +67,54 @@ void jceStatusBar::setIconConnectionStatus(jceProgressStatus update) { case jceProgressStatus::Error: setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); + iconPix.load(":/icons/disconnected.png"); showMessage(tr("Error")); break; case jceProgressStatus::Disconnected: setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); + iconPix.load(":/icons/disconnected.png"); showMessage(tr("Disconnected")); break; case jceProgressStatus::Ready: setProgressValue(0); - iconPix.load(":/icons/redStatusIcon.png"); + iconPix.load(":/icons/disconnected.png"); showMessage(tr("Ready")); break; case jceProgressStatus::Connecting: setProgressValue(5); - iconPix.load(":/icons/blueStatusIcon.png"); + iconPix.load(":/icons/busy.png"); showMessage(tr("Connecting...")); break; case jceProgressStatus::Sending: if (progressBar->value() < 10) setProgressValue(10); - iconPix.load(":/icons/blueStatusIcon.png"); + iconPix.load(":/icons/busy.png"); showMessage(tr("Sending...")); break; case jceProgressStatus::Recieving: if (progressBar->value() < 15) setProgressValue(15); - iconPix.load(":/icons/blueStatusIcon.png"); + iconPix.load(":/icons/busy.png"); showMessage(tr("Recieving...")); break; case jceProgressStatus::Connected: setProgressValue(30); - iconPix.load(":/icons/blueStatusIcon.png"); + iconPix.load(":/icons/busy.png"); showMessage(tr("Connected")); break; case jceProgressStatus::Inserting: setProgressValue(80); - iconPix.load(":/icons/blueStatusIcon.png"); + iconPix.load(":/icons/busy.png"); showMessage(tr("Inserting")); break; case jceProgressStatus::LoggedIn: setProgressValue(100); - iconPix.load(":/icons/greenStatusIcon.png"); + iconPix.load(":/icons/connected.png"); showMessage(tr("Logged In.")); break; case jceProgressStatus::Done: setProgressValue(100); - iconPix.load(":/icons/greenStatusIcon.png"); + iconPix.load(":/icons/connected.png"); showMessage(tr("Done")); break; diff --git a/main/jceWidgets/jcestatusbar.h b/main/jceWidgets/jcestatusbar.h index 226980c..78d1051 100644 --- a/main/jceWidgets/jcestatusbar.h +++ b/main/jceWidgets/jcestatusbar.h @@ -3,11 +3,12 @@ #include +#include #include #include #include -#define STATUS_ICON_HEIGH 35 +#define STATUS_ICON_HEIGH 48 class jceStatusBar : public QStatusBar { diff --git a/resources/blueStatusIcon.png b/resources/blueStatusIcon.png deleted file mode 100644 index 1f70d90fe2b98a7d65649e9abb6188d9d4c33e8a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1990 zcmV;%2RZnOP) zh#iL*lad&vN+1svQZ^_%5JIR5n?68As#K|qN?ml>Wf$!VwNf`A^|c~uRjH4ti_mV` z&;ofW1ScUclcY9d#~#}=o;&y6^L26W*p3w_J<>Plj^^n6&j0)VXYM(|=QjcRfKlKu zVvmb;$HbT^5mN(D4NVQpr1GKXSE`55X|$YRC%SZI=F9q*Q6hx z+(WHCLbM6F)~zXg`Q z2zWQ}{X%{G^}R=)8+`et7dd|HFnf28ZNNUOtw%A}KAGolXU_76KmLiU@Bh8oU7C9f zcmw!k>sb2`=#Tu+uGbE~@b&6l?kfiv8LX0|fp!$r?tVr@F>xBGR?0j!Il<(f zz0Aj@()``o17Uq-1h@b+9|j%-e&~lDd2P>gCo122?S$-kWQ>5&?#8sDgtaK96~(l= zdEbl9=5ssh5(lMLt?<}mk8)*MeY0_AUuds*;60$T6fclDh=n0WT(>NmdjqKpmI zh|<7X6tnt3B-_5ntaf5nqwdDowN96IH^vyl&WT-eeFfiY+}R&GYxjZkKv0p52&AI3ai7@K;kzV{%bJBDZ_DXsM`VoV0jLnWulHcx5~oI!h`AwWpkv15q( z-h*`JZaf*yUV4ELE<0dUO4V2V?k8-0=LBjk%iR=AfE=8uHmKREc8la(sRTd+f7>m?LF+)2Yi}#K@aqgHMn?wr*+6c>uA}DG#gZJh(Kp;>1R;7SS zt~47X8=*+5Xri0M83V?Gby#cg*5Jh8j9?9zTya2210w` zo@$JesE~?5oXc#I#Hec15yGvowpDHwQXvXLKX&S*_?>XJl&vl(m*E_oCrpsCD0WJz0!n0n4g6>I^#&=)1h(qJFP-fBmWsEOU8dR_c|dUnR@zCxTfv$%e~$=B zP|~2J3-g4Tb15rJCxM0o+Jxj3*Dt>0K6>wP-`F@6=c#y0wP2~{egBqP7jlCEq`Fz( zf(K6;<%qxO87LR1mHY;9u;{3HN3Gzf`poeqXDL{-QB%ZZYE?<&gq2&@^v;_w;SL>t`>wKLJA~lpxbKm z>CA_G_=_L6)-IoW8~6z@--B&GWj28eQDe?GuU+0>^o7#!@G!%*0R{?=YQa(~IBMQf z&9|5{1~EdKn=FoF?%%n?%;{5{|K-n`OEVYW%AvDcLEFJS_3oEVwdHT|W1)9%nyhj{$aNp{q00DQXCsPNN3-|6_U2Zf^ zhNRoO!gL-s`R9RqzxOU}M+$|~@ls#;8SmVbwb`XDO+zzIliQv3^)ua0=N;e!zQCpJ YzxA!b_1%Arx&QzG07*qoM6N<$f?Sce{Qv*} diff --git a/resources/busy.png b/resources/busy.png new file mode 100644 index 0000000000000000000000000000000000000000..a542419fe34e8379adaefb5960854fd298dcdc3e GIT binary patch literal 5475 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 Z{|Psk!b*w^aM1t&002ovPDHLkV1llgaf$!{ literal 0 HcmV?d00001 diff --git a/resources/connected.png b/resources/connected.png new file mode 100644 index 0000000000000000000000000000000000000000..ae7e8c0c92f9421bc58d74744ab97f8987457aa2 GIT binary patch literal 4992 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 KMNUMnLSTYdpKId) literal 0 HcmV?d00001 diff --git a/resources/connectionstatus.qrc b/resources/connectionstatus.qrc index ee4dc40..7f92be0 100644 --- a/resources/connectionstatus.qrc +++ b/resources/connectionstatus.qrc @@ -1,8 +1,5 @@ - blueStatusIcon.png - greenStatusIcon.png - redStatusIcon.png icon.ico iconX.png iconV.png @@ -10,5 +7,8 @@ us.png help.png team.png + busy.png + connected.png + disconnected.png diff --git a/resources/disconnected.png b/resources/disconnected.png new file mode 100644 index 0000000000000000000000000000000000000000..c8817f9b3d707ab1dea7924f1c6ec0711fb2fa68 GIT binary patch literal 4569 zcmV;~5hm`5P)^%JGlbiP;P|AR$03mLM^N zV1pL|l1u`r#FQ%u1&JY5cF8M_Nky?iNJ1-m+TOm-zIA_-b8h!Mo?awj96O00?wZl) zP4_+bo_p@OpKPgL@gM7#anql?vMcJkZnn{E>O!fc>h-#7Ja6m|KC;gIzXb5?^DkVK zNvGGw9OvS2SYH?lMS4P(jvPGlx(bKF3P6M=i_RZCUze3SE}aVq1ORIYk&|Mc`Z+Oq|$0mPmdZI8=C;lwp{kUOTPL` z1@P3@pI#TW?I*L@Y%bT)(Mlwfmg7VXK2woUM2GE=iAHSouRFe@mo8pxx;i`Yt(Fdj zLgo;vfT!tPHe*WVs%kbGy5YK}yR#FYb+nG3?6&~;K&@84>VxmUY}YRwz+ZjsiS6-N z>}m#;%jML>#DuC=Ysy2GJ2DwHf8M!j;rs<^aBxuVJA7E3J9n;{11fp0r}~Z`Q&A_X zw53%tkw8;7SplILGOuu7KwLOJm`0 z@t+3A4Eje`YgJRJRDq|ZJG0qVtzNfAMn|8#{DU9(^z*gpgqyN;5t&$v~77b(9W=&>JBY;>GB3At7?{r^RwWsnACX z+*hcC>I6MW&2ohxN~*tqVB06I`sj6U8NeNz@7;=$UK@8D6Hg^|I+-w;bVjF=NxY_+ zWj+|HsZA)%07F8XD7bv=_;C$t7*v75BkPv20t(4{9{}joG6u9kpBPGRqh8ltU7e;@ zZ>UPOsw?HPnaUURiIXR;zUEV(eBx&Yu<`ECt@S+b1qQ(kBWR5tFzHl6cXV_Z{8^#w z(gPS&NTR2jn7T=Ti^pT?*ol)ui^&LBbT(-`;@tRNfy(xh8o9=QD&X3eGx8b&0l2~cr( zbX1i(^X6)Vy4;jq@l;gCrq(a zR8v!VoiF5->w3Sp@lS7h_KX0K{WO9Y0h?{y*#fPNjSNGlHJaC?&rqX3_bwnAMb-6)=Yk@WdH#A_h3ChAtikjMM4_7ukWZ? zxM03Ie)6Q=wR5DIdj^E28@N3KqypfO$1#ZDu`tL?VC6B1RTnZ(5#WR_ zl}j>T#>P;Ap&=B=wQsrM`qn7`w%q?0x8dbM1Pp5srYiVjA7yr;F=@n+krBvf)+CcL zQ6vD+@mSpN0n7ws&5$->R09A^0Duz$JwQ zoiZf=C=?2MbZo**jE||QVnGiNk6gBS)9v3o1;C#@_|P};uqzOZ*?-`GC<1OM4ZCXP z3jNx?{nTesBkFWK5mTu|3VKfp`9lqvHyP+03tq!=^5b90gxV4@*m0j0)$5>Mw+;Z=VBbo z_C_i0?(9-!cp?HAhw~jB8)Q%Pb2qTj2a#w*qaS8epgjk~hf;Tf3K%hSNVGhY z6v8|)>^G$xOf;(18k3oTw2kBND2GK%fw* z(guLwOeT|7aVMrx0Yle|!1d6O4}f$6E5;wZZ%fxSfDL!veJ&`|zw&|$)ELS|+VDwx zUVDwrq%Qx^@2aE6jw|i~bf(OBJdO$NkV1}1#u7e-I1i%!Ot5Fs=u{^v6%Zsc13X?$ zh5m)1Ymi`Ah~}t#v4{pPf;wYrcxXrskBy3r_guI5m4_ZoPXqYuZFii5Y7Q`n-rin} z@}}CgYZo$PL@}6|70Z{Ke5t4@*bI05;y9#SJIuX~@?e zEZWdq-9OMTH>Rqf`i9#Twk)$`NiQ1xb^0MtDrREwsK{Ov@3|949mpss7Y!7N_vAic z1wGIPz(Gd2CII*xQ9c4-6?zvff)^S$G;#=BWB)L4r>cyhhTk9F`sGLFo}xlGZrE4_ z#~t#PzJ$r*slv$Uag-z`o)LdaSDLXtiN?XH2!?< z0Gx;{6(r5na5D-ydctr(A*-x}Oj{cUE@q>tW5_y&oy`X4=cG;47ApZ?habP8`3^lG zyyPC>(MT8kbLP(Fs2ArrU73JB z&P*VUjL7_UH*Hm@9Ldv8I;jT zdk*-^ytcR-01Q@3EHPLBqyku`Tby7m-J}Zn0A!G1wPet`$!Z{Y9uhb4IsV?l-{qg$ z`dId~b{aJL57>z{SYTx8(wDGtT(_y;^R9OpG?xa)WhbT^r3yu1r!fRM=Jhkr{fjIs zBCn1!y%Ur71k(b5Hz?$RA~e3POnGKsypY#0&3aS7@Z_$J&v}aHp&tyClRN-2v%T}=rpaC<~ zyLgd?lo?2w3?JK$TG$0z*-S>fkPjdtM=Zhm$Wt}*?H%9s6%73l*a!{+`Up0q+>5XN zv5F^wdK_-Zc8j|~@LoPAKx5wd_fKr!c~$_yP}>avt01fF1+{GHQe7$*O{G?oY;m(9 z#jw<9Okp{>zyOm9h+7aVWyu+6|GuCYpu>RHy@PIwwxDF1m)Z969WW8f~DS$o*?!v)@j`+(w_f9S+ zl*vY;DeK`(4zm)h(kr`O6}gsaOlZt-%U>^BtXBJT?h4K3INmM>_e(z$fB?jGpwi=9 z=BX<1H>RhvTSK3@0E&hystQ-fkgxD!GjT_%Nv+;M&u}5Hh(%^ok}iS5$x#Uavjox? z%(Rl@M&Im_ZhR0V)&h;*hu~j4U7Tk<+=a>8hTyMhs}dZdEbi@1P52qSXK#ujbNyk1 zprvB8B0RLM^VE&|GAc!j%z+mKJsk-T-T7|_gux{7{-Er&fAiR*+s_o^oBsR2H8*|s z>s{SFe~1aqWkt`QHxCs_h|y!lFe429hXCuSPD7le9L!eAh9}IpbfZ?63ZSQS9o68J zZZ|Yf;Qf9HDIHV*KO7bomiXJh@zj%ldA9h@2EgjbW_2Q&GOO3DdF-OqZ@-Rqf&;3j zyGwO-bumk_7PhT$z1BdZ`$5A?$q?jbM+(t#f{yZ@Jwq8~;O&3(-~)M5Ek|@{u$@2t zx0_yi@rRG5Gnr5!pZDG>0Dd0EWe2b3H{P-4Q)@rG?qT#rh_cDkxo!X<3;aE?B@NCa zkxHo|mbeNq97;U26~Vz>8=x1Ldk!)s)KkG$CNjzIPd@+bGkR58+$3FJ((({(R4RmNhnJg|VYFfyGnkV!6m>mNk?V@;F@)bl^M* z0P1P1BZm(S{ouPho*5Y$`d$!lBM6v*mvI$>&+7p&F92t(S;0qw%MOB01|ZVG`(yx& z`{=wyy-R-m-50-i`9-T&cPHXWi~gVL;ww`Kc=CR2uB>A3xT2WN>VB^aL3eT$4e-l^MZS zgDTW#1l+#7b`{Rl1G6tZ3s@W6%u1z$D-nDa3BIR-vNwXDNstrj9X`D1a9mk&W%$s>X?!7E##&#?xZJ%^>@0RceJPT=@6@IH`#7VsEwn8X}OrYHCA{>onU)fe{h z+^(nDy>$o8O_L-h0w62<+-fiI!SzeL`{7ys`Hxea`_~!Uox6L6ZuvXl_rT((0dE6- zB&L$1+rIIovG0ECI~@4(H`&$PPHdtFM(TlHk#p|WW&Zl^-}vL}f8yHTKWOT_) zaBc1LY6Iv`X(q4C9Qs=QhlgJk2cG#lkJcZdaF(p>(|v$tWuL-UG~yaN9-C(Cj%hy9 zOVPr$TTjs`CxNp-Ya{R&@DrNJD-+*-I{oqYUKKl=kK=H3ii}Rt8;%*BGFzP&8J&FX zeUH+WjMp~t#N*pJUCf#6#^MZ}(g5!OeE>a#hQMJq$4AoxJJatUd`To>#C&&g<6^A; zZKK}x5Qh2jRgwM;ax}&d!RHHy0cJ3Kkxz^KMTs(;5oCc;y^~*f5NsTur@e-Eu4#**F zt>X3S*QeUApZmcmVZ1p>dq+cYy?cn|;4mRD>eX^ z&Ju(HOxNLz*~xP8tVW6bOvak=5Gx!V+e3OeRJ9LNE*Zn6l5-^Z8Jh?2Hxe!*&5Qr zQoXjeZWWx{lFa3U&sD5IiiTbRC_yDG%eITv5n^3YS4u5BLiiQ_fF*E<`?5WndGE+< zpGw++VmWwI<9&3X2wkNPpRJ1;4nKw5!t5?4ub z2NmFjTZL8v+66d2r>WfA+~__tO83A(X-}jpB5jGZBUGM1Is)mD(ytW40nP~uFDR@e zw*ny~2t`jQs!^frFg@41P`Oi@(!a^=-VazRG@pw=f!3bXcoJiYv?bP#P&ooM0Bh-1 z{#D+Cb&|pfaw`a|!bp#ngK~C}RDSqDxSPZ6UPbBO(!hHx78m$mYd6gZr9H86q=6?f zoKsp>_?FrSuv|QUq2l}1U8lp4gqJO<}VtgXl|_vrrNM$6yKj{$E0)d*~X|N5n>?r!v+YCIX5u}LRt zaY!wSshNO!V5o(Ln$e_zAvK0r8v-4mWr$P}LWCeAoCxr~#Foo+uJrxWY6Y3ZvBczN$BzO_w zkhm(N$QHPFKI8H)Zg+bh_Fe;i2HYOO*6%V~z}a%XGRv2Gy8>gQ@rfQ|jfx~Nq$Z&j zjFFl;iB1Vs4K3>+W1P1**P$x!(E9i`SKe%K;Wvw|&VTabL+I7Dp!MJp{GDRK-dnnm zZ*E`BH~U^&HX1F)8*S=liPW@7b(>HwA-IcoHz|r6%wPGK^MAR+`>!qA%ddCObgov% zhUvY%9`cDt7^yi}n-Yh{w#c1ZXQZBa2DW`(^2qq$p~XeGcGYq5-*D}stCnuKi=BCY z!c{9rnEpo29|j(+j}C3mnt=U5%JW(=trQIaXK7WIxxB}zvd>$FjBK4F*BcxV2^^#j}NWD}Qho(K%QjmIRq)6t_ zq7oE79O62}kODE-#xDlHuYDi8v(v-wnzd_VI?`YB-tNr*_y3sx&WzysO#peIADFb^ zL>AtVFf5=4z(7^Q{Wg5&!!&RMr~qE{dV9s&H3xWE!JB1xYmeiM9O&=2$NKvja9xUy z13;tGVX0ncu2SJ{r4p=kI$uA9sQ^9!ZULSD2iyz%q7Tj<&gTywA0L-Le(g059z9BF ze4Na{05YEkKzknD6vD8<~#TZ_zUp#MZiPAuSSG;_sq~x z@2S(L898~9!q^xxmjkhlt;P_xS~TY7nE&)sKDl_2sfC5=yfGJm^T0xSxZDEz+n3<& z4@O4Z)9<|}hEJZv*|P__T|&%0y6x`$Qyd$!E_hLF7OubH6udnyX@3e%Q-i7r#q32- z(*DZ#$5!D9Fau~6=lSJ+IQugpdM76*v0ayNbrm7y`XWeYc5{|D*NjO-YwSXSBa@Tj z=a(<{{Lz@R6}SRiQ$Sw9n@8aAPh1ywU;sQ1(`rQvDYclMS9@s#3}B4G7z4)O4h(SI zb-7ln{pb>$3SdqF{eAG(F_1&$GSV1WTic*;C*V#^0z>68$7(fs3(hRVpA;~;8%AFR z>`VsHZiChvpowf}gowRN`n2}|!uPQ=8D0f0!ss%*qB3ye0H{GgYK>?#5SE1itXP?~ z3A$B|)9^5!6DIS+5UDjozPV6YA`Ojc zVN^YYFWAb##g|3$~3gD~46u_&X3JU=7?^GPt)j6GwZn z`-@swSLh1Wn}^4KBpcZ_}X7-~|5pQkN$;*4RB?4|g{@b<1_uaPxIUrjE!o zz;1%5f&U#e7xC8?xcBWt{&wprf0zyRNB5YS_c$Mi_wi=Pj#rqB#i>07&J6W1dT1}| z$Uzt!l(^rEY_31iJba|Nc^7Uk58002ovPDHLkV1neY31R>M From 0c0fb2fd952bf318c8c76c623c804cc9eafb4627 Mon Sep 17 00:00:00 2001 From: Sagi Dayan Date: Tue, 14 Oct 2014 12:41:09 +0300 Subject: [PATCH 51/58] compilation error - escape char in exporter --- resources/connectionstatus.qrc | 1 + resources/logo.png | Bin 0 -> 38362 bytes src/jceConnection/jcesslclient.h | 2 +- src/jceData/CSV/csv_exporter.cpp | 4 ++-- 4 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 resources/logo.png diff --git a/resources/connectionstatus.qrc b/resources/connectionstatus.qrc index 7f92be0..0a27809 100644 --- a/resources/connectionstatus.qrc +++ b/resources/connectionstatus.qrc @@ -10,5 +10,6 @@ busy.png connected.png disconnected.png + logo.png diff --git a/resources/logo.png b/resources/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..2a8c5ab8dc53df903cb05d132c9ead9a8fae2702 GIT binary patch literal 38362 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

                                          04C50 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 +#include #include #include #include diff --git a/src/jceData/CSV/csv_exporter.cpp b/src/jceData/CSV/csv_exporter.cpp index 96adf43..1dd6e6d 100644 --- a/src/jceData/CSV/csv_exporter.cpp +++ b/src/jceData/CSV/csv_exporter.cpp @@ -222,9 +222,9 @@ QString CSV_Exporter::makeLine(QString name, QDate *date, int startH, int startM } if(room == "") - description = "\"\Good Luck!\n"; + description = "\"Good Luck!\n"; - description.append("\n Created with JCE Manager.\""); + description.append("\nCreated with JCE Manager.\""); //Create the Fucking Line //Header: Subject,Start Date,Start Time,End Date,End Time,Description,Location From 1974104c2cddbf56269005f3c734b006825a54e9 Mon Sep 17 00:00:00 2001 From: Liran BN Date: Tue, 14 Oct 2014 17:40:17 +0300 Subject: [PATCH 52/58] update translations --- jce_en.qm | Bin 24660 -> 24431 bytes jce_en.ts | 228 +++++++++++++++++++++++++----------------------------- jce_he.qm | Bin 23078 -> 22849 bytes jce_he.ts | 228 +++++++++++++++++++++++++----------------------------- 4 files changed, 208 insertions(+), 248 deletions(-) diff --git a/jce_en.qm b/jce_en.qm index 2d167f62eaa8303d8f1f680827dcb17c5f519c16..cd567accea76246a85de164f01fce3ae828d70c2 100644 GIT binary patch delta 1349 zcmX|BYfw}L6#njOckk}K3kXVtz^;p};7W*?iloR63b?WYON)=i!CVnVM6iUk))$d! zSS(E7BZnryN13n_x#gG-P%$$tn$Z#l#n+^RlV(#&O=o9k{IT=hx%-`SzVn@PZtqFv z;R)u$5LY9BS-@*WgsFtxgl59KfUpS2y$)FD{}^~a^j2y=t9-Bh~Dw${Ty_E1a%lvi|NEu>HsafP!J3C?EGZM0cec7>%oXBG{bE(7d z%WUQB86;H4eq^Wt?6cT&2Mz*Ze{(8po{Ks&awE=^0`r@=B#{aQm2zobveJH&%T(8q zkO8jX?Q)t*H&<3e9ayh&mDW5U`!07RB9bgV$#sUkL8Fqm3r}_fIve-%JbJI)%m>=Y zv9M$O%=QEzUCo>Kp8zgQ1|rew(m(sxQ7#Sh12E zOWGi;y)y#H*d)9ucz}s%!p1+w0MYfrPS?eHz{Us-x2I4dN!asODv-8R*t=^ZS-;+o zwglmGU!k-_#lA5tFvYBBHd3MR6^iD?9mH!UcsUaHw*J$%#~lYDwP>Af`*@YUr5;jQv-2Xz&(wW)PXD1;D&^F{8>rR(6YX zuh)^{3Nh=HKv%I{%>S_*n4uNd+#{Z?SKOt$M9Y>S_L!-FK2^McP`Z*Dv9FTeYgUQ( zzx#^vM5s+$X8<7u>XalBkmyiX#YF<6@?7dq%=8dit6?ItDA9V2`pjdp#-XvCBVm?8 z&2oJ!T}QFz@DJ2s&M%tdyXo9!4@&{>52@A3}sB`O5@sF9`nPn10y`l;hH@>vT*La%89!$??CsCGn3 z3OTw^8?7fk->FUBNzU0`*H*Y9fHCs}6oW$~%o-H1Xx(a>r5sS5_yOIgJz($RLo}=U zfS&y^)am(RvZd4W6TedBSt-{Ax#OeE?zX774qY-6szN%PC_$OZCrLp+KHXVT=Dwm0 zaj(+9>ba)xVm-e`Ph?G_U?XNBRzpYMw{m)3hGMLH9;dN63s>vR<<4cr>)dN2M|ou9 bZDypJa<4%VF-xB_1$Uq!%=2j6(kcG~Adg-$ delta 1524 zcmYjRdrVVz7(KW5{@UBy-d2%`C}1rDih!uY*D7PwA|SL%!66DpV$qrow1DDtcGD^I zH8-`HqRy}fzL+4*m}JC>8X3lkOk*@dqvD*IM(2!gv+XNQbbmA__ulh;=X~e){d)f> zci|ZKS+M5_fOmj*;|Nm;*Atov>j5?k$gKsk==&fygk}pc^FD-50T}o%Sb7o=-v#!? zWnf4s*f9q%Qd+cfnfyEifVoHrG}lt`2r_B@odDdm%L*%mpw$6Zt>1 z00r%sbEE(;x(JD%{}-x-<3LIVYVY2I2Q!Ot`pi*4+{T6U&}5@LT+E`YKse8NyFUd? z*SS5X5`Z^ma0jDuNO%(WBJlzxaX`WSc7ww6DdJMCl-6NI{Ize$z(TX5)%^Kvdar8` z`s7klp|^y$50558oq~DKQGl0)?HR39A12gwc*tQ+ws7hBIw1C@&{MaU8pR1W2T(*K zHwbsOx6=eA!eeg(;jb)qe>b2qv$(4~U^vH;Zk?nZsAOrGR3HB}n|jTkOf;L0DHM4P zn?2s&r;sgJNXfmG!WQ2O0x~UZ3G)G?CAPxzzz9UmWE;Kf76~H7@0CS(PdcTn6nR2&L0gM-wwJ{_VHe6XdyNP%URlNBIFu|=-ULgVHGgZ2& zjgDlbYSnYn8Ph0Qn;y|o*hTwGO2ljwJ#(&Hr^(le-i`@C^l|Y(&rOv_ z(DHt#&FHJ6E4@=|O}s??cWWIZC^^+WZS93YwDcZX`;{jZ7*?-su~DO#WNk}fFeMVI z{gEpt$8Fl5mr1ll4YC|NhLRCv$F<|YSg*YJ{RANKf&AeZ|FYWTHFZ=!wL#v{a+U-k zH^wMvC!Wc^45tR0oD|P;Uz4y<94H|gX>h^? zhv@g9q#uh;bGjT`69)wQ!sIP|4LbUJbHjmo#H&F0E1t^icFc2Dl>3=m4@H=XXhA9F zQ!^*ZvEVh)Qaaz|EML$|d=QZkA`-F6-|ZDeuv9rKdL;)BHgSU_c7t`X+w3y?^A$yz z?kILUmi9JTYnT+SMLNo`6b9s??0>AXrH0(H-c~0JCl$kkVS}AWlWBqy%ta;Hd#x+k c?1ssXlDUW0D24B7)E}Hr9#%Z=KaHS-G5`Po diff --git a/jce_en.ts b/jce_en.ts index dbe99e4..f17f2bd 100644 --- a/jce_en.ts +++ b/jce_en.ts @@ -64,166 +64,149 @@ JCE Manager - - + + Login Login - + Keep login Keep login - + Username Username - + Password Password - + GPA GPA - + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> - + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> - + Average: Average: - + Only Main Courses Only Main Courses - - + + Year: Year: - - + + Semester: Semester: - + Export to CSV Export to .CSV - + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="right">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - + <html><head/><body><p align="center">To</p></body></html> <html><head/><body><p align="center">To</p></body></html> - + + login + login + + + Clear Table Clear Table - + Get GPA Get GPA - + Revert Changes Revert Changes - + <html><head/><body><p align="center">From</p></body></html> <html><head/><body><p align="center">From</p></body></html> - + Graph View Graph View - + Schedule Schedule - + Get Schedule && Exam Get Schedule && Exam - + Show Exams Show Exams - - &File - &File + + + Team Credit + Team Credit - + + + Help + Help + + + + Language Language - - - Credits - Credits - - - - Exit - Exit - - - - Hebrew - עברית - - - - English - English - - - - OS Default - OS Default - - - - How To - How To - - - + + Error Error @@ -235,8 +218,8 @@ Make Sure everything is correct and try again - - + + Not Connected Not Connected @@ -246,29 +229,29 @@ Make Sure everything is correct and try again Missmatching Data - + License: License: - + Powered By: powered by: Powered By: - + Developed By Developed By - + Help Guide Guide Help Guide - + Liran Liran Ben Gida @@ -280,50 +263,47 @@ Click on 'Get GPA' Click on 'Get GPA' - + Sagi Sagi Dayan - + <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> - + <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> - + <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> - + <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> - + <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> - + <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> - - + Settings Settings - - - + Your settings will take effect next time you start the program Your settings will take effect next time you start the program @@ -469,134 +449,134 @@ If this message appear without reason, please contact me at liranbg@gmail.comFriday - + ConnectionRefusedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + RemoteHostClosedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + HostNotFoundError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketAccessError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketTimeoutError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + NetworkError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslHandshakeFailedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslInternalError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SslInvalidUserDataError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + DatagramTooLargeError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + OperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + AddressInUseError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + SocketAddressNotAvailableError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnsupportedSocketOperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyAuthenticationRequiredError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionRefusedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnfinishedSocketOperationError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionClosedError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyConnectionTimeoutError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyNotFoundError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + ProxyProtocolError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + TemporaryError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + UnknownSocketError Your error is critical. Our team need your help, please send your log file named J_M_Log.log to us. see link in About. The file DOES NOT CONTAIN YOUR PASSWORD - + Unable to open or create the file. Exporting Failed Unable to open or create the file. Exporting Failed - + JceManager Save Schedule Dialog JceManager Save Schedule Dialog - + CSV Files (*.csv);;All Files (*) CSV Files (*.csv);;All Files (*) @@ -610,37 +590,37 @@ Exporting Failed Exam Dialog - + <html><head/><body><p>Revert changes</p></body></html> <html><head/><body><p>Revert changes</p></body></html> - + Revert Revert - + <html><head/><body><p>Discard and hide</p></body></html> <html><head/><body><p>Discard and hide</p></body></html> - + Cancel Cancel - + <html><head/><body><p>Save and hide</p></body></html> <html><head/><body><p>Save and hide</p></body></html> - + Ok Ok - + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> @@ -755,53 +735,53 @@ In Example: 08:25 or 12:05 jceStatusBar - - + + Ready Ready - + Error Error - + Disconnected Disconnected - + Connecting... Connecting... - + Sending... Sending... - + Recieving... Recieving... - + Connected Connected - + Inserting Inserting - + Logged In. Logged In. - + Done Done diff --git a/jce_he.qm b/jce_he.qm index 9a00e7a309e153d73eabe1edb47c64b5244d3746..764fd3afba35cd2e081f83223199aad17250e58d 100644 GIT binary patch delta 1312 zcmX9;dr(w$7(Ms#+r4*p?=G$w4+WQ9ba_c2f~15iD+nws@^CU0HEo+LG!$&4%v&a* zqlL0E;v*d#-9*cbEsM!99|b}tRx;_NK%(Z9V`D^9_^5A(Kkl6S_#Wq+@B3Zfr`(xV zZdb#2J=2|Bcivl_>1{~ zC4`XTOJY$Kh>Pk&op=_Qz7frL??FY$c641h1xO+nG9Utpvp9QYFDdNd8n3+vq*rtM z+Y^D&SGc1SN{GNd?m^OJD%j0)Ki>c{+WCYmH@Q{LPwGDiMC9>LmTx2{R6f6y6oxnP zYjZMzvA^-#ZFS`AGknM4781Nekc#H2q|76j&#eUV2ZU)dH42(2WVex(#dm~!T>~W^ z5f;6%8kkWiRMwG#{1{lQNe$;QN3Iw}>}G$)bd<;-AL9 zsGyIUS)oAxPz^`Zv|`)wpG2b18`4Zjkl&!A&KqzI}31}W_#<`k@X!T=w8A; z3^a1=(7bQufhnC-?q`s`xT&D(_UE17?Gqe+f+6}|hC@D{J zw+_*>T`GM@PGl<5;_I~NF_6^8&ZmIrx1=KjH)(di%G~fGAXhKv)!0b+a@lpQff)ZQ zyU#E>9WC;_?$yAwH2IY~6z3k6>n#_7vS7K>Ne#yL%UuYe;uY{wu{sV%5ggn#7|WGulJJTLrQxANB@ahV^A0oOZ&)Zb~s3Rs4+T< z;>Aj1##VC9z1>))M$j<~H)#g$5s|!QrUlh2DDhiU?UZ)`t76)_@CePS%+$F*mi|qT zmy<1<{6C129fLEiHb)4fw86a5X5m7I5_#mvN9Per9S*%<6iwmj|MV>!09q?}i z`^rh7egkOV0`_1%Fufbf-<5!3CWd6}1EhQe-uVa6wIl3&FyK;&uuQ6=f`7oebrB_A zIDnxw186-wfR4XmeHa9!?SQRxCom=!_S{M!YzG{wb%3D+j%-S7I5>de@tE^P1CX&7 z3l2X6jFJh7pWcU3u?dJvMeVPBaKSMft!It{s%Xx;i#m&vxR8QQ!1p9q)$ukE6T@vk z6$$7S+}_}HD!iC`FzymLv6<(7x(-Y&<0DKqax0r3du<2c7sE$oze-Ld@fHU)<~xrs zPL2mg{>Z-*SV{s$@~3z028RDBsO*_8>L^U`YR&^@>=I%nD&(0Vm>bB-^iKtgyomy9 zg!wNP0tsG1K`C`;`AsOcXVO@Dgnb4-AVn=4@>xZB9to{?YXD=Ea50U}wR1(!403At z>*CX&MU$Y*V&eAW0N*B7ryiyFEU~V|MGCED;+6YvP-mWESKY^yC{MgGoGcnUOT1Nm znmULO?^W$5tY%@mJ7|{OETU7OnXh3Jd%mU}$YIGAiVv@1Gp_YJ6ToI+I$1u6Wj)oO zCxk6qPR>m}#a8rq0p?)#Jad!NSoxXFv}`w7Rrh3?=~?#PJrnKa2DYtY zEsdaj0PVr-lm0@}<|^I~;DHH!irNq=G~%wJHmja^N0dV1bzsssrQ#|TP;6DE#GRm> z=u)n~Pj#NusciLk>D^o9cu0=KUr@OgT>TjcJ*lc{i2;I>ReQQ_P-l9HyFZ_-Jujt} z1d^p&q!}HXNbzyWc7oBe=1Ftf3W3-MQhqP-?2S@|@fU!oqkBYWE5RhpQGx%XQ|_~bLyitbPY|nH6E`K-)p8OZhtyC zqSmB7p`$BZp|Op-Lj18BXE-^hG-+xt`4YNzYCd$CfDo0Y!A^;Sn=}pCdU7O9^CeeA zoh;UTQzDbFOszI-JPE4TIHz3OHYxT_-8MM7cRgP^35) z6*^Zxu4MC{S{dl?rBtNkuQq1nKh{|0e}E6w{}uNWqt`|M3p*i-FaQ7m diff --git a/jce_he.ts b/jce_he.ts index 0d3844e..39a46a0 100644 --- a/jce_he.ts +++ b/jce_he.ts @@ -64,166 +64,149 @@ JCE Manager - - + + Login התחבר - + Keep login שמור פרטים - + Username שם משתמש - + Password סיסמה - + GPA גליון ציונים - + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">ציונים הצג</span></p></body></html> - + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> <html><head/><body><p><span style=" font-weight:600;">טבלה נקהe</span></p></body></html> - + Average: ממוצע: - + Only Main Courses הצג קורסים משמעותיים בלבד - - + + Year: שנה: - - + + Semester: סמסטר: - + Export to CSV .CSV ייצא אל קובץ - + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="right">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> <p align="center">נוצר ע"י: <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> - + <html><head/><body><p align="center">To</p></body></html> <html><head/><body><p align="center">סוף סמסטר</p></body></html> - + + login + התחבר + + + Clear Table נקה טבלה - + Get GPA קבל גליון ציונים - + Revert Changes שחזר שינויים - + <html><head/><body><p align="center">From</p></body></html> <html><head/><body><p align="center">תחילת סמסטר</p></body></html> - + Graph View הצג גרף - + Schedule מערכת שעות - + Get Schedule && Exam קבל מערכת שעות && לוח מבחנים - + Show Exams הצג מבחנים - - &File - &קובץ + + + Team Credit + מי אנחנו - + + + Help + עזרה + + + + Language שפה - - - Credits - קרדיט - - - - Exit - יציאה - - - - Hebrew - עברית - - - - English - English - - - - OS Default - ברירת מחדל - - - - How To - עזרה - - - + + Error שגיאה @@ -235,8 +218,8 @@ Make Sure everything is correct and try again - - + + Not Connected לא מחובר @@ -246,29 +229,29 @@ Make Sure everything is correct and try again שגיאה בהכנסת נתונים - + License: רישיון: - + Powered By: powered by: מנוע: - + Developed By פותח ע"י - + Help Guide Guide תפריט עזרה - + Liran לירן בן גידה @@ -280,50 +263,47 @@ Click on 'Get GPA' לחץ על 'קבל מערכת שעות && לוח מבחנים' - + Sagi שגיא דיין - + <br><li>Login: <ul><li>Type your username and password and click Login.</li><li>Once you are connected, you will see a green ball in the right buttom panel.</li></ul></li> <br><li>התחברות: <ul><li>הזן את שם המשתמש והסיסמה ולחץ על התחבר</li><li>בגמר ההתחברות תראה בכדור ירוק בשורת המצב. המשמעות שהינך מחובר לאתר</li></ul></li> - + <br><li>Getting GPA sheet<ul><li>Click on GPA Tab</li><li> Select your dates and click on Add</li></ul></li> <br><li>קבלת גליון ציונים<ul><li>לחץ על לשונית הציונים</li><li>בחר את טווח התאריכים הרצויים ולחץ על הוספה</li></ul></li> - + <br><li>Average Changing<ul><li>Change one of your grade and see the average in the buttom panel changing.</li></ul></li> <br><li>שינוי ממוצע<ul><li>שנה את אחד הציונים שלך בקורס והממוצע ישתנה בהתאם.</li></ul></li> - + <br><li>Getting Calendar<ul><li>Click on Calendar Tab</li><li> Select your dates and click on Get Calendar</li></ul></li> <br><li>קבלת שעות מערכת<ul><li>לחץ על לשונית שעות מערכת</li><li>בחר את השנה והסמסטר ולחץ על הצג מערכת</li></ul></li> - + <br><li>For exporting your calendar to a .CSV file:<ul><li>Do previous step and continue to next step</li><li> Click on Export to CSV</li><li>Select your dates and click OK</li><li>Once you're Done, go on your calendar and import your csv file</li></li> <br><li>על מנת לייצא לקובץ CSV<ul><li>בצע את השלב הקודם ואז</li><li> לחץ על ייצוא לCSV</li><li>בחר את התאריכים המתאימים ולחץ אישור</li><li>לאחר השלמת הפעולה תוכל לייבא את המערכת שעות</li></li> - + <b>For more information, please visit us at: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> <b>לעוד מידע: <a href='http://liranbg.github.io/JceManager/'>Jce Manager site</a></b> - - + Settings הגדרות - - - + Your settings will take effect next time you start the program ההגדרות שלך ייכנסו לתוקפן בפעם הבאה שתפעיל את התוכנה @@ -469,134 +449,134 @@ If this message appear without reason, please contact me at liranbg@gmail.comשישי - + ConnectionRefusedError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + RemoteHostClosedError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + HostNotFoundError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SocketAccessError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SocketTimeoutError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + NetworkError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SslHandshakeFailedError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SslInternalError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SslInvalidUserDataError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + DatagramTooLargeError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + OperationError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + AddressInUseError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + SocketAddressNotAvailableError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + UnsupportedSocketOperationError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyAuthenticationRequiredError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyConnectionRefusedError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + UnfinishedSocketOperationError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyConnectionClosedError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyConnectionTimeoutError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyNotFoundError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + ProxyProtocolError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + TemporaryError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + UnknownSocketError הטעות הזאת הינה קריטית. אנא שלח אלינו (מייל בקובץ > אודות) את קובץ J_M_Log על מנת שנבין טוב יותר את הבעייה (קובץ זה איננו מכיל את סיסמתך) - + Unable to open or create the file. Exporting Failed לא ניתן ליצור את הקובץ. היצוא נכשל - + JceManager Save Schedule Dialog JceManager שמירת מערכת שעות - + CSV Files (*.csv);;All Files (*) CSV Files (*.csv);;All Files (*) @@ -610,37 +590,37 @@ Exporting Failed מבחנים - + <html><head/><body><p>Revert changes</p></body></html> <html><head/><body><p>בטל שינויים</p></body></html> - + Revert בטל שינויים - + <html><head/><body><p>Discard and hide</p></body></html> <html><head/><body><p>בטל שינויים וצא</p></body></html> - + Cancel ביטול - + <html><head/><body><p>Save and hide</p></body></html> <html><head/><body><p>שמור וצא</p></body></html> - + Ok אישור - + <html><head/><body><p align="center"><span style=" font-size:14pt;">Exams Schedule</span></p></body></html> <html><head/><body><p align="center"><span style=" font-size:14pt;">לוח בחינות</span></p></body></html> @@ -755,53 +735,53 @@ In Example: 08:25 or 12:05 jceStatusBar - - + + Ready מוכן - + Error שגיאה - + Disconnected מנותק - + Connecting... מתחבר... - + Sending... שולח... - + Recieving... מקבל... - + Connected מחובר - + Inserting מכניס נתונים - + Logged In. מחובר לאתר. - + Done בוצע From 6c2345ad46fa4ca1e8e1812415927e879334c79a Mon Sep 17 00:00:00 2001 From: Liran BN Date: Tue, 14 Oct 2014 18:01:45 +0300 Subject: [PATCH 53/58] unlock bug fix --- main/mainscreen.cpp | 2 ++ main/mainscreen.ui | 8 -------- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/main/mainscreen.cpp b/main/mainscreen.cpp index 884d9b5..0653feb 100644 --- a/main/mainscreen.cpp +++ b/main/mainscreen.cpp @@ -77,6 +77,8 @@ void MainScreen::on_loginButton_clicked() } else ui->labelPswInputStatus->setVisible(false); + + unlock(); return; } else diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 0971feb..5a84582 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -192,10 +192,6 @@ font-size: 15px; - - - - @@ -304,10 +300,6 @@ font-size: 15px; - - - - From dd237a80939a603c6dcb30723d6cead8adfdb47c Mon Sep 17 00:00:00 2001 From: Liran BN Date: Tue, 14 Oct 2014 18:10:11 +0300 Subject: [PATCH 54/58] version set to 1.1 --- jceGrade.pro | 2 +- main/mainscreen.ui | 220 ++++++++++++++++++++++----------------------- winConf.rc | 8 +- 3 files changed, 115 insertions(+), 115 deletions(-) diff --git a/jceGrade.pro b/jceGrade.pro index 3da80c6..6855b35 100644 --- a/jceGrade.pro +++ b/jceGrade.pro @@ -10,7 +10,7 @@ CONFIG += qt c++11 #CONFIG-=app_bundle TARGET = jceManager -VERSION = 1.0.0 +VERSION = 1.1.0 TEMPLATE = app DEFINES += APP_VERSION=\\\"$$VERSION\\\" diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 5a84582..3b941ca 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -192,114 +192,114 @@ font-size: 15px; - - - - - - - 20 - 20 - - - - - - - - - - - - 0 - 0 - - - - Qt::ImhHiddenText|Qt::ImhNoAutoUppercase|Qt::ImhNoPredictiveText|Qt::ImhSensitiveData - - - 20 - - - QLineEdit::Password - - - true - - - - - - - - 0 - 0 - - - - - 81 - 0 - - - - Username - - - Qt::RichText - - - - - - - - 0 - 0 - - - - Qt::ImhLatinOnly|Qt::ImhNoPredictiveText - - - 20 - - - true - - - - - - - - 0 - 0 - - - - - 81 - 0 - - - - Password - - - Qt::RichText - - - - - - - - - - - + + + + + + + 20 + 20 + + + + + + + + + + + + 0 + 0 + + + + Qt::ImhHiddenText|Qt::ImhNoAutoUppercase|Qt::ImhNoPredictiveText|Qt::ImhSensitiveData + + + 20 + + + QLineEdit::Password + + + true + + + + + + + + 0 + 0 + + + + + 81 + 0 + + + + Username + + + Qt::RichText + + + + + + + + 0 + 0 + + + + Qt::ImhLatinOnly|Qt::ImhNoPredictiveText + + + 20 + + + true + + + + + + + + 0 + 0 + + + + + 81 + 0 + + + + Password + + + Qt::RichText + + + + + + + + + + + @@ -840,9 +840,9 @@ font-size: 15px; - + - + diff --git a/winConf.rc b/winConf.rc index 9046098..16fcc0f 100644 --- a/winConf.rc +++ b/winConf.rc @@ -2,8 +2,8 @@ IDI_ICON1 ICON DISCARDABLE "./resources/icon.ico" #include VS_VERSION_INFO VERSIONINFO -FILEVERSION 1, 0, 0 -PRODUCTVERSION 1, 0, 0 +FILEVERSION 1, 1, 0 +PRODUCTVERSION 1, 1, 0 FILEFLAGSMASK 0x3fL FILEFLAGS 0 FILEOS VOS_NT_WINDOWS32 @@ -20,12 +20,12 @@ BEGIN BEGIN VALUE "CompanyName", "Jce Manager\0" VALUE "FileDescription", "\0" - VALUE "FileVersion", "1.0.0\0" + VALUE "FileVersion", "1.1.0\0" VALUE "InternalName", "jceManager\0" VALUE "LegalCopyright", "Jce Manager Team, liranbg@gmail.com\0" VALUE "OriginalFilename", "jceManager\0" VALUE "ProductName", "Jce Manager\0" - VALUE "ProductVersion", "1.0.0\0" + VALUE "ProductVersion", "1.1.0\0" END END END From 85e2ea645fc61a7503fec80fa866d8ab45ba5f8a Mon Sep 17 00:00:00 2001 From: Liran BN Date: Wed, 15 Oct 2014 11:55:12 +0300 Subject: [PATCH 55/58] headers fix --- main/CalendarTab/CalendarManager.h | 12 ++++++------ main/CourseTab/coursestablemanager.h | 6 +++--- main/LoginTab/loginhandler.h | 6 +++--- src/jceConnection/jcesslclient.h | 2 +- src/jceData/Grades/graph/gradegraph.h | 3 +-- src/jceData/Grades/graph/gradegraph.ui | 2 +- src/jceSettings/jceLoginHtmlScripts.h | 2 +- src/jceSettings/jcelogin.cpp | 14 +++++++------- src/jceSettings/jcelogin.h | 4 ++-- 9 files changed, 25 insertions(+), 26 deletions(-) diff --git a/main/CalendarTab/CalendarManager.h b/main/CalendarTab/CalendarManager.h index e45430c..f835f65 100644 --- a/main/CalendarTab/CalendarManager.h +++ b/main/CalendarTab/CalendarManager.h @@ -1,13 +1,13 @@ #ifndef CALENDARMANAGER_H #define CALENDARMANAGER_H -#include "./src/jceData/Calendar/coursesSchedule/calendarPage.h" -#include "./src/jceData/Calendar/coursesSchedule/calendarSchedule.h" -#include "./src/jceData/Calendar/coursesSchedule/calendarDialog.h" -#include "./src/jceData/CSV/csv_exporter.h" +#include "../../src/jceData/Calendar/coursesSchedule/calendarPage.h" +#include "../../src/jceData/Calendar/coursesSchedule/calendarSchedule.h" +#include "../../src/jceData/Calendar/coursesSchedule/calendarDialog.h" +#include "../../src/jceData/CSV/csv_exporter.h" -#include "./src/jceData/Calendar/Exams/calendarExam.h" -#include "./src/jceData/Calendar/Exams/examDialog.h" +#include "../../src/jceData/Calendar/Exams/calendarExam.h" +#include "../../src/jceData/Calendar/Exams/examDialog.h" #include #include diff --git a/main/CourseTab/coursestablemanager.h b/main/CourseTab/coursestablemanager.h index 41e8713..6600400 100644 --- a/main/CourseTab/coursestablemanager.h +++ b/main/CourseTab/coursestablemanager.h @@ -9,9 +9,9 @@ #include #include -#include "./src/jceData/Grades/graph/gradegraph.h" -#include "./src/jceData/Grades/gradePage.h" -#include "./src/jceSettings/user.h" +#include "../../src/jceData/Grades/graph/gradegraph.h" +#include "../../src/jceData/Grades/gradePage.h" +#include "../../src/jceSettings/user.h" class coursesTableManager { diff --git a/main/LoginTab/loginhandler.h b/main/LoginTab/loginhandler.h index 6b13fbf..fb8b77f 100644 --- a/main/LoginTab/loginhandler.h +++ b/main/LoginTab/loginhandler.h @@ -8,9 +8,9 @@ #include #include -#include "./src/jceSettings/jcelogin.h" -#include "./src/appDatabase/savedata.h" -#include "./main/jceWidgets/jcestatusbar.h" +#include "../../src/jceSettings/jcelogin.h" +#include "../../src/appDatabase/savedata.h" +#include "../../main/jceWidgets/jcestatusbar.h" class loginHandler : public QObject diff --git a/src/jceConnection/jcesslclient.h b/src/jceConnection/jcesslclient.h index 122481d..63362f4 100644 --- a/src/jceConnection/jcesslclient.h +++ b/src/jceConnection/jcesslclient.h @@ -11,7 +11,7 @@ #include #include -#include "./main/jceWidgets/jcestatusbar.h" +#include "../../main/jceWidgets/jcestatusbar.h" #define packetSize 4096 //4k #define milisTimeOut 5000 //4 seconds diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index b5324fe..f842805 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -1,8 +1,7 @@ #ifndef GRADEGRAPH_H #define GRADEGRAPH_H -#include "./src/jceData/Grades/gradePage.h" -#include "qcustomplot.h" +#include "../gradePage.h" #include namespace Ui { diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 5744652..12e8834 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -82,7 +82,7 @@ QCustomPlot QWidget -

                                          src/jceData/Grades/graph/qcustomplot.h
                                          +
                                          qcustomplot.h
                                          1 diff --git a/src/jceSettings/jceLoginHtmlScripts.h b/src/jceSettings/jceLoginHtmlScripts.h index 2eba6c3..b90bad4 100644 --- a/src/jceSettings/jceLoginHtmlScripts.h +++ b/src/jceSettings/jceLoginHtmlScripts.h @@ -1,7 +1,7 @@ #ifndef JCELOGINHTMLSCRIPTS_H #define JCELOGINHTMLSCRIPTS_H -#include "./src/jceSettings/user.h" +#include "../../src/jceSettings/user.h" #define dst_host "yedion.jce.ac.il" #define dst_port 443 diff --git a/src/jceSettings/jcelogin.cpp b/src/jceSettings/jcelogin.cpp index 7819b46..59118d1 100644 --- a/src/jceSettings/jcelogin.cpp +++ b/src/jceSettings/jcelogin.cpp @@ -38,7 +38,7 @@ int jceLogin::makeConnection() returnMode = checkConnection(); //checking socket status. is connected? - if (returnMode == false) + if (returnMode == (int)false) { statusBar->setIconConnectionStatus(jceStatusBar::Connecting); if (JceConnector->makeConnect(dst_host,dst_port) == false) //couldnt make a connection @@ -47,19 +47,19 @@ int jceLogin::makeConnection() returnMode = true; } - if (returnMode == true) //connected to host + if (returnMode == (int)true) //connected to host { statusBar->setIconConnectionStatus(jceStatusBar::Connected); returnMode = makeFirstVisit(); - if (returnMode == true) //requst and send first validation + if (returnMode == (int)true) //requst and send first validation { status = jceStatus::JCE_START_VALIDATING_PROGRESS; returnMode = checkValidation(); - if (returnMode == true) //check if username and password are matching + if (returnMode == (int)true) //check if username and password are matching { status = jceStatus::JCE_VALIDATION_PASSED; returnMode = makeSecondVisit(); - if (returnMode == true) //siging in the website + if (returnMode == (int)true) //siging in the website { qDebug() << Q_FUNC_INFO << "Signed in succeesfully"; status = jceStatus::JCE_YOU_ARE_IN; @@ -317,11 +317,11 @@ void jceLogin::reValidation() { qDebug() << Q_FUNC_INFO << "Revalidating user"; - if (makeFirstVisit() == true) + if (makeFirstVisit() == (int)true) { if (checkValidation()) { - if (makeSecondVisit() == true) + if (makeSecondVisit() == (int)true) { statusBar->setIconConnectionStatus(jceStatusBar::LoggedIn); qDebug() << Q_FUNC_INFO << "Validated"; diff --git a/src/jceSettings/jcelogin.h b/src/jceSettings/jcelogin.h index a0443d6..1e0a2ff 100644 --- a/src/jceSettings/jcelogin.h +++ b/src/jceSettings/jcelogin.h @@ -2,8 +2,8 @@ #define JCELOGIN_H -#include "./src/jceConnection/jcesslclient.h" -#include "./src/jceSettings/user.h" +#include "../../src/jceConnection/jcesslclient.h" +#include "../../src/jceSettings/user.h" #include "jceLoginHtmlScripts.h" From 68030355c82bdb1231456dbf60dea615722d414b Mon Sep 17 00:00:00 2001 From: Liran BN Date: Wed, 15 Oct 2014 12:26:30 +0300 Subject: [PATCH 56/58] sagi ha manyak --- src/jceData/Grades/graph/gradegraph.cpp | 83 +++++++++++++------------ src/jceData/Grades/graph/gradegraph.h | 2 + src/jceData/Grades/graph/gradegraph.ui | 39 +++++------- 3 files changed, 61 insertions(+), 63 deletions(-) diff --git a/src/jceData/Grades/graph/gradegraph.cpp b/src/jceData/Grades/graph/gradegraph.cpp index a1ad338..327bc30 100644 --- a/src/jceData/Grades/graph/gradegraph.cpp +++ b/src/jceData/Grades/graph/gradegraph.cpp @@ -5,6 +5,8 @@ gradegraph::gradegraph(QWidget *parent) : QDialog(parent), ui(new Ui::gradegraph ui->setupUi(this); this->setModal(true); //makes it on top of application this->gp = NULL; + tableWidget = new QCustomPlot(this); + ui->verticalLayoutTable->addWidget(tableWidget); } @@ -13,13 +15,14 @@ void gradegraph::showGraph(GradePage *gpPTR) qDebug() << Q_FUNC_INFO; this->gp = gpPTR; - if (ui->graphwidget->graphCount() > 0) + if (tableWidget->graphCount() > 0) clearGraph(); setVisualization(); setGraphsData(); - ui->graphwidget->replot(); + + tableWidget->replot(); this->show(); } @@ -42,8 +45,8 @@ void gradegraph::setGraphsData() indicatorX[i] = i; if (i%4==1) //years { - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); + QCPItemText *textLabel = new QCPItemText(tableWidget); + tableWidget->addItem(textLabel); double lastAvg = gp->getAvg(minYearInList+yearCount); @@ -72,8 +75,8 @@ void gradegraph::setGraphsData() { if (i+4 < xRangeForYear) //semesters { - QCPItemText *textLabel = new QCPItemText(ui->graphwidget); - ui->graphwidget->addItem(textLabel); + QCPItemText *textLabel = new QCPItemText(tableWidget); + tableWidget->addItem(textLabel); //qDebug() << "year: " << minYearInList+yearCount << "sem " << (i-1)%4; double avg = gp->getAvg(minYearInList+yearCount,(i-1)%4); @@ -105,9 +108,9 @@ void gradegraph::setGraphsData() } } //yearly - ui->graphwidget->graph(0)->setData(indicatorX,yearlyAvg); + tableWidget->graph(0)->setData(indicatorX,yearlyAvg); //yearly - ui->graphwidget->graph(1)->setData(indicatorX,SemesterialAvg); + tableWidget->graph(1)->setData(indicatorX,SemesterialAvg); } /** @@ -115,21 +118,21 @@ void gradegraph::setGraphsData() */ void gradegraph::setVisualization() { - ui->graphwidget->setBackground(QBrush(Qt::white)); - ui->graphwidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box + tableWidget->setBackground(QBrush(Qt::white)); + tableWidget->axisRect()->setupFullAxesBox(true); //make the graph looks like a box - ui->graphwidget->addGraph(); //yearly and semesterial graphs - ui->graphwidget->addGraph(); + tableWidget->addGraph(); //yearly and semesterial graphs + tableWidget->addGraph(); - ui->graphwidget->graph(0)->setName(tr("Yearly Average")); - ui->graphwidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); - ui->graphwidget->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::blue, 7)); - ui->graphwidget->graph(0)->setLineStyle(QCPGraph::lsImpulse ); + tableWidget->graph(0)->setName(tr("Yearly Average")); + tableWidget->graph(0)->setPen(QPen(Qt::GlobalColor::blue)); + tableWidget->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::blue, 7)); + tableWidget->graph(0)->setLineStyle(QCPGraph::lsImpulse ); - ui->graphwidget->graph(1)->setName(tr("Semesterial Average")); - ui->graphwidget->graph(1)->setLineStyle(QCPGraph::lsStepLeft); - ui->graphwidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); - ui->graphwidget->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::red, 7)); + tableWidget->graph(1)->setName(tr("Semesterial Average")); + tableWidget->graph(1)->setLineStyle(QCPGraph::lsStepLeft); + tableWidget->graph(1)->setPen(QPen( QColor(Qt::GlobalColor::red))); + tableWidget->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::red, 7)); int minYearInList = gp->getMinYearInList()-1; int maxYearInList = gp->getMaxYearInList()+1; @@ -163,33 +166,33 @@ void gradegraph::setVisualization() } } - ui->graphwidget->yAxis->setLabel(tr("AVG Grade")); - ui->graphwidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); - ui->graphwidget->yAxis->setRange(MIN_GRADE,MAX_GRADE); - ui->graphwidget->yAxis->setTickStep(2); - ui->graphwidget->yAxis->setAutoSubTicks(false); - ui->graphwidget->yAxis->setAutoTickStep(false); - ui->graphwidget->yAxis->setSubTickCount(5); + tableWidget->yAxis->setLabel(tr("AVG Grade")); + tableWidget->yAxis->setTickLabelFont(QFont(QFont().family(), 8)); + tableWidget->yAxis->setRange(MIN_GRADE,MAX_GRADE); + tableWidget->yAxis->setTickStep(2); + tableWidget->yAxis->setAutoSubTicks(false); + tableWidget->yAxis->setAutoTickStep(false); + tableWidget->yAxis->setSubTickCount(5); - ui->graphwidget->xAxis->setLabel(tr("Years")); - ui->graphwidget->xAxis->setAutoTickLabels(false); - ui->graphwidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); - ui->graphwidget->xAxis->setAutoTickStep(false); - ui->graphwidget->xAxis->setTickStep(1); - ui->graphwidget->xAxis->setAutoSubTicks(false); - ui->graphwidget->xAxis->setSubTickCount(0); - ui->graphwidget->xAxis->setTickVectorLabels(xStrings); - ui->graphwidget->xAxis->setRange(1,xRangeForYear); + tableWidget->xAxis->setLabel(tr("Years")); + tableWidget->xAxis->setAutoTickLabels(false); + tableWidget->xAxis->setTickLabelFont(QFont(QFont().family(), 7)); + tableWidget->xAxis->setAutoTickStep(false); + tableWidget->xAxis->setTickStep(1); + tableWidget->xAxis->setAutoSubTicks(false); + tableWidget->xAxis->setSubTickCount(0); + tableWidget->xAxis->setTickVectorLabels(xStrings); + tableWidget->xAxis->setRange(1,xRangeForYear); - ui->graphwidget->legend->setVisible(true); //show graph name on top right + tableWidget->legend->setVisible(true); //show graph name on top right } void gradegraph::clearGraph() { int itemDeleted,graphs,plots; - itemDeleted = ui->graphwidget->clearItems(); - graphs = ui->graphwidget->clearGraphs(); - plots = ui->graphwidget->clearPlottables(); + itemDeleted = tableWidget->clearItems(); + graphs = tableWidget->clearGraphs(); + plots = tableWidget->clearPlottables(); qDebug() << Q_FUNC_INFO << "items:" << itemDeleted << "graphs" << graphs << "plots:" << plots; } void gradegraph::on_pushButton_clicked() diff --git a/src/jceData/Grades/graph/gradegraph.h b/src/jceData/Grades/graph/gradegraph.h index f842805..055a195 100644 --- a/src/jceData/Grades/graph/gradegraph.h +++ b/src/jceData/Grades/graph/gradegraph.h @@ -2,6 +2,7 @@ #define GRADEGRAPH_H #include "../gradePage.h" +#include "qcustomplot.h" #include namespace Ui { @@ -27,6 +28,7 @@ private: GradePage *gp; + QCustomPlot *tableWidget; void setVisualization(); void setGraphsData(); void clearGraph(); diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 12e8834..171f6fd 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -17,8 +17,8 @@ :/icons/icon.ico:/icons/icon.ico - - + + @@ -37,29 +37,30 @@ - - + + - - - - 0 - 0 - - - - + - + + + 0 + + + QLayout::SetMinimumSize + Qt::Horizontal + + QSizePolicy::MinimumExpanding + - 88 + 90 20 @@ -78,14 +79,6 @@ - - - QCustomPlot - QWidget -
                                          qcustomplot.h
                                          - 1 -
                                          -
                                          From 27764123cc5cde10a1697e204600ad8ad726dc0d Mon Sep 17 00:00:00 2001 From: liranbg Date: Thu, 16 Oct 2014 10:03:24 +0300 Subject: [PATCH 57/58] added ui tooltips added tooltips to each ui to describe its ui action --- main/mainscreen.ui | 44 +++++++++++++++++-- src/jceData/Calendar/Exams/examDialog.ui | 13 +++--- .../coursesSchedule/calendarDialog.ui | 3 ++ src/jceData/Grades/graph/gradegraph.ui | 3 ++ 4 files changed, 54 insertions(+), 9 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 3b941ca..325088c 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -64,7 +64,7 @@ background: qlineargradient(spread:pad, x1:0.496, y1:0, x2:0.508, y2:1, stop:0 r QTabWidget::Rounded - 0 + 1 false @@ -391,6 +391,9 @@ font-size: 15px;
                                          + + ending semester + 1 @@ -420,6 +423,9 @@ font-size: 15px; + + ending year + 2008 @@ -521,7 +527,7 @@ font-size: 15px; - <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> + clear table Clear Table @@ -539,8 +545,11 @@ font-size: 15px; 0 + + get GPA + - <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> + Get GPA @@ -558,6 +567,9 @@ font-size: 15px; + + revert any changes + Revert Changes @@ -599,6 +611,9 @@ font-size: 15px; 0 + + show only course's grade point greater than zero + Only Main Courses @@ -686,6 +701,9 @@ font-size: 15px; + + starting year + 2008 @@ -715,6 +733,9 @@ font-size: 15px; + + starting semester + 1 @@ -871,6 +892,9 @@ font-size: 15px; + + show studential schedule and exam list + Get Schedule && Exam @@ -878,6 +902,9 @@ font-size: 15px; + + show exam dialog + Show Exams @@ -885,6 +912,9 @@ font-size: 15px; + + show exportion dialog + Export to CSV @@ -915,8 +945,14 @@ font-size: 15px; + + http://liranbg.github.io/JceManager + + + + - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></ps true diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index aa07e3d..bebd0f9 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -6,8 +6,8 @@ 0 0 - 810 - 306 + 811 + 327 @@ -68,7 +68,10 @@ - <html><head/><body><p>Revert changes</p></body></html> + revert any changes + + + Revert @@ -78,7 +81,7 @@ - <html><head/><body><p>Discard and hide</p></body></html> + discard and close Cancel @@ -88,7 +91,7 @@ - <html><head/><body><p>Save and hide</p></body></html> + save and close Ok diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui index 8ca5dda..63c9281 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui @@ -185,6 +185,9 @@ + + integrate exam schedule + Include Exams diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 171f6fd..5b9ad37 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -68,6 +68,9 @@ + + + Close From 938610fc7f020ea7cbab3f0357107c46c5a3af9c Mon Sep 17 00:00:00 2001 From: liranbg Date: Thu, 16 Oct 2014 10:38:35 +0300 Subject: [PATCH 58/58] Revert to "added ui tooltips" This reverts commit 27764123cc5cde10a1697e204600ad8ad726dc0d. --- main/mainscreen.ui | 42 ++----------------- src/jceData/Calendar/Exams/examDialog.ui | 13 +++--- .../coursesSchedule/calendarDialog.ui | 3 -- src/jceData/Grades/graph/gradegraph.ui | 3 -- 4 files changed, 8 insertions(+), 53 deletions(-) diff --git a/main/mainscreen.ui b/main/mainscreen.ui index 7327af1..3b941ca 100644 --- a/main/mainscreen.ui +++ b/main/mainscreen.ui @@ -391,9 +391,6 @@ font-size: 15px; - - ending semester - 1 @@ -423,9 +420,6 @@ font-size: 15px; - - ending year - 2008 @@ -527,7 +521,7 @@ font-size: 15px; - clear table + <html><head/><body><p><span style=" font-weight:600;">Clear table</span></p></body></html> Clear Table @@ -545,11 +539,8 @@ font-size: 15px; 0 - - get GPA - - + <html><head/><body><p><span style=" font-weight:600;">Get your grades</span></p></body></html> Get GPA @@ -567,9 +558,6 @@ font-size: 15px; - - revert any changes - Revert Changes @@ -611,9 +599,6 @@ font-size: 15px; 0 - - show only course's grade point greater than zero - Only Main Courses @@ -701,9 +686,6 @@ font-size: 15px; - - starting year - 2008 @@ -733,9 +715,6 @@ font-size: 15px; - - starting semester - 1 @@ -892,9 +871,6 @@ font-size: 15px; - - show studential schedule and exam list - Get Schedule && Exam @@ -902,9 +878,6 @@ font-size: 15px; - - show exam dialog - Show Exams @@ -912,9 +885,6 @@ font-size: 15px; - - show exportion dialog - Export to CSV @@ -945,14 +915,8 @@ font-size: 15px; - - http://liranbg.github.io/JceManager - - - - - <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></ps + <p align="center">Made By <a href="http://liranbg.github.io/JceManager/"><span style=" text-decoration: underline; color:#0000ff;">JceManager</span></a></p> true diff --git a/src/jceData/Calendar/Exams/examDialog.ui b/src/jceData/Calendar/Exams/examDialog.ui index bebd0f9..aa07e3d 100644 --- a/src/jceData/Calendar/Exams/examDialog.ui +++ b/src/jceData/Calendar/Exams/examDialog.ui @@ -6,8 +6,8 @@ 0 0 - 811 - 327 + 810 + 306 @@ -68,10 +68,7 @@ - revert any changes - - - + <html><head/><body><p>Revert changes</p></body></html> Revert @@ -81,7 +78,7 @@ - discard and close + <html><head/><body><p>Discard and hide</p></body></html> Cancel @@ -91,7 +88,7 @@ - save and close + <html><head/><body><p>Save and hide</p></body></html> Ok diff --git a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui index 63c9281..8ca5dda 100644 --- a/src/jceData/Calendar/coursesSchedule/calendarDialog.ui +++ b/src/jceData/Calendar/coursesSchedule/calendarDialog.ui @@ -185,9 +185,6 @@ - - integrate exam schedule - Include Exams diff --git a/src/jceData/Grades/graph/gradegraph.ui b/src/jceData/Grades/graph/gradegraph.ui index 5b9ad37..171f6fd 100644 --- a/src/jceData/Grades/graph/gradegraph.ui +++ b/src/jceData/Grades/graph/gradegraph.ui @@ -68,9 +68,6 @@ - - - Close