From 4482b6517fb850c3b840ef7da23f6c0bc0c51045 Mon Sep 17 00:00:00 2001 From: Tino Pyssysalo Date: Mon, 28 Jan 2019 09:49:41 +0200 Subject: [PATCH] Code guideline changes. Fix to maxOS download window crash. --- lib/tmcclient/course.cpp | 48 +++++------ lib/tmcclient/course.h | 20 ++--- lib/tmcclient/exercise.cpp | 50 +++++------ lib/tmcclient/exercise.h | 15 ++-- lib/tmcclient/organization.cpp | 18 ++-- lib/tmcclient/organization.h | 10 +-- lib/tmcclient/submission.cpp | 2 +- lib/tmcclient/testcase.cpp | 17 ++-- lib/tmcclient/testcase.h | 4 +- lib/tmcclient/tmcclient.cpp | 150 ++++++++++++++++----------------- lib/tmcclient/tmcclient.h | 50 +++++------ src/downloadpanel.cpp | 115 ++++++++++++------------- src/downloadpanel.h | 12 +-- src/exercisedelegate.cpp | 48 +++++------ src/exercisemodel.cpp | 51 +++++------ src/exercisemodel.h | 6 +- src/exercisewidget.cpp | 6 +- src/exercisewidget.h | 4 +- src/loginwidget.cpp | 8 +- src/loginwidget.h | 4 +- src/settingswidget.cpp | 61 ++++++-------- src/settingswidget.h | 10 +-- src/submitwidget.cpp | 11 +-- src/submitwidget.h | 4 +- src/testmycode.cpp | 19 +++-- src/testmycode.h | 14 ++- src/tmcmanager.cpp | 28 +++--- src/tmcmanager.h | 9 +- src/tmcoutputpane.cpp | 2 +- src/tmcoutputpane.h | 6 +- src/tmcresultmodel.cpp | 6 +- src/tmcresultreader.cpp | 16 ++-- src/tmcresultreader.h | 4 +- src/tmctestresult.cpp | 2 +- src/ui/exercisewidget.ui | 6 +- src/ziphelper.cpp | 2 +- test/testmycode_tests.cpp | 2 +- 37 files changed, 416 insertions(+), 424 deletions(-) diff --git a/lib/tmcclient/course.cpp b/lib/tmcclient/course.cpp index ce267da..bb9df1b 100644 --- a/lib/tmcclient/course.cpp +++ b/lib/tmcclient/course.cpp @@ -78,7 +78,7 @@ void Course::setId(int id) /*! Sets the course name to \a name. */ -void Course::setName(QString name) +void Course::setName(const QString &name) { m_name = name; } @@ -88,7 +88,7 @@ QString Course::getTitle() const return m_title; } -void Course::setTitle(QString title) +void Course::setTitle(const QString &title) { m_title = title; } @@ -125,7 +125,7 @@ Exercise Course::getExercise(const int id) If no such \l Exercise object is found in the \l Course object's collection, the function returns a new \l Exercise object instantiated by \l Exercise::Exercise(). */ -Exercise Course::getExercise(const Exercise ex) +Exercise Course::getExercise(const Exercise &ex) { return m_exercises.value(ex.getId(), Exercise()); } @@ -133,7 +133,7 @@ Exercise Course::getExercise(const Exercise ex) /*! Adds parameter \a ex to the \l Course object's \l Exercise collection. */ -void Course::addExercise(const Exercise ex) +void Course::addExercise(const Exercise &ex) { m_exercises.insert(ex.getId(), ex); } @@ -142,7 +142,7 @@ void Course::addExercise(const Exercise ex) Returns \c true if the \l Course object's collection contains an \l Exercise object with the same ID as that of parameter \a ex; otherwise returns \c false. */ -bool Course::hasExercise(Exercise ex) +bool Course::hasExercise(const Exercise &ex) { return m_exercises.contains(ex.getId()); } @@ -153,7 +153,7 @@ bool Course::hasExercise(Exercise ex) The ID and name fields of the \l Course object are set to the values extracted from \a jsonCourse. */ -Course Course::fromJson(const QJsonObject jsonCourse) +Course Course::fromJson(const QJsonObject &jsonCourse) { Course course; course.setTitle(jsonCourse["title"].toString()); @@ -168,12 +168,12 @@ Course Course::fromJson(const QJsonObject jsonCourse) object includes setting the course name and ID to the values specified in \a settings. If \a settings doesn't contain the appropriate values, defaults are used. */ -Course Course::fromQSettings(QSettings *settings) +Course Course::fromQSettings(QSettings &settings) { Course course; - course.setName(settings->value("courseName", "").toString()); - course.setTitle(settings->value("courseTitle", "").toString()); - course.setId(settings->value("courseId", -1).toInt()); + course.setName(settings.value("courseName", "").toString()); + course.setTitle(settings.value("courseTitle", "").toString()); + course.setId(settings.value("courseId", -1).toInt()); return course; } @@ -182,11 +182,11 @@ Course Course::fromQSettings(QSettings *settings) the \l Course parameter \a c into the \l {http://doc.qt.io/qt-5/qsettings.html} {QSettings} object pointed to by parameter \a settings. */ -void Course::toQSettings(QSettings *settings, Course c) +void Course::toQSettings(QSettings &settings, const Course &c) { - settings->setValue("courseName", c.getName()); - settings->setValue("courseTitle", c.getTitle()); - settings->setValue("courseId", c.getId()); + settings.setValue("courseName", c.getName()); + settings.setValue("courseTitle", c.getTitle()); + settings.setValue("courseId", c.getId()); } /*! @@ -197,19 +197,19 @@ void Course::toQSettings(QSettings *settings, Course c) list, they are preserved. Any new exercises from \a settings are added to the existing ones. */ -void Course::exerciseListFromQSettings(QSettings *settings) -{ - settings->beginGroup(m_name); - QStringList exerciseList = settings->childGroups(); - foreach (QString exercise, exerciseList) { - settings->beginGroup(exercise); - if (!QDir(settings->value("location", "?").toString()).exists() ) { - settings->endGroup(); +void Course::exerciseListFromQSettings(QSettings &settings) +{ + settings.beginGroup(m_name); + QStringList exerciseList = settings.childGroups(); + for (const QString &exercise : exerciseList) { + settings.beginGroup(exercise); + if (!QDir(settings.value("location", "?").toString()).exists() ) { + settings.endGroup(); continue; } Exercise ex = Exercise::fromQSettings(settings, exercise); - settings->endGroup(); + settings.endGroup(); addExercise(ex); } - settings->endGroup(); + settings.endGroup(); } diff --git a/lib/tmcclient/course.h b/lib/tmcclient/course.h index 45e1cbe..945eed9 100644 --- a/lib/tmcclient/course.h +++ b/lib/tmcclient/course.h @@ -14,22 +14,22 @@ class Course bool operator!=(const Course &other) const; bool operator!() const; explicit operator bool() const; - void setId(int id); - void setName(QString name); + void setName(const QString &name); int getId() const; QString getName() const; QString getTitle() const; - void setTitle(QString title); + void setTitle(const QString &title); Exercise getExercise(const int id); - Exercise getExercise(const Exercise ex); - void addExercise(const Exercise ex); + Exercise getExercise(const Exercise &ex); + void addExercise(const Exercise &ex); QMap getExercises(); - bool hasExercise(Exercise ex); - static Course fromJson(const QJsonObject jsonCourse); - static Course fromQSettings(QSettings *settings); - static void toQSettings(QSettings *settings, Course c); - void exerciseListFromQSettings(QSettings *settings); + bool hasExercise(const Exercise &ex); + static Course fromJson(const QJsonObject &jsonCourse); + static Course fromQSettings(QSettings &settings); + static void toQSettings(QSettings &settings, const Course &c); + void exerciseListFromQSettings(QSettings &settings); + private: int m_id; QString m_name; diff --git a/lib/tmcclient/exercise.cpp b/lib/tmcclient/exercise.cpp index f2a6deb..0e4b6f2 100644 --- a/lib/tmcclient/exercise.cpp +++ b/lib/tmcclient/exercise.cpp @@ -22,7 +22,7 @@ Exercise::Exercise() m_unzipped = false; } -Exercise::Exercise(int id, QString name) +Exercise::Exercise(int id, const QString &name) { m_id = id; m_name = name; @@ -179,7 +179,7 @@ void Exercise::setId(int id) /*! Sets the exercise name to \a name. */ -void Exercise::setName(QString name) +void Exercise::setName(const QString &name) { m_name = name; } @@ -187,7 +187,7 @@ void Exercise::setName(QString name) /*! Sets the directory location of the exercise to \a location. */ -void Exercise::setLocation(QString location) +void Exercise::setLocation(const QString &location) { m_location = location; } @@ -196,7 +196,7 @@ void Exercise::setLocation(QString location) Sets the TMC exercise checksum field of the \l Exercise object to \a checksum. */ -void Exercise::setChecksum(QString checksum) +void Exercise::setChecksum(const QString &checksum) { m_checksum = checksum; } @@ -246,19 +246,19 @@ void Exercise::setUnzipped(bool zipped) is used as a prefix in forming the key names with \l {http://doc.qt.io/qt-5/qsettings.html#beginGroup} {QSettings::beginGroup()}. */ -void Exercise::saveQSettings(QSettings *settings, const QString courseName) +void Exercise::saveQSettings(QSettings &settings, const QString &courseName) { - settings->beginGroup(courseName); - settings->beginGroup(m_name); - settings->setValue("id", m_id); - settings->setValue("checksum", m_checksum); - settings->setValue("location", m_location); - settings->setValue("deadline", m_deadline); - settings->setValue("state", m_state); - settings->setValue("downloaded", m_downloaded); - settings->setValue("unzipped", m_unzipped); - settings->endGroup(); - settings->endGroup(); + settings.beginGroup(courseName); + settings.beginGroup(m_name); + settings.setValue("id", m_id); + settings.setValue("checksum", m_checksum); + settings.setValue("location", m_location); + settings.setValue("deadline", m_deadline); + settings.setValue("state", m_state); + settings.setValue("downloaded", m_downloaded); + settings.setValue("unzipped", m_unzipped); + settings.endGroup(); + settings.endGroup(); } /*! @@ -271,15 +271,15 @@ void Exercise::saveQSettings(QSettings *settings, const QString courseName) parameter in the calling function using \l {http://doc.qt.io/qt-5/qsettings.html#beginGroup} {QSettings::beginGroup()}. */ -Exercise Exercise::fromQSettings(QSettings *settings, QString exerciseName) +Exercise Exercise::fromQSettings(QSettings &settings, const QString &exerciseName) { - Exercise ex = Exercise(settings->value("id").toInt(), exerciseName); - ex.setChecksum(settings->value("checksum").toString()); - ex.setLocation(settings->value("location").toString()); - ex.setDeadline(settings->value("deadline").toString()); - ex.setState(State(settings->value("state", 0).toInt())); - ex.setDownloaded(settings->value("downloaded", false).toBool()); - ex.setUnzipped(settings->value("unzipped", false).toBool()); + Exercise ex = Exercise(settings.value("id").toInt(), exerciseName); + ex.setChecksum(settings.value("checksum").toString()); + ex.setLocation(settings.value("location").toString()); + ex.setDeadline(settings.value("deadline").toString()); + ex.setState(State(settings.value("state", 0).toInt())); + ex.setDownloaded(settings.value("downloaded", false).toBool()); + ex.setUnzipped(settings.value("unzipped", false).toBool()); return ex; } @@ -291,7 +291,7 @@ Exercise Exercise::fromQSettings(QSettings *settings, QString exerciseName) and \l {Exercise::getDlDate()} {deadline} fields to the values extracted from \a jsonExercise. */ -Exercise Exercise::fromJson(const QJsonObject jsonExercise) +Exercise Exercise::fromJson(const QJsonObject &jsonExercise) { Exercise fromJson = Exercise(jsonExercise["id"].toInt(), jsonExercise["name"].toString()); diff --git a/lib/tmcclient/exercise.h b/lib/tmcclient/exercise.h index f210102..baf2420 100644 --- a/lib/tmcclient/exercise.h +++ b/lib/tmcclient/exercise.h @@ -11,7 +11,7 @@ class Exercise { public: Exercise(); - Exercise(int id, QString name); + Exercise(int id,const QString &name); enum State { None, @@ -25,9 +25,9 @@ class Exercise bool operator<(const Exercise &other) const; void setId(int id); - void setName(QString name); - void setLocation(QString location); - void setChecksum(QString checksum); + void setName(const QString &name); + void setLocation(const QString &location); + void setChecksum(const QString &checksum); void setDeadline(const QString &date); void setState(State state); void setDownloaded(bool downloaded); @@ -45,13 +45,12 @@ class Exercise bool isUnzipped() const; QMap getSubmissions() const; - void saveQSettings(QSettings *settings, const QString courseName); - static Exercise fromQSettings(QSettings *settings, QString exerciseName); - static Exercise fromJson(const QJsonObject jsonExercise); + void saveQSettings(QSettings &settings, const QString &courseName); + static Exercise fromQSettings(QSettings &settings, const QString &exerciseName); + static Exercise fromJson(const QJsonObject &jsonExercise); private: QMap m_submissions; - QString m_name; QString m_location; QString m_checksum; diff --git a/lib/tmcclient/organization.cpp b/lib/tmcclient/organization.cpp index 72878f2..af9727e 100644 --- a/lib/tmcclient/organization.cpp +++ b/lib/tmcclient/organization.cpp @@ -23,7 +23,7 @@ Organization::Organization() m_slug = ""; } -Organization::Organization(QString name, QString slug) : +Organization::Organization(const QString &name, const QString &slug) : m_name(name), m_slug(slug) { @@ -79,7 +79,7 @@ QString Organization::getSlug() const /*! Adds the \l Course parameter \a c to the collection of the organization's courses. */ -void Organization::addCourse(Course c) +void Organization::addCourse(const Course &c) { m_courses.append(c); } @@ -100,10 +100,10 @@ QList Organization::getCourses() The main purpose of the function is to preserve the user-selected organization between sessions. */ -Organization Organization::fromQSettings(QSettings *settings) +Organization Organization::fromQSettings(QSettings &settings) { - return Organization(settings->value("orgName", "").toString(), - settings->value("orgSlug", "").toString()); + return Organization(settings.value("orgName", "").toString(), + settings.value("orgSlug", "").toString()); } /*! @@ -112,10 +112,10 @@ Organization Organization::fromQSettings(QSettings *settings) \a org in the \l {http://doc.qt.io/qt-5/qsettings.html} {QSettings} parameter \a settings. */ -void Organization::toQSettings(QSettings *settings, Organization org) +void Organization::toQSettings(QSettings &settings, const Organization &org) { - settings->setValue("orgName", org.getName()); - settings->setValue("orgSlug", org.getSlug()); + settings.setValue("orgName", org.getName()); + settings.setValue("orgSlug", org.getSlug()); } /*! @@ -125,7 +125,7 @@ void Organization::toQSettings(QSettings *settings, Organization org) fields of the \l Organization object are set to the values extracted from \a jsonOrg. */ -Organization Organization::fromJson(const QJsonObject jsonOrg) +Organization Organization::fromJson(const QJsonObject &jsonOrg) { Organization fromJson = Organization( jsonOrg["name"].toString(), diff --git a/lib/tmcclient/organization.h b/lib/tmcclient/organization.h index f490da1..7be90a9 100644 --- a/lib/tmcclient/organization.h +++ b/lib/tmcclient/organization.h @@ -11,19 +11,19 @@ class Organization { public: Organization(); - Organization(QString name, QString slug); + Organization(const QString &name, const QString &slug); bool operator==(const Organization &other) const; bool operator!=(const Organization &other) const; bool operator!() const; QString getName() const; QString getSlug() const; - void addCourse(Course c); + void addCourse(const Course &c); QList getCourses(); - static Organization fromQSettings(QSettings *settings); - static Organization fromJson(const QJsonObject jsonOrg); - static void toQSettings(QSettings *settings, Organization org); + static Organization fromQSettings(QSettings &settings); + static Organization fromJson(const QJsonObject &jsonOrg); + static void toQSettings(QSettings &settings, const Organization &org); private: QString m_name; diff --git a/lib/tmcclient/submission.cpp b/lib/tmcclient/submission.cpp index 70b2317..86cac9d 100644 --- a/lib/tmcclient/submission.cpp +++ b/lib/tmcclient/submission.cpp @@ -100,7 +100,7 @@ Submission Submission::fromJson(const int id, const QJsonObject jsonSubmission) submission.setStatus(Status::Fail); QList testCases; QJsonArray jsonCases = jsonSubmission["test_cases"].toArray(); - foreach (QJsonValue jsonCase, jsonCases) { + for (QJsonValue jsonCase : jsonCases) { testCases << TestCase::fromJson(jsonCase.toObject()); } submission.setTestCases(testCases); diff --git a/lib/tmcclient/testcase.cpp b/lib/tmcclient/testcase.cpp index 96dfb05..d8b62e7 100644 --- a/lib/tmcclient/testcase.cpp +++ b/lib/tmcclient/testcase.cpp @@ -1,19 +1,18 @@ #include "testcase.h" -TestCase::TestCase(QString d_msg, QString ex, QString msg, QString name, bool pass) : - detailed_message(d_msg), - exception(ex), - message(msg), - name(name), - successful(pass) +TestCase::TestCase(const QString &d_msg, const QString &ex, const QString &msg, const QString &name, bool pass) + : detailed_message(d_msg) + , exception(ex) + , message(msg) + , name(name) + , successful(pass) { - } -TestCase TestCase::fromJson(const QJsonObject jsonCase) +TestCase TestCase::fromJson(const QJsonObject &jsonCase) { return TestCase( - jsonCase["detailed_message"].toString(), + jsonCase["detailed_message"].toString(), jsonCase["exception"].toString(), jsonCase["message"].toString(), jsonCase["name"].toString(), diff --git a/lib/tmcclient/testcase.h b/lib/tmcclient/testcase.h index 8a757b6..456c279 100644 --- a/lib/tmcclient/testcase.h +++ b/lib/tmcclient/testcase.h @@ -7,7 +7,7 @@ class TestCase { public: - TestCase(QString d_msg, QString ex, QString msg, QString name, bool pass); + TestCase(const QString &d_msg, const QString &ex, const QString &msg, const QString &name, bool pass); public: QString detailed_message; @@ -16,7 +16,7 @@ class TestCase QString name; bool successful; - static TestCase fromJson(const QJsonObject jsonCase); + static TestCase fromJson(const QJsonObject &jsonCase); }; #endif // TESTCASE_H diff --git a/lib/tmcclient/tmcclient.cpp b/lib/tmcclient/tmcclient.cpp index 855559d..430ed51 100644 --- a/lib/tmcclient/tmcclient.cpp +++ b/lib/tmcclient/tmcclient.cpp @@ -118,34 +118,34 @@ TmcClient *TmcClient::instance() */ void TmcClient::setNetworkManager(QNetworkAccessManager *m) { - manager = m; + m_manager = m; } /*! Sets the value of the private \c accessToken member of \l TmcClient to \a token. */ -void TmcClient::setAccessToken(QString token) +void TmcClient::setAccessToken(const QString &token) { - accessToken = token; + m_accessToken = token; } /*! Sets the value of the private \c clientId member of \l TmcClient to \a id. */ -void TmcClient::setClientId(QString id) +void TmcClient::setClientId(const QString &id) { - clientId = id; + m_clientId = id; } /*! Sets the value of the private \c clientSecret member of \l TmcClient to \a secret. */ -void TmcClient::setClientSecret(QString secret) +void TmcClient::setClientSecret(const QString &secret) { - clientSecret = secret; + m_clientSecret = secret; } /*! @@ -156,11 +156,11 @@ void TmcClient::setClientSecret(QString secret) This makes it straightforward to concatenate the server address with a path such as \c {/one/two.txt}. */ -void TmcClient::setServerAddress(QString address) +void TmcClient::setServerAddress(QString &address) { if (address.endsWith("/")) address.remove(address.length()-1, 1); - serverAddress = address; + m_serverAddress = address; } /*! @@ -171,7 +171,7 @@ void TmcClient::setServerAddress(QString address) */ bool TmcClient::isAuthorized() { - return !(clientId.isEmpty() || clientSecret.isEmpty()); + return !(m_clientId.isEmpty() || m_clientSecret.isEmpty()); } /*! @@ -182,21 +182,21 @@ bool TmcClient::isAuthorized() */ bool TmcClient::isAuthenticated() { - return !accessToken.isEmpty(); + return !m_accessToken.isEmpty(); } -QNetworkRequest TmcClient::buildRequest(QUrl url) +QNetworkRequest TmcClient::buildRequest(const QUrl &url) { QNetworkRequest request(url); QString a = "Bearer "; - request.setRawHeader(QByteArray("Authorization") , QByteArray(a.append(accessToken).toUtf8())); + request.setRawHeader(QByteArray("Authorization") , QByteArray(a.append(m_accessToken).toUtf8())); return request; } -QNetworkReply* TmcClient::doGet(QUrl url) +QNetworkReply* TmcClient::doGet(const QUrl &url) { QNetworkRequest request = buildRequest(url); - QNetworkReply *reply = manager->get(request); + QNetworkReply *reply = m_manager->get(request); return reply; } @@ -204,7 +204,7 @@ bool TmcClient::checkRequestStatus(QNetworkReply *reply) { if (reply->error()) { if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 403) { - emit accessTokenNotValid(); + Q_EMIT accessTokenNotValid(); } reply->close(); reply->deleteLater(); @@ -218,7 +218,7 @@ bool TmcClient::checkRequestStatus(QNetworkReply *reply) */ void TmcClient::authorize() { - QUrl url(serverAddress + "/api/v8/application/qtcreator_plugin/credentials.json"); + QUrl url(m_serverAddress + "/api/v8/application/qtcreator_plugin/credentials.json"); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ @@ -231,22 +231,22 @@ void TmcClient::authorize() \tt {TMC Login} dialog. The values for the parameters \a username and \a password are those entered by the user in the dialog. */ -void TmcClient::authenticate(QString username, QString password) +void TmcClient::authenticate(const QString &username, const QString &password) { if (!isAuthorized()) { - emit TMCError(QString("Login failed: " - "no client id/secret available")); - emit authenticationFinished(""); + Q_EMIT TMCError(QString("Login failed: " + "no client id/secret available")); + Q_EMIT authenticationFinished(""); return; } - QUrl url(serverAddress + "/oauth/token"); + QUrl url(m_serverAddress + "/oauth/token"); QString grantType = "password"; QUrlQuery params; - params.addQueryItem("client_id", clientId); - params.addQueryItem("client_secret", clientSecret); + params.addQueryItem("client_id", m_clientId); + params.addQueryItem("client_secret", m_clientSecret); // Need to encode with percent encoding for the literal + character params.addQueryItem("username", QUrl::toPercentEncoding(username)); params.addQueryItem("password", QUrl::toPercentEncoding(password)); @@ -256,7 +256,7 @@ void TmcClient::authenticate(QString username, QString password) request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); - QNetworkReply *reply = manager->post(request, params.toString(QUrl::FullyEncoded).toUtf8()); + QNetworkReply *reply = m_manager->post(request, params.toString(QUrl::FullyEncoded).toUtf8()); connect(reply, &QNetworkReply::finished, this, [=](){ authenticationReplyFinished(reply); @@ -269,7 +269,7 @@ void TmcClient::authenticate(QString username, QString password) */ void TmcClient::getOrganizationList() { - QUrl url(QString(serverAddress + "/api/v8/org.json")); + QUrl url(QString(m_serverAddress + "/api/v8/org.json")); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ organizationListReplyFinished(reply); @@ -280,9 +280,9 @@ void TmcClient::getOrganizationList() Retrieves the course list for the organization specified by the \l Organization parameter \a org. */ -void TmcClient::getCourseList(Organization org) +void TmcClient::getCourseList(Organization &org) { - QUrl url(QString(serverAddress + "/api/v8/core/org/%1/courses").arg(org.getSlug())); + QUrl url(QString(m_serverAddress + "/api/v8/core/org/%1/courses").arg(org.getSlug())); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ courseListReplyFinished(reply, org); @@ -296,9 +296,9 @@ void TmcClient::getCourseList(Organization org) automatically extracted to the appropriate directory (determining what this directory is involves \l {Exercise::} {getLocation()}). */ -QNetworkReply* TmcClient::getExerciseZip(Exercise ex) +QNetworkReply *TmcClient::getExerciseZip(const Exercise &ex) { - QUrl url(QString(serverAddress + "/api/v8/core/exercises/%1/download").arg(ex.getId())); + QUrl url(QString(m_serverAddress + "/api/v8/core/exercises/%1/download").arg(ex.getId())); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ exerciseZipReplyFinished(reply, ex); @@ -312,12 +312,12 @@ QNetworkReply* TmcClient::getExerciseZip(Exercise ex) to the TMC server using the HTTP(S) protocol. The project directory along with all its files has been packed into the archive file \a zipData prior to sending. */ -void TmcClient::postExerciseZip(Exercise ex, QByteArray zipData) +void TmcClient::postExerciseZip(const Exercise &ex, const QByteArray &zipData) { - QUrl url(QString(serverAddress + "/api/v8/core/exercises/%1/submissions").arg(ex.getId())); + QUrl url(QString(m_serverAddress + "/api/v8/core/exercises/%1/submissions").arg(ex.getId())); QNetworkRequest request = buildRequest(url); - QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); + auto *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, @@ -327,12 +327,12 @@ void TmcClient::postExerciseZip(Exercise ex, QByteArray zipData) filePart.setBody(zipData); multiPart->append(filePart); - QNetworkReply *reply = manager->post(request, multiPart); + QNetworkReply *reply = m_manager->post(request, multiPart); multiPart->setParent(reply); // delete multipart with reply connect(reply, &QNetworkReply::uploadProgress, this, [=](qint64 bytesSent, qint64 bytesTotal){ if (bytesSent == 0) return; - emit exerciseSubmitProgress(ex, bytesSent, bytesTotal); + Q_EMIT exerciseSubmitProgress(ex, bytesSent, bytesTotal); }); connect(reply, &QNetworkReply::finished, this, [=](){ @@ -342,7 +342,7 @@ void TmcClient::postExerciseZip(Exercise ex, QByteArray zipData) void TmcClient::getSubmissionStatus(int submissionId) { - QUrl url(serverAddress + "/api/v8/core/submissions/" + QString::number(submissionId)); + QUrl url(m_serverAddress + "/api/v8/core/submissions/" + QString::number(submissionId)); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ @@ -357,7 +357,7 @@ void TmcClient::getSubmissionStatus(int submissionId) */ void TmcClient::getExerciseList(Course *course) { - QUrl url(serverAddress + "/api/v8/core/courses/" + QString::number(course->getId())); + QUrl url(m_serverAddress + "/api/v8/core/courses/" + QString::number(course->getId())); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ @@ -370,7 +370,7 @@ void TmcClient::getExerciseList(Course *course) */ void TmcClient::getUserInfo() { - QUrl url(serverAddress + "/api/v8/users/current"); + QUrl url(m_serverAddress + "/api/v8/users/current"); QNetworkReply *reply = doGet(url); connect(reply, &QNetworkReply::finished, this, [=](){ @@ -382,8 +382,8 @@ void TmcClient::getUserInfo() void TmcClient::authorizationReplyFinished(QNetworkReply *reply) { if (!checkRequestStatus(reply)) { - emit TMCError(QString("Client authorization failed: %1: %2") - .arg(reply->errorString(), reply->error())); + Q_EMIT TMCError(QString("Client authorization failed: %1: %2") + .arg(reply->errorString(), reply->error())); return; } @@ -391,15 +391,17 @@ void TmcClient::authorizationReplyFinished(QNetworkReply *reply) setClientId(json["application_id"].toString()); setClientSecret(json["secret"].toString()); - emit authorizationFinished(clientId, clientSecret); + Q_EMIT authorizationFinished(m_clientId, m_clientSecret); + + reply->deleteLater(); } void TmcClient::authenticationReplyFinished(QNetworkReply *reply) { if (!checkRequestStatus(reply)) { - emit TMCError(QString("Login failed: %1: %2") - .arg(reply->errorString(), reply->error())); - emit authenticationFinished(""); + Q_EMIT TMCError(QString("Login failed: %1: %2") + .arg(reply->errorString(), reply->error())); + Q_EMIT authenticationFinished(""); return; } qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString(); @@ -409,12 +411,10 @@ void TmcClient::authenticationReplyFinished(QNetworkReply *reply) qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); - qDebug() << json.toJson(); auto name = json.object(); - accessToken = name["access_token"].toString(); - qDebug() << accessToken; + m_accessToken = name["access_token"].toString(); - emit authenticationFinished(accessToken); + Q_EMIT authenticationFinished(m_accessToken); reply->deleteLater(); } @@ -422,17 +422,17 @@ void TmcClient::organizationListReplyFinished(QNetworkReply *reply) { if (!checkRequestStatus(reply)) { qDebug() << "Error at Organization list reply finished"; - emit TMCError(QString("Failed to download organization list: %1: %2") - .arg(reply->errorString(), reply->error())); + Q_EMIT TMCError(QString("Failed to download organization list: %1: %2") + .arg(reply->errorString(), reply->error())); return; } QList organizations; QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); QJsonArray orgJson = json.array(); - foreach (QJsonValue jsonVal, orgJson) { + for (QJsonValue jsonVal : orgJson) { organizations.append(Organization::fromJson(jsonVal.toObject())); } - emit organizationListReady(organizations); + Q_EMIT organizationListReady(organizations); reply->deleteLater(); } @@ -440,16 +440,16 @@ void TmcClient::courseListReplyFinished(QNetworkReply *reply, Organization org) { if (!checkRequestStatus(reply)) { qDebug() << "Error at Course list reply finished"; - emit TMCError(QString("Failed to download course list: %1: %2") - .arg(reply->errorString(), reply->error())); + Q_EMIT TMCError(QString("Failed to download course list: %1: %2") + .arg(reply->errorString(), reply->error())); return; } QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); QJsonArray coursesJson = json.array(); - foreach (QJsonValue courseJson, coursesJson) { + for (QJsonValue courseJson : coursesJson) { org.addCourse(Course::fromJson(courseJson.toObject())); } - emit courseListReady(org); + Q_EMIT courseListReady(org); reply->deleteLater(); } @@ -457,11 +457,10 @@ void TmcClient::exerciseListReplyFinished(QNetworkReply *reply, Course *course) { if (!checkRequestStatus(reply)) { qDebug() << "Error at Exercise list reply finished"; - emit TMCError(QString("Failed to download exercise list: %1: %2") - .arg(reply->errorString(), reply->error())); + Q_EMIT TMCError(QString("Failed to download exercise list: %1: %2") + .arg(reply->errorString(), reply->error())); return; } - QJsonDocument json = QJsonDocument::fromJson(reply->readAll()); QJsonObject jsonObj = json.object(); @@ -469,16 +468,15 @@ void TmcClient::exerciseListReplyFinished(QNetworkReply *reply, Course *course) QJsonArray exercises = jsonCourse["exercises"].toArray(); QList courseList; - foreach (QJsonValue jsonVal, exercises) { + for (QJsonValue jsonVal: exercises) { courseList.append(Exercise::fromJson(jsonVal.toObject())); } - emit exerciseListReady(course, courseList); - + Q_EMIT exerciseListReady(course, courseList); reply->deleteLater(); } -void TmcClient::exerciseZipReplyFinished(QNetworkReply *reply, Exercise ex) +void TmcClient::exerciseZipReplyFinished(QNetworkReply *reply, const Exercise &ex) { if (!checkRequestStatus(reply)) { // One of the downloads was cancelled by the user @@ -486,42 +484,42 @@ void TmcClient::exerciseZipReplyFinished(QNetworkReply *reply, Exercise ex) qDebug() << "Cancelled download:" << ex.getName(); } else { qDebug() << "Error at exerciseListReplyFinished"; - emit TMCError(QString("Zip download error %1: %2") - .arg(reply->errorString(), reply->error())); + Q_EMIT TMCError(QString("Zip download error %1: %2") + .arg(reply->errorString(), reply->error())); } return; } - emit exerciseZipReady(reply->readAll(), ex); + Q_EMIT exerciseZipReady(reply->readAll(), ex); reply->close(); - reply->deleteLater(); + // reply->deleteLater(); } -void TmcClient::zipSubmitReplyFinished(QNetworkReply *reply, Exercise ex) +void TmcClient::zipSubmitReplyFinished(QNetworkReply *reply, const Exercise &ex) { if (!checkRequestStatus(reply)) { - emit TMCError(QString("Zip upload error %1: %2") - .arg(reply->errorString(), reply->error())); - return; + Q_EMIT TMCError(QString("Zip upload error %1: %2") + .arg(reply->errorString(), reply->error())); + return; } QJsonObject submission = QJsonDocument::fromJson(reply->readAll()).object(); QString submissionUrl = submission["submission_url"].toString(); - emit exerciseSubmitReady(ex, submissionUrl); + Q_EMIT exerciseSubmitReady(ex, submissionUrl); reply->deleteLater(); } void TmcClient::submissionStatusReplyFinished(QNetworkReply *reply, int submissionId) { if (!checkRequestStatus(reply)) { - emit TMCError(QString("Submission status update error %1: %2") - .arg(reply->errorString(), reply->error())); - return; + Q_EMIT TMCError(QString("Submission status update error %1: %2") + .arg(reply->errorString(), reply->error())); + return; } QJsonObject jsonSubmission = QJsonDocument::fromJson(reply->readAll()).object(); Submission submission = Submission::fromJson(submissionId, jsonSubmission); - emit submissionStatusReady(submission); + Q_EMIT submissionStatusReady(submission); reply->deleteLater(); } diff --git a/lib/tmcclient/tmcclient.h b/lib/tmcclient/tmcclient.h index 2b34f6f..56aefec 100644 --- a/lib/tmcclient/tmcclient.h +++ b/lib/tmcclient/tmcclient.h @@ -1,6 +1,11 @@ #ifndef TMCCLIENT_H #define TMCCLIENT_H +#include "exercise.h" +#include "course.h" +#include "organization.h" +#include "submission.h" + #include #include #include @@ -11,38 +16,33 @@ #include #include -#include "exercise.h" -#include "course.h" -#include "organization.h" -#include "submission.h" - class TmcClient : public QObject { Q_OBJECT public: explicit TmcClient(QObject *parent = nullptr); - static TmcClient* instance(); + static TmcClient *instance(); void setNetworkManager(QNetworkAccessManager *m); - void setAccessToken(QString token); - void setClientId(QString id); - void setClientSecret(QString secret); - void setServerAddress(QString address); + void setAccessToken(const QString &token); + void setClientId(const QString &id); + void setClientSecret(const QString &secret); + void setServerAddress(QString &address); void authorize(); - void authenticate(QString username, QString password); + void authenticate(const QString &username, const QString &password); void getUserInfo(); void getExerciseList(Course *course); - QNetworkReply* getExerciseZip(Exercise ex); - void postExerciseZip(Exercise ex, QByteArray zipData); + QNetworkReply *getExerciseZip(const Exercise &ex); + void postExerciseZip(const Exercise &ex, const QByteArray &zipData); void getSubmissionStatus(int submissionId); - void getCourseList(Organization org); + void getCourseList(Organization &org); void getOrganizationList(); bool isAuthorized(); bool isAuthenticated(); -signals: +Q_SIGNALS: void TMCError(QString errorString); void authorizationFinished(QString clientId, QString clientSecret); void authenticationFinished(QString accessToken); @@ -55,25 +55,25 @@ class TmcClient : public QObject void submissionStatusReady(Submission submission); void accessTokenNotValid(); -private slots: +private Q_SLOTS: void authorizationReplyFinished (QNetworkReply *reply); void authenticationReplyFinished (QNetworkReply *reply); void organizationListReplyFinished(QNetworkReply *reply); void courseListReplyFinished(QNetworkReply *reply, Organization org); void exerciseListReplyFinished (QNetworkReply *reply, Course *course); - void exerciseZipReplyFinished (QNetworkReply *reply, Exercise ex); - void zipSubmitReplyFinished(QNetworkReply *reply, Exercise ex); + void exerciseZipReplyFinished (QNetworkReply *reply, const Exercise &ex); + void zipSubmitReplyFinished(QNetworkReply *reply, const Exercise &ex); void submissionStatusReplyFinished(QNetworkReply *reply, int submissionId); private: - QNetworkRequest buildRequest(QUrl url); - QNetworkReply* doGet(QUrl url); - QNetworkAccessManager *manager; - QString accessToken; - QString clientId; - QString clientSecret; - QString serverAddress; + QNetworkRequest buildRequest(const QUrl &url); + QNetworkReply* doGet(const QUrl &url); + QNetworkAccessManager *m_manager; + QString m_accessToken; + QString m_clientId; + QString m_clientSecret; + QString m_serverAddress; bool checkRequestStatus(QNetworkReply *reply); }; diff --git a/src/downloadpanel.cpp b/src/downloadpanel.cpp index 6cbdfba..8ffab0f 100644 --- a/src/downloadpanel.cpp +++ b/src/downloadpanel.cpp @@ -26,11 +26,11 @@ approximation \c AVERAGE_DOWNLOAD_SIZE. */ +#include "downloadpanel.h" + #include #include -#include "downloadpanel.h" - static const int TIME_BEFORE_WINDOW_CLOSES_AFTER_DOWNLOADS = 2000; // Perhaps with a different font the height of the widgets could be reduced // to less than 15. @@ -39,19 +39,20 @@ static const int FIXED_WIDGET_HEIGHT = 15; // so the following crude estimate is needed. static const int AVERAGE_DOWNLOAD_SIZE = 1500000; -DownloadPanel::DownloadPanel( QWidget *parent ) : QWidget( parent ) +DownloadPanel::DownloadPanel(QWidget *parent) + : QWidget(parent) + , infoLabel(nullptr) { - layout = new QGridLayout( parent ); + layout = new QGridLayout(parent); numberOfProgressBars = 0; doneAddingWidgets = false; - setLayout( layout ); - setWindowTitle( "Download Panel" ); + setLayout(layout); + setWindowTitle("Download Panel"); } DownloadPanel::~DownloadPanel() { - } /*! @@ -61,16 +62,16 @@ DownloadPanel::~DownloadPanel() */ void DownloadPanel::addInfoLabel() { - if( doneAddingWidgets ) { + if (doneAddingWidgets) { qDebug() << "DownloadPanel::addInfoLabel() was called even though " "doneAddingWidgets was false"; return; } - infoLabel = new QLabel( "Downloading files...", this ); - infoLabel->setAlignment( Qt::AlignCenter ); - infoLabel->setFixedHeight( 35 ); - layout->addWidget( infoLabel, 2 * numberOfProgressBars + 1, 0 ); + infoLabel = new QLabel("Downloading files...", this); + infoLabel->setAlignment(Qt::AlignCenter); + infoLabel->setFixedHeight(35); + layout->addWidget(infoLabel, 2 * numberOfProgressBars + 1, 0); doneAddingWidgets = true; } @@ -82,36 +83,36 @@ void DownloadPanel::addInfoLabel() displaying the progress. The parameter \a downloadName is displayed in the \c QLabel. */ -void DownloadPanel::addWidgetsToDownloadPanel( QString downloadName ) +void DownloadPanel::addWidgetsToDownloadPanel(const QString &downloadName) { - if( doneAddingWidgets ) { + if (doneAddingWidgets) { qDebug() << "DownloadPanel::addWidgetsToDownloadPanel() was called " "even though doneAddingWidgets was false"; return; } // Add the label - QLabel *label = new QLabel( downloadName, this ); - label->setFixedHeight( FIXED_WIDGET_HEIGHT ); - layout->addWidget( label, 2 * numberOfProgressBars, 0 ); - progressBarLabels.append( label ); + QLabel *label = new QLabel(downloadName, this); + label->setFixedHeight(FIXED_WIDGET_HEIGHT); + layout->addWidget(label, 2 * numberOfProgressBars, 0); + progressBarLabels.append(label); // Add the progress bar - QProgressBar *bar = new QProgressBar( this ); - bar->setMinimum( 0 ); - bar->setMaximum( AVERAGE_DOWNLOAD_SIZE ); - bar->setValue( 0 ); - bar->setFixedHeight( FIXED_WIDGET_HEIGHT ); - layout->addWidget( bar, 2 * numberOfProgressBars + 1, 0 ); - progressBars.append( bar ); + QProgressBar *bar = new QProgressBar(this); + bar->setMinimum(0); + bar->setMaximum(AVERAGE_DOWNLOAD_SIZE); + bar->setValue(0); + bar->setFixedHeight(FIXED_WIDGET_HEIGHT); + layout->addWidget(bar, 2 * numberOfProgressBars + 1, 0); + progressBars.append(bar); // Add the button - QPushButton *button = new QPushButton( "❎", this ); - button->setFixedHeight( FIXED_WIDGET_HEIGHT ); - button->setFixedWidth( FIXED_WIDGET_HEIGHT ); - layout->addWidget( button, 2 * numberOfProgressBars + 1, 1 ); - connect( button, SIGNAL( clicked() ), this, SLOT( cancelDownload() ) ); - downloadCancelButtons.append( button ); + QPushButton *button = new QPushButton("❎", this); + button->setFixedHeight(FIXED_WIDGET_HEIGHT); + button->setFixedWidth(FIXED_WIDGET_HEIGHT); + layout->addWidget(button, 2 * numberOfProgressBars + 1, 1); + connect(button, &QPushButton::clicked, this, &DownloadPanel::cancelDownload); + downloadCancelButtons.append(button); ++numberOfProgressBars; } @@ -122,18 +123,18 @@ void DownloadPanel::addWidgetsToDownloadPanel( QString downloadName ) \c replies. Each element in \c replies corresponds to the element at the same index in \c progressBars. */ -void DownloadPanel::addReplyToList( QNetworkReply *reply ) +void DownloadPanel::addReplyToList(QNetworkReply *reply) { - replies.append( reply ); + replies.append(reply); } /*! Returns the \c QNetworkReply pointer specified by the \a index parameter. The pointer is an element in the \c QList instance variable \c replies. */ -QNetworkReply *DownloadPanel::getRepliesListItem( int index ) +QNetworkReply *DownloadPanel::getRepliesListItem(int index) { - return replies.at( index ); + return replies.at(index); } /*! @@ -145,15 +146,14 @@ QNetworkReply *DownloadPanel::getRepliesListItem( int index ) the download. If the value of \a bytesTotal is -1, the total download size is unknown. */ -void DownloadPanel::networkReplyProgress( - qint64 bytesReceived, qint64 bytesTotal ) +void DownloadPanel::networkReplyProgress(qint64 bytesReceived, qint64 bytesTotal) { int senderIndex = replies.indexOf(reinterpret_cast (QObject::sender())); - progressBars[ senderIndex ]->setMaximum( - bytesTotal != -1 ? bytesTotal : AVERAGE_DOWNLOAD_SIZE ); - progressBars[ senderIndex ]->setValue( bytesReceived ); + progressBars[senderIndex]->setMaximum( + bytesTotal != -1 ? bytesTotal : AVERAGE_DOWNLOAD_SIZE); + progressBars[senderIndex]->setValue(bytesReceived); } /*! @@ -167,9 +167,10 @@ void DownloadPanel::httpFinished() (QObject::sender())); // Grey out the cancel button of the download - downloadCancelButtons[ senderIndex ]->setEnabled( false ); + downloadCancelButtons[senderIndex]->setEnabled(false); - replies[ senderIndex ] = Q_NULLPTR; + replies[senderIndex]->deleteLater(); + replies[senderIndex] = nullptr; closeWindowIfAllDownloadsComplete(); } @@ -192,15 +193,15 @@ void DownloadPanel::sanityCheck() */ void DownloadPanel::closeWindowIfAllDownloadsComplete() { - for( int i = 0; i < replies.size(); i++ ) { - if( replies[ i ] ) { // Not a null pointer + for (int i = 0; i < replies.size(); i++) { + if (replies[ i ]) { // Not a null pointer return; } } - infoLabel->setText( "Done!" ); - QTimer::singleShot( TIME_BEFORE_WINDOW_CLOSES_AFTER_DOWNLOADS, - this, SLOT( close() ) ); + infoLabel->setText("Done!"); + QTimer::singleShot(TIME_BEFORE_WINDOW_CLOSES_AFTER_DOWNLOADS, + this, &DownloadPanel::close); } /*! @@ -209,19 +210,19 @@ void DownloadPanel::closeWindowIfAllDownloadsComplete() */ void DownloadPanel::cancelDownload() { - for( int i = 0; i < downloadCancelButtons.size(); i++ ) { - if( downloadCancelButtons[ i ] == QObject::sender() ) { - downloadCancelButtons[ i ]->setEnabled( false ); - replies[ i ]->abort(); - progressBars[ i ]->setValue( 0 ); + for (int i = 0; i < downloadCancelButtons.size(); i++) { + if (downloadCancelButtons[i] == QObject::sender()) { + downloadCancelButtons[i]->setEnabled(false); + replies[i]->abort(); + progressBars[i]->setValue(0); // Without the following statement the progress bar of a cancelled // download that has not yet started will look different from one // that has already started - progressBars[ i ]->setMaximum( -1 ); - progressBars[ i ]->setTextVisible( false ); - infoLabel->setText( "Cancelled download of\n" + - progressBarLabels[ i ]->text() ); - progressBarLabels[ i ]->setText( "(cancelled)" ); + progressBars[i]->setMaximum(-1); + progressBars[i]->setTextVisible(false); + infoLabel->setText("Cancelled download of\n" + + progressBarLabels[ i ]->text()); + progressBarLabels[i]->setText("(cancelled)"); } } diff --git a/src/downloadpanel.h b/src/downloadpanel.h index 260f63e..528c484 100644 --- a/src/downloadpanel.h +++ b/src/downloadpanel.h @@ -13,16 +13,16 @@ class DownloadPanel : public QWidget Q_OBJECT public: - DownloadPanel( QWidget *parent = 0 ); + DownloadPanel(QWidget *parent = nullptr); ~DownloadPanel(); - void addReplyToList( QNetworkReply *reply ); - QNetworkReply *getRepliesListItem( int index ); + void addReplyToList(QNetworkReply *reply); + QNetworkReply *getRepliesListItem(int index); void sanityCheck(); - void addWidgetsToDownloadPanel( QString downloadName ); + void addWidgetsToDownloadPanel(const QString &downloadName); void addInfoLabel(); -public slots: - void networkReplyProgress( qint64 bytesReceived, qint64 bytesTotal ); +public Q_SLOTS: + void networkReplyProgress(qint64 bytesReceived, qint64 bytesTotal); void httpFinished(); void cancelDownload(); diff --git a/src/exercisedelegate.cpp b/src/exercisedelegate.cpp index 43b4510..6b83b71 100644 --- a/src/exercisedelegate.cpp +++ b/src/exercisedelegate.cpp @@ -6,46 +6,40 @@ #include #include -ExerciseDelegate::ExerciseDelegate(QWidget *parent) : QStyledItemDelegate(parent) +ExerciseDelegate::ExerciseDelegate(QWidget *parent) + : QStyledItemDelegate(parent) { - } void ExerciseDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - if (index.column() != 1) { - QStyledItemDelegate::paint(painter, option, index); - return; - } + int progress(index.data().toInt()); + QStyleOptionButton opt; - int progress = index.data().toInt(); - - if (progress == 0) { - QStyleOptionButton opt; + switch (progress) { + case 0: opt.state |= QStyle::State_Active; opt.text = "Download"; opt.rect = option.rect; QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter); - return; - } - - if (progress == -1) { - QStyleOptionButton opt; + break; + case -1: opt.state |= QStyle::State_Active; opt.text = "Open"; opt.rect = option.rect; QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter); - return; + break; + default: + QStyleOptionProgressBar progressBarOption; + progressBarOption.rect = option.rect; + progressBarOption.minimum = 0; + progressBarOption.maximum = 100; + progressBarOption.progress = progress; + progressBarOption.text = QString::number(progress) + "%"; + progressBarOption.textVisible = true; + + QApplication::style()->drawControl(QStyle::CE_ProgressBar, + &progressBarOption, painter); + break; } - - QStyleOptionProgressBar progressBarOption; - progressBarOption.rect = option.rect; - progressBarOption.minimum = 0; - progressBarOption.maximum = 100; - progressBarOption.progress = progress; - progressBarOption.text = QString::number(progress) + "%"; - progressBarOption.textVisible = true; - - QApplication::style()->drawControl(QStyle::CE_ProgressBar, - &progressBarOption, painter); } diff --git a/src/exercisemodel.cpp b/src/exercisemodel.cpp index 9f3b435..ba20f2e 100644 --- a/src/exercisemodel.cpp +++ b/src/exercisemodel.cpp @@ -1,13 +1,14 @@ #include "exercisemodel.h" #include "tmcclient.h" -#include #include +#include +#include ExerciseModel::ExerciseModel(QObject *parent) : QAbstractTableModel(parent) + , m_activeCourse(nullptr) { - } void ExerciseModel::onActiveCourseChanged(Course *course) @@ -19,30 +20,33 @@ void ExerciseModel::onActiveCourseChanged(Course *course) QList ExerciseModel::exercises() const { + if (!m_activeCourse) + return {}; + return m_activeCourse->getExercises().values(); } void ExerciseModel::onExerciseListUpdated(Course *updatedCourse, QList newExercises) { - QString courseName = updatedCourse->getName(); + QString courseName(updatedCourse->getName()); if (courseName.isEmpty()) { qDebug() << "Updated course name is null!"; return; } - QString saveDirectory = QString("%1/%2").arg(m_workingDir, courseName); beginResetModel(); + for (Exercise &ex : newExercises) { ex.setLocation(saveDirectory); - Exercise found = updatedCourse->getExercise(ex); if (!found) { // Not found, new exercise ex.setState(Exercise::None); updatedCourse->addExercise(ex); + continue; } @@ -53,18 +57,16 @@ void ExerciseModel::onExerciseListUpdated(Course *updatedCourse, QList newExercises.removeAll(ex); } } - } endResetModel(); // Have new exercises if (!newExercises.isEmpty()) { - emit exerciseUpdates(); + Q_EMIT exerciseUpdates(); } - } -void ExerciseModel::onWorkingDirectoryChanged(QString workingDir) +void ExerciseModel::onWorkingDirectoryChanged(const QString &workingDir) { m_workingDir = workingDir; } @@ -72,7 +74,7 @@ void ExerciseModel::onWorkingDirectoryChanged(QString workingDir) void ExerciseModel::triggerDownload() { for (auto &ex : m_selected) { - QNetworkReply* reply = TmcClient::instance()->getExerciseZip(ex); + QNetworkReply *reply = TmcClient::instance()->getExerciseZip(ex); m_downloads[reply] = exercises().indexOf(ex); connect(reply, &QNetworkReply::downloadProgress, this, &ExerciseModel::onProgressUpdate); connect(reply, &QNetworkReply::finished, this, &ExerciseModel::onDownloadFinished); @@ -81,12 +83,11 @@ void ExerciseModel::triggerDownload() void ExerciseModel::onTableClicked(const QModelIndex &index) { - qDebug() << "onTableClicked"; if (index.isValid() && index.column() == 1) { - const Exercise &ex = exercises()[index.row()]; + const Exercise ex = exercises().at(index.row()); if (ex.getState() == Exercise::Downloaded) { - emit exerciseOpen(ex); + Q_EMIT exerciseOpen(ex); return; } @@ -96,9 +97,9 @@ void ExerciseModel::onTableClicked(const QModelIndex &index) qDebug() << "Downloading exercise" << ex.getName(); m_progress[index.row()] = 1; - QNetworkReply* reply = TmcClient::instance()->getExerciseZip(ex); + QNetworkReply *reply = TmcClient::instance()->getExerciseZip(ex); m_downloads.insert(reply, index.row()); - emit dataChanged(index, index); + Q_EMIT dataChanged(index, index); connect(reply, &QNetworkReply::finished, this, &ExerciseModel::onDownloadFinished); } @@ -114,8 +115,7 @@ void ExerciseModel::onSelectAll(int state) void ExerciseModel::onProgressUpdate(qint64 bytesReceived, qint64 bytesTotal) { - qDebug() << "onProgressUpdate"; - int row = m_downloads[(static_cast(QObject::sender()))]; + int row = m_downloads[(dynamic_cast(QObject::sender()))]; QModelIndex modelIndex = index(row, 1); if (bytesTotal == -1) @@ -123,17 +123,16 @@ void ExerciseModel::onProgressUpdate(qint64 bytesReceived, qint64 bytesTotal) m_progress[row] = static_cast((bytesReceived * 100) / bytesTotal); - emit dataChanged(modelIndex, modelIndex); + Q_EMIT dataChanged(modelIndex, modelIndex); } void ExerciseModel::onDownloadFinished() { - qDebug() << "onDownloadFinished"; - int row = m_downloads[(static_cast(QObject::sender()))]; + int row = m_downloads[(dynamic_cast(QObject::sender()))]; QModelIndex modelIndex = index(row, 1); m_progress[row] = -1; - emit dataChanged(modelIndex, modelIndex); + Q_EMIT dataChanged(modelIndex, modelIndex); } QString ExerciseModel::calculateDeadline(const Exercise &ex) const @@ -191,10 +190,12 @@ QVariant ExerciseModel::data(const QModelIndex &index, int role) const } if (role == Qt::DisplayRole) { - const Exercise& ex = exercises().at(index.row()); + const Exercise ex = exercises().at(index.row()); + switch (index.column()) { - case 0: + case 0: { return ex.getName(); + } case 1: return ex.isDownloaded() ? -1 : m_progress[index.row()]; case 2: @@ -207,14 +208,14 @@ QVariant ExerciseModel::data(const QModelIndex &index, int role) const } bool ExerciseModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ +{ if (role == Qt::CheckStateRole && index.column() == 0) { if (value == Qt::Checked){ m_selected.append(exercises().at(index.row())); } else { m_selected.removeAll(exercises().at(index.row())); } - emit dataChanged(index, index); + Q_EMIT dataChanged(index, index); return true; } diff --git a/src/exercisemodel.h b/src/exercisemodel.h index 4df9484..72976d7 100644 --- a/src/exercisemodel.h +++ b/src/exercisemodel.h @@ -31,15 +31,15 @@ class ExerciseModel : public QAbstractTableModel Qt::ItemFlags flags(const QModelIndex &index) const override; -public slots: +public Q_SLOTS: void onExerciseListUpdated(Course *updatedCourse, QList newExercises); - void onWorkingDirectoryChanged(QString workingDir); + void onWorkingDirectoryChanged(const QString &workingDir); void onSelectAll(int state); void onProgressUpdate(qint64 bytesReceived, qint64 bytesTotal); void onDownloadFinished(); -signals: +Q_SIGNALS: void exerciseUpdates(); void exerciseOpen(const Exercise &ex); diff --git a/src/exercisewidget.cpp b/src/exercisewidget.cpp index e78d3fb..6502bb8 100644 --- a/src/exercisewidget.cpp +++ b/src/exercisewidget.cpp @@ -1,7 +1,9 @@ #include "exercisewidget.h" #include "exercisedelegate.h" -ExerciseWidget::ExerciseWidget(QWidget *parent) : QWidget(parent) +ExerciseWidget::ExerciseWidget(QWidget *parent) + : QWidget(parent) + , m_model(nullptr) { m_exerciseWindow = new Ui::ExerciseWindow; m_exerciseWindow->setupUi(this); @@ -12,7 +14,7 @@ ExerciseWidget::ExerciseWidget(QWidget *parent) : QWidget(parent) m_tableView->horizontalHeader()->setStretchLastSection(true); m_tableView->horizontalHeader()->setMinimumSectionSize(60); m_tableView->setWordWrap(false); - m_tableView->setItemDelegate(new ExerciseDelegate); + m_tableView->setItemDelegateForColumn(1, new ExerciseDelegate(this)); m_selectAll = m_exerciseWindow->selectAll; diff --git a/src/exercisewidget.h b/src/exercisewidget.h index ab28ab2..2d1296b 100644 --- a/src/exercisewidget.h +++ b/src/exercisewidget.h @@ -16,11 +16,9 @@ class ExerciseWidget : public QWidget explicit ExerciseWidget(QWidget *parent = nullptr); void setModel(ExerciseModel *model); -signals: +Q_SIGNALS: void onExercisesSelected(QList selected); -public slots: - private: Ui::ExerciseWindow *m_exerciseWindow; ExerciseModel *m_model; diff --git a/src/loginwidget.cpp b/src/loginwidget.cpp index 71e294f..5979dba 100644 --- a/src/loginwidget.cpp +++ b/src/loginwidget.cpp @@ -5,8 +5,8 @@ #include #include -LoginWidget::LoginWidget(QWidget *parent) : - QWidget(parent) +LoginWidget::LoginWidget(QWidget *parent) + : QWidget(parent) { loginWindow = new Ui::loginform; loginWindow->setupUi(this); @@ -41,7 +41,7 @@ void LoginWidget::onLoginClicked() QString username = m_username->text(); QString password = m_password->text(); m_password->setText(""); - emit credentialsChanged(username, password); + Q_EMIT credentialsChanged(username, password); } void LoginWidget::onChangeServerClicked() @@ -57,5 +57,5 @@ void LoginWidget::onChangeServerClicked() } m_server->setText(address); - emit serverAddressChanged(address); + Q_EMIT serverAddressChanged(address); } diff --git a/src/loginwidget.h b/src/loginwidget.h index ec04b9c..a837dbb 100644 --- a/src/loginwidget.h +++ b/src/loginwidget.h @@ -16,11 +16,11 @@ class LoginWidget : public QWidget void setFields(QString username, QString server); -signals: +Q_SIGNALS: void credentialsChanged(QString username, QString password); void serverAddressChanged(QString server); -public slots: +public Q_SLOTS: void handleLoginResponse(QString accessToken); private: diff --git a/src/settingswidget.cpp b/src/settingswidget.cpp index 92735a7..09c3b0e 100644 --- a/src/settingswidget.cpp +++ b/src/settingswidget.cpp @@ -8,7 +8,10 @@ #include -SettingsWidget::SettingsWidget(QWidget *parent) : QWidget(parent) +SettingsWidget::SettingsWidget(QWidget *parent) + : QWidget(parent) + , m_loginWidget(nullptr) + , m_interval(60) { m_client = TmcClient::instance(); settingsWindow = new Ui::settingsForm; @@ -47,12 +50,12 @@ void SettingsWidget::loadSettings() connect(m_client, &TmcClient::organizationListReady, this, &SettingsWidget::handleOrganizationList); connect(m_client, &TmcClient::courseListReady, this, &SettingsWidget::handleCourseList); - m_activeOrganization = Organization::fromQSettings(&settings); - m_activeCourse = Course::fromQSettings(&settings); - m_activeCourse.exerciseListFromQSettings(&settings); + m_activeOrganization = Organization::fromQSettings(settings); + m_activeCourse = Course::fromQSettings(settings); + m_activeCourse.exerciseListFromQSettings(settings); if (m_activeCourse) { - emit activeCourseChanged(&m_activeCourse); + Q_EMIT activeCourseChanged(&m_activeCourse); } workingDirectory = settings.value("workingDir", "").toString(); @@ -61,8 +64,6 @@ void SettingsWidget::loadSettings() m_autoUpdateInterval->setValue(m_interval); m_userLoggedInLabel->setText("Logged in as " + m_username + ""); - settings.deleteLater(); - connect(settingsWindow->logoutButton, &QPushButton::clicked, this, [=](){ clearCredentials(); close(); @@ -88,7 +89,7 @@ void SettingsWidget::loadSettings() m_loginWidget = new LoginWidget(); m_loginWidget->setFields(m_username, m_serverAddress); - connect(m_loginWidget, &LoginWidget::credentialsChanged, this, [=](QString username, QString password) { + connect(m_loginWidget, &LoginWidget::credentialsChanged, this, [=](const QString &username, const QString &password) { m_client->authenticate(username, password); m_username = username; m_userLoggedInLabel->setText("Logged in as " + m_username + ""); @@ -96,11 +97,10 @@ void SettingsWidget::loadSettings() m_activeCourse = Course(); m_activeOrganization = Organization(); - emit activeCourseChanged(&m_activeCourse); + Q_EMIT activeCourseChanged(&m_activeCourse); QSettings settings(getSettingsPath(), QSettings::IniFormat); settings.setValue("username", username); - settings.deleteLater(); }); connect(m_loginWidget, &LoginWidget::serverAddressChanged, this, [=](QString serverAddress) { @@ -112,14 +112,12 @@ void SettingsWidget::loadSettings() m_activeCourse = Course(); m_activeOrganization = Organization(); - emit activeCourseChanged(&m_activeCourse); + Q_EMIT activeCourseChanged(&m_activeCourse); QSettings settings(getSettingsPath(), QSettings::IniFormat); settings.setValue("server", serverAddress); - settings.deleteLater(); }); - connect(m_client, &TmcClient::authenticationFinished, m_loginWidget, &LoginWidget::handleLoginResponse); connect(m_client, &TmcClient::accessTokenNotValid, m_loginWidget, &LoginWidget::show); } @@ -127,7 +125,7 @@ void SettingsWidget::loadSettings() void SettingsWidget::setUpdateInterval(int interval) { m_interval = interval; - emit autoUpdateIntervalChanged(m_interval); + Q_EMIT autoUpdateIntervalChanged(m_interval); } void SettingsWidget::display() @@ -148,8 +146,7 @@ void SettingsWidget::display() void SettingsWidget::saveExercise(Exercise &ex, Course *course) { QSettings settings(getSettingsPath(), QSettings::IniFormat); - ex.saveQSettings(&settings, course->getName()); - settings.deleteLater(); + ex.saveQSettings(settings, course->getName()); } QString SettingsWidget::getServerAddress() @@ -178,7 +175,7 @@ Course* SettingsWidget::getActiveCourse() return &m_activeCourse; } -void SettingsWidget::setComboboxIndex(QComboBox *box, QString value) +void SettingsWidget::setComboboxIndex(QComboBox *box, const QString &value) { int index = box->findText(value); if (index != -1) { @@ -196,10 +193,9 @@ void SettingsWidget::clearCredentials() QSettings settings(getSettingsPath(), QSettings::IniFormat); settings.setValue("username", ""); settings.setValue("accessToken", ""); - settings.deleteLater(); m_client->setAccessToken(""); - emit enableDownloadSubmit(false); - emit activeCourseChanged(nullptr); + Q_EMIT enableDownloadSubmit(false); + Q_EMIT activeCourseChanged(nullptr); } QString SettingsWidget::askSaveLocation() @@ -215,25 +211,23 @@ QString SettingsWidget::askSaveLocation() return directory; } -void SettingsWidget::handleLoginResponse(QString accessToken) +void SettingsWidget::handleLoginResponse(const QString &accessToken) { QSettings settings(getSettingsPath(), QSettings::IniFormat); if (accessToken == "") { settings.setValue("username", ""); } else { settings.setValue("accessToken", accessToken); - emit enableDownloadSubmit(true); + Q_EMIT enableDownloadSubmit(true); display(); } - settings.deleteLater(); } -void SettingsWidget::handleAuthResponse(QString clientId, QString clientSecret) +void SettingsWidget::handleAuthResponse(const QString &clientId, const QString &clientSecret) { QSettings settings(getSettingsPath(), QSettings::IniFormat); settings.setValue("clientId", clientId); settings.setValue("clientSecret", clientSecret); - settings.deleteLater(); m_client->setClientId(clientId); m_client->setClientSecret(clientSecret); @@ -248,7 +242,7 @@ void SettingsWidget::handleCourseList(Organization org) return lhs.getTitle() < rhs.getTitle(); }); - foreach (Course c, courses) { + for (const Course &c : courses) { m_courseComboBox->addItem(c.getTitle(), QVariant::fromValue(c)); } setComboboxIndex(m_courseComboBox, m_activeCourse.getTitle()); @@ -272,7 +266,7 @@ void SettingsWidget::handleOrganizationList(QList orgs) QVariant::fromValue(Organization())); } - foreach (Organization org, m_organizations) { + for (Organization &org : m_organizations) { m_orgComboBox->addItem(org.getName(), QVariant::fromValue(org)); } @@ -296,29 +290,28 @@ void SettingsWidget::onSettingsOkClicked() if (setDir != workingDirectory) { workingDirectory = setDir; settings.setValue("workingDir", workingDirectory); - emit workingDirectoryChanged(workingDirectory); + Q_EMIT workingDirectoryChanged(workingDirectory); } int setInterval = m_autoUpdateInterval->value(); if (setInterval != m_interval) { m_interval = setInterval; settings.setValue("autoupdateInterval", m_interval); - emit autoUpdateIntervalChanged(m_interval); + Q_EMIT autoUpdateIntervalChanged(m_interval); } Organization setOrg = m_orgComboBox->currentData().value(); if (m_activeOrganization != setOrg) { m_activeOrganization = setOrg; - Organization::toQSettings(&settings, setOrg); - emit organizationChanged(setOrg); + Organization::toQSettings(settings, setOrg); + Q_EMIT organizationChanged(setOrg); } Course setCourse = m_courseComboBox->currentData().value(); if (!!setCourse && m_activeCourse != setCourse) { m_activeCourse = setCourse; - Course::toQSettings(&settings, setCourse); - emit activeCourseChanged(&m_activeCourse); + Course::toQSettings(settings, setCourse); + Q_EMIT activeCourseChanged(&m_activeCourse); } - settings.deleteLater(); close(); } diff --git a/src/settingswidget.h b/src/settingswidget.h index e6ed5f8..83e1e92 100644 --- a/src/settingswidget.h +++ b/src/settingswidget.h @@ -27,14 +27,14 @@ class SettingsWidget : public QWidget Course* getActiveCourse(); int getAutoupdateInterval(); -signals: +Q_SIGNALS: void workingDirectoryChanged(QString location); void organizationChanged(Organization org); void activeCourseChanged(Course *course); void autoUpdateIntervalChanged(int interval); void enableDownloadSubmit(bool enable); -public slots: +public Q_SLOTS: void showLoginWidget(); private: @@ -58,11 +58,11 @@ public slots: QString workingDirectory; int m_interval; - void handleLoginResponse(QString accessToken); - void handleAuthResponse(QString clientId, QString clientSecret); + void handleLoginResponse(const QString &accessToken); + void handleAuthResponse(const QString &clientId, const QString &clientSecret); void handleOrganizationList(QList orgs); void handleCourseList(Organization org); - void setComboboxIndex(QComboBox *box, QString value); + void setComboboxIndex(QComboBox *box, const QString &value); void onSettingsOkClicked(); void onBrowseClicked(); void clearCredentials(); diff --git a/src/submitwidget.cpp b/src/submitwidget.cpp index 46459e6..99cf199 100644 --- a/src/submitwidget.cpp +++ b/src/submitwidget.cpp @@ -74,7 +74,7 @@ void SubmitWidget::submitProject(const Project *project) m_uploadProgress.reportStarted(); zipBuffer->open(QIODevice::ReadOnly); qDebug() << "Posting:" << project->displayName(); - emit projectSubmissionReady(ex, zipBuffer->readAll()); + Q_EMIT projectSubmissionReady(ex, zipBuffer->readAll()); } void SubmitWidget::onSubmitReply(Exercise ex, QString submissionUrl) @@ -96,7 +96,7 @@ void SubmitWidget::onSubmitReply(Exercise ex, QString submissionUrl) TestMyCodePlugin::Constants::TASK_INDEX); connect(&m_submitTimer, &QTimer::timeout, this, [this, submissionId]() { - emit submissionStatusRequest(submissionId); + Q_EMIT submissionStatusRequest(submissionId); }); m_submitTimer.start(); } @@ -114,11 +114,11 @@ void SubmitWidget::onSubmissionStatusReply(Submission sub) } else { m_submitTimer.stop(); m_submitProgress.reportFinished(); - emit submitTimedOut(sub); + Q_EMIT submitTimedOut(sub); return; } - emit submitResult(sub); + Q_EMIT submitResult(sub); } void SubmitWidget::submitProgress(Exercise ex, qint64 bytesSent, qint64 bytesTotal) @@ -144,7 +144,7 @@ void SubmitWidget::updateStatus(Submission submission) m_progressBar->setMinimum(0); break; case (Submission::Fail): - foreach (TestCase testCase, submission.getTestCases()) { + for (const TestCase &testCase : submission.getTestCases()) { output.append(QString("%1: %2\n") .arg(testCase.name, testCase.message)); } @@ -158,6 +158,7 @@ void SubmitWidget::updateStatus(Submission submission) "Click here for the suggested solution") .arg(submission.getPoints().join(", "), submission.solutionUrl())); + // TODO: Change standard button role from Cancel to Close for better UX m_status->setTextFormat(Qt::RichText); m_status->setTextInteractionFlags(Qt::TextBrowserInteraction); m_status->setOpenExternalLinks(true); diff --git a/src/submitwidget.h b/src/submitwidget.h index 438d505..6000f7b 100644 --- a/src/submitwidget.h +++ b/src/submitwidget.h @@ -27,13 +27,13 @@ class SubmitWidget : public QWidget void submitProject(const Project *project); -signals: +Q_SIGNALS: void projectSubmissionReady(Exercise ex, QByteArray zipData); void submissionStatusRequest(int submissionId); void submitResult(Submission sub); void submitTimedOut(Submission sub); -public slots: +public Q_SLOTS: void onSubmitReply(Exercise ex, QString submissionUrl); void onSubmissionStatusReply(Submission sub); void submitProgress(Exercise ex, qint64 bytesSent, qint64 bytesTotal); diff --git a/src/testmycode.cpp b/src/testmycode.cpp index 8514433..9fd74ca 100644 --- a/src/testmycode.cpp +++ b/src/testmycode.cpp @@ -26,7 +26,7 @@ #include "tmcoutputpane.h" #include "course.h" -#include +#include #include #include @@ -56,8 +56,10 @@ namespace TestMyCodePlugin { namespace Internal { TestMyCode::TestMyCode() + : m_tmcClient(nullptr) + , m_settingsWidget(nullptr) + , m_tmcManager(nullptr) { - // Create your members } TestMyCode::~TestMyCode() @@ -65,6 +67,9 @@ TestMyCode::~TestMyCode() // Unregister objects from the plugin manager's object pool // Delete members TmcOutputPane::destroy(); + delete m_tmcClient; + delete m_settingsWidget; + delete m_tmcManager; } bool TestMyCode::initialize(const QStringList &arguments, QString *errorString) @@ -128,10 +133,10 @@ bool TestMyCode::initialize(const QStringList &arguments, QString *errorString) auto tools_menu = ActionManager::actionContainer(Core::Constants::M_WINDOW); ActionManager::actionContainer(Core::Constants::MENU_BAR)->addMenu(tools_menu, menu); - // TmcClient - tmcClient = TmcClient::instance(); + // m_tmcClient + m_tmcClient = TmcClient::instance(); auto *m = new QNetworkAccessManager; - tmcClient->setNetworkManager(m); + m_tmcClient->setNetworkManager(m); // Initialize settings window m_settingsWidget = new SettingsWidget; @@ -160,7 +165,7 @@ bool TestMyCode::initialize(const QStringList &arguments, QString *errorString) TmcOutputPane::instance(); // TmcManager - m_tmcManager = new TmcManager(tmcClient); + m_tmcManager = new TmcManager(m_tmcClient); m_tmcManager->setSettings(m_settingsWidget); connect(downloadUpdateAction, &QAction::triggered, m_tmcManager, &TmcManager::updateExercises); @@ -172,7 +177,7 @@ bool TestMyCode::initialize(const QStringList &arguments, QString *errorString) connect(courseAction, &QAction::triggered, m_tmcManager, &TmcManager::openActiveCoursePage); // Disable/Enable Download/Update and Submit buttons - if (!tmcClient->isAuthenticated()) { + if (!m_tmcClient->isAuthenticated()) { downloadUpdateAction->setDisabled(true); submitAction->setDisabled(true); } diff --git a/src/testmycode.h b/src/testmycode.h index c88d1d0..d0deebb 100644 --- a/src/testmycode.h +++ b/src/testmycode.h @@ -21,15 +21,13 @@ class TestMyCode : public ExtensionSystem::IPlugin TestMyCode(); ~TestMyCode(); - bool initialize(const QStringList &arguments, QString *errorString); - void extensionsInitialized(); - ShutdownFlag aboutToShutdown(); - -private slots: + bool initialize(const QStringList &arguments, QString *errorString) override; + void extensionsInitialized() override; + ShutdownFlag aboutToShutdown() override; private: - // tmcClient - TmcClient *tmcClient; + // m_tmcClient + TmcClient *m_tmcClient; // SettingsWidget SettingsWidget *m_settingsWidget; @@ -37,7 +35,7 @@ private slots: // TmcManager TmcManager *m_tmcManager; - void displayTMCError(QString errorText); + void displayTMCError(const QString &errorText); }; } // namespace Internal diff --git a/src/tmcmanager.cpp b/src/tmcmanager.cpp index 1185291..e99a86e 100644 --- a/src/tmcmanager.cpp +++ b/src/tmcmanager.cpp @@ -32,9 +32,10 @@ using Core::ProgressManager; using Core::FutureProgress; -TmcManager::TmcManager(TmcClient *client, QObject *parent) : - QObject(parent), - m_client(client) +TmcManager::TmcManager(TmcClient *client, QObject *parent) + : QObject(parent) + , m_client(client) + , m_settings(nullptr) { m_updateTimer.setSingleShot(false); connect(&m_updateTimer, &QTimer::timeout, this, [this]() { updateExercises(); }); @@ -59,6 +60,7 @@ TmcManager::TmcManager(TmcClient *client, QObject *parent) : this, &TmcManager::onStartupProjectChanged); // TmcClient + connect(m_client, &TmcClient::exerciseListReady, this, &TmcManager::handleUpdates); connect(m_client, &TmcClient::exerciseZipReady, this, &TmcManager::handleZip); connect(m_client, &TmcClient::TMCError, this, &TmcManager::displayTMCError); @@ -71,9 +73,6 @@ TmcManager::~TmcManager() { if (m_updateProgress.isRunning()) m_updateProgress.reportFinished(); - - if (m_downloadProgress.isRunning()) - m_downloadProgress.reportFinished(); } /*! @@ -114,7 +113,7 @@ Exercise TmcManager::getProjectExercise(ProjectExplorer::Project *project) QMap exercises = m_settings->getActiveCourse()->getExercises(); Exercise projectExercise; - foreach (const Exercise &ex, exercises) { + for (const Exercise &ex : exercises) { QStringList parts = ex.getName().split("-"); QString exerciseName = parts.last(); if (exerciseName == projectName) { @@ -160,8 +159,8 @@ void TmcManager::askSubmit(const ProjectExplorer::Project *project) return; int ret = QMessageBox::question(m_settings, - tr("Submit exercise to server"), - tr("All tests passed!\nSubmit exercise to server?")); + tr("Submit exercise to server"), + tr("All tests passed!\nSubmit exercise to server?")); if (ret == QMessageBox::Yes) { showSubmitWidget(project); @@ -265,18 +264,21 @@ void TmcManager::onExerciseOpen(const Exercise &ex) */ void TmcManager::updateExercises() { - Course* activeCourse = m_settings->getActiveCourse(); + Course *activeCourse = m_settings->getActiveCourse(); if (!activeCourse || !(*activeCourse)) { m_settings->display(); return; } qDebug() << "Updating exercises for course" << activeCourse->getName(); + m_updateProgress.setProgressRange(0, activeCourse->getExercises().size()); + ProgressManager::addTask(m_updateProgress.future(), tr("Updating TestMyCode exercises"), TestMyCodePlugin::Constants::TASK_INDEX); m_updateProgress.reportStarted(); + m_client->getExerciseList(activeCourse); } @@ -287,12 +289,16 @@ void TmcManager::updateExercises() void TmcManager::setUpdateInterval(int interval) { // Interval in minutes + m_updateTimer.stop(); + if (m_updateProgress.isRunning()) + m_updateProgress.reportFinished(); + m_updateTimer.setInterval(interval * 60000); if (m_updateTimer.interval() > 0) m_updateTimer.start(); } -void TmcManager::displayTMCError(QString errorText) +void TmcManager::displayTMCError(const QString &errorText) { QMessageBox::critical(m_settings, "TMC", errorText, QMessageBox::Ok); } diff --git a/src/tmcmanager.h b/src/tmcmanager.h index c6f6f8a..06d1c27 100644 --- a/src/tmcmanager.h +++ b/src/tmcmanager.h @@ -40,10 +40,8 @@ class TmcManager : public QObject void setSettings(SettingsWidget *settings); void loadSettings(); -signals: - -public slots: - void displayTMCError(QString errorText); +public Q_SLOTS: + void displayTMCError(const QString &errorText); void onStartupProjectChanged(Project *project); Exercise getProjectExercise(Project *project); @@ -56,11 +54,10 @@ public slots: void handleUpdates(Course *updatedCourse, QList newExercises); -private slots: +private Q_SLOTS: void handleZip(QByteArray zipData, Exercise ex); private: - TmcClient *m_client; SettingsWidget *m_settings; diff --git a/src/tmcoutputpane.cpp b/src/tmcoutputpane.cpp index 98d7a7c..ce14d37 100644 --- a/src/tmcoutputpane.cpp +++ b/src/tmcoutputpane.cpp @@ -41,7 +41,7 @@ TmcListView::TmcListView(QWidget *parent) void TmcListView::keyPressEvent(QKeyEvent *event) { if (event->matches(QKeySequence::Copy)) { - emit copyShortcutTriggered(); + Q_EMIT copyShortcutTriggered(); event->accept(); } ListView::keyPressEvent(event); diff --git a/src/tmcoutputpane.h b/src/tmcoutputpane.h index e5c88fb..d5a684d 100644 --- a/src/tmcoutputpane.h +++ b/src/tmcoutputpane.h @@ -28,11 +28,11 @@ class TmcListView : public Utils::ListView public: explicit TmcListView(QWidget *parent = nullptr); -signals: +Q_SIGNALS: void copyShortcutTriggered(); protected: - void keyPressEvent(QKeyEvent *event); + void keyPressEvent(QKeyEvent *event) override; }; @@ -64,7 +64,7 @@ class TmcOutputPane : public Core::IOutputPane void onCustomContextMenuRequested(const QPoint &pos); void onCopyItemTriggered(const TmcTestResult &result); -public slots: +public Q_SLOTS: void onTestRunFinished(); private: diff --git a/src/tmcresultmodel.cpp b/src/tmcresultmodel.cpp index 99a839b..34c9e59 100644 --- a/src/tmcresultmodel.cpp +++ b/src/tmcresultmodel.cpp @@ -2,11 +2,11 @@ #include "tmctestresult.h" #include -#include +#include -TmcResultModel::TmcResultModel(QObject *parent) : QAbstractListModel(parent) +TmcResultModel::TmcResultModel(QObject *parent) + : QAbstractListModel(parent) { - } TmcTestResult TmcResultModel::testResult(const QModelIndex &idx) const diff --git a/src/tmcresultreader.cpp b/src/tmcresultreader.cpp index e5de972..80468f5 100644 --- a/src/tmcresultreader.cpp +++ b/src/tmcresultreader.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include using namespace Autotest::Internal; @@ -44,7 +44,7 @@ void TmcResultReader::testProject(Project *project) TestTreeModel *model = TestTreeModel::instance(); runner->setSelectedTests(model->getAllTestCases()); runner->prepareToRunTests(TestRunMode::Run); - emit testRunStarted(); + Q_EMIT testRunStarted(); } void TmcResultReader::readTestResult(const TestResultPtr &result) { @@ -59,7 +59,7 @@ void TmcResultReader::readTestResult(const TestResultPtr &result) { // Start a new result m_openResult = TmcTestResult(); // Emit start of test cases ? - // emit testResultReady(TmcTestResult(TmcResult::TestCaseStart)); + // Q_EMIT testResultReady(TmcTestResult(TmcResult::TestCaseStart)); break; case Result::Pass: @@ -88,10 +88,10 @@ void TmcResultReader::readTestResult(const TestResultPtr &result) { // TestCase results have ended, lets see if we have the name and points if (!(m_openResult.name().isEmpty() && m_openResult.points().isEmpty())) { m_testResults.append(m_openResult); - emit testResultReady(m_openResult); + Q_EMIT testResultReady(m_openResult); } // Emit end ? - // emit testResultReady(TmcTestResult(TmcResult::TestCaseEnd)); + // Q_EMIT testResultReady(TmcTestResult(TmcResult::TestCaseEnd)); break; case Result::MessageFatal: @@ -99,7 +99,7 @@ void TmcResultReader::readTestResult(const TestResultPtr &result) { m_openResult.setResult(TmcResult::Invalid); m_openResult.setMessage("Test runner failed to run. It may have crashed or failed to build."); m_testResults.append(m_openResult); - emit testResultReady(m_openResult); + Q_EMIT testResultReady(m_openResult); break; default: @@ -114,7 +114,7 @@ void TmcResultReader::resultsReady() { return; } - emit testRunFinished(); + Q_EMIT testRunFinished(); auto not_passing = std::find_if(m_testResults.begin(), m_testResults.end(), [](TmcTestResult r) { return r.result() != TmcResult::Pass; }); @@ -122,7 +122,7 @@ void TmcResultReader::resultsReady() { if (testsPassed) { qDebug("Project tests passed"); - emit projectTestsPassed(m_project); + Q_EMIT projectTestsPassed(m_project); } } diff --git a/src/tmcresultreader.h b/src/tmcresultreader.h index 632bc93..40ec8b7 100644 --- a/src/tmcresultreader.h +++ b/src/tmcresultreader.h @@ -23,13 +23,13 @@ class TmcResultReader : public QObject static TmcResultReader* instance(); void testProject(Project *project); -signals: +Q_SIGNALS: void testRunStarted(); void testResultReady(const TmcTestResult &result); void testRunFinished(); void projectTestsPassed(Project *passedProject); -public slots: +public Q_SLOTS: void readTestResult(const TestResultPtr &result); void resultsReady(); diff --git a/src/tmctestresult.cpp b/src/tmctestresult.cpp index f0d20a3..4234fde 100644 --- a/src/tmctestresult.cpp +++ b/src/tmctestresult.cpp @@ -17,7 +17,7 @@ QString TmcTestResult::toString() const switch (m_result) { case TmcResult::Pass: { QString points = QString(" "); - foreach (QString point, m_points) { + for (const QString &point : m_points) { points.append(QString("[ %1 ]").arg(point)); } return QString("[%1]: PASSED, points awarded: %2").arg(m_name, points); diff --git a/src/ui/exercisewidget.ui b/src/ui/exercisewidget.ui index 3cdf4d1..a54d925 100644 --- a/src/ui/exercisewidget.ui +++ b/src/ui/exercisewidget.ui @@ -6,8 +6,8 @@ 0 0 - 450 - 400 + 600 + 500 @@ -53,7 +53,7 @@ - Cancel + Close diff --git a/src/ziphelper.cpp b/src/ziphelper.cpp index 966ad8b..6756b3a 100644 --- a/src/ziphelper.cpp +++ b/src/ziphelper.cpp @@ -16,7 +16,7 @@ bool ZipHelper::createZip(QDir projectDir, FileNameList files, QBuffer *zipBuffe QuaZipFile zipFile(&zip); QFile inFile; - foreach(FileName file, files) { + for (const FileName &file : files) { if (!file.toFileInfo().isFile()) continue; diff --git a/test/testmycode_tests.cpp b/test/testmycode_tests.cpp index 322fa8e..4119d20 100644 --- a/test/testmycode_tests.cpp +++ b/test/testmycode_tests.cpp @@ -3,7 +3,7 @@ class TestMyCodeTest : public QObject { Q_OBJECT -private slots: +private Q_SLOTS: void initTestCase(); // called before the first test function is executed void init(); // called before each test function is executed void cleanup(); // called after every test function