From d0c96ce829e72e38d0648b0a8ec5871d09375e5f Mon Sep 17 00:00:00 2001 From: Evgeniy Alekseev Date: Fri, 5 May 2017 17:55:52 +0300 Subject: [PATCH] massive refactoring --- CONTRIBUTING.md | 31 +- sources/awdebug.cpp | 91 ++- sources/awdebug.h | 2 +- .../plugin/awabstractselector.cpp | 33 +- .../plugin/awabstractselector.h | 8 +- sources/awesome-widget/plugin/awactions.cpp | 61 +- sources/awesome-widget/plugin/awactions.h | 18 +- .../awesome-widget/plugin/awbugreporter.cpp | 78 +-- sources/awesome-widget/plugin/awbugreporter.h | 20 +- .../awesome-widget/plugin/awconfighelper.cpp | 188 +++--- .../awesome-widget/plugin/awconfighelper.h | 42 +- .../plugin/awdataaggregator.cpp | 252 ++++---- .../awesome-widget/plugin/awdataaggregator.h | 39 +- .../plugin/awdataengineaggregator.cpp | 58 +- .../plugin/awdataengineaggregator.h | 10 +- .../awesome-widget/plugin/awdbusadaptor.cpp | 8 +- sources/awesome-widget/plugin/awdbusadaptor.h | 9 +- .../plugin/awformatterconfig.cpp | 22 +- .../awesome-widget/plugin/awformatterconfig.h | 8 +- .../plugin/awformatterconfigfactory.cpp | 8 +- .../plugin/awformatterconfigfactory.h | 4 +- .../plugin/awformatterhelper.cpp | 87 +-- .../awesome-widget/plugin/awformatterhelper.h | 12 +- sources/awesome-widget/plugin/awkeycache.cpp | 101 ++-- sources/awesome-widget/plugin/awkeycache.h | 8 +- .../awesome-widget/plugin/awkeyoperations.cpp | 219 ++++--- .../awesome-widget/plugin/awkeyoperations.h | 18 +- sources/awesome-widget/plugin/awkeys.cpp | 225 ++++--- sources/awesome-widget/plugin/awkeys.h | 41 +- .../plugin/awkeysaggregator.cpp | 568 +++++++++--------- .../awesome-widget/plugin/awkeysaggregator.h | 26 +- .../plugin/awpatternfunctions.cpp | 177 +++--- .../plugin/awpatternfunctions.h | 28 +- .../plugin/awtelemetryhandler.cpp | 90 +-- .../plugin/awtelemetryhandler.h | 24 +- .../awesome-widget/plugin/awupdatehelper.cpp | 77 ++- .../awesome-widget/plugin/awupdatehelper.h | 16 +- sources/awesomewidgets/abstractextitem.cpp | 51 +- sources/awesomewidgets/abstractextitem.h | 32 +- .../abstractextitemaggregator.cpp | 32 +- .../abstractextitemaggregator.h | 4 +- .../awesomewidgets/abstractweatherprovider.h | 12 +- .../awesomewidgets/awabstractformatter.cpp | 40 +- sources/awesomewidgets/awabstractformatter.h | 8 +- .../awesomewidgets/awdatetimeformatter.cpp | 26 +- sources/awesomewidgets/awdatetimeformatter.h | 8 +- sources/awesomewidgets/awfloatformatter.cpp | 48 +- sources/awesomewidgets/awfloatformatter.h | 6 +- sources/awesomewidgets/awjsonformatter.cpp | 53 +- sources/awesomewidgets/awjsonformatter.h | 13 +- sources/awesomewidgets/awlistformatter.cpp | 29 +- sources/awesomewidgets/awlistformatter.h | 10 +- sources/awesomewidgets/awnoformatter.cpp | 12 +- sources/awesomewidgets/awnoformatter.h | 5 +- sources/awesomewidgets/awscriptformatter.cpp | 39 +- sources/awesomewidgets/awscriptformatter.h | 8 +- sources/awesomewidgets/awstringformatter.cpp | 30 +- sources/awesomewidgets/awstringformatter.h | 6 +- sources/awesomewidgets/extitemaggregator.h | 9 +- sources/awesomewidgets/extnetworkrequest.cpp | 32 +- sources/awesomewidgets/extnetworkrequest.h | 13 +- sources/awesomewidgets/extquotes.cpp | 110 ++-- sources/awesomewidgets/extquotes.h | 12 +- sources/awesomewidgets/extscript.cpp | 75 ++- sources/awesomewidgets/extscript.h | 24 +- sources/awesomewidgets/extupgrade.cpp | 34 +- sources/awesomewidgets/extupgrade.h | 16 +- sources/awesomewidgets/extweather.cpp | 75 ++- sources/awesomewidgets/extweather.h | 26 +- sources/awesomewidgets/graphicalitem.cpp | 118 ++-- sources/awesomewidgets/graphicalitem.h | 44 +- .../awesomewidgets/graphicalitemhelper.cpp | 122 ++-- sources/awesomewidgets/graphicalitemhelper.h | 26 +- sources/awesomewidgets/owmweatherprovider.cpp | 43 +- sources/awesomewidgets/owmweatherprovider.h | 8 +- sources/awesomewidgets/qcronscheduler.cpp | 48 +- sources/awesomewidgets/qcronscheduler.h | 10 +- .../awesomewidgets/yahooweatherprovider.cpp | 74 ++- sources/awesomewidgets/yahooweatherprovider.h | 12 +- sources/desktop-panel/plugin/dpadds.cpp | 159 ++--- sources/desktop-panel/plugin/dpadds.h | 39 +- sources/extsysmon/extsysmon.cpp | 119 ++-- sources/extsysmon/extsysmon.h | 8 +- sources/extsysmon/extsysmonaggregator.cpp | 52 +- sources/extsysmon/extsysmonaggregator.h | 12 +- .../abstractextsysmonsource.h | 14 +- sources/extsysmonsources/batterysource.cpp | 65 +- sources/extsysmonsources/batterysource.h | 6 +- sources/extsysmonsources/customsource.cpp | 36 +- sources/extsysmonsources/customsource.h | 6 +- sources/extsysmonsources/desktopsource.cpp | 78 +-- sources/extsysmonsources/desktopsource.h | 6 +- sources/extsysmonsources/gpuloadsource.cpp | 77 ++- sources/extsysmonsources/gpuloadsource.h | 6 +- sources/extsysmonsources/gputempsource.cpp | 86 +-- sources/extsysmonsources/gputempsource.h | 7 +- sources/extsysmonsources/hddtempsource.cpp | 68 +-- sources/extsysmonsources/hddtempsource.h | 8 +- sources/extsysmonsources/loadsource.cpp | 34 +- sources/extsysmonsources/loadsource.h | 6 +- sources/extsysmonsources/networksource.cpp | 32 +- sources/extsysmonsources/networksource.h | 6 +- sources/extsysmonsources/playersource.cpp | 341 +++++------ sources/extsysmonsources/playersource.h | 20 +- sources/extsysmonsources/processessource.cpp | 75 ++- sources/extsysmonsources/processessource.h | 6 +- sources/extsysmonsources/quotessource.cpp | 181 +++--- sources/extsysmonsources/quotessource.h | 6 +- sources/extsysmonsources/requestsource.cpp | 42 +- sources/extsysmonsources/requestsource.h | 6 +- sources/extsysmonsources/upgradesource.cpp | 37 +- sources/extsysmonsources/upgradesource.h | 6 +- sources/extsysmonsources/weathersource.cpp | 131 ++-- sources/extsysmonsources/weathersource.h | 6 +- sources/test/awtestlibrary.cpp | 22 +- sources/test/awtestlibrary.h | 8 +- sources/test/testabstractextitem.cpp | 2 +- sources/test/testabstractformatter.cpp | 4 +- sources/test/testawkeys.cpp | 61 +- sources/test/testawpatternfunctions.cpp | 15 +- sources/test/testawtelemetryhandler.cpp | 4 +- sources/test/testawtelemetryhandler.h | 5 +- sources/test/testbatterysource.cpp | 2 +- sources/test/testbatterysource.h | 2 +- sources/test/testdatetimeformatter.cpp | 7 +- sources/test/testdesktopsource.cpp | 10 +- sources/test/testdpplugin.cpp | 12 +- sources/test/testdpplugin.h | 2 +- sources/test/testextitemaggregator.h | 2 +- sources/test/testextquotes.cpp | 2 +- sources/test/testextquotes.h | 7 +- sources/test/testextscript.cpp | 19 +- sources/test/testextupgrade.cpp | 23 +- sources/test/testextweather.cpp | 31 +- sources/test/testextweather.h | 4 +- sources/test/testfloatformatter.cpp | 10 +- sources/test/testgpuloadsource.cpp | 2 +- sources/test/testgpuloadsource.h | 2 +- sources/test/testgputempsource.cpp | 5 +- sources/test/testgputempsource.h | 2 +- sources/test/testhddtempsource.cpp | 13 +- sources/test/testhddtempsource.h | 4 +- sources/test/testjsonformatter.cpp | 2 +- sources/test/testlistformatter.cpp | 4 +- sources/test/testnetworksource.h | 2 +- sources/test/testnoformatter.cpp | 2 +- sources/test/testplayersource.cpp | 48 +- sources/test/testplayersource.h | 4 +- sources/test/testprocessessource.cpp | 7 +- sources/test/testscriptformatter.cpp | 2 +- sources/test/testscriptformatter.h | 2 +- sources/test/teststringformatter.cpp | 8 +- 152 files changed, 3041 insertions(+), 3219 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 982ae08..67bf515 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,32 +37,17 @@ for more details. To avoid manual labor there is automatic cmake target named * `Q_PROPERTY` macro is allowed and recommended for QObject based classes. * Qt macros (e.g. `signals`, `slots`, `Q_OBJECT`, etc) are allowed. In other hand -`Q_FOREACH` (`foreach`) is not allowed use `for (auto foo : bar)` instead. +`Q_FOREACH` (`foreach`) is not allowed use `for (auto &foo : bar)` instead. * Current project standard is **C++11**. * Do not use C-like code: - * C-like style iteration if possible. Use `for (auto foo : bar)` and + * C-like style iteration if possible. Use `for (auto &foo : bar)` and `std::for_each` instead if possible. It is also recommended to use iterators. * C-like casts, use `const_cast`, `static_cast`, `dymanic_Cast` instead. Using of `reinterpret_cast` is not recommended. It is highly recommended to use `dynamic_cast` with the exception catching. It is also possible to use - `qvariant_cast` if required. Exception is class constructors, e.g.: - - ``` - char c = 'c'; - std::string s = "string"; - qDebug() << QString("some string") << QChar(c) << QString(s); - ``` - + `qvariant_cast` if required. * C-like `NULL`, use `nullptr` instead. * C-like constant definition, use `const vartype foo = bar` definition instead. -* It is highly recommended to avoid implicit casts. Exception `nullptr` casts to - boolean, e.g.: - - ``` - if (nullptr) - qDebug() << "nullptr is true, wtf"; - ``` - * Abstract classes (which have at least one pure virtual method) are allowed. * Templates are allowed and recommended. Templates usually should be described inside header not source code file. @@ -93,6 +78,7 @@ for more details. To avoid manual labor there is automatic cmake target named * Any global pointer should be assign to `nullptr` after deletion and before initialization. Exception: if object is deleted into class destructor. * Do not use semicolon in qml files unless it is required. +* Any method argument including class constructors should start with `_`. Comments -------- @@ -178,8 +164,7 @@ Testing 1. `-DCMAKE_BUILD_TYPE=Debug`. 2. `-DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON`. 3. `-DCMAKE_BUILD_TYPE=Release`. -* It is recommended to create addition test if possible. -* Addition test functions should be declated and used only inside `BUILD_TESTING` +* Additional test functions should be declated and used only inside `BUILD_TESTING` definition. Tools @@ -210,9 +195,9 @@ Tools * Recommended class constructor for QObject based classes: ``` - FooClass::FooClass(QObject *parent, const QVariant var) - : QObject(parent) - , m_var(var) + FooClass::FooClass(QObject *_parent, const QVariant _var) + : QObject(_parent) + , m_var(_var) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; // some code below if any diff --git a/sources/awdebug.cpp b/sources/awdebug.cpp index bbe0166..84c14ba 100644 --- a/sources/awdebug.cpp +++ b/sources/awdebug.cpp @@ -33,73 +33,70 @@ Q_LOGGING_CATEGORY(LOG_LIB, "org.kde.plasma.awesomewidgets", QtMsgType::QtWarningMsg) -QString AWDebug::getAboutText(const QString type) +QString AWDebug::getAboutText(const QString &_type) { QString text; - if (type == QString("header")) { - text = QString(NAME); - } else if (type == QString("version")) { - text = i18n("Version %1 (build date %2)", QString(VERSION), - QString(BUILD_DATE)); + if (_type == "header") { + text = NAME; + } else if (_type == "version") { + text = i18n("Version %1 (build date %2)", VERSION, BUILD_DATE); if (!QString(COMMIT_SHA).isEmpty()) - text += QString(" (%1)").arg(QString(COMMIT_SHA)); - } else if (type == QString("description")) { + text += QString(" (%1)").arg(COMMIT_SHA); + } else if (_type == "description") { text = i18n("A set of minimalistic plasmoid widgets"); - } else if (type == QString("links")) { - text = i18n("Links:") + QString(""; + } else if (_type == "copy") { text = QString("© %1 %3
") - .arg(QString(DATE)) - .arg(QString(EMAIL)) - .arg(QString(AUTHOR)) - + i18n("This software is licensed under %1", QString(LICENSE)) - + QString("
"); - } else if (type == QString("translators")) { - QStringList translatorList = QString(TRANSLATORS).split(QChar(',')); + .arg(DATE) + .arg(EMAIL) + .arg(AUTHOR) + + i18n("This software is licensed under %1", LICENSE) + + ""; + } else if (_type == "translators") { + QStringList translatorList = QString(TRANSLATORS).split(','); for (auto &translator : translatorList) translator = QString("
  • %1
  • ").arg(translator); - text = i18n("Translators:") + QString(""); - } else if (type == QString("3rdparty")) { + text + = i18n("Translators:") + ""; + } else if (_type == "3rdparty") { QStringList trdPartyList - = QString(TRDPARTY_LICENSE) - .split(QChar(';'), QString::SkipEmptyParts); + = QString(TRDPARTY_LICENSE).split(';', QString::SkipEmptyParts); for (int i = 0; i < trdPartyList.count(); i++) trdPartyList[i] = QString("
  • %1 (%2 license)
  • ") - .arg(trdPartyList.at(i).split(QChar(','))[0]) - .arg(trdPartyList.at(i).split(QChar(','))[1]) - .arg(trdPartyList.at(i).split(QChar(','))[2]); - text = i18n("This software uses:") + QString(""); - } else if (type == QString("thanks")) { - QStringList thanks = QString(SPECIAL_THANKS) - .split(QChar(';'), QString::SkipEmptyParts); + .arg(trdPartyList.at(i).split(',')[0]) + .arg(trdPartyList.at(i).split(',')[1]) + .arg(trdPartyList.at(i).split(',')[2]); + text = i18n("This software uses:") + ""; + } else if (_type == "thanks") { + QStringList thanks + = QString(SPECIAL_THANKS).split(';', QString::SkipEmptyParts); for (int i = 0; i < thanks.count(); i++) thanks[i] = QString("
  • %1
  • ") - .arg(thanks.at(i).split(QChar(','))[0]) - .arg(thanks.at(i).split(QChar(','))[1]); - text = i18n("Special thanks to:") + QString(""); + .arg(thanks.at(i).split(',')[0]) + .arg(thanks.at(i).split(',')[1]); + text = i18n("Special thanks to:") + ""; } return text; @@ -109,14 +106,14 @@ QString AWDebug::getAboutText(const QString type) QStringList AWDebug::getBuildData() { QStringList metadata; - metadata.append(QString("=== Awesome Widgets configuration details ===")); + metadata.append("=== Awesome Widgets configuration details ==="); // build information - metadata.append(QString("Build details:")); + metadata.append("Build details:"); metadata.append(QString(" VERSION: %1").arg(VERSION)); metadata.append(QString(" COMMIT_SHA: %1").arg(COMMIT_SHA)); metadata.append(QString(" BUILD_DATE: %1").arg(BUILD_DATE)); // configuration - metadata.append(QString("API details:")); + metadata.append("API details:"); metadata.append(QString(" AW_GRAPHITEM_API: %1").arg(AW_GRAPHITEM_API)); metadata.append(QString(" AW_EXTQUOTES_API: %1").arg(AW_EXTQUOTES_API)); metadata.append(QString(" AW_EXTSCRIPT_API: %1").arg(AW_EXTSCRIPT_API)); @@ -129,7 +126,7 @@ QStringList AWDebug::getBuildData() metadata.append(QString(" TIME_KEYS: %1").arg(TIME_KEYS)); metadata.append(QString(" STATIC_KEYS: %1").arg(STATIC_KEYS)); // cmake properties - metadata.append(QString("cmake properties:")); + metadata.append("cmake properties:"); metadata.append(QString(" CMAKE_BUILD_TYPE: %1").arg(CMAKE_BUILD_TYPE)); metadata.append( QString(" CMAKE_CXX_COMPILER: %1").arg(CMAKE_CXX_COMPILER)); @@ -149,7 +146,7 @@ QStringList AWDebug::getBuildData() metadata.append(QString(" CMAKE_SHARED_LINKER_FLAGS: %1") .arg(CMAKE_SHARED_LINKER_FLAGS)); // components - metadata.append(QString("Components data:")); + metadata.append("Components data:"); metadata.append(QString(" BUILD_PLASMOIDS: %1").arg(BUILD_PLASMOIDS)); metadata.append( QString(" BUILD_DEB_PACKAGE: %1").arg(BUILD_DEB_PACKAGE)); diff --git a/sources/awdebug.h b/sources/awdebug.h index f24dab0..8447c65 100644 --- a/sources/awdebug.h +++ b/sources/awdebug.h @@ -31,7 +31,7 @@ const char LOG_FORMAT[] = "[%{time " "fatal}FF%{endif}][%{category}][%{function}] " "%{message}"; -QString getAboutText(const QString type); +QString getAboutText(const QString &_type); QStringList getBuildData(); } diff --git a/sources/awesome-widget/plugin/awabstractselector.cpp b/sources/awesome-widget/plugin/awabstractselector.cpp index e34cfc0..4dc3bfd 100644 --- a/sources/awesome-widget/plugin/awabstractselector.cpp +++ b/sources/awesome-widget/plugin/awabstractselector.cpp @@ -21,16 +21,16 @@ #include "awdebug.h" -AWAbstractSelector::AWAbstractSelector(QWidget *parent, - const QPair &editable) - : QWidget(parent) +AWAbstractSelector::AWAbstractSelector(QWidget *_parent, + const QPair &_editable) + : QWidget(_parent) , ui(new Ui::AWAbstractSelector) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; ui->setupUi(this); - ui->comboBox_key->setEditable(editable.first); - ui->comboBox_value->setEditable(editable.second); + ui->comboBox_key->setEditable(_editable.first); + ui->comboBox_value->setEditable(_editable.second); connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this, SIGNAL(selectionChanged())); @@ -56,25 +56,26 @@ QPair AWAbstractSelector::current() const } -void AWAbstractSelector::init(const QStringList &keys, - const QStringList &values, - const QPair ¤t) +void AWAbstractSelector::init(const QStringList &_keys, + const QStringList &_values, + const QPair &_current) { - if ((!keys.contains(current.first)) || (!values.contains(current.second))) { - qCWarning(LOG_AW) << "Invalid current value" << current + if ((!_keys.contains(_current.first)) + || (!_values.contains(_current.second))) { + qCWarning(LOG_AW) << "Invalid current value" << _current << "not found in default ones"; return; } - qCDebug(LOG_AW) << "Init selector with keys" << keys << "and values" - << values << "and current ones are" << current; + qCDebug(LOG_AW) << "Init selector with keys" << _keys << "and values" + << _values << "and current ones are" << _current; // set data ui->comboBox_key->clear(); - ui->comboBox_key->addItems(keys); + ui->comboBox_key->addItems(_keys); ui->comboBox_value->clear(); - ui->comboBox_value->addItems(values); + ui->comboBox_value->addItems(_values); // set current values - ui->comboBox_key->setCurrentText(current.first); - ui->comboBox_value->setCurrentText(current.second); + ui->comboBox_key->setCurrentText(_current.first); + ui->comboBox_value->setCurrentText(_current.second); } diff --git a/sources/awesome-widget/plugin/awabstractselector.h b/sources/awesome-widget/plugin/awabstractselector.h index 4de7aa9..ef85ab8 100644 --- a/sources/awesome-widget/plugin/awabstractselector.h +++ b/sources/awesome-widget/plugin/awabstractselector.h @@ -32,13 +32,13 @@ class AWAbstractSelector : public QWidget Q_OBJECT public: - explicit AWAbstractSelector(QWidget *parent = nullptr, - const QPair &editable + explicit AWAbstractSelector(QWidget *_parent = nullptr, + const QPair &_editable = {false, false}); virtual ~AWAbstractSelector(); QPair current() const; - void init(const QStringList &keys, const QStringList &values, - const QPair ¤t); + void init(const QStringList &_keys, const QStringList &_values, + const QPair &_current); signals: void selectionChanged(); diff --git a/sources/awesome-widget/plugin/awactions.cpp b/sources/awesome-widget/plugin/awactions.cpp index eb50729..639a8e9 100644 --- a/sources/awesome-widget/plugin/awactions.cpp +++ b/sources/awesome-widget/plugin/awactions.cpp @@ -31,8 +31,8 @@ #include "awupdatehelper.h" -AWActions::AWActions(QObject *parent) - : QObject(parent) +AWActions::AWActions(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -48,24 +48,24 @@ AWActions::~AWActions() } -void AWActions::checkUpdates(const bool showAnyway) +void AWActions::checkUpdates(const bool _showAnyway) { - qCDebug(LOG_AW) << "Show anyway" << showAnyway; + qCDebug(LOG_AW) << "Show anyway" << _showAnyway; if (!m_updateHelper->checkVersion()) - m_updateHelper->checkUpdates(showAnyway); + m_updateHelper->checkUpdates(_showAnyway); } -QString AWActions::getFileContent(const QString &path) const +QString AWActions::getFileContent(const QString &_path) const { - qCDebug(LOG_AW) << "Get content from file" << path; + qCDebug(LOG_AW) << "Get content from file" << _path; - QFile inputFile(path); + QFile inputFile(_path); if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCWarning(LOG_AW) << "Could not open file as text" << inputFile.fileName(); - return QString(); + return ""; } QString output = inputFile.readAll(); @@ -81,13 +81,13 @@ bool AWActions::isDebugEnabled() const } -bool AWActions::runCmd(const QString &cmd) const +bool AWActions::runCmd(const QString &_cmd) const { - qCDebug(LOG_AW) << "Cmd" << cmd; + qCDebug(LOG_AW) << "Cmd" << _cmd; - sendNotification(QString("Info"), i18n("Run %1", cmd)); + sendNotification(QString("Info"), i18n("Run %1", _cmd)); - return QProcess::startDetached(cmd); + return QProcess::startDetached(_cmd); } @@ -105,7 +105,7 @@ void AWActions::showLegacyInfo() const msgBox->setModal(false); msgBox->setWindowTitle(i18n("Not supported")); msgBox->setText( - i18n("You are using mammoth's Qt version, try to update it first!")); + i18n("You are using mammoth's Qt version, try to update it first")); msgBox->setStandardButtons(QMessageBox::Ok); msgBox->setIcon(QMessageBox::Information); @@ -114,42 +114,43 @@ void AWActions::showLegacyInfo() const // HACK: this method uses variables from version.h -QString AWActions::getAboutText(const QString &type) const +QString AWActions::getAboutText(const QString &_type) const { - qCDebug(LOG_AW) << "Type" << type; + qCDebug(LOG_AW) << "Type" << _type; - return AWDebug::getAboutText(type); + return AWDebug::getAboutText(_type); } -QVariantMap AWActions::getFont(const QVariantMap &defaultFont) const +QVariantMap AWActions::getFont(const QVariantMap &_defaultFont) const { - qCDebug(LOG_AW) << "Default font is" << defaultFont; + qCDebug(LOG_AW) << "Default font is" << _defaultFont; QVariantMap fontMap; int ret = 0; - CFont defaultCFont = CFont(defaultFont[QString("family")].toString(), - defaultFont[QString("size")].toInt(), 400, false, - defaultFont[QString("color")].toString()); + CFont defaultCFont + = CFont(_defaultFont["family"].toString(), _defaultFont["size"].toInt(), + 400, false, _defaultFont["color"].toString()); CFont font = CFontDialog::getFont(i18n("Select font"), defaultCFont, false, false, &ret); - fontMap[QString("applied")] = ret; - fontMap[QString("color")] = font.color().name(); - fontMap[QString("family")] = font.family(); - fontMap[QString("size")] = font.pointSize(); + fontMap["applied"] = ret; + fontMap["color"] = font.color().name(); + fontMap["family"] = font.family(); + fontMap["size"] = font.pointSize(); return fontMap; } // to avoid additional object definition this method is static -void AWActions::sendNotification(const QString &eventId, const QString &message) +void AWActions::sendNotification(const QString &_eventId, + const QString &_message) { - qCDebug(LOG_AW) << "Event" << eventId << "with message" << message; + qCDebug(LOG_AW) << "Event" << _eventId << "with message" << _message; KNotification *notification = KNotification::event( - eventId, QString("Awesome Widget ::: %1").arg(eventId), message); + _eventId, QString("Awesome Widget ::: %1").arg(_eventId), _message); notification->setComponentName( - QString("plasma-applet-org.kde.plasma.awesome-widget")); + "plasma-applet-org.kde.plasma.awesome-widget"); } diff --git a/sources/awesome-widget/plugin/awactions.h b/sources/awesome-widget/plugin/awactions.h index fe1efe3..9b8937b 100644 --- a/sources/awesome-widget/plugin/awactions.h +++ b/sources/awesome-widget/plugin/awactions.h @@ -30,23 +30,21 @@ class AWActions : public QObject Q_OBJECT public: - explicit AWActions(QObject *parent = nullptr); + explicit AWActions(QObject *_parent = nullptr); virtual ~AWActions(); - Q_INVOKABLE void checkUpdates(const bool showAnyway = false); - Q_INVOKABLE QString getFileContent(const QString &path) const; + Q_INVOKABLE void checkUpdates(const bool _showAnyway = false); + Q_INVOKABLE QString getFileContent(const QString &_path) const; Q_INVOKABLE bool isDebugEnabled() const; - Q_INVOKABLE bool runCmd(const QString &cmd - = QString("/usr/bin/true")) const; + Q_INVOKABLE bool runCmd(const QString &_cmd) const; Q_INVOKABLE void showLegacyInfo() const; Q_INVOKABLE void showReadme() const; // configuration slots - Q_INVOKABLE QString getAboutText(const QString &type - = QString("header")) const; - Q_INVOKABLE QVariantMap getFont(const QVariantMap &defaultFont) const; + Q_INVOKABLE QString getAboutText(const QString &_type) const; + Q_INVOKABLE QVariantMap getFont(const QVariantMap &_defaultFont) const; public slots: - Q_INVOKABLE static void sendNotification(const QString &eventId, - const QString &message); + Q_INVOKABLE static void sendNotification(const QString &_eventId, + const QString &_message); private: AWUpdateHelper *m_updateHelper = nullptr; diff --git a/sources/awesome-widget/plugin/awbugreporter.cpp b/sources/awesome-widget/plugin/awbugreporter.cpp index 4480e78..ae4fc7b 100644 --- a/sources/awesome-widget/plugin/awbugreporter.cpp +++ b/sources/awesome-widget/plugin/awbugreporter.cpp @@ -30,8 +30,8 @@ #include "awdebug.h" -AWBugReporter::AWBugReporter(QObject *parent) - : QObject(parent) +AWBugReporter::AWBugReporter(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; } @@ -51,33 +51,33 @@ void AWBugReporter::doConnect() } -QString AWBugReporter::generateText(const QString &description, - const QString &reproduce, - const QString &expected, - const QString &logs) const +QString AWBugReporter::generateText(const QString &_description, + const QString &_reproduce, + const QString &_expected, + const QString &_logs) const { - // do not log logs here, it may have quite large size - qCDebug(LOG_AW) << "Generate text with description" << description - << "steps" << reproduce << "and expected result" - << expected; + // do not log _logs here, it may have quite large size + qCDebug(LOG_AW) << "Generate text with description" << _description + << "steps" << _reproduce << "and expected result" + << _expected; QString output; - output += QString("**Description**\n\n%1\n\n").arg(description); - output += QString("**Step to reproduce**\n\n%1\n\n").arg(reproduce); - output += QString("**Expected result**\n\n%1\n\n").arg(expected); + output += QString("**Description**\n\n%1\n\n").arg(_description); + output += QString("**Step to _reproduce**\n\n%1\n\n").arg(_reproduce); + output += QString("**Expected result**\n\n%1\n\n").arg(_expected); output += QString("**Version**\n\n%1\n\n") .arg(AWDebug::getBuildData().join(QString("\n"))); - // append logs - output += QString("**Logs**\n\n%1").arg(logs); + // append _logs + output += QString("**Logs**\n\n%1").arg(_logs); return output; } -void AWBugReporter::sendBugReport(const QString &title, const QString &body) +void AWBugReporter::sendBugReport(const QString &_title, const QString &_body) { - qCDebug(LOG_AW) << "Send bug report with title" << title << "and body" - << body; + qCDebug(LOG_AW) << "Send bug report with title" << _title << "and body" + << _body; QNetworkAccessManager *manager = new QNetworkAccessManager(nullptr); connect(manager, SIGNAL(finished(QNetworkReply *)), this, @@ -88,57 +88,57 @@ void AWBugReporter::sendBugReport(const QString &title, const QString &body) // generate payload QVariantMap payload; - payload[QString("title")] = title; - payload[QString("body")] = body; - payload[QString("labels")] = QStringList() << QString("from application"); + payload["title"] = _title; + payload["body"] = _body; + payload["labels"] = QStringList() << "from application"; // convert to QByteArray to send request QByteArray data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact); - qCInfo(LOG_AW) << "Send request with body" << data.data() << "and size" + qCInfo(LOG_AW) << "Send request with _body" << data.data() << "and size" << data.size(); manager->post(request, data); } -void AWBugReporter::issueReplyRecieved(QNetworkReply *reply) +void AWBugReporter::issueReplyRecieved(QNetworkReply *_reply) { - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); - return emit(replyReceived(0, QString())); + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); + return emit(replyReceived(0, "")); } QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); + QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error); if (error.error != QJsonParseError::NoError) { qCWarning(LOG_AW) << "Parse error" << error.errorString(); - return emit(replyReceived(0, QString())); + return emit(replyReceived(0, "")); } - reply->deleteLater(); + _reply->deleteLater(); // convert to map QVariantMap response = jsonDoc.toVariant().toMap(); - QString url = response[QString("html_url")].toString(); - int number = response[QString("number")].toInt(); + QString url = response["html_url"].toString(); + int number = response["number"].toInt(); return emit(replyReceived(number, url)); } -void AWBugReporter::showInformation(const int number, const QString &url) +void AWBugReporter::showInformation(const int _number, const QString &_url) { - qCDebug(LOG_AW) << "Created issue with number" << number << "and url" - << url; + qCDebug(LOG_AW) << "Created issue with number" << _number << "and url" + << _url; // cache url first - m_lastBugUrl = url; + m_lastBugUrl = _url; QMessageBox *msgBox = new QMessageBox(nullptr); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setModal(false); msgBox->setWindowTitle(i18n("Issue created")); - msgBox->setText(i18n("Issue %1 has been created", number)); + msgBox->setText(i18n("Issue %1 has been created", _number)); msgBox->setStandardButtons(QMessageBox::Open | QMessageBox::Close); msgBox->setIcon(QMessageBox::Information); @@ -146,10 +146,10 @@ void AWBugReporter::showInformation(const int number, const QString &url) } -void AWBugReporter::userReplyOnBugReport(QAbstractButton *button) +void AWBugReporter::userReplyOnBugReport(QAbstractButton *_button) { QMessageBox::ButtonRole ret - = static_cast(sender())->buttonRole(button); + = static_cast(sender())->buttonRole(_button); qCInfo(LOG_AW) << "User select" << ret; switch (ret) { diff --git a/sources/awesome-widget/plugin/awbugreporter.h b/sources/awesome-widget/plugin/awbugreporter.h index 0c24da2..e7bae5b 100644 --- a/sources/awesome-widget/plugin/awbugreporter.h +++ b/sources/awesome-widget/plugin/awbugreporter.h @@ -30,22 +30,22 @@ class AWBugReporter : public QObject Q_OBJECT public: - explicit AWBugReporter(QObject *parent = nullptr); + explicit AWBugReporter(QObject *_parent = nullptr); virtual ~AWBugReporter(); Q_INVOKABLE void doConnect(); - Q_INVOKABLE QString generateText(const QString &description, - const QString &reproduce, - const QString &expected, - const QString &logs) const; - Q_INVOKABLE void sendBugReport(const QString &title, const QString &body); + Q_INVOKABLE QString generateText(const QString &_description, + const QString &_reproduce, + const QString &_expected, + const QString &_logs) const; + Q_INVOKABLE void sendBugReport(const QString &_title, const QString &_body); signals: - void replyReceived(const int number, const QString &url); + void replyReceived(const int _number, const QString &_url); private slots: - void issueReplyRecieved(QNetworkReply *reply); - void showInformation(const int number, const QString &url); - void userReplyOnBugReport(QAbstractButton *button); + void issueReplyRecieved(QNetworkReply *_reply); + void showInformation(const int _number, const QString &_url); + void userReplyOnBugReport(QAbstractButton *_button); private: QString m_lastBugUrl; diff --git a/sources/awesome-widget/plugin/awconfighelper.cpp b/sources/awesome-widget/plugin/awconfighelper.cpp index e2fdf37..50592e9 100644 --- a/sources/awesome-widget/plugin/awconfighelper.cpp +++ b/sources/awesome-widget/plugin/awconfighelper.cpp @@ -27,8 +27,8 @@ #include "awdebug.h" -AWConfigHelper::AWConfigHelper(QObject *parent) - : QObject(parent) +AWConfigHelper::AWConfigHelper(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; } @@ -69,16 +69,16 @@ bool AWConfigHelper::dropCache() const } -bool AWConfigHelper::exportConfiguration(QObject *nativeConfig, - const QString &fileName) const +bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig, + const QString &_fileName) const { - qCDebug(LOG_AW) << "Selected filename" << fileName; + qCDebug(LOG_AW) << "Selected filename" << _fileName; - QSettings settings(fileName, QSettings::IniFormat); + QSettings settings(_fileName, QSettings::IniFormat); // plasmoid configuration const QQmlPropertyMap *configuration - = static_cast(nativeConfig); - settings.beginGroup(QString("plasmoid")); + = static_cast(_nativeConfig); + settings.beginGroup("plasmoid"); for (auto &key : configuration->keys()) { QVariant value = configuration->value(key); if (!value.isValid()) @@ -91,8 +91,7 @@ bool AWConfigHelper::exportConfiguration(QObject *nativeConfig, for (auto &item : m_dirs) { QStringList items = QDir(QString("%1/%2").arg(m_baseDir).arg(item)) - .entryList(QStringList() << QString("*.desktop"), - QDir::Files); + .entryList(QStringList() << "*.desktop", QDir::Files); settings.beginGroup(item); for (auto &it : items) copyExtensions(it, item, settings, false); @@ -100,17 +99,17 @@ bool AWConfigHelper::exportConfiguration(QObject *nativeConfig, } // additional files - settings.beginGroup(QString("json")); + settings.beginGroup("json"); // script filters - readFile(settings, QString("filters"), + readFile(settings, "filters", QString("%1/scripts/awesomewidgets-extscripts-filters.json") .arg(m_baseDir)); // weather icon settings - readFile(settings, QString("weathers"), + readFile(settings, "weathers", QString("%1/weather/awesomewidgets-extweather-ids.json") .arg(m_baseDir)); // formatter settings - readFile(settings, QString("formatters"), + readFile(settings, "formatters", QString("%1/formatters/formatters.ini").arg(m_baseDir)); settings.endGroup(); @@ -121,18 +120,18 @@ bool AWConfigHelper::exportConfiguration(QObject *nativeConfig, } -QVariantMap AWConfigHelper::importConfiguration(const QString &fileName, - const bool importPlasmoid, - const bool importExtensions, - const bool importAdds) const +QVariantMap AWConfigHelper::importConfiguration(const QString &_fileName, + const bool _importPlasmoid, + const bool _importExtensions, + const bool _importAdds) const { - qCDebug(LOG_AW) << "Selected filename" << fileName; + qCDebug(LOG_AW) << "Selected filename" << _fileName; QVariantMap configuration; - QSettings settings(fileName, QSettings::IniFormat); + QSettings settings(_fileName, QSettings::IniFormat); // extensions - if (importExtensions) { + if (_importExtensions) { for (auto &item : m_dirs) { settings.beginGroup(item); for (auto &it : settings.childGroups()) @@ -142,25 +141,25 @@ QVariantMap AWConfigHelper::importConfiguration(const QString &fileName, } // additional files - if (importAdds) { - settings.beginGroup(QString("json")); + if (_importAdds) { + settings.beginGroup("json"); // script filters - writeFile(settings, QString("filters"), + writeFile(settings, "filters", QString("%1/scripts/awesomewidgets-extscripts-filters.json") .arg(m_baseDir)); // weather icon settings - writeFile(settings, QString("weathers"), + writeFile(settings, "weathers", QString("%1/weather/awesomewidgets-extweather-ids.json") .arg(m_baseDir)); // formatter settings - writeFile(settings, QString("formatters"), + writeFile(settings, "formatters", QString("%1/formatters/formatters.ini").arg(m_baseDir)); settings.endGroup(); } // plasmoid configuration - if (importPlasmoid) { - settings.beginGroup(QString("plasmoid")); + if (_importPlasmoid) { + settings.beginGroup("plasmoid"); for (auto &key : settings.childKeys()) configuration[key] = settings.value(key); settings.endGroup(); @@ -172,32 +171,24 @@ QVariantMap AWConfigHelper::importConfiguration(const QString &fileName, QVariantMap AWConfigHelper::readDataEngineConfiguration() const { - QString fileName - = QStandardPaths::locate(QStandardPaths::ConfigLocation, - QString("plasma-dataengine-extsysmon.conf")); + QString fileName = QStandardPaths::locate( + QStandardPaths::ConfigLocation, "plasma-dataengine-extsysmon.conf"); qCInfo(LOG_AW) << "Configuration file" << fileName; QSettings settings(fileName, QSettings::IniFormat); QVariantMap configuration; - settings.beginGroup(QString("Configuration")); - configuration[QString("ACPIPATH")] = settings.value( - QString("ACPIPATH"), QString("/sys/class/power_supply/")); - configuration[QString("GPUDEV")] - = settings.value(QString("GPUDEV"), QString("auto")); - configuration[QString("HDDDEV")] - = settings.value(QString("HDDDEV"), QString("all")); - configuration[QString("HDDTEMPCMD")] - = settings.value(QString("HDDTEMPCMD"), QString("sudo smartctl -a")); - configuration[QString("MPDADDRESS")] - = settings.value(QString("MPDADDRESS"), QString("localhost")); - configuration[QString("MPDPORT")] - = settings.value(QString("MPDPORT"), QString("6600")); - configuration[QString("MPRIS")] - = settings.value(QString("MPRIS"), QString("auto")); - configuration[QString("PLAYER")] - = settings.value(QString("PLAYER"), QString("mpris")); - configuration[QString("PLAYERSYMBOLS")] - = settings.value(QString("PLAYERSYMBOLS"), QString("10")); + settings.beginGroup("Configuration"); + configuration["ACPIPATH"] + = settings.value("ACPIPATH", "/sys/class/power_supply/"); + configuration["GPUDEV"] = settings.value("GPUDEV", "auto"); + configuration["HDDDEV"] = settings.value("HDDDEV", "all"); + configuration["HDDTEMPCMD"] + = settings.value("HDDTEMPCMD", "sudo smartctl -a"); + configuration["MPDADDRESS"] = settings.value("MPDADDRESS", "localhost"); + configuration["MPDPORT"] = settings.value("MPDPORT", "6600"); + configuration["MPRIS"] = settings.value("MPRIS", "auto"); + configuration["PLAYER"] = settings.value("PLAYER", "mpris"); + configuration["PLAYERSYMBOLS"] = settings.value("PLAYERSYMBOLS", "10"); settings.endGroup(); qCInfo(LOG_AW) << "Configuration" << configuration; @@ -207,29 +198,26 @@ QVariantMap AWConfigHelper::readDataEngineConfiguration() const bool AWConfigHelper::writeDataEngineConfiguration( - const QVariantMap &configuration) const + const QVariantMap &_configuration) const { - qCDebug(LOG_AW) << "Configuration" << configuration; + qCDebug(LOG_AW) << "Configuration" << _configuration; - QString fileName - = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) - + QString("/plasma-dataengine-extsysmon.conf"); + QString fileName = QString("%1/plasma-dataengine-extsysmon.conf") + .arg(QStandardPaths::writableLocation( + QStandardPaths::ConfigLocation)); QSettings settings(fileName, QSettings::IniFormat); qCInfo(LOG_AW) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Configuration")); - settings.setValue(QString("ACPIPATH"), configuration[QString("ACPIPATH")]); - settings.setValue(QString("GPUDEV"), configuration[QString("GPUDEV")]); - settings.setValue(QString("HDDDEV"), configuration[QString("HDDDEV")]); - settings.setValue(QString("HDDTEMPCMD"), - configuration[QString("HDDTEMPCMD")]); - settings.setValue(QString("MPDADDRESS"), - configuration[QString("MPDADDRESS")]); - settings.setValue(QString("MPDPORT"), configuration[QString("MPDPORT")]); - settings.setValue(QString("MPRIS"), configuration[QString("MPRIS")]); - settings.setValue(QString("PLAYER"), configuration[QString("PLAYER")]); - settings.setValue(QString("PLAYERSYMBOLS"), - configuration[QString("PLAYERSYMBOLS")]); + settings.beginGroup("Configuration"); + settings.setValue("ACPIPATH", _configuration["ACPIPATH"]); + settings.setValue("GPUDEV", _configuration["GPUDEV"]); + settings.setValue("HDDDEV", _configuration["HDDDEV"]); + settings.setValue("HDDTEMPCMD", _configuration["HDDTEMPCMD"]); + settings.setValue("MPDADDRESS", _configuration["MPDADDRESS"]); + settings.setValue("MPDPORT", _configuration["MPDPORT"]); + settings.setValue("MPRIS", _configuration["MPRIS"]); + settings.setValue("PLAYER", _configuration["PLAYER"]); + settings.setValue("PLAYERSYMBOLS", _configuration["PLAYERSYMBOLS"]); settings.endGroup(); settings.sync(); @@ -238,19 +226,19 @@ bool AWConfigHelper::writeDataEngineConfiguration( } -void AWConfigHelper::copyConfigs(const QString &localDir) const +void AWConfigHelper::copyConfigs(const QString &_localDir) const { - qCDebug(LOG_AW) << "Local directory" << localDir; + qCDebug(LOG_AW) << "Local directory" << _localDir; QStringList dirs = QStandardPaths::locateAll( - QStandardPaths::GenericDataLocation, QString("awesomewidgets/configs"), + QStandardPaths::GenericDataLocation, "awesomewidgets/configs", QStandardPaths::LocateDirectory); for (auto &dir : dirs) { - if (dir == localDir) + if (dir == _localDir) continue; QStringList files = QDir(dir).entryList(QDir::Files); for (auto &source : files) { - QString destination = QString("%1/%2").arg(localDir).arg(source); + QString destination = QString("%1/%2").arg(_localDir).arg(source); bool status = QFile::copy(QString("%1/%2").arg(dir).arg(source), destination); qCInfo(LOG_AW) << "File" << source << "has been copied to" @@ -260,66 +248,66 @@ void AWConfigHelper::copyConfigs(const QString &localDir) const } -void AWConfigHelper::copyExtensions(const QString &item, const QString &type, - QSettings &settings, - const bool inverse) const +void AWConfigHelper::copyExtensions(const QString &_item, const QString &_type, + QSettings &_settings, + const bool _inverse) const { - qCDebug(LOG_AW) << "Extension" << item << "has type" << type - << "inverse copying" << inverse; + qCDebug(LOG_AW) << "Extension" << _item << "has type" << _type + << "inverse copying" << _inverse; - settings.beginGroup(item); + _settings.beginGroup(_item); QSettings itemSettings( - QString("%1/%2/%3").arg(m_baseDir).arg(type).arg(item), + QString("%1/%2/%3").arg(m_baseDir).arg(_type).arg(_item), QSettings::IniFormat); - itemSettings.beginGroup(QString("Desktop Entry")); - if (inverse) - copySettings(settings, itemSettings); + itemSettings.beginGroup("Desktop Entry"); + if (_inverse) + copySettings(_settings, itemSettings); else - copySettings(itemSettings, settings); + copySettings(itemSettings, _settings); itemSettings.endGroup(); - settings.endGroup(); + _settings.endGroup(); - if (inverse) + if (_inverse) itemSettings.sync(); } -void AWConfigHelper::copySettings(QSettings &from, QSettings &to) const +void AWConfigHelper::copySettings(QSettings &_from, QSettings &_to) const { - for (auto &key : from.childKeys()) - to.setValue(key, from.value(key)); + for (auto &key : _from.childKeys()) + _to.setValue(key, _from.value(key)); } -void AWConfigHelper::readFile(QSettings &settings, const QString &key, - const QString &fileName) const +void AWConfigHelper::readFile(QSettings &_settings, const QString &_key, + const QString &_fileName) const { - qCDebug(LOG_AW) << "Key" << key << "from file" << fileName; + qCDebug(LOG_AW) << "Key" << _key << "from file" << _fileName; - QFile file(fileName); + QFile file(_fileName); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QString text = QString::fromUtf8(file.readAll()); file.close(); - settings.setValue(key, text); + _settings.setValue(_key, text); } else { qCWarning(LOG_AW) << "Could not open" << file.fileName(); } } -void AWConfigHelper::writeFile(QSettings &settings, const QString &key, - const QString &fileName) const +void AWConfigHelper::writeFile(QSettings &_settings, const QString &_key, + const QString &_fileName) const { - qCDebug(LOG_AW) << "Key" << key << "to file" << fileName; + qCDebug(LOG_AW) << "Key" << _key << "to file" << _fileName; - if (!settings.contains(key)) + if (!_settings.contains(_key)) return; - QFile file(fileName); + QFile file(_fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out.setCodec("UTF-8"); - out << settings.value(key).toString().toUtf8(); + out << _settings.value(_key).toString().toUtf8(); out.flush(); file.close(); } else { diff --git a/sources/awesome-widget/plugin/awconfighelper.h b/sources/awesome-widget/plugin/awconfighelper.h index 62123c9..f613495 100644 --- a/sources/awesome-widget/plugin/awconfighelper.h +++ b/sources/awesome-widget/plugin/awconfighelper.h @@ -31,39 +31,41 @@ class AWConfigHelper : public QObject Q_OBJECT public: - explicit AWConfigHelper(QObject *parent = nullptr); + explicit AWConfigHelper(QObject *_parent = nullptr); virtual ~AWConfigHelper(); Q_INVOKABLE QString configurationDirectory() const; Q_INVOKABLE bool dropCache() const; - Q_INVOKABLE bool exportConfiguration(QObject *nativeConfig, - const QString &fileName) const; - Q_INVOKABLE QVariantMap importConfiguration(const QString &fileName, - const bool importPlasmoid, - const bool importExtensions, - const bool importAdds) const; + Q_INVOKABLE bool exportConfiguration(QObject *_nativeConfig, + const QString &_fileName) const; + Q_INVOKABLE QVariantMap importConfiguration(const QString &_fileName, + const bool _importPlasmoid, + const bool _importExtensions, + const bool _importAdds) const; // dataengine Q_INVOKABLE QVariantMap readDataEngineConfiguration() const; Q_INVOKABLE bool - writeDataEngineConfiguration(const QVariantMap &configuration) const; + writeDataEngineConfiguration(const QVariantMap &_configuration) const; private: // methods - void copyConfigs(const QString &localDir) const; - void copyExtensions(const QString &item, const QString &type, - QSettings &settings, const bool inverse) const; - void copySettings(QSettings &from, QSettings &to) const; - void readFile(QSettings &settings, const QString &key, - const QString &fileName) const; - void writeFile(QSettings &settings, const QString &key, - const QString &fileName) const; + void copyConfigs(const QString &_localDir) const; + void copyExtensions(const QString &_item, const QString &_type, + QSettings &_settings, const bool _inverse) const; + void copySettings(QSettings &_from, QSettings &_to) const; + void readFile(QSettings &_settings, const QString &_key, + const QString &_fileName) const; + void writeFile(QSettings &_settings, const QString &_key, + const QString &_fileName) const; // properties QString m_baseDir = QString("%1/awesomewidgets") .arg(QStandardPaths::writableLocation( QStandardPaths::GenericDataLocation)); - QStringList m_dirs = QStringList() - << QString("desktops") << QString("quotes") - << QString("scripts") << QString("upgrade") - << QString("weather") << QString("formatters"); + QStringList m_dirs = QStringList() << "desktops" + << "quotes" + << "scripts" + << "upgrade" + << "weather" + << "formatters"; }; diff --git a/sources/awesome-widget/plugin/awdataaggregator.cpp b/sources/awesome-widget/plugin/awdataaggregator.cpp index 2ef81be..86fd530 100644 --- a/sources/awesome-widget/plugin/awdataaggregator.cpp +++ b/sources/awesome-widget/plugin/awdataaggregator.cpp @@ -30,18 +30,18 @@ #include "awdebug.h" -AWDataAggregator::AWDataAggregator(QObject *parent) - : QObject(parent) +AWDataAggregator::AWDataAggregator(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; - m_boundaries[QString("cpuTooltip")] = 100.0; - m_boundaries[QString("cpuclTooltip")] = 4000.0; - m_boundaries[QString("memTooltip")] = 100.0; - m_boundaries[QString("swapTooltip")] = 100.0; - m_boundaries[QString("downkbTooltip")] = 1.0; - m_boundaries[QString("upkbTooltip")] = 1.0; - m_boundaries[QString("batTooltip")] = 100.0; + m_boundaries["cpuTooltip"] = 100.0; + m_boundaries["cpuclTooltip"] = 4000.0; + m_boundaries["memTooltip"] = 100.0; + m_boundaries["swapTooltip"] = 100.0; + m_boundaries["downkbTooltip"] = 1.0; + m_boundaries["upkbTooltip"] = 1.0; + m_boundaries["batTooltip"] = 100.0; initScene(); connect(this, SIGNAL(updateData(const QVariantHash &)), this, @@ -57,67 +57,66 @@ AWDataAggregator::~AWDataAggregator() } -QList AWDataAggregator::getData(const QString &key) const +QList AWDataAggregator::getData(const QString &_key) const { - qCDebug(LOG_AW) << "Key" << key; + qCDebug(LOG_AW) << "Key" << _key; - return m_values[QString("%1Tooltip").arg(key)]; + return m_values[QString("%1Tooltip").arg(_key)]; } -QString AWDataAggregator::htmlImage(const QPixmap &source) const +QString AWDataAggregator::htmlImage(const QPixmap &_source) const { QByteArray byteArray; QBuffer buffer(&byteArray); - source.save(&buffer, "PNG"); + _source.save(&buffer, "PNG"); return byteArray.isEmpty() - ? QString() + ? "" : QString("") .arg(QString(byteArray.toBase64())); } -void AWDataAggregator::setParameters(const QVariantMap &settings) +void AWDataAggregator::setParameters(const QVariantMap &_settings) { - qCDebug(LOG_AW) << "Settings" << settings; + qCDebug(LOG_AW) << "Settings" << _settings; // cast from QVariantMap to QVariantHash without data lost - m_configuration = qvariant_cast(settings); + m_configuration = qvariant_cast(_settings); - m_enablePopup = m_configuration[QString("notify")].toBool(); + m_enablePopup = m_configuration["notify"].toBool(); m_counts = 0; - m_counts += m_configuration[QString("cpuTooltip")].toInt(); - m_counts += m_configuration[QString("cpuclTooltip")].toInt(); - m_counts += m_configuration[QString("memTooltip")].toInt(); - m_counts += m_configuration[QString("swapTooltip")].toInt(); - m_counts += m_configuration[QString("downkbTooltip")].toInt(); - m_counts += m_configuration[QString("batTooltip")].toInt(); + m_counts += m_configuration["cpuTooltip"].toInt(); + m_counts += m_configuration["cpuclTooltip"].toInt(); + m_counts += m_configuration["memTooltip"].toInt(); + m_counts += m_configuration["swapTooltip"].toInt(); + m_counts += m_configuration["downkbTooltip"].toInt(); + m_counts += m_configuration["batTooltip"].toInt(); // resize tooltip image m_toolTipView->resize(100 * m_counts, 105); requiredKeys.clear(); - if (m_configuration[QString("cpuTooltip")].toBool()) - requiredKeys.append(QString("cpuTooltip")); - if (m_configuration[QString("cpuclTooltip")].toBool()) - requiredKeys.append(QString("cpuclTooltip")); - if (m_configuration[QString("memTooltip")].toBool()) - requiredKeys.append(QString("memTooltip")); - if (m_configuration[QString("swapTooltip")].toBool()) - requiredKeys.append(QString("swapTooltip")); - if (m_configuration[QString("downkbTooltip")].toBool()) - requiredKeys.append(QString("downkbTooltip")); - if (m_configuration[QString("upkbTooltip")].toBool()) - requiredKeys.append(QString("upkbTooltip")); - if (m_configuration[QString("batTooltip")].toBool()) - requiredKeys.append(QString("batTooltip")); + if (m_configuration["cpuTooltip"].toBool()) + requiredKeys.append("cpuTooltip"); + if (m_configuration["cpuclTooltip"].toBool()) + requiredKeys.append("cpuclTooltip"); + if (m_configuration["memTooltip"].toBool()) + requiredKeys.append("memTooltip"); + if (m_configuration["swapTooltip"].toBool()) + requiredKeys.append("swapTooltip"); + if (m_configuration["downkbTooltip"].toBool()) + requiredKeys.append("downkbTooltip"); + if (m_configuration["upkbTooltip"].toBool()) + requiredKeys.append("upkbTooltip"); + if (m_configuration["batTooltip"].toBool()) + requiredKeys.append("batTooltip"); // background m_toolTipScene->setBackgroundBrush( - m_configuration[QString("useTooltipBackground")].toBool() - ? QBrush(QColor( - m_configuration[QString("tooltipBackground")].toString())) + m_configuration["useTooltipBackground"].toBool() + ? QBrush(QColor(m_configuration["tooltipBackground"].toString())) : QBrush(Qt::NoBrush)); } @@ -136,7 +135,7 @@ QPixmap AWDataAggregator::tooltipImage() if (down) shift -= 100.0; // apply pen color - if (key != QString("batTooltip")) + if (key != "batTooltip") pen.setColor(QColor( m_configuration[QString("%1Color").arg(key)].toString())); // paint data inside frame @@ -146,19 +145,17 @@ QPixmap AWDataAggregator::tooltipImage() float y1 = -std::fabs(m_values[key].at(j)) * normY + 5.0f; float x2 = (j + 1) * normX + shift; float y2 = -std::fabs(m_values[key].at(j + 1)) * normY + 5.0f; - if (key == QString("batTooltip")) { + if (key == "batTooltip") { if (m_values[key].at(j + 1) > 0) pen.setColor( - QColor(m_configuration[QString("batTooltipColor")] - .toString())); + QColor(m_configuration["batTooltipColor"].toString())); else - pen.setColor( - QColor(m_configuration[QString("batInTooltipColor")] - .toString())); + pen.setColor(QColor( + m_configuration["batInTooltipColor"].toString())); } m_toolTipScene->addLine(x1, y1, x2, y2, pen); } - if (key == QString("downkbTooltip")) + if (key == "downkbTooltip") down = true; } @@ -166,43 +163,44 @@ QPixmap AWDataAggregator::tooltipImage() } -void AWDataAggregator::dataUpdate(const QVariantHash &values) +void AWDataAggregator::dataUpdate(const QVariantHash &_values) { // do not log these arguments - setData(values); + setData(_values); emit(toolTipPainted(htmlImage(tooltipImage()))); } -void AWDataAggregator::checkValue(const QString &source, const float value, - const float extremum) const +void AWDataAggregator::checkValue(const QString &_source, const float _value, + const float _extremum) const { - qCDebug(LOG_AW) << "Notification source" << source << "with value" << value - << "called with extremum" << extremum; + qCDebug(LOG_AW) << "Notification source" << _source << "with value" + << _value << "called with extremum" << _extremum; - if (value >= 0.0) { - if ((m_enablePopup) && (value > extremum) - && (m_values[source].last() < extremum)) - return AWActions::sendNotification(QString("event"), - notificationText(source, value)); + if (_value >= 0.0) { + if ((m_enablePopup) && (_value > _extremum) + && (m_values[_source].last() < _extremum)) + return AWActions::sendNotification( + "event", notificationText(_source, _value)); } else { - if ((m_enablePopup) && (value < extremum) - && (m_values[source].last() > extremum)) - return AWActions::sendNotification(QString("event"), - notificationText(source, value)); + if ((m_enablePopup) && (_value < _extremum) + && (m_values[_source].last() > _extremum)) + return AWActions::sendNotification( + "event", notificationText(_source, _value)); } } -void AWDataAggregator::checkValue(const QString &source, const QString ¤t, - const QString &received) const +void AWDataAggregator::checkValue(const QString &_source, + const QString &_current, + const QString &_received) const { - qCDebug(LOG_AW) << "Notification source" << source << "with current value" - << current << "and received one" << received; + qCDebug(LOG_AW) << "Notification source" << _source << "with current value" + << _current << "and received one" << _received; - if ((m_enablePopup) && (current != received) && (!received.isEmpty())) - return AWActions::sendNotification(QString("event"), - notificationText(source, received)); + if ((m_enablePopup) && (_current != _received) && (!_received.isEmpty())) + return AWActions::sendNotification( + "event", notificationText(_source, _received)); } @@ -210,7 +208,7 @@ void AWDataAggregator::initScene() { m_toolTipScene = new QGraphicsScene(nullptr); m_toolTipView = new QGraphicsView(m_toolTipScene); - m_toolTipView->setStyleSheet(QString("background: transparent")); + m_toolTipView->setStyleSheet("background: transparent"); m_toolTipView->setContentsMargins(0, 0, 0, 0); m_toolTipView->setFrameShape(QFrame::NoFrame); m_toolTipView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -218,105 +216,105 @@ void AWDataAggregator::initScene() } -QString AWDataAggregator::notificationText(const QString &source, - const float value) const +QString AWDataAggregator::notificationText(const QString &_source, + const float _value) const { - qCDebug(LOG_AW) << "Notification source" << source << "with value" << value; + qCDebug(LOG_AW) << "Notification source" << _source << "with value" + << _value; QString output; - if (source == QString("batTooltip")) - output = value > 0.0 ? i18n("AC online") : i18n("AC offline"); - else if (source == QString("cpuTooltip")) + if (_source == "batTooltip") + output = _value > 0.0 ? i18n("AC online") : i18n("AC offline"); + else if (_source == "cpuTooltip") output = i18n("High CPU load"); - else if (source == QString("memTooltip")) + else if (_source == "memTooltip") output = i18n("High memory usage"); - else if (source == QString("swapTooltip")) + else if (_source == "swapTooltip") output = i18n("Swap is used"); - else if (source == QString("gpu")) + else if (_source == "gpu") output = i18n("High GPU load"); return output; } -QString AWDataAggregator::notificationText(const QString &source, - const QString &value) const +QString AWDataAggregator::notificationText(const QString &_source, + const QString &_value) const { - qCDebug(LOG_AW) << "Notification source" << source << "with value" << value; + qCDebug(LOG_AW) << "Notification source" << _source << "with value" + << _value; QString output; - if (source == QString("netdev")) - output = i18n("Network device has been changed to %1", value); + if (_source == "netdev") + output = i18n("Network device has been changed to %1", _value); return output; } -void AWDataAggregator::setData(const QVariantHash &values) +void AWDataAggregator::setData(const QVariantHash &_values) { // do not log these arguments // battery update requires info is AC online or not - setData(values[QString("ac")].toString() - == m_configuration[QString("acOnline")], - QString("batTooltip"), values[QString("bat")].toFloat()); + setData(_values["ac"].toString() == m_configuration["acOnline"], + "batTooltip", _values["bat"].toFloat()); // usual case - setData(QString("cpuTooltip"), values[QString("cpu")].toFloat(), 90.0); - setData(QString("cpuclTooltip"), values[QString("cpucl")].toFloat()); - setData(QString("memTooltip"), values[QString("mem")].toFloat(), 80.0); - setData(QString("swapTooltip"), values[QString("swap")].toFloat(), 0.0); - setData(QString("downkbTooltip"), values[QString("downkb")].toFloat()); - setData(QString("upkbTooltip"), values[QString("upkb")].toFloat()); + setData("cpuTooltip", _values["cpu"].toFloat(), 90.0); + setData("cpuclTooltip", _values["cpucl"].toFloat()); + setData("memTooltip", _values["mem"].toFloat(), 80.0); + setData("swapTooltip", _values["swap"].toFloat(), 0.0); + setData("downkbTooltip", _values["downkb"].toFloat()); + setData("upkbTooltip", _values["upkb"].toFloat()); // additional check for network device - [this](const QString value) { - checkValue(QString("netdev"), m_currentNetworkDevice, value); + [this](const QString &value) { + checkValue("netdev", m_currentNetworkDevice, value); m_currentNetworkDevice = value; - }(values[QString("netdev")].toString()); + }(_values["netdev"].toString()); // additional check for GPU load [this](const float value) { - checkValue(QString("gpu"), value, 90.0); + checkValue("gpu", value, 90.0); m_currentGPULoad = value; - }(values[QString("gpu")].toFloat()); + }(_values["gpu"].toFloat()); } -void AWDataAggregator::setData(const QString &source, float value, - const float extremum) +void AWDataAggregator::setData(const QString &_source, float _value, + const float _extremum) { - qCDebug(LOG_AW) << "Source" << source << "to value" << value - << "with extremum" << extremum; + qCDebug(LOG_AW) << "Source" << _source << "to value" << _value + << "with extremum" << _extremum; - if (m_values[source].count() == 0) - m_values[source].append(0.0); - else if (m_values[source].count() - > m_configuration[QString("tooltipNumber")].toInt()) - m_values[source].removeFirst(); - if (std::isnan(value)) - value = 0.0; + if (m_values[_source].count() == 0) + m_values[_source].append(0.0); + else if (m_values[_source].count() + > m_configuration["tooltipNumber"].toInt()) + m_values[_source].removeFirst(); + if (std::isnan(_value)) + _value = 0.0; // notifications - checkValue(source, value, extremum); + checkValue(_source, _value, _extremum); - m_values[source].append(value); - if (source == QString("downkbTooltip")) { - QList netValues = m_values[QString("downkbTooltip")] - + m_values[QString("upkbTooltip")]; + m_values[_source].append(_value); + if (_source == "downkbTooltip") { + QList netValues + = m_values["downkbTooltip"] + m_values["upkbTooltip"]; // to avoid inf value of normY netValues << 1.0; - m_boundaries[QString("downkbTooltip")] + m_boundaries["downkbTooltip"] = 1.2f * *std::max_element(netValues.cbegin(), netValues.cend()); - m_boundaries[QString("upkbTooltip")] - = m_boundaries[QString("downkbTooltip")]; + m_boundaries["upkbTooltip"] = m_boundaries["downkbTooltip"]; } } -void AWDataAggregator::setData(const bool dontInvert, const QString &source, - float value) +void AWDataAggregator::setData(const bool _dontInvert, const QString &_source, + float _value) { - qCDebug(LOG_AW) << "Do not invert" << dontInvert << "value" << value - << "for source" << source; + qCDebug(LOG_AW) << "Do not invert" << _dontInvert << "value" << _value + << "for source" << _source; // invert values for different battery colours - value = dontInvert ? value : -value; - return setData(source, value, 0.0); + _value = _dontInvert ? _value : -_value; + return setData(_source, _value, 0.0); } diff --git a/sources/awesome-widget/plugin/awdataaggregator.h b/sources/awesome-widget/plugin/awdataaggregator.h index 373ae04..720b490 100644 --- a/sources/awesome-widget/plugin/awdataaggregator.h +++ b/sources/awesome-widget/plugin/awdataaggregator.h @@ -33,42 +33,43 @@ class AWDataAggregator : public QObject Q_OBJECT public: - explicit AWDataAggregator(QObject *parent = nullptr); + explicit AWDataAggregator(QObject *_parent = nullptr); virtual ~AWDataAggregator(); - QList getData(const QString &key) const; - QString htmlImage(const QPixmap &source) const; - void setParameters(const QVariantMap &settings); + QList getData(const QString &_key) const; + QString htmlImage(const QPixmap &_source) const; + void setParameters(const QVariantMap &_settings); QPixmap tooltipImage(); signals: - void updateData(const QVariantHash &values); - void toolTipPainted(const QString &image) const; + void updateData(const QVariantHash &_values); + void toolTipPainted(const QString &_image) const; private slots: - void dataUpdate(const QVariantHash &values); + void dataUpdate(const QVariantHash &_values); private: // ui QGraphicsScene *m_toolTipScene = nullptr; QGraphicsView *m_toolTipView = nullptr; - void checkValue(const QString &source, const float value, - const float extremum) const; - void checkValue(const QString &source, const QString ¤t, - const QString &received) const; + void checkValue(const QString &_source, const float _value, + const float _extremum) const; + void checkValue(const QString &_source, const QString &_current, + const QString &_received) const; void initScene(); - QString notificationText(const QString &source, const float value) const; - QString notificationText(const QString &source, const QString &value) const; + QString notificationText(const QString &_source, const float _value) const; + QString notificationText(const QString &_source, + const QString &_value) const; // main method - void setData(const QVariantHash &values); - void setData(const QString &source, float value, - const float extremum = -1.0f); + void setData(const QVariantHash &_values); + void setData(const QString &_source, float _value, + const float _extremum = -1.0f); // different signature for battery device - void setData(const bool dontInvert, const QString &source, float value); + void setData(const bool _dontInvert, const QString &_source, float _value); // variables int m_counts = 0; QVariantHash m_configuration; - float m_currentGPULoad = 0.0; - QString m_currentNetworkDevice = QString("lo"); + float m_currentGPULoad = 0.0f; + QString m_currentNetworkDevice = "lo"; QHash m_boundaries; QHash> m_values; bool m_enablePopup = false; diff --git a/sources/awesome-widget/plugin/awdataengineaggregator.cpp b/sources/awesome-widget/plugin/awdataengineaggregator.cpp index 92fdd41..b2c69ff 100644 --- a/sources/awesome-widget/plugin/awdataengineaggregator.cpp +++ b/sources/awesome-widget/plugin/awdataengineaggregator.cpp @@ -23,8 +23,8 @@ #include "awkeys.h" -AWDataEngineAggregator::AWDataEngineAggregator(QObject *parent) - : QObject(parent) +AWDataEngineAggregator::AWDataEngineAggregator(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -52,57 +52,51 @@ void AWDataEngineAggregator::clear() void AWDataEngineAggregator::disconnectSources() { - for (auto &dataengine : m_dataEngines.values()) + for (auto dataengine : m_dataEngines.values()) for (auto &source : dataengine->sources()) dataengine->disconnectSource(source, parent()); } -void AWDataEngineAggregator::initDataEngines(const int interval) +void AWDataEngineAggregator::initDataEngines(const int _interval) { - qCDebug(LOG_AW) << "Init dataengines with interval" << interval; + qCDebug(LOG_AW) << "Init dataengines with interval" << _interval; m_consumer = new Plasma::DataEngineConsumer(); - m_dataEngines[QString("systemmonitor")] - = m_consumer->dataEngine(QString("systemmonitor")); - m_dataEngines[QString("extsysmon")] - = m_consumer->dataEngine(QString("extsysmon")); - m_dataEngines[QString("time")] = m_consumer->dataEngine(QString("time")); + m_dataEngines["systemmonitor"] = m_consumer->dataEngine("systemmonitor"); + m_dataEngines["extsysmon"] = m_consumer->dataEngine("extsysmon"); + m_dataEngines["time"] = m_consumer->dataEngine("time"); // additional method required by systemmonitor structure - connect(m_dataEngines[QString("systemmonitor")], - &Plasma::DataEngine::sourceAdded, - [this, interval](const QString source) { + connect(m_dataEngines["systemmonitor"], &Plasma::DataEngine::sourceAdded, + [this, _interval](const QString source) { emit(deviceAdded(source)); - m_dataEngines[QString("systemmonitor")]->connectSource( - source, parent(), interval); + m_dataEngines["systemmonitor"]->connectSource(source, parent(), + _interval); }); - return reconnectSources(interval); + return reconnectSources(_interval); } -void AWDataEngineAggregator::dropSource(const QString &source) +void AWDataEngineAggregator::dropSource(const QString &_source) { - qCDebug(LOG_AW) << "Source" << source; + qCDebug(LOG_AW) << "Source" << _source; // HACK there is no possibility to check to which dataengine source // connected we will try to disconnect it from systemmonitor and extsysmon - m_dataEngines[QString("systemmonitor")]->disconnectSource(source, parent()); - m_dataEngines[QString("extsysmon")]->disconnectSource(source, parent()); - m_dataEngines[QString("time")]->disconnectSource(source, parent()); + for (auto dataengine : m_dataEngines.values()) + dataengine->disconnectSource(_source, parent()); } -void AWDataEngineAggregator::reconnectSources(const int interval) +void AWDataEngineAggregator::reconnectSources(const int _interval) { - qCDebug(LOG_AW) << "Reconnect sources with interval" << interval; + qCDebug(LOG_AW) << "Reconnect sources with interval" << _interval; - m_dataEngines[QString("systemmonitor")]->connectAllSources(parent(), - interval); - m_dataEngines[QString("extsysmon")]->connectAllSources(parent(), interval); - m_dataEngines[QString("time")]->connectSource(QString("Local"), parent(), - 1000); + m_dataEngines["systemmonitor"]->connectAllSources(parent(), _interval); + m_dataEngines["extsysmon"]->connectAllSources(parent(), _interval); + m_dataEngines["time"]->connectSource("Local", parent(), 1000); #ifdef BUILD_FUTURE createQueuedConnection(); @@ -116,11 +110,9 @@ void AWDataEngineAggregator::createQueuedConnection() // for more details refer to plasma-framework source code for (auto &dataEngine : m_dataEngines.keys()) { // different source set for different engines - QStringList sources; - if (dataEngine == QString("time")) - sources.append(QString("Local")); - else - sources = m_dataEngines[dataEngine]->sources(); + QStringList sources = dataEngine == "time" + ? QStringList() << "Local" + : m_dataEngines[dataEngine]->sources(); // reconnect sources for (auto &source : sources) { Plasma::DataContainer *container diff --git a/sources/awesome-widget/plugin/awdataengineaggregator.h b/sources/awesome-widget/plugin/awdataengineaggregator.h index 4defc43..558d3d0 100644 --- a/sources/awesome-widget/plugin/awdataengineaggregator.h +++ b/sources/awesome-widget/plugin/awdataengineaggregator.h @@ -30,18 +30,18 @@ class AWDataEngineAggregator : public QObject Q_OBJECT public: - explicit AWDataEngineAggregator(QObject *parent = nullptr); + explicit AWDataEngineAggregator(QObject *_parent = nullptr); virtual ~AWDataEngineAggregator(); void clear(); void disconnectSources(); - void initDataEngines(const int interval); + void initDataEngines(const int _interval); signals: - void deviceAdded(const QString &source); + void deviceAdded(const QString &_source); public slots: - void dropSource(const QString &source); - void reconnectSources(const int interval); + void dropSource(const QString &_source); + void reconnectSources(const int _interval); private: void createQueuedConnection(); diff --git a/sources/awesome-widget/plugin/awdbusadaptor.cpp b/sources/awesome-widget/plugin/awdbusadaptor.cpp index d422c6f..b5258b1 100644 --- a/sources/awesome-widget/plugin/awdbusadaptor.cpp +++ b/sources/awesome-widget/plugin/awdbusadaptor.cpp @@ -21,9 +21,9 @@ #include "awkeys.h" -AWDBusAdaptor::AWDBusAdaptor(AWKeys *parent) - : QDBusAbstractAdaptor(parent) - , m_plugin(parent) +AWDBusAdaptor::AWDBusAdaptor(AWKeys *_parent) + : QDBusAbstractAdaptor(_parent) + , m_plugin(_parent) { qCDebug(LOG_DBUS) << __PRETTY_FUNCTION__; } @@ -86,7 +86,7 @@ void AWDBusAdaptor::SetLogLevel(const QString &what, const QString &level, return; } - QString state = enabled ? QString("true") : QString("false"); + QString state = enabled ? "true" : "false"; QLoggingCategory::setFilterRules( QString("%1.%2=%3").arg(what).arg(level).arg(state)); } diff --git a/sources/awesome-widget/plugin/awdbusadaptor.h b/sources/awesome-widget/plugin/awdbusadaptor.h index 181d352..1cad635 100644 --- a/sources/awesome-widget/plugin/awdbusadaptor.h +++ b/sources/awesome-widget/plugin/awdbusadaptor.h @@ -32,7 +32,7 @@ class AWDBusAdaptor : public QDBusAbstractAdaptor Q_CLASSINFO("D-Bus Interface", AWDBUS_SERVICE_NAME) public: - explicit AWDBusAdaptor(AWKeys *parent = nullptr); + explicit AWDBusAdaptor(AWKeys *_parent = nullptr); virtual ~AWDBusAdaptor(); public slots: @@ -48,9 +48,10 @@ public slots: private: AWKeys *m_plugin = nullptr; - QStringList m_logLevels = QStringList() - << QString("debug") << QString("info") - << QString("warning") << QString("critical"); + QStringList m_logLevels = QStringList() << "debug" + << "info" + << "warning" + << "critical"; }; diff --git a/sources/awesome-widget/plugin/awformatterconfig.cpp b/sources/awesome-widget/plugin/awformatterconfig.cpp index 5903498..e9ed850 100644 --- a/sources/awesome-widget/plugin/awformatterconfig.cpp +++ b/sources/awesome-widget/plugin/awformatterconfig.cpp @@ -27,10 +27,10 @@ #include "awformatterhelper.h" -AWFormatterConfig::AWFormatterConfig(QWidget *parent, const QStringList &keys) - : QDialog(parent) +AWFormatterConfig::AWFormatterConfig(QWidget *_parent, const QStringList &_keys) + : QDialog(_parent) , ui(new Ui::AWFormatterConfig) - , m_keys(keys) + , m_keys(_keys) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -96,16 +96,16 @@ void AWFormatterConfig::updateUi() } -void AWFormatterConfig::addSelector(const QStringList &keys, - const QStringList &values, - const QPair ¤t) +void AWFormatterConfig::addSelector(const QStringList &_keys, + const QStringList &_values, + const QPair &_current) { - qCDebug(LOG_AW) << "Add selector with keys" << keys << "values" << values - << "and current ones" << current; + qCDebug(LOG_AW) << "Add selector with keys" << _keys << "values" << _values + << "and current ones" << _current; AWAbstractSelector *selector = new AWAbstractSelector(ui->scrollAreaWidgetContents); - selector->init(keys, values, current); + selector->init(_keys, _values, _current); ui->verticalLayout->insertWidget(ui->verticalLayout->count() - 1, selector); connect(selector, SIGNAL(selectionChanged()), this, SLOT(updateUi())); m_selectors.append(selector); @@ -158,10 +158,10 @@ void AWFormatterConfig::init() QPair AWFormatterConfig::initKeys() const { // we are adding empty string at the start - QStringList keys = QStringList() << QString(""); + QStringList keys = QStringList() << ""; keys.append(m_keys); keys.sort(); - QStringList knownFormatters = QStringList() << QString(""); + QStringList knownFormatters = QStringList() << ""; knownFormatters.append(m_helper->knownFormatters()); knownFormatters.sort(); diff --git a/sources/awesome-widget/plugin/awformatterconfig.h b/sources/awesome-widget/plugin/awformatterconfig.h index 3a66230..b0ce3df 100644 --- a/sources/awesome-widget/plugin/awformatterconfig.h +++ b/sources/awesome-widget/plugin/awformatterconfig.h @@ -34,8 +34,8 @@ class AWFormatterConfig : public QDialog Q_OBJECT public: - explicit AWFormatterConfig(QWidget *parent = nullptr, - const QStringList &keys = QStringList()); + explicit AWFormatterConfig(QWidget *_parent = nullptr, + const QStringList &_keys = QStringList()); virtual ~AWFormatterConfig(); Q_INVOKABLE void showDialog(); @@ -51,8 +51,8 @@ private: // properties QStringList m_keys; // methods - void addSelector(const QStringList &keys, const QStringList &values, - const QPair ¤t); + void addSelector(const QStringList &_keys, const QStringList &_values, + const QPair &_current); void clearSelectors(); void execDialog(); void init(); diff --git a/sources/awesome-widget/plugin/awformatterconfigfactory.cpp b/sources/awesome-widget/plugin/awformatterconfigfactory.cpp index 9afdff7..33484d1 100644 --- a/sources/awesome-widget/plugin/awformatterconfigfactory.cpp +++ b/sources/awesome-widget/plugin/awformatterconfigfactory.cpp @@ -21,8 +21,8 @@ #include "awformatterconfig.h" -AWFormatterConfigFactory::AWFormatterConfigFactory(QObject *parent) - : QObject(parent) +AWFormatterConfigFactory::AWFormatterConfigFactory(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; } @@ -34,9 +34,9 @@ AWFormatterConfigFactory::~AWFormatterConfigFactory() } -void AWFormatterConfigFactory::showDialog(const QStringList &keys) +void AWFormatterConfigFactory::showDialog(const QStringList &_keys) { - AWFormatterConfig *config = new AWFormatterConfig(nullptr, keys); + AWFormatterConfig *config = new AWFormatterConfig(nullptr, _keys); config->showDialog(); config->deleteLater(); } diff --git a/sources/awesome-widget/plugin/awformatterconfigfactory.h b/sources/awesome-widget/plugin/awformatterconfigfactory.h index 94ae3df..e4c4c69 100644 --- a/sources/awesome-widget/plugin/awformatterconfigfactory.h +++ b/sources/awesome-widget/plugin/awformatterconfigfactory.h @@ -27,9 +27,9 @@ class AWFormatterConfigFactory : public QObject Q_OBJECT public: - explicit AWFormatterConfigFactory(QObject *parent = nullptr); + explicit AWFormatterConfigFactory(QObject *_parent = nullptr); virtual ~AWFormatterConfigFactory(); - Q_INVOKABLE void showDialog(const QStringList &keys); + Q_INVOKABLE void showDialog(const QStringList &_keys); private: }; diff --git a/sources/awesome-widget/plugin/awformatterhelper.cpp b/sources/awesome-widget/plugin/awformatterhelper.cpp index 7f2a12a..29f0567 100644 --- a/sources/awesome-widget/plugin/awformatterhelper.cpp +++ b/sources/awesome-widget/plugin/awformatterhelper.cpp @@ -33,12 +33,12 @@ #include "awstringformatter.h" -AWFormatterHelper::AWFormatterHelper(QWidget *parent) - : AbstractExtItemAggregator(parent, QString("formatters")) +AWFormatterHelper::AWFormatterHelper(QWidget *_parent) + : AbstractExtItemAggregator(_parent, "formatters") { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; - m_filePath = QString("awesomewidgets/formatters/formatters.ini"); + m_filePath = "awesomewidgets/formatters/formatters.ini"; initItems(); } @@ -52,13 +52,13 @@ AWFormatterHelper::~AWFormatterHelper() } -QString AWFormatterHelper::convert(const QVariant &value, - const QString &name) const +QString AWFormatterHelper::convert(const QVariant &_value, + const QString &_name) const { - qCDebug(LOG_AW) << "Convert value" << value << "for" << name; + qCDebug(LOG_AW) << "Convert value" << _value << "for" << _name; - return m_formatters.contains(name) ? m_formatters[name]->convert(value) - : value.toString(); + return m_formatters.contains(_name) ? m_formatters[_name]->convert(_value) + : _value.toString(); } @@ -94,9 +94,9 @@ QStringList AWFormatterHelper::knownFormatters() const } -bool AWFormatterHelper::removeUnusedFormatters(const QStringList &keys) const +bool AWFormatterHelper::removeUnusedFormatters(const QStringList &_keys) const { - qCDebug(LOG_AW) << "Remove formatters" << keys; + qCDebug(LOG_AW) << "Remove formatters" << _keys; QString fileName = QString("%1/%2") .arg(QStandardPaths::writableLocation( @@ -105,10 +105,10 @@ bool AWFormatterHelper::removeUnusedFormatters(const QStringList &keys) const QSettings settings(fileName, QSettings::IniFormat); qCInfo(LOG_AW) << "Configuration file" << fileName; - settings.beginGroup(QString("Formatters")); + settings.beginGroup("Formatters"); QStringList foundKeys = settings.childKeys(); for (auto &key : foundKeys) { - if (keys.contains(key)) + if (_keys.contains(key)) continue; settings.remove(key); } @@ -121,9 +121,9 @@ bool AWFormatterHelper::removeUnusedFormatters(const QStringList &keys) const bool AWFormatterHelper::writeFormatters( - const QHash &configuration) const + const QHash &_configuration) const { - qCDebug(LOG_AW) << "Write configuration" << configuration; + qCDebug(LOG_AW) << "Write configuration" << _configuration; QString fileName = QString("%1/%2") .arg(QStandardPaths::writableLocation( @@ -132,9 +132,9 @@ bool AWFormatterHelper::writeFormatters( QSettings settings(fileName, QSettings::IniFormat); qCInfo(LOG_AW) << "Configuration file" << fileName; - settings.beginGroup(QString("Formatters")); - for (auto &key : configuration.keys()) - settings.setValue(key, configuration[key]); + settings.beginGroup("Formatters"); + for (auto &key : _configuration.keys()) + settings.setValue(key, _configuration[key]); settings.endGroup(); settings.sync(); @@ -152,28 +152,28 @@ void AWFormatterHelper::editItems() AWAbstractFormatter::FormatterClass -AWFormatterHelper::defineFormatterClass(const QString &stringType) const +AWFormatterHelper::defineFormatterClass(const QString &_stringType) const { - qCDebug(LOG_AW) << "Define formatter class for" << stringType; + qCDebug(LOG_AW) << "Define formatter class for" << _stringType; AWAbstractFormatter::FormatterClass formatter = AWAbstractFormatter::FormatterClass::NoFormat; - if (stringType == QString("DateTime")) + if (_stringType == "DateTime") formatter = AWAbstractFormatter::FormatterClass::DateTime; - else if (stringType == QString("Float")) + else if (_stringType == "Float") formatter = AWAbstractFormatter::FormatterClass::Float; - else if (stringType == QString("List")) + else if (_stringType == "List") formatter = AWAbstractFormatter::FormatterClass::List; - else if (stringType == QString("NoFormat")) + else if (_stringType == "NoFormat") ; - else if (stringType == QString("Script")) + else if (_stringType == "Script") formatter = AWAbstractFormatter::FormatterClass::Script; - else if (stringType == QString("String")) + else if (_stringType == "String") formatter = AWAbstractFormatter::FormatterClass::String; - else if (stringType == QString("Json")) + else if (_stringType == "Json") formatter = AWAbstractFormatter::FormatterClass::Json; else - qCWarning(LOG_AW) << "Unknown formatter" << stringType; + qCWarning(LOG_AW) << "Unknown formatter" << _stringType; return formatter; } @@ -187,7 +187,7 @@ void AWFormatterHelper::initFormatters() QStringList files = QDir(m_directories.at(i)).entryList(QDir::Files, QDir::Name); for (auto &file : files) { - if (!file.endsWith(QString(".desktop"))) + if (!file.endsWith(".desktop")) continue; qCInfo(LOG_AW) << "Found file" << file << "in" << m_directories.at(i); @@ -242,7 +242,7 @@ void AWFormatterHelper::initKeys() QSettings settings(fileName, QSettings::IniFormat); qCInfo(LOG_AW) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Formatters")); + settings.beginGroup("Formatters"); QStringList keys = settings.childKeys(); for (auto &key : keys) { QString name = settings.value(key).toString(); @@ -275,21 +275,20 @@ void AWFormatterHelper::installDirectories() qCInfo(LOG_AW) << "Created directory" << localDir; m_directories = QStandardPaths::locateAll( - QStandardPaths::GenericDataLocation, - QString("awesomewidgets/formatters"), QStandardPaths::LocateDirectory); + QStandardPaths::GenericDataLocation, "awesomewidgets/formatters", + QStandardPaths::LocateDirectory); } QPair -AWFormatterHelper::readMetadata(const QString &filePath) const +AWFormatterHelper::readMetadata(const QString &_filePath) const { - qCDebug(LOG_AW) << "Read initial parameters from" << filePath; + qCDebug(LOG_AW) << "Read initial parameters from" << _filePath; - QSettings settings(filePath, QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - QString name = settings.value(QString("Name"), filePath).toString(); - QString type - = settings.value(QString("X-AW-Type"), QString("NoFormat")).toString(); + QSettings settings(_filePath, QSettings::IniFormat); + settings.beginGroup("Desktop Entry"); + QString name = settings.value("Name", _filePath).toString(); + QString type = settings.value("X-AW-Type", "NoFormat").toString(); AWAbstractFormatter::FormatterClass formatter = defineFormatterClass(type); settings.endGroup(); @@ -299,11 +298,13 @@ AWFormatterHelper::readMetadata(const QString &filePath) const void AWFormatterHelper::doCreateItem() { - QStringList selection = QStringList() - << QString("NoFormat") << QString("DateTime") - << QString("Float") << QString("List") - << QString("Script") << QString("String") - << QString("Json"); + QStringList selection = QStringList() << "NoFormat" + << "DateTime" + << "Float" + << "List" + << "Script" + << "String" + << "Json"; bool ok; QString select = QInputDialog::getItem( this, i18n("Select type"), i18n("Type:"), selection, 0, false, &ok); diff --git a/sources/awesome-widget/plugin/awformatterhelper.h b/sources/awesome-widget/plugin/awformatterhelper.h index 6061ae3..577c84d 100644 --- a/sources/awesome-widget/plugin/awformatterhelper.h +++ b/sources/awesome-widget/plugin/awformatterhelper.h @@ -31,15 +31,15 @@ class AWFormatterHelper : public AbstractExtItemAggregator Q_OBJECT public: - explicit AWFormatterHelper(QWidget *parent = nullptr); + explicit AWFormatterHelper(QWidget *_parent = nullptr); virtual ~AWFormatterHelper(); - QString convert(const QVariant &value, const QString &name) const; + QString convert(const QVariant &_value, const QString &_name) const; QStringList definedFormatters() const; QHash getFormatters() const; QList items() const; QStringList knownFormatters() const; - bool removeUnusedFormatters(const QStringList &keys) const; - bool writeFormatters(const QHash &configuration) const; + bool removeUnusedFormatters(const QStringList &_keys) const; + bool writeFormatters(const QHash &_configuration) const; public slots: void editItems(); @@ -47,12 +47,12 @@ public slots: private: // methods AWAbstractFormatter::FormatterClass - defineFormatterClass(const QString &stringType) const; + defineFormatterClass(const QString &_stringType) const; void initFormatters(); void initKeys(); void installDirectories(); QPair - readMetadata(const QString &filePath) const; + readMetadata(const QString &_filePath) const; // parent methods void doCreateItem(); void initItems(); diff --git a/sources/awesome-widget/plugin/awkeycache.cpp b/sources/awesome-widget/plugin/awkeycache.cpp index b705a5d..dc91798 100644 --- a/sources/awesome-widget/plugin/awkeycache.cpp +++ b/sources/awesome-widget/plugin/awkeycache.cpp @@ -26,9 +26,9 @@ #include "awdebug.h" -bool AWKeyCache::addKeyToCache(const QString &type, const QString &key) +bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key) { - qCDebug(LOG_AW) << "Key" << key << "with type" << type; + qCDebug(LOG_AW) << "Key" << _key << "with type" << _type; QString fileName = QString("%1/awesomewidgets.ndx") .arg(QStandardPaths::writableLocation( @@ -36,45 +36,45 @@ bool AWKeyCache::addKeyToCache(const QString &type, const QString &key) qCInfo(LOG_AW) << "Cache file" << fileName; QSettings cache(fileName, QSettings::IniFormat); - cache.beginGroup(type); + cache.beginGroup(_type); QStringList cachedValues; for (auto &number : cache.allKeys()) cachedValues.append(cache.value(number).toString()); - if (type == QString("hdd")) { + if (_type == "hdd") { QStringList allDevices - = QDir(QString("/dev")).entryList(QDir::System, QDir::Name); - QStringList devices - = allDevices.filter(QRegExp(QString("^[hms]d[a-z]$"))); + = QDir("/dev").entryList(QDir::System, QDir::Name); + QStringList devices = allDevices.filter(QRegExp("^[hms]d[a-z]$")); for (auto &dev : devices) { QString device = QString("/dev/%1").arg(dev); if (cachedValues.contains(device)) continue; - qCInfo(LOG_AW) << "Found new key" << device << "for type" << type; + qCInfo(LOG_AW) << "Found new key" << device << "for type" << _type; cachedValues.append(device); cache.setValue( QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), device); } - } else if (type == QString("net")) { + } else if (_type == "net") { QList rawInterfaceList = QNetworkInterface::allInterfaces(); for (auto &interface : rawInterfaceList) { QString device = interface.name(); if (cachedValues.contains(device)) continue; - qCInfo(LOG_AW) << "Found new key" << device << "for type" << type; + qCInfo(LOG_AW) << "Found new key" << device << "for type" << _type; cachedValues.append(device); cache.setValue( QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), device); } } else { - if (cachedValues.contains(key)) + if (cachedValues.contains(_key)) return false; - qCInfo(LOG_AW) << "Found new key" << key << "for type" << type; + qCInfo(LOG_AW) << "Found new key" << _key << "for type" << _type; cache.setValue( - QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), key); + QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), + _key); } cache.endGroup(); @@ -83,86 +83,89 @@ bool AWKeyCache::addKeyToCache(const QString &type, const QString &key) } -QStringList AWKeyCache::getRequiredKeys(const QStringList &keys, - const QStringList &bars, - const QVariantMap &tooltip, - const QStringList &allKeys) +QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys, + const QStringList &_bars, + const QVariantMap &_tooltip, + const QStringList &_allKeys) { - qCDebug(LOG_AW) << "Looking for required keys in" << keys << bars - << "using tooltip settings" << tooltip; + qCDebug(LOG_AW) << "Looking for required keys in" << _keys << _bars + << "using tooltip settings" << _tooltip; // initial copy - QSet used = QSet::fromList(keys); - used.unite(QSet::fromList(bars)); + QSet used = QSet::fromList(_keys); + used.unite(QSet::fromList(_bars)); // insert keys from tooltip - for (auto &key : tooltip.keys()) { - if ((key.endsWith(QString("Tooltip"))) && (tooltip[key].toBool())) { - key.remove(QString("Tooltip")); + for (auto &key : _tooltip.keys()) { + if ((key.endsWith("Tooltip")) && (_tooltip[key].toBool())) { + key.remove("Tooltip"); used << key; } } // insert depending keys, refer to AWKeys::calculateValues() // hddtotmb* - for (auto &key : allKeys.filter(QRegExp(QString("^hddtotmb")))) { + for (auto &key : _allKeys.filter(QRegExp("^hddtotmb"))) { if (!used.contains(key)) continue; - key.remove(QString("hddtotmb")); + key.remove("hddtotmb"); int index = key.toInt(); used << QString("hddfreemb%1").arg(index) << QString("hddmb%1").arg(index); } // hddtotgb* - for (auto &key : allKeys.filter(QRegExp(QString("^hddtotgb")))) { + for (auto &key : _allKeys.filter(QRegExp("^hddtotgb"))) { if (!used.contains(key)) continue; - key.remove(QString("hddtotgb")); + key.remove("hddtotgb"); int index = key.toInt(); used << QString("hddfreegb%1").arg(index) << QString("hddgb%1").arg(index); } // mem - if (used.contains(QString("mem"))) - used << QString("memmb") << QString("memtotmb"); + if (used.contains("mem")) + used << "memmb" + << "memtotmb"; // memtotmb - if (used.contains(QString("memtotmb"))) - used << QString("memusedmb") << QString("memfreemb"); + if (used.contains("memtotmb")) + used << "memusedmb" + << "memfreemb"; // memtotgb - if (used.contains(QString("memtotgb"))) - used << QString("memusedgb") << QString("memfreegb"); + if (used.contains("memtotgb")) + used << "memusedgb" + << "memfreegb"; // swap - if (used.contains(QString("swap"))) - used << QString("swapmb") << QString("swaptotmb"); + if (used.contains("swap")) + used << "swapmb" + << "swaptotmb"; // swaptotmb - if (used.contains(QString("swaptotmb"))) - used << QString("swapmb") << QString("swapfreemb"); + if (used.contains("swaptotmb")) + used << "swapmb" + << "swapfreemb"; // memtotgb - if (used.contains(QString("swaptotgb"))) - used << QString("swapgb") << QString("swapfreegb"); + if (used.contains("swaptotgb")) + used << "swapgb" + << "swapfreegb"; // network keys - QStringList netKeys(QStringList() - << QString("up") << QString("upkb") - << QString("uptotal") << QString("uptotalkb") - << QString("upunits") << QString("down") - << QString("downkb") << QString("downtotal") - << QString("downtotalkb") << QString("downunits")); + QStringList netKeys({"up", "upkb", "uptotal", "uptotalkb", "upunits", + "down", "downkb", "downtotal", "downtotalkb", + "downunits"}); for (auto &key : netKeys) { if (!used.contains(key)) continue; QStringList filt - = allKeys.filter(QRegExp(QString("^%1[0-9]{1,}").arg(key))); + = _allKeys.filter(QRegExp(QString("^%1[0-9]{1,}").arg(key))); for (auto &filtered : filt) used << filtered; } // netdev key if (std::any_of(netKeys.cbegin(), netKeys.cend(), [&used](const QString &key) { return used.contains(key); })) - used << QString("netdev"); + used << "netdev"; // HACK append dummy if there are no other keys. This hack is required // because empty list leads to the same behaviour as skip checking if (used.isEmpty()) - used << QString("dummy"); + used << "dummy"; return used.toList(); } diff --git a/sources/awesome-widget/plugin/awkeycache.h b/sources/awesome-widget/plugin/awkeycache.h index ae5e76f..6d2077a 100644 --- a/sources/awesome-widget/plugin/awkeycache.h +++ b/sources/awesome-widget/plugin/awkeycache.h @@ -26,10 +26,10 @@ namespace AWKeyCache { -bool addKeyToCache(const QString &type, const QString &key = QString("")); -QStringList getRequiredKeys(const QStringList &keys, const QStringList &bars, - const QVariantMap &tooltip, - const QStringList &allKeys); +bool addKeyToCache(const QString &_type, const QString &_key = ""); +QStringList getRequiredKeys(const QStringList &_keys, const QStringList &_bars, + const QVariantMap &_tooltip, + const QStringList &_allKeys); QHash loadKeysFromCache(); }; diff --git a/sources/awesome-widget/plugin/awkeyoperations.cpp b/sources/awesome-widget/plugin/awkeyoperations.cpp index a14cb5d..68d4c63 100644 --- a/sources/awesome-widget/plugin/awkeyoperations.cpp +++ b/sources/awesome-widget/plugin/awkeyoperations.cpp @@ -34,8 +34,8 @@ #include "graphicalitem.h" -AWKeyOperations::AWKeyOperations(QObject *parent) - : QObject(parent) +AWKeyOperations::AWKeyOperations(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; } @@ -55,11 +55,11 @@ AWKeyOperations::~AWKeyOperations() } -QStringList AWKeyOperations::devices(const QString &type) const +QStringList AWKeyOperations::devices(const QString &_type) const { - qCDebug(LOG_AW) << "Looking for type" << type; + qCDebug(LOG_AW) << "Looking for type" << _type; - return m_devices[type]; + return m_devices[_type]; } @@ -72,8 +72,8 @@ QHash AWKeyOperations::devices() const void AWKeyOperations::updateCache() { // update network and hdd list - addKeyToCache(QString("hdd")); - addKeyToCache(QString("net")); + addKeyToCache("hdd"); + addKeyToCache("net"); } @@ -82,12 +82,12 @@ QStringList AWKeyOperations::dictKeys() const QStringList allKeys; // weather for (auto &item : m_extWeather->activeItems()) { - allKeys.append(item->tag(QString("weatherId"))); - allKeys.append(item->tag(QString("weather"))); - allKeys.append(item->tag(QString("humidity"))); - allKeys.append(item->tag(QString("pressure"))); - allKeys.append(item->tag(QString("temperature"))); - allKeys.append(item->tag(QString("timestamp"))); + allKeys.append(item->tag("weatherId")); + allKeys.append(item->tag("weather")); + allKeys.append(item->tag("humidity")); + allKeys.append(item->tag("pressure")); + allKeys.append(item->tag("temperature")); + allKeys.append(item->tag("timestamp")); } // cpuclock & cpu for (int i = 0; i < QThread::idealThreadCount(); i++) { @@ -95,10 +95,10 @@ QStringList AWKeyOperations::dictKeys() const allKeys.append(QString("cpu%1").arg(i)); } // temperature - for (int i = 0; i < m_devices[QString("temp")].count(); i++) + for (int i = 0; i < m_devices["temp"].count(); i++) allKeys.append(QString("temp%1").arg(i)); // hdd - for (int i = 0; i < m_devices[QString("mount")].count(); i++) { + for (int i = 0; i < m_devices["mount"].count(); i++) { allKeys.append(QString("hddmb%1").arg(i)); allKeys.append(QString("hddgb%1").arg(i)); allKeys.append(QString("hddfreemb%1").arg(i)); @@ -108,15 +108,15 @@ QStringList AWKeyOperations::dictKeys() const allKeys.append(QString("hdd%1").arg(i)); } // hdd speed - for (int i = 0; i < m_devices[QString("disk")].count(); i++) { + for (int i = 0; i < m_devices["disk"].count(); i++) { allKeys.append(QString("hddr%1").arg(i)); allKeys.append(QString("hddw%1").arg(i)); } // hdd temp - for (int i = 0; i < m_devices[QString("hdd")].count(); i++) + for (int i = 0; i < m_devices["hdd"].count(); i++) allKeys.append(QString("hddtemp%1").arg(i)); // network - for (int i = 0; i < m_devices[QString("net")].count(); i++) { + for (int i = 0; i < m_devices["net"].count(); i++) { allKeys.append(QString("downunits%1").arg(i)); allKeys.append(QString("upunits%1").arg(i)); allKeys.append(QString("downtotalkb%1").arg(i)); @@ -130,37 +130,37 @@ QStringList AWKeyOperations::dictKeys() const } // battery QStringList allBatteryDevices - = QDir(QString("/sys/class/power_supply")) - .entryList(QStringList() << QString("BAT*"), + = QDir("/sys/class/power_supply") + .entryList(QStringList({"BAT*"}), QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); for (int i = 0; i < allBatteryDevices.count(); i++) allKeys.append(QString("bat%1").arg(i)); // package manager for (auto &item : m_extUpgrade->activeItems()) - allKeys.append(item->tag(QString("pkgcount"))); + allKeys.append(item->tag("pkgcount")); // quotes for (auto &item : m_extQuotes->activeItems()) { - allKeys.append(item->tag(QString("ask"))); - allKeys.append(item->tag(QString("askchg"))); - allKeys.append(item->tag(QString("percaskchg"))); - allKeys.append(item->tag(QString("bid"))); - allKeys.append(item->tag(QString("bidchg"))); - allKeys.append(item->tag(QString("percbidchg"))); - allKeys.append(item->tag(QString("price"))); - allKeys.append(item->tag(QString("pricechg"))); - allKeys.append(item->tag(QString("percpricechg"))); + allKeys.append(item->tag("ask")); + allKeys.append(item->tag("askchg")); + allKeys.append(item->tag("percaskchg")); + allKeys.append(item->tag("bid")); + allKeys.append(item->tag("bidchg")); + allKeys.append(item->tag("percbidchg")); + allKeys.append(item->tag("price")); + allKeys.append(item->tag("pricechg")); + allKeys.append(item->tag("percpricechg")); } // custom for (auto &item : m_extScripts->activeItems()) - allKeys.append(item->tag(QString("custom"))); + allKeys.append(item->tag("custom")); // network requests for (auto &item : m_extNetRequest->activeItems()) - allKeys.append(item->tag(QString("response"))); + allKeys.append(item->tag("response")); // bars for (auto &item : m_graphicalItems->activeItems()) - allKeys.append(item->tag(QString("bar"))); + allKeys.append(item->tag("bar")); // static keys - allKeys.append(QString(STATIC_KEYS).split(QChar(','))); + allKeys.append(QString(STATIC_KEYS).split(',')); // sort in valid order allKeys.sort(); @@ -172,71 +172,70 @@ QStringList AWKeyOperations::dictKeys() const // this method is required to provide GraphicalItem functions (e.g. paint()) to // parent classes -GraphicalItem *AWKeyOperations::giByKey(const QString &key) const +GraphicalItem *AWKeyOperations::giByKey(const QString &_key) const { - qCDebug(LOG_AW) << "Looking for item" << key; + qCDebug(LOG_AW) << "Looking for item" << _key; - return m_graphicalItems->itemByTag(key, QString("bar")); + return m_graphicalItems->itemByTag(_key, "bar"); } -QString AWKeyOperations::infoByKey(const QString &key) const +QString AWKeyOperations::infoByKey(const QString &_key) const { - qCDebug(LOG_AW) << "Requested key" << key; + qCDebug(LOG_AW) << "Requested key" << _key; - QString stripped = key; - stripped.remove(QRegExp(QString("\\d+"))); + QString stripped = _key; + stripped.remove(QRegExp("\\d+")); QString output; - if (key.startsWith(QString("bar"))) { - AbstractExtItem *item = m_graphicalItems->itemByTag(key, stripped); + if (_key.startsWith("bar")) { + AbstractExtItem *item = m_graphicalItems->itemByTag(_key, stripped); if (item) output = item->uniq(); - } else if (key.startsWith(QString("custom"))) { - AbstractExtItem *item = m_extScripts->itemByTag(key, stripped); + } else if (_key.startsWith("custom")) { + AbstractExtItem *item = m_extScripts->itemByTag(_key, stripped); if (item) output = item->uniq(); - } else if (key.contains(QRegExp(QString("^hdd[rw]")))) { - QString index = key; + } else if (_key.contains(QRegExp("^hdd[rw]"))) { + QString index = _key; index.remove(QRegExp("hdd[rw]")); output = m_devices["disk"][index.toInt()]; - } else if (key.contains(QRegExp( - QString("^hdd([0-9]|mb|gb|freemb|freegb|totmb|totgb)")))) { - QString index = key; + } else if (_key.contains( + QRegExp("^hdd([0-9]|mb|gb|freemb|freegb|totmb|totgb)"))) { + QString index = _key; index.remove(QRegExp("^hdd(|mb|gb|freemb|freegb|totmb|totgb)")); - output = m_devices[QString("mount")][index.toInt()]; - } else if (key.startsWith(QString("hddtemp"))) { - QString index = key; + output = m_devices["mount"][index.toInt()]; + } else if (_key.startsWith("hddtemp")) { + QString index = _key; index.remove("hddtemp"); - output = m_devices[QString("hdd")][index.toInt()]; - } else if (key.contains(QRegExp(QString("^(down|up)[0-9]")))) { - QString index = key; + output = m_devices["hdd"][index.toInt()]; + } else if (_key.contains(QRegExp("^(down|up)[0-9]"))) { + QString index = _key; index.remove(QRegExp("^(down|up)")); - output = m_devices[QString("net")][index.toInt()]; - } else if (key.startsWith(QString("pkgcount"))) { - AbstractExtItem *item = m_extUpgrade->itemByTag(key, stripped); + output = m_devices["net"][index.toInt()]; + } else if (_key.startsWith("pkgcount")) { + AbstractExtItem *item = m_extUpgrade->itemByTag(_key, stripped); if (item) output = item->uniq(); - } else if (key.contains( - QRegExp(QString("(^|perc)(ask|bid|price)(chg|)")))) { - AbstractExtItem *item = m_extQuotes->itemByTag(key, stripped); + } else if (_key.contains(QRegExp("(^|perc)(ask|bid|price)(chg|)"))) { + AbstractExtItem *item = m_extQuotes->itemByTag(_key, stripped); if (item) output = item->uniq(); - } else if (key.contains(QRegExp(QString( - "(weather|weatherId|humidity|pressure|temperature)")))) { - AbstractExtItem *item = m_extWeather->itemByTag(key, stripped); + } else if (_key.contains(QRegExp( + "(weather|weatherId|humidity|pressure|temperature)"))) { + AbstractExtItem *item = m_extWeather->itemByTag(_key, stripped); if (item) output = item->uniq(); - } else if (key.startsWith(QString("temp"))) { - QString index = key; + } else if (_key.startsWith("temp")) { + QString index = _key; index.remove("temp"); - output = m_devices[QString("temp")][index.toInt()]; - } else if (key.startsWith(QString("response"))) { - AbstractExtItem *item = m_extNetRequest->itemByTag(key, stripped); + output = m_devices["temp"][index.toInt()]; + } else if (_key.startsWith("response")) { + AbstractExtItem *item = m_extNetRequest->itemByTag(_key, stripped); if (item) output = item->uniq(); } else { - output = QString("(none)"); + output = "(none)"; } return output; @@ -249,65 +248,64 @@ QString AWKeyOperations::pattern() const } -void AWKeyOperations::setPattern(const QString ¤tPattern) +void AWKeyOperations::setPattern(const QString &_currentPattern) { - qCDebug(LOG_AW) << "Set pattern" << currentPattern; + qCDebug(LOG_AW) << "Set pattern" << _currentPattern; - m_pattern = currentPattern; + m_pattern = _currentPattern; } -void AWKeyOperations::editItem(const QString &type) +void AWKeyOperations::editItem(const QString &_type) { - qCDebug(LOG_AW) << "Item type" << type; + qCDebug(LOG_AW) << "Item type" << _type; - if (type == QString("graphicalitem")) { - QStringList keys = dictKeys().filter(QRegExp( - QString("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)"))); + if (_type == "graphicalitem") { + QStringList keys = dictKeys().filter( + QRegExp("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)")); keys.sort(); m_graphicalItems->setConfigArgs(keys); return m_graphicalItems->editItems(); - } else if (type == QString("extnetworkrequest")) { + } else if (_type == "extnetworkrequest") { return m_extNetRequest->editItems(); - } else if (type == QString("extquotes")) { + } else if (_type == "extquotes") { return m_extQuotes->editItems(); - } else if (type == QString("extscript")) { + } else if (_type == "extscript") { return m_extScripts->editItems(); - } else if (type == QString("extupgrade")) { + } else if (_type == "extupgrade") { return m_extUpgrade->editItems(); - } else if (type == QString("extweather")) { + } else if (_type == "extweather") { return m_extWeather->editItems(); } } -void AWKeyOperations::addDevice(const QString &source) +void AWKeyOperations::addDevice(const QString &_source) { - qCDebug(LOG_AW) << "Source" << source; + qCDebug(LOG_AW) << "Source" << _source; - QRegExp diskRegexp - = QRegExp(QString("disk/(?:md|sd|hd)[a-z|0-9]_.*/Rate/(?:rblk)")); - QRegExp mountRegexp = QRegExp(QString("partitions/.*/filllevel")); + QRegExp diskRegexp = QRegExp("disk/(?:md|sd|hd)[a-z|0-9]_.*/Rate/(?:rblk)"); + QRegExp mountRegexp = QRegExp("partitions/.*/filllevel"); - if (source.contains(diskRegexp)) { - QString device = source; - device.remove(QString("/Rate/rblk")); - addKeyToCache(QString("disk"), device); - } else if (source.contains(mountRegexp)) { - QString device = source; - device.remove(QString("partitions")).remove(QString("/filllevel")); - addKeyToCache(QString("mount"), device); - } else if (source.startsWith(QString("lmsensors"))) { - addKeyToCache(QString("temp"), source); + if (_source.contains(diskRegexp)) { + QString device = _source; + device.remove("/Rate/rblk"); + addKeyToCache("disk", device); + } else if (_source.contains(mountRegexp)) { + QString device = _source; + device.remove("partitions").remove("/filllevel"); + addKeyToCache("mount", device); + } else if (_source.startsWith("lmsensors")) { + addKeyToCache("temp", _source); } } -void AWKeyOperations::addKeyToCache(const QString &type, const QString &key) +void AWKeyOperations::addKeyToCache(const QString &_type, const QString &_key) { - qCDebug(LOG_AW) << "Key" << key << "with type" << type; + qCDebug(LOG_AW) << "Key" << _key << "with type" << _type; - if (AWKeyCache::addKeyToCache(type, key)) { + if (AWKeyCache::addKeyToCache(_type, _key)) { m_devices = AWKeyCache::loadKeysFromCache(); reinitKeys(); } @@ -332,16 +330,13 @@ void AWKeyOperations::reinitKeys() m_extWeather = nullptr; // create m_graphicalItems - = new ExtItemAggregator(nullptr, QString("desktops")); - m_extNetRequest = new ExtItemAggregator( - nullptr, QString("requests")); - m_extQuotes = new ExtItemAggregator(nullptr, QString("quotes")); - m_extScripts - = new ExtItemAggregator(nullptr, QString("scripts")); - m_extUpgrade - = new ExtItemAggregator(nullptr, QString("upgrade")); - m_extWeather - = new ExtItemAggregator(nullptr, QString("weather")); + = new ExtItemAggregator(nullptr, "desktops"); + m_extNetRequest + = new ExtItemAggregator(nullptr, "requests"); + m_extQuotes = new ExtItemAggregator(nullptr, "quotes"); + m_extScripts = new ExtItemAggregator(nullptr, "scripts"); + m_extUpgrade = new ExtItemAggregator(nullptr, "upgrade"); + m_extWeather = new ExtItemAggregator(nullptr, "weather"); // init QStringList allKeys = dictKeys(); diff --git a/sources/awesome-widget/plugin/awkeyoperations.h b/sources/awesome-widget/plugin/awkeyoperations.h index c7016ac..fbff5c0 100644 --- a/sources/awesome-widget/plugin/awkeyoperations.h +++ b/sources/awesome-widget/plugin/awkeyoperations.h @@ -44,30 +44,30 @@ class AWKeyOperations : public QObject Q_PROPERTY(QString pattern READ pattern WRITE setPattern) public: - explicit AWKeyOperations(QObject *parent = nullptr); + explicit AWKeyOperations(QObject *_parent = nullptr); virtual ~AWKeyOperations(); - QStringList devices(const QString &type) const; + QStringList devices(const QString &_type) const; QHash devices() const; void updateCache(); // keys QStringList dictKeys() const; - GraphicalItem *giByKey(const QString &key) const; + GraphicalItem *giByKey(const QString &_key) const; // values - QString infoByKey(const QString &key) const; + QString infoByKey(const QString &_key) const; QString pattern() const; - void setPattern(const QString ¤tPattern); + void setPattern(const QString &_currentPattern); // configuration - void editItem(const QString &type); + void editItem(const QString &_type); signals: - void updateKeys(const QStringList ¤tKeys); + void updateKeys(const QStringList &_currentKeys); public slots: - void addDevice(const QString &source); + void addDevice(const QString &_source); private: // methods - void addKeyToCache(const QString &type, const QString &key = QString("")); + void addKeyToCache(const QString &_type, const QString &_key = ""); void reinitKeys(); // objects ExtItemAggregator *m_graphicalItems = nullptr; diff --git a/sources/awesome-widget/plugin/awkeys.cpp b/sources/awesome-widget/plugin/awkeys.cpp index 1d4f24d..e5cd5b9 100644 --- a/sources/awesome-widget/plugin/awkeys.cpp +++ b/sources/awesome-widget/plugin/awkeys.cpp @@ -35,8 +35,8 @@ #include "graphicalitem.h" -AWKeys::AWKeys(QObject *parent) - : QObject(parent) +AWKeys::AWKeys(QObject *_parent) + : QObject(_parent) { qSetMessagePattern(AWDebug::LOG_FORMAT); qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -57,14 +57,14 @@ AWKeys::AWKeys(QObject *parent) createDBusInterface(); // update key data if required - connect(m_keyOperator, SIGNAL(updateKeys(QStringList)), this, - SLOT(reinitKeys(QStringList))); + connect(m_keyOperator, SIGNAL(updateKeys(const QStringList &)), this, + SLOT(reinitKeys(const QStringList &))); connect(m_timer, SIGNAL(timeout()), this, SLOT(updateTextData())); // transfer signal from AWDataAggregator object to QML ui - connect(m_dataAggregator, SIGNAL(toolTipPainted(const QString)), this, - SIGNAL(needToolTipToBeUpdated(const QString))); - connect(this, SIGNAL(dropSourceFromDataengine(QString)), - m_dataEngineAggregator, SLOT(dropSource(QString))); + connect(m_dataAggregator, SIGNAL(toolTipPainted(const QString &)), this, + SIGNAL(needToolTipToBeUpdated(const QString &))); + connect(this, SIGNAL(dropSourceFromDataengine(const QString &)), + m_dataEngineAggregator, SLOT(dropSource(const QString &))); // transfer signal from dataengine to update source list connect(m_dataEngineAggregator, SIGNAL(deviceAdded(const QString &)), m_keyOperator, SLOT(addDevice(const QString &))); @@ -97,53 +97,53 @@ bool AWKeys::isDBusActive() const } -void AWKeys::initDataAggregator(const QVariantMap &tooltipParams) +void AWKeys::initDataAggregator(const QVariantMap &_tooltipParams) { - qCDebug(LOG_AW) << "Tooltip parameters" << tooltipParams; + qCDebug(LOG_AW) << "Tooltip parameters" << _tooltipParams; // store parameters to generate m_requiredKeys - m_tooltipParams = tooltipParams; + m_tooltipParams = _tooltipParams; m_dataAggregator->setParameters(m_tooltipParams); } -void AWKeys::initKeys(const QString ¤tPattern, const int interval, - const int limit, const bool optimize) +void AWKeys::initKeys(const QString &_currentPattern, const int _interval, + const int _limit, const bool _optimize) { - qCDebug(LOG_AW) << "Pattern" << currentPattern << "with interval" - << interval << "and queue limit" << limit - << "with optimization" << optimize; + qCDebug(LOG_AW) << "Pattern" << _currentPattern << "with interval" + << _interval << "and queue limit" << _limit + << "with optimization" << _optimize; // init - m_optimize = optimize; - m_threadPool->setMaxThreadCount(limit == 0 ? QThread::idealThreadCount() - : limit); + m_optimize = _optimize; + m_threadPool->setMaxThreadCount(_limit == 0 ? QThread::idealThreadCount() + : _limit); // child objects m_aggregator->initFormatters(); - m_keyOperator->setPattern(currentPattern); + m_keyOperator->setPattern(_currentPattern); m_keyOperator->updateCache(); m_dataEngineAggregator->clear(); - m_dataEngineAggregator->initDataEngines(interval); + m_dataEngineAggregator->initDataEngines(_interval); // timer - m_timer->setInterval(interval); + m_timer->setInterval(_interval); m_timer->start(); } -void AWKeys::setAggregatorProperty(const QString &key, const QVariant &value) +void AWKeys::setAggregatorProperty(const QString &_key, const QVariant &_value) { - qCDebug(LOG_AW) << "Key" << key << "with value" << value; + qCDebug(LOG_AW) << "Key" << _key << "with value" << _value; - m_aggregator->setProperty(key.toUtf8().constData(), value); + m_aggregator->setProperty(_key.toUtf8().constData(), _value); } -void AWKeys::setWrapNewLines(const bool wrap) +void AWKeys::setWrapNewLines(const bool _wrap) { - qCDebug(LOG_AW) << "Is wrapping enabled" << wrap; + qCDebug(LOG_AW) << "Is wrapping enabled" << _wrap; - m_wrapNewLines = wrap; + m_wrapNewLines = _wrap; } @@ -153,37 +153,37 @@ void AWKeys::updateCache() } -QStringList AWKeys::dictKeys(const bool sorted, const QString ®exp) const +QStringList AWKeys::dictKeys(const bool _sorted, const QString &_regexp) const { - qCDebug(LOG_AW) << "Should be sorted" << sorted << "and filter applied" - << regexp; + qCDebug(LOG_AW) << "Should be sorted" << _sorted << "and filter applied" + << _regexp; // check if functions asked - if (regexp == QString("functions")) - return QString(STATIC_FUNCTIONS).split(QChar(',')); + if (_regexp == "functions") + return QString(STATIC_FUNCTIONS).split(','); QStringList allKeys = m_keyOperator->dictKeys(); // sort if required - if (sorted) + if (_sorted) allKeys.sort(); - return allKeys.filter(QRegExp(regexp)); + return allKeys.filter(QRegExp(_regexp)); } QVariantList AWKeys::getHddDevices() const { - QStringList hddDevices = m_keyOperator->devices(QString("hdd")); + QStringList hddDevices = m_keyOperator->devices("hdd"); // required by selector in the UI - hddDevices.insert(0, QString("disable")); - hddDevices.insert(0, QString("auto")); + hddDevices.insert(0, "disable"); + hddDevices.insert(0, "auto"); // build model QVariantList devices; for (auto &device : hddDevices) { QVariantMap model; - model[QString("label")] = device; - model[QString("name")] = device; + model["label"] = device; + model["name"] = device; devices.append(model); } @@ -191,52 +191,52 @@ QVariantList AWKeys::getHddDevices() const } -QString AWKeys::infoByKey(const QString &key) const +QString AWKeys::infoByKey(const QString &_key) const { - qCDebug(LOG_AW) << "Requested info for key" << key; + qCDebug(LOG_AW) << "Requested info for key" << _key; - return m_keyOperator->infoByKey(key); + return m_keyOperator->infoByKey(_key); } // HACK this method requires to define tag value from bar from UI interface -QString AWKeys::valueByKey(const QString &key) const +QString AWKeys::valueByKey(const QString &_key) const { - qCDebug(LOG_AW) << "Requested value for key" << key; + qCDebug(LOG_AW) << "Requested value for key" << _key; QString trueKey - = key.startsWith(QString("bar")) ? m_keyOperator->infoByKey(key) : key; + = _key.startsWith("bar") ? m_keyOperator->infoByKey(_key) : _key; return m_aggregator->formatter(m_values[trueKey], trueKey); } -void AWKeys::editItem(const QString &type) +void AWKeys::editItem(const QString &_type) { - qCDebug(LOG_AW) << "Item type" << type; + qCDebug(LOG_AW) << "Item type" << _type; - return m_keyOperator->editItem(type); + return m_keyOperator->editItem(_type); } -void AWKeys::dataUpdated(const QString &sourceName, - const Plasma::DataEngine::Data &data) +void AWKeys::dataUpdated(const QString &_sourceName, + const Plasma::DataEngine::Data &_data) { // run concurrent data update - QtConcurrent::run(m_threadPool, this, &AWKeys::setDataBySource, sourceName, - data); + QtConcurrent::run(m_threadPool, this, &AWKeys::setDataBySource, _sourceName, + _data); } -void AWKeys::reinitKeys(const QStringList ¤tKeys) +void AWKeys::reinitKeys(const QStringList &_currentKeys) { - qCDebug(LOG_AW) << "Update found keys by using list" << currentKeys; + qCDebug(LOG_AW) << "Update found keys by using list" << _currentKeys; // append lists m_foundBars = AWPatternFunctions::findKeys(m_keyOperator->pattern(), - currentKeys, true); + _currentKeys, true); m_foundKeys = AWPatternFunctions::findKeys(m_keyOperator->pattern(), - currentKeys, false); + _currentKeys, false); m_foundLambdas = AWPatternFunctions::findLambdas(m_keyOperator->pattern()); // generate list of required keys for bars QStringList barKeys; @@ -244,15 +244,15 @@ void AWKeys::reinitKeys(const QStringList ¤tKeys) GraphicalItem *item = m_keyOperator->giByKey(bar); if (item->isCustom()) item->setUsedKeys( - AWPatternFunctions::findKeys(item->bar(), currentKeys, false)); + AWPatternFunctions::findKeys(item->bar(), _currentKeys, false)); else item->setUsedKeys(QStringList() << item->bar()); barKeys.append(item->usedKeys()); } // get required keys m_requiredKeys - = m_optimize ? AWKeyCache::getRequiredKeys(m_foundKeys, barKeys, - m_tooltipParams, currentKeys) + = m_optimize ? AWKeyCache::getRequiredKeys( + m_foundKeys, barKeys, m_tooltipParams, _currentKeys) : QStringList(); // set key data to m_aggregator @@ -278,7 +278,7 @@ void AWKeys::updateTextData() void AWKeys::calculateValues() { // hddtot* - QStringList mountDevices = m_keyOperator->devices(QString("mount")); + QStringList mountDevices = m_keyOperator->devices("mount"); for (auto &device : mountDevices) { int index = mountDevices.indexOf(device); m_values[QString("hddtotmb%1").arg(index)] @@ -290,41 +290,36 @@ void AWKeys::calculateValues() } // memtot* - m_values[QString("memtotmb")] = m_values[QString("memusedmb")].toInt() - + m_values[QString("memfreemb")].toInt(); - m_values[QString("memtotgb")] = m_values[QString("memusedgb")].toFloat() - + m_values[QString("memfreegb")].toFloat(); + m_values["memtotmb"] + = m_values["memusedmb"].toInt() + m_values["memfreemb"].toInt(); + m_values["memtotgb"] + = m_values["memusedgb"].toFloat() + m_values["memfreegb"].toFloat(); // mem - m_values[QString("mem")] = 100.0f * m_values[QString("memmb")].toFloat() - / m_values[QString("memtotmb")].toFloat(); + m_values["mem"] + = 100.0f * m_values["memmb"].toFloat() / m_values["memtotmb"].toFloat(); // up, down, upkb, downkb, upunits, downunits - int netIndex = m_keyOperator->devices(QString("net")) - .indexOf(m_values[QString("netdev")].toString()); - m_values[QString("down")] = m_values[QString("down%1").arg(netIndex)]; - m_values[QString("downkb")] = m_values[QString("downkb%1").arg(netIndex)]; - m_values[QString("downtotal")] - = m_values[QString("downtotal%1").arg(netIndex)]; - m_values[QString("downtotalkb")] - = m_values[QString("downtotalkb%1").arg(netIndex)]; - m_values[QString("downunits")] - = m_values[QString("downunits%1").arg(netIndex)]; - m_values[QString("up")] = m_values[QString("up%1").arg(netIndex)]; - m_values[QString("upkb")] = m_values[QString("upkb%1").arg(netIndex)]; - m_values[QString("uptotal")] = m_values[QString("uptotal%1").arg(netIndex)]; - m_values[QString("uptotalkb")] - = m_values[QString("uptotalkb%1").arg(netIndex)]; - m_values[QString("upunits")] = m_values[QString("upunits%1").arg(netIndex)]; + int netIndex + = m_keyOperator->devices("net").indexOf(m_values["netdev"].toString()); + m_values["down"] = m_values[QString("down%1").arg(netIndex)]; + m_values["downkb"] = m_values[QString("downkb%1").arg(netIndex)]; + m_values["downtotal"] = m_values[QString("downtotal%1").arg(netIndex)]; + m_values["downtotalkb"] = m_values[QString("downtotalkb%1").arg(netIndex)]; + m_values["downunits"] = m_values[QString("downunits%1").arg(netIndex)]; + m_values["up"] = m_values[QString("up%1").arg(netIndex)]; + m_values["upkb"] = m_values[QString("upkb%1").arg(netIndex)]; + m_values["uptotal"] = m_values[QString("uptotal%1").arg(netIndex)]; + m_values["uptotalkb"] = m_values[QString("uptotalkb%1").arg(netIndex)]; + m_values["upunits"] = m_values[QString("upunits%1").arg(netIndex)]; // swaptot* - m_values[QString("swaptotmb")] = m_values[QString("swapmb")].toInt() - + m_values[QString("swapfreemb")].toInt(); - m_values[QString("swaptotgb")] - = m_values[QString("swapgb")].toFloat() - + m_values[QString("swapfreegb")].toFloat(); + m_values["swaptotmb"] + = m_values["swapmb"].toInt() + m_values["swapfreemb"].toInt(); + m_values["swaptotgb"] + = m_values["swapgb"].toFloat() + m_values["swapfreegb"].toFloat(); // swap - m_values[QString("swap")] = 100.0f * m_values[QString("swapmb")].toFloat() - / m_values[QString("swaptotmb")].toFloat(); + m_values["swap"] = 100.0f * m_values["swapmb"].toFloat() + / m_values["swaptotmb"].toFloat(); // lambdas for (auto &key : m_foundLambdas) @@ -354,25 +349,25 @@ void AWKeys::createDBusInterface() } -QString AWKeys::parsePattern(QString pattern) const +QString AWKeys::parsePattern(QString _pattern) const { // screen sign - pattern.replace(QString("$$"), QString(0x1d)); + _pattern.replace("$$", QString(0x1d)); // lambdas for (auto &key : m_foundLambdas) - pattern.replace(QString("${{%1}}").arg(key), m_values[key].toString()); + _pattern.replace(QString("${{%1}}").arg(key), m_values[key].toString()); // main keys for (auto &key : m_foundKeys) - pattern.replace(QString("$%1").arg(key), [this](const QString &tag, - const QVariant &value) { - QString strValue = m_aggregator->formatter(value, tag); - if ((!tag.startsWith(QString("custom"))) - && (!tag.startsWith(QString("weather")))) - strValue.replace(QString(" "), QString(" ")); - return strValue; - }(key, m_values[key])); + _pattern.replace( + QString("$%1").arg(key), + [this](const QString &tag, const QVariant &value) { + QString strValue = m_aggregator->formatter(value, tag); + if ((!tag.startsWith("custom")) && (!tag.startsWith("weather"))) + strValue.replace(" ", " "); + return strValue; + }(key, m_values[key])); // bars for (auto &bar : m_foundBars) { @@ -382,41 +377,41 @@ QString AWKeys::parsePattern(QString pattern) const ? item->image(AWPatternFunctions::expandLambdas( item->bar(), m_aggregator, m_values, item->usedKeys())) : item->image(m_values[item->bar()]); - pattern.replace(QString("$%1").arg(bar), image); + _pattern.replace(QString("$%1").arg(bar), image); } // prepare strings - pattern.replace(QString(0x1d), QString("$")); + _pattern.replace(QString(0x1d), "$"); if (m_wrapNewLines) - pattern.replace(QString("\n"), QString("
    ")); + _pattern.replace("\n", "
    "); - return pattern; + return _pattern; } -void AWKeys::setDataBySource(const QString &sourceName, const QVariantMap &data) +void AWKeys::setDataBySource(const QString &_sourceName, + const QVariantMap &_data) { - qCDebug(LOG_AW) << "Source" << sourceName << "with data" << data; + qCDebug(LOG_AW) << "Source" << _sourceName << "with data" << _data; // first list init - QStringList tags = m_aggregator->keysFromSource(sourceName); + QStringList tags = m_aggregator->keysFromSource(_sourceName); if (tags.isEmpty()) tags = m_aggregator->registerSource( - sourceName, data[QString("units")].toString(), m_requiredKeys); + _sourceName, _data["units"].toString(), m_requiredKeys); // update data or drop source if there are no matches and exit if (tags.isEmpty()) { - qCInfo(LOG_AW) << "Source" << sourceName << "not found"; - return emit(dropSourceFromDataengine(sourceName)); + qCInfo(LOG_AW) << "Source" << _sourceName << "not found"; + return emit(dropSourceFromDataengine(_sourceName)); } m_mutex.lock(); // HACK workaround for time values which are stored in the different path std::for_each(tags.cbegin(), tags.cend(), - [this, &data, &sourceName](const QString &tag) { - m_values[tag] = sourceName == QString("Local") - ? data[QString("DateTime")] - : data[QString("value")]; + [this, &_data, &_sourceName](const QString &tag) { + m_values[tag] = _sourceName == "Local" ? _data["DateTime"] + : _data["value"]; }); m_mutex.unlock(); } diff --git a/sources/awesome-widget/plugin/awkeys.h b/sources/awesome-widget/plugin/awkeys.h index 2c0b043..e7b6535 100644 --- a/sources/awesome-widget/plugin/awkeys.h +++ b/sources/awesome-widget/plugin/awkeys.h @@ -37,49 +37,50 @@ class AWKeys : public QObject Q_OBJECT public: - explicit AWKeys(QObject *parent = nullptr); + explicit AWKeys(QObject *_parent = nullptr); virtual ~AWKeys(); bool isDBusActive() const; - Q_INVOKABLE void initDataAggregator(const QVariantMap &tooltipParams); - Q_INVOKABLE void initKeys(const QString ¤tPattern, const int interval, - const int limit, const bool optimize); - Q_INVOKABLE void setAggregatorProperty(const QString &key, - const QVariant &value); - Q_INVOKABLE void setWrapNewLines(const bool wrap = false); + Q_INVOKABLE void initDataAggregator(const QVariantMap &_tooltipParams); + Q_INVOKABLE void initKeys(const QString &_currentPattern, + const int _interval, const int _limit, + const bool _optimize); + Q_INVOKABLE void setAggregatorProperty(const QString &_key, + const QVariant &_value); + Q_INVOKABLE void setWrapNewLines(const bool _wrap = false); // additional method to force load keys from Qml UI. Used in some // configuration pages Q_INVOKABLE void updateCache(); // keys - Q_INVOKABLE QStringList dictKeys(const bool sorted = false, - const QString ®exp = QString()) const; + Q_INVOKABLE QStringList dictKeys(const bool _sorted = false, + const QString &_regexp = "") const; Q_INVOKABLE QVariantList getHddDevices() const; // values - Q_INVOKABLE QString infoByKey(const QString &key) const; - Q_INVOKABLE QString valueByKey(const QString &key) const; + Q_INVOKABLE QString infoByKey(const QString &_key) const; + Q_INVOKABLE QString valueByKey(const QString &_key) const; // configuration - Q_INVOKABLE void editItem(const QString &type); + Q_INVOKABLE void editItem(const QString &_type); public slots: - void dataUpdated(const QString &sourceName, - const Plasma::DataEngine::Data &data); + void dataUpdated(const QString &_sourceName, + const Plasma::DataEngine::Data &_data); // dummy method required by DataEngine connections void modelChanged(QString, QAbstractItemModel *){}; signals: - void dropSourceFromDataengine(const QString &source); - void needTextToBeUpdated(const QString &newText) const; - void needToolTipToBeUpdated(const QString &newText) const; + void dropSourceFromDataengine(const QString &_source); + void needTextToBeUpdated(const QString &_newText) const; + void needToolTipToBeUpdated(const QString &_newText) const; private slots: - void reinitKeys(const QStringList ¤tKeys); + void reinitKeys(const QStringList &_currentKeys); void updateTextData(); private: // methods void calculateValues(); void createDBusInterface(); - QString parsePattern(QString pattern) const; - void setDataBySource(const QString &sourceName, const QVariantMap &data); + QString parsePattern(QString _pattern) const; + void setDataBySource(const QString &_sourceName, const QVariantMap &_data); // objects AWDataAggregator *m_dataAggregator = nullptr; AWDataEngineAggregator *m_dataEngineAggregator = nullptr; diff --git a/sources/awesome-widget/plugin/awkeysaggregator.cpp b/sources/awesome-widget/plugin/awkeysaggregator.cpp index 9e9af4f..62066cc 100644 --- a/sources/awesome-widget/plugin/awkeysaggregator.cpp +++ b/sources/awesome-widget/plugin/awkeysaggregator.cpp @@ -27,8 +27,8 @@ #include "awformatterhelper.h" -AWKeysAggregator::AWKeysAggregator(QObject *parent) - : QObject(parent) +AWKeysAggregator::AWKeysAggregator(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -38,20 +38,20 @@ AWKeysAggregator::AWKeysAggregator(QObject *parent) // default formatters // memory - m_formatter[QString("mem")] = FormatterType::Float; - m_formatter[QString("memtotmb")] = FormatterType::MemMBFormat; - m_formatter[QString("memtotgb")] = FormatterType::MemGBFormat; + m_formatter["mem"] = FormatterType::Float; + m_formatter["memtotmb"] = FormatterType::MemMBFormat; + m_formatter["memtotgb"] = FormatterType::MemGBFormat; // network - m_formatter[QString("down")] = FormatterType::NetSmartFormat; - m_formatter[QString("downkb")] = FormatterType::Integer; - m_formatter[QString("downunits")] = FormatterType::NetSmartUnits; - m_formatter[QString("up")] = FormatterType::NetSmartFormat; - m_formatter[QString("upkb")] = FormatterType::Integer; - m_formatter[QString("upunits")] = FormatterType::NetSmartUnits; + m_formatter["down"] = FormatterType::NetSmartFormat; + m_formatter["downkb"] = FormatterType::Integer; + m_formatter["downunits"] = FormatterType::NetSmartUnits; + m_formatter["up"] = FormatterType::NetSmartFormat; + m_formatter["upkb"] = FormatterType::Integer; + m_formatter["upunits"] = FormatterType::NetSmartUnits; // swap - m_formatter[QString("swap")] = FormatterType::Float; - m_formatter[QString("swaptotmb")] = FormatterType::MemMBFormat; - m_formatter[QString("swaptotgb")] = FormatterType::MemGBFormat; + m_formatter["swap"] = FormatterType::Float; + m_formatter["swaptotmb"] = FormatterType::MemMBFormat; + m_formatter["swaptotgb"] = FormatterType::MemGBFormat; } @@ -71,42 +71,42 @@ void AWKeysAggregator::initFormatters() } -QString AWKeysAggregator::formatter(const QVariant &data, - const QString &key) const +QString AWKeysAggregator::formatter(const QVariant &_data, + const QString &_key) const { - qCDebug(LOG_AW) << "Data" << data << "for key" << key; + qCDebug(LOG_AW) << "Data" << _data << "for key" << _key; QString output; QLocale loc = m_translate ? QLocale::system() : QLocale::c(); // case block - switch (m_formatter[key]) { + switch (m_formatter[_key]) { case FormatterType::Float: - output = QString("%1").arg(data.toFloat(), 5, 'f', 1); + output = QString("%1").arg(_data.toFloat(), 5, 'f', 1); break; case FormatterType::FloatTwoSymbols: - output = QString("%1").arg(data.toFloat(), 5, 'f', 2); + output = QString("%1").arg(_data.toFloat(), 5, 'f', 2); break; case FormatterType::Integer: - output = QString("%1").arg(data.toFloat(), 4, 'f', 0); + output = QString("%1").arg(_data.toFloat(), 4, 'f', 0); break; case FormatterType::IntegerFive: - output = QString("%1").arg(data.toFloat(), 5, 'f', 0); + output = QString("%1").arg(_data.toFloat(), 5, 'f', 0); break; case FormatterType::IntegerThree: - output = QString("%1").arg(data.toFloat(), 3, 'f', 0); + output = QString("%1").arg(_data.toFloat(), 3, 'f', 0); break; case FormatterType::List: - output = data.toStringList().join(QChar(',')); + output = _data.toStringList().join(','); break; case FormatterType::ACFormat: - output = data.toBool() ? m_acOnline : m_acOffline; + output = _data.toBool() ? m_acOnline : m_acOffline; break; case FormatterType::MemGBFormat: output - = QString("%1").arg(data.toFloat() / (1024.0 * 1024.0), 5, 'f', 1); + = QString("%1").arg(_data.toFloat() / (1024.0 * 1024.0), 5, 'f', 1); break; case FormatterType::MemMBFormat: - output = QString("%1").arg(data.toFloat() / 1024.0, 5, 'f', 0); + output = QString("%1").arg(_data.toFloat() / 1024.0, 5, 'f', 0); break; case FormatterType::NetSmartFormat: output = [](const float value) { @@ -114,44 +114,44 @@ QString AWKeysAggregator::formatter(const QVariant &data, return QString("%1").arg(value / 1024.0, 4, 'f', 1); else return QString("%1").arg(value, 4, 'f', 0); - }(data.toFloat()); + }(_data.toFloat()); break; case FormatterType::NetSmartUnits: - if (data.toFloat() > 1024.0) - output = m_translate ? i18n("MB/s") : QString("MB/s"); + if (_data.toFloat() > 1024.0) + output = m_translate ? i18n("MB/s") : "MB/s"; else - output = m_translate ? i18n("KB/s") : QString("KB/s"); + output = m_translate ? i18n("KB/s") : "KB/s"; break; case FormatterType::Quotes: // first cast - output = QString("%1").arg(data.toDouble(), 0, 'f'); + output = QString("%1").arg(_data.toDouble(), 0, 'f'); output = output.rightJustified(8, QLatin1Char(' '), true); break; case FormatterType::Temperature: - output = QString("%1").arg(temperature(data.toFloat()), 5, 'f', 1); + output = QString("%1").arg(temperature(_data.toFloat()), 5, 'f', 1); break; case FormatterType::Time: - output = data.toDateTime().toString(); + output = _data.toDateTime().toString(); break; case FormatterType::TimeCustom: output = m_customTime; [&output, loc, this](const QDateTime dt) { for (auto &key : m_timeKeys) output.replace(QString("$%1").arg(key), loc.toString(dt, key)); - }(data.toDateTime()); + }(_data.toDateTime()); break; case FormatterType::TimeISO: - output = data.toDateTime().toString(Qt::ISODate); + output = _data.toDateTime().toString(Qt::ISODate); break; case FormatterType::TimeLong: - output = loc.toString(data.toDateTime(), QLocale::LongFormat); + output = loc.toString(_data.toDateTime(), QLocale::LongFormat); break; case FormatterType::TimeShort: - output = loc.toString(data.toDateTime(), QLocale::ShortFormat); + output = loc.toString(_data.toDateTime(), QLocale::ShortFormat); break; case FormatterType::Timestamp: output = QString("%1").arg( - data.toDateTime().toMSecsSinceEpoch() / 1000.0, 10, 'f', 0); + _data.toDateTime().toMSecsSinceEpoch() / 1000.0, 10, 'f', 0); break; case FormatterType::Uptime: case FormatterType::UptimeCustom: @@ -161,27 +161,26 @@ QString AWKeysAggregator::formatter(const QVariant &data, int minutes = seconds / 60 % 60; int hours = ((seconds / 60) - minutes) / 60 % 24; int days = (((seconds / 60) - minutes) / 60 - hours) / 24; - source.replace(QString("$dd"), + source.replace("$dd", QString("%1").arg(days, 3, 10, QChar('0'))); - source.replace(QString("$d"), QString("%1").arg(days)); - source.replace(QString("$hh"), + source.replace("$d", QString("%1").arg(days)); + source.replace("$hh", QString("%1").arg(hours, 2, 10, QChar('0'))); - source.replace(QString("$h"), QString("%1").arg(hours)); - source.replace(QString("$mm"), + source.replace("$h", QString("%1").arg(hours)); + source.replace("$mm", QString("%1").arg(minutes, 2, 10, QChar('0'))); - source.replace(QString("$m"), QString("%1").arg(minutes)); + source.replace("$m", QString("%1").arg(minutes)); return source; - }(m_formatter[key] == FormatterType::Uptime - ? QString("$ddd$hhh$mmm") - : m_customUptime, - static_cast(data.toFloat())); + }(m_formatter[_key] == FormatterType::Uptime ? "$ddd$hhh$mmm" + : m_customUptime, + static_cast(_data.toFloat())); break; case FormatterType::NoFormat: - output = data.toString(); + output = _data.toString(); break; case FormatterType::Custom: if (m_customFormatters) - output = m_customFormatters->convert(data, key); + output = m_customFormatters->convert(_data, _key); break; } @@ -189,176 +188,176 @@ QString AWKeysAggregator::formatter(const QVariant &data, } -QStringList AWKeysAggregator::keysFromSource(const QString &source) const +QStringList AWKeysAggregator::keysFromSource(const QString &_source) const { - qCDebug(LOG_AW) << "Search for source" << source; + qCDebug(LOG_AW) << "Search for source" << _source; - return m_map.values(source); + return m_map.values(_source); } -void AWKeysAggregator::setAcOffline(const QString &inactive) +void AWKeysAggregator::setAcOffline(const QString &_inactive) { - qCDebug(LOG_AW) << "Inactive AC string" << inactive; + qCDebug(LOG_AW) << "Inactive AC string" << _inactive; - m_acOffline = inactive; + m_acOffline = _inactive; } -void AWKeysAggregator::setAcOnline(const QString &active) +void AWKeysAggregator::setAcOnline(const QString &_active) { - qCDebug(LOG_AW) << "Active AC string" << active; + qCDebug(LOG_AW) << "Active AC string" << _active; - m_acOnline = active; + m_acOnline = _active; } -void AWKeysAggregator::setCustomTime(const QString &customTime) +void AWKeysAggregator::setCustomTime(const QString &_customTime) { - qCDebug(LOG_AW) << "Format" << customTime; + qCDebug(LOG_AW) << "Format" << _customTime; - m_customTime = customTime; + m_customTime = _customTime; } -void AWKeysAggregator::setCustomUptime(const QString &customUptime) +void AWKeysAggregator::setCustomUptime(const QString &_customUptime) { - qCDebug(LOG_AW) << "Format" << customUptime; + qCDebug(LOG_AW) << "Format" << _customUptime; - m_customUptime = customUptime; + m_customUptime = _customUptime; } -void AWKeysAggregator::setDevices(const QHash &devices) +void AWKeysAggregator::setDevices(const QHash &_devices) { - qCDebug(LOG_AW) << "Devices" << devices; + qCDebug(LOG_AW) << "Devices" << _devices; - m_devices = devices; + m_devices = _devices; } -void AWKeysAggregator::setTempUnits(const QString &units) +void AWKeysAggregator::setTempUnits(const QString &_units) { - qCDebug(LOG_AW) << "Units" << units; + qCDebug(LOG_AW) << "Units" << _units; - m_tempUnits = units; + m_tempUnits = _units; } -void AWKeysAggregator::setTranslate(const bool translate) +void AWKeysAggregator::setTranslate(const bool _translate) { - qCDebug(LOG_AW) << "Translate" << translate; + qCDebug(LOG_AW) << "Translate" << _translate; - m_translate = translate; + m_translate = _translate; } // HACK units required to define should the value be calculated as temperature // or fan data -QStringList AWKeysAggregator::registerSource(const QString &source, - const QString &units, - const QStringList &keys) +QStringList AWKeysAggregator::registerSource(const QString &_source, + const QString &_units, + const QStringList &_keys) { - qCDebug(LOG_AW) << "Source" << source << "with units" << units; + qCDebug(LOG_AW) << "Source" << _source << "with units" << _units; // regular expressions - QRegExp cpuRegExp = QRegExp(QString("cpu/cpu.*/TotalLoad")); - QRegExp cpuclRegExp = QRegExp(QString("cpu/cpu.*/clock")); - QRegExp hddrRegExp = QRegExp(QString("disk/.*/Rate/rblk")); - QRegExp hddwRegExp = QRegExp(QString("disk/.*/Rate/wblk")); - QRegExp mountFillRegExp = QRegExp(QString("partitions/.*/filllevel")); - QRegExp mountFreeRegExp = QRegExp(QString("partitions/.*/freespace")); - QRegExp mountUsedRegExp = QRegExp(QString("partitions/.*/usedspace")); - QRegExp netRegExp = QRegExp( - QString("network/interfaces/.*/(receiver|transmitter)/data$")); - QRegExp netTotalRegExp = QRegExp( - QString("network/interfaces/.*/(receiver|transmitter)/dataTotal$")); + QRegExp cpuRegExp = QRegExp("cpu/cpu.*/TotalLoad"); + QRegExp cpuclRegExp = QRegExp("cpu/cpu.*/clock"); + QRegExp hddrRegExp = QRegExp("disk/.*/Rate/rblk"); + QRegExp hddwRegExp = QRegExp("disk/.*/Rate/wblk"); + QRegExp mountFillRegExp = QRegExp("partitions/.*/filllevel"); + QRegExp mountFreeRegExp = QRegExp("partitions/.*/freespace"); + QRegExp mountUsedRegExp = QRegExp("partitions/.*/usedspace"); + QRegExp netRegExp + = QRegExp("network/interfaces/.*/(receiver|transmitter)/data$"); + QRegExp netTotalRegExp + = QRegExp("network/interfaces/.*/(receiver|transmitter)/dataTotal$"); - if (source == QString("battery/ac")) { + if (_source == "battery/ac") { // AC - m_map[source] = QString("ac"); - m_formatter[QString("ac")] = FormatterType::ACFormat; - } else if (source.startsWith(QString("battery/"))) { + m_map[_source] = "ac"; + m_formatter["ac"] = FormatterType::ACFormat; + } else if (_source.startsWith("battery/")) { // battery stats - QString key = source; - key.remove(QString("battery/")); - m_map[source] = key; + QString key = _source; + key.remove("battery/"); + m_map[_source] = key; m_formatter[key] = FormatterType::IntegerThree; - } else if (source == QString("cpu/system/TotalLoad")) { + } else if (_source == "cpu/system/TotalLoad") { // cpu - m_map[source] = QString("cpu"); - m_formatter[QString("cpu")] = FormatterType::Float; - } else if (source.contains(cpuRegExp)) { + m_map[_source] = "cpu"; + m_formatter["cpu"] = FormatterType::Float; + } else if (_source.contains(cpuRegExp)) { // cpus - QString key = source; - key.remove(QString("cpu/")).remove(QString("/TotalLoad")); - m_map[source] = key; + QString key = _source; + key.remove("cpu/").remove("/TotalLoad"); + m_map[_source] = key; m_formatter[key] = FormatterType::Float; - } else if (source == QString("cpu/system/AverageClock")) { + } else if (_source == "cpu/system/AverageClock") { // cpucl - m_map[source] = QString("cpucl"); - m_formatter[QString("cpucl")] = FormatterType::Integer; - } else if (source.contains(cpuclRegExp)) { + m_map[_source] = "cpucl"; + m_formatter["cpucl"] = FormatterType::Integer; + } else if (_source.contains(cpuclRegExp)) { // cpucls - QString key = source; - key.remove(QString("cpu/cpu")).remove(QString("/clock")); + QString key = _source; + key.remove("cpu/cpu").remove("/clock"); key = QString("cpucl%1").arg(key); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Integer; - } else if (source.startsWith(QString("custom"))) { + } else if (_source.startsWith("custom")) { // custom - QString key = source; - key.remove(QString("custom/")); - m_map[source] = key; + QString key = _source; + key.remove("custom/"); + m_map[_source] = key; m_formatter[key] = FormatterType::NoFormat; - } else if (source == QString("desktop/current/name")) { + } else if (_source == "desktop/current/name") { // current desktop name - m_map[source] = QString("desktop"); - m_formatter[QString("desktop")] = FormatterType::NoFormat; - } else if (source == QString("desktop/current/number")) { + m_map[_source] = "desktop"; + m_formatter["desktop"] = FormatterType::NoFormat; + } else if (_source == "desktop/current/number") { // current desktop number - m_map[source] = QString("ndesktop"); - m_formatter[QString("ndesktop")] = FormatterType::NoFormat; - } else if (source == QString("desktop/total/number")) { + m_map[_source] = "ndesktop"; + m_formatter["ndesktop"] = FormatterType::NoFormat; + } else if (_source == "desktop/total/number") { // desktop count - m_map[source] = QString("tdesktops"); - m_formatter[QString("tdesktops")] = FormatterType::NoFormat; - } else if (source.contains(hddrRegExp)) { + m_map[_source] = "tdesktops"; + m_formatter["tdesktops"] = FormatterType::NoFormat; + } else if (_source.contains(hddrRegExp)) { // read speed - QString device = source; - device.remove(QString("/Rate/rblk")); - int index = m_devices[QString("disk")].indexOf(device); + QString device = _source; + device.remove("/Rate/rblk"); + int index = m_devices["disk"].indexOf(device); if (index > -1) { QString key = QString("hddr%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Integer; } - } else if (source.contains(hddwRegExp)) { + } else if (_source.contains(hddwRegExp)) { // write speed - QString device = source; - device.remove(QString("/Rate/wblk")); - int index = m_devices[QString("disk")].indexOf(device); + QString device = _source; + device.remove("/Rate/wblk"); + int index = m_devices["disk"].indexOf(device); if (index > -1) { QString key = QString("hddw%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Integer; } - } else if (source == QString("gpu/load")) { + } else if (_source == "gpu/load") { // gpu load - m_map[source] = QString("gpu"); - m_formatter[QString("gpu")] = FormatterType::Float; - } else if (source == QString("gpu/temperature")) { + m_map[_source] = "gpu"; + m_formatter["gpu"] = FormatterType::Float; + } else if (_source == "gpu/temperature") { // gpu temperature - m_map[source] = QString("gputemp"); - m_formatter[QString("gputemp")] = FormatterType::Temperature; - } else if (source.contains(mountFillRegExp)) { + m_map[_source] = "gputemp"; + m_formatter["gputemp"] = FormatterType::Temperature; + } else if (_source.contains(mountFillRegExp)) { // fill level - QString device = source; - device.remove(QString("partitions")).remove(QString("/filllevel")); - int index = m_devices[QString("mount")].indexOf(device); + QString device = _source; + device.remove("partitions").remove("/filllevel"); + int index = m_devices["mount"].indexOf(device); if (index > -1) { QString key = QString("hdd%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Float; // additional keys m_formatter[QString("hddtotmb%1").arg(index)] @@ -366,229 +365,224 @@ QStringList AWKeysAggregator::registerSource(const QString &source, m_formatter[QString("hddtotgb%1").arg(index)] = FormatterType::MemGBFormat; } - } else if (source.contains(mountFreeRegExp)) { + } else if (_source.contains(mountFreeRegExp)) { // free space - QString device = source; - device.remove(QString("partitions")).remove(QString("/freespace")); - int index = m_devices[QString("mount")].indexOf(device); + QString device = _source; + device.remove("partitions").remove("/freespace"); + int index = m_devices["mount"].indexOf(device); if (index > -1) { // mb QString key = QString("hddfreemb%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::MemMBFormat; // gb key = QString("hddfreegb%1").arg(index); - m_map.insertMulti(source, key); + m_map.insertMulti(_source, key); m_formatter[key] = FormatterType::MemGBFormat; } - } else if (source.contains(mountUsedRegExp)) { + } else if (_source.contains(mountUsedRegExp)) { // used - QString device = source; - device.remove(QString("partitions")).remove(QString("/usedspace")); - int index = m_devices[QString("mount")].indexOf(device); + QString device = _source; + device.remove("partitions").remove("/usedspace"); + int index = m_devices["mount"].indexOf(device); if (index > -1) { // mb QString key = QString("hddmb%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::MemMBFormat; // gb key = QString("hddgb%1").arg(index); - m_map.insertMulti(source, key); + m_map.insertMulti(_source, key); m_formatter[key] = FormatterType::MemGBFormat; } - } else if (source.startsWith(QString("hdd/temperature"))) { + } else if (_source.startsWith("hdd/temperature")) { // hdd temperature - QString device = source; - device.remove(QString("hdd/temperature")); - int index = m_devices[QString("hdd")].indexOf(device); + QString device = _source; + device.remove("hdd/temperature"); + int index = m_devices["hdd"].indexOf(device); if (index > -1) { QString key = QString("hddtemp%1").arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Temperature; } - } else if (source.startsWith(QString("cpu/system/loadavg"))) { + } else if (_source.startsWith("cpu/system/loadavg")) { // load average - QString time = source; - time.remove(QString("cpu/system/loadavg")); + QString time = _source; + time.remove("cpu/system/loadavg"); QString key = QString("la%1").arg(time); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::FloatTwoSymbols; - } else if (source == QString("mem/physical/application")) { + } else if (_source == "mem/physical/application") { // app memory // mb - m_map[source] = QString("memmb"); - m_formatter[QString("memmb")] = FormatterType::MemMBFormat; + m_map[_source] = "memmb"; + m_formatter["memmb"] = FormatterType::MemMBFormat; // gb - m_map.insertMulti(source, QString("memgb")); - m_formatter[QString("memgb")] = FormatterType::MemGBFormat; - } else if (source == QString("mem/physical/free")) { + m_map.insertMulti(_source, "memgb"); + m_formatter["memgb"] = FormatterType::MemGBFormat; + } else if (_source == "mem/physical/free") { // free memory // mb - m_map[source] = QString("memfreemb"); - m_formatter[QString("memfreemb")] = FormatterType::MemMBFormat; + m_map[_source] = "memfreemb"; + m_formatter["memfreemb"] = FormatterType::MemMBFormat; // gb - m_map.insertMulti(source, QString("memfreegb")); - m_formatter[QString("memfreegb")] = FormatterType::MemGBFormat; - } else if (source == QString("mem/physical/used")) { + m_map.insertMulti(_source, "memfreegb"); + m_formatter["memfreegb"] = FormatterType::MemGBFormat; + } else if (_source == "mem/physical/used") { // used memory // mb - m_map[source] = QString("memusedmb"); - m_formatter[QString("memusedmb")] = FormatterType::MemMBFormat; + m_map[_source] = "memusedmb"; + m_formatter["memusedmb"] = FormatterType::MemMBFormat; // gb - m_map.insertMulti(source, QString("memusedgb")); - m_formatter[QString("memusedgb")] = FormatterType::MemGBFormat; - } else if (source == QString("network/current/name")) { + m_map.insertMulti(_source, "memusedgb"); + m_formatter["memusedgb"] = FormatterType::MemGBFormat; + } else if (_source == "network/current/name") { // network device - m_map[source] = QString("netdev"); - m_formatter[QString("netdev")] = FormatterType::NoFormat; - } else if (source.startsWith(QString("network/response"))) { + m_map[_source] = "netdev"; + m_formatter["netdev"] = FormatterType::NoFormat; + } else if (_source.startsWith("network/response")) { // network response - QString key = source; - key.remove(QString("network/")); - m_map[source] = key; + QString key = _source; + key.remove("network/"); + m_map[_source] = key; m_formatter[key] = FormatterType::NoFormat; - } else if (source.contains(netRegExp)) { + } else if (_source.contains(netRegExp)) { // network speed - QString type = source.contains(QString("receiver")) ? QString("down") - : QString("up"); - int index - = m_devices[QString("net")].indexOf(source.split(QChar('/'))[2]); + QString type = _source.contains("receiver") ? "down" : "up"; + int index = m_devices["net"].indexOf(_source.split('/')[2]); if (index > -1) { // kb QString key = QString("%1kb%2").arg(type).arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Integer; // smart key = QString("%1%2").arg(type).arg(index); - m_map.insertMulti(source, key); + m_map.insertMulti(_source, key); m_formatter[key] = FormatterType::NetSmartFormat; // units key = QString("%1units%2").arg(type).arg(index); - m_map.insertMulti(source, key); + m_map.insertMulti(_source, key); m_formatter[key] = FormatterType::NetSmartUnits; } - } else if (source.contains(netTotalRegExp)) { + } else if (_source.contains(netTotalRegExp)) { // network data total - QString type = source.contains(QString("receiver")) ? QString("down") - : QString("up"); - int index - = m_devices[QString("net")].indexOf(source.split(QChar('/'))[2]); + QString type = _source.contains("receiver") ? "down" : "up"; + int index = m_devices["net"].indexOf(_source.split('/')[2]); if (index > -1) { // kb QString key = QString("%1totalkb%2").arg(type).arg(index); - m_map[source] = key; + m_map[_source] = key; m_formatter[key] = FormatterType::Integer; // mb key = QString("%1total%2").arg(type).arg(index); - m_map.insertMulti(source, key); + m_map.insertMulti(_source, key); m_formatter[key] = FormatterType::MemMBFormat; } - } else if (source.startsWith(QString("upgrade"))) { + } else if (_source.startsWith("upgrade")) { // package manager - QString key = source; - key.remove(QString("upgrade/")); - m_map[source] = key; + QString key = _source; + key.remove("upgrade/"); + m_map[_source] = key; m_formatter[key] = FormatterType::IntegerThree; - } else if (source.startsWith(QString("player"))) { + } else if (_source.startsWith("player")) { // player - QString key = source; - key.remove(QString("player/")); - m_map[source] = key; + QString key = _source; + key.remove("player/"); + m_map[_source] = key; m_formatter[key] = FormatterType::NoFormat; - } else if (source == QString("ps/running/count")) { + } else if (_source == "ps/running/count") { // running processes count - m_map[source] = QString("pscount"); - m_formatter[QString("pscount")] = FormatterType::NoFormat; - } else if (source == QString("ps/running/list")) { + m_map[_source] = "pscount"; + m_formatter["pscount"] = FormatterType::NoFormat; + } else if (_source == "ps/running/list") { // list of running processes - m_map[source] = QString("ps"); - m_formatter[QString("ps")] = FormatterType::List; - } else if (source == QString("ps/total/count")) { + m_map[_source] = "ps"; + m_formatter["ps"] = FormatterType::List; + } else if (_source == "ps/total/count") { // total processes count - m_map[source] = QString("pstotal"); - m_formatter[QString("pstotal")] = FormatterType::NoFormat; - } else if (source.startsWith(QString("quotes"))) { + m_map[_source] = "pstotal"; + m_formatter["pstotal"] = FormatterType::NoFormat; + } else if (_source.startsWith("quotes")) { // quotes - QString key = source; - key.remove(QString("quotes/")); - m_map[source] = key; + QString key = _source; + key.remove("quotes/"); + m_map[_source] = key; m_formatter[key] = FormatterType::Quotes; - } else if (source == QString("mem/swap/free")) { + } else if (_source == "mem/swap/free") { // free swap // mb - m_map[source] = QString("swapfreemb"); - m_formatter[QString("swapfreemb")] = FormatterType::MemMBFormat; + m_map[_source] = "swapfreemb"; + m_formatter["swapfreemb"] = FormatterType::MemMBFormat; // gb - m_map.insertMulti(source, QString("swapfreegb")); - m_formatter[QString("swapfreegb")] = FormatterType::MemGBFormat; - } else if (source == QString("mem/swap/used")) { + m_map.insertMulti(_source, "swapfreegb"); + m_formatter["swapfreegb"] = FormatterType::MemGBFormat; + } else if (_source == "mem/swap/used") { // used swap // mb - m_map[source] = QString("swapmb"); - m_formatter[QString("swapmb")] = FormatterType::MemMBFormat; + m_map[_source] = "swapmb"; + m_formatter["swapmb"] = FormatterType::MemMBFormat; // gb - m_map.insertMulti(source, QString("swapgb")); - m_formatter[QString("swapgb")] = FormatterType::MemGBFormat; - } else if (source.startsWith(QString("lmsensors/"))) { + m_map.insertMulti(_source, "swapgb"); + m_formatter["swapgb"] = FormatterType::MemGBFormat; + } else if (_source.startsWith("lmsensors/")) { // temperature - int index = m_devices[QString("temp")].indexOf(source); + int index = m_devices["temp"].indexOf(_source); // HACK on DE initialization there are no units key - if (units.isEmpty()) - return QStringList() << QString("temp%1").arg(index); + if (_units.isEmpty()) + return QStringList({QString("temp%1").arg(index)}); if (index > -1) { QString key = QString("temp%1").arg(index); - m_map[source] = key; - m_formatter[key] = units == QString("°C") - ? FormatterType::Temperature - : FormatterType::Integer; + m_map[_source] = key; + m_formatter[key] = _units == "°C" ? FormatterType::Temperature + : FormatterType::Integer; } - } else if (source == QString("Local")) { + } else if (_source == "Local") { // time - m_map[source] = QString("time"); - m_formatter[QString("time")] = FormatterType::Time; + m_map[_source] = "time"; + m_formatter["time"] = FormatterType::Time; // custom time - m_map.insertMulti(source, QString("ctime")); - m_formatter[QString("ctime")] = FormatterType::TimeCustom; + m_map.insertMulti(_source, "ctime"); + m_formatter["ctime"] = FormatterType::TimeCustom; // ISO time - m_map.insertMulti(source, QString("isotime")); - m_formatter[QString("isotime")] = FormatterType::TimeISO; + m_map.insertMulti(_source, "isotime"); + m_formatter["isotime"] = FormatterType::TimeISO; // long time - m_map.insertMulti(source, QString("longtime")); - m_formatter[QString("longtime")] = FormatterType::TimeLong; + m_map.insertMulti(_source, "longtime"); + m_formatter["longtime"] = FormatterType::TimeLong; // short time - m_map.insertMulti(source, QString("shorttime")); - m_formatter[QString("shorttime")] = FormatterType::TimeShort; + m_map.insertMulti(_source, "shorttime"); + m_formatter["shorttime"] = FormatterType::TimeShort; // timestamp - m_map.insertMulti(source, QString("tstime")); - m_formatter[QString("tstime")] = FormatterType::Timestamp; - } else if (source == QString("system/uptime")) { + m_map.insertMulti(_source, "tstime"); + m_formatter["tstime"] = FormatterType::Timestamp; + } else if (_source == "system/uptime") { // uptime - m_map[source] = QString("uptime"); - m_formatter[QString("uptime")] = FormatterType::Uptime; + m_map[_source] = "uptime"; + m_formatter["uptime"] = FormatterType::Uptime; // custom uptime - m_map.insertMulti(source, QString("cuptime")); - m_formatter[QString("cuptime")] = FormatterType::UptimeCustom; - } else if (source.startsWith(QString("weather/temperature"))) { + m_map.insertMulti(_source, "cuptime"); + m_formatter["cuptime"] = FormatterType::UptimeCustom; + } else if (_source.startsWith("weather/temperature")) { // temperature - QString key = source; - key.remove(QString("weather/")); - m_map[source] = key; + QString key = _source; + key.remove("weather/"); + m_map[_source] = key; m_formatter[key] = FormatterType::Temperature; - } else if (source.startsWith(QString("weather/"))) { + } else if (_source.startsWith("weather/")) { // other weather - QString key = source; - key.remove(QString("weather/")); - m_map[source] = key; + QString key = _source; + key.remove("weather/"); + m_map[_source] = key; m_formatter[key] = FormatterType::NoFormat; - } else if (source.startsWith(QString("load/load"))) { + } else if (_source.startsWith("load/load")) { // load source - QString key = source; - key.remove(QString("load/")); - m_map[source] = key; + QString key = _source; + key.remove("load/"); + m_map[_source] = key; m_formatter[key] = FormatterType::Temperature; } - QStringList foundKeys = keysFromSource(source); + QStringList foundKeys = keysFromSource(_source); // rewrite formatters for custom ones QStringList customFormattersKeys; @@ -603,19 +597,19 @@ QStringList AWKeysAggregator::registerSource(const QString &source, } // drop key from dictionary if no one user requested key required it - qCInfo(LOG_AW) << "Looking for keys" << foundKeys << "in" << keys; + qCInfo(LOG_AW) << "Looking for keys" << foundKeys << "in" << _keys; bool required - = keys.isEmpty() || std::any_of(foundKeys.cbegin(), foundKeys.cend(), - [&keys](const QString &key) { - return keys.contains(key); - }); + = _keys.isEmpty() || std::any_of(foundKeys.cbegin(), foundKeys.cend(), + [&_keys](const QString &key) { + return _keys.contains(key); + }); if (!required) { - m_map.remove(source); + m_map.remove(_source); for (auto &key : foundKeys) m_formatter.remove(key); } - return keysFromSource(source); + return keysFromSource(_source); } @@ -624,18 +618,18 @@ float AWKeysAggregator::temperature(const float temp) const qCDebug(LOG_AW) << "Temperature value" << temp; float converted = temp; - if (m_tempUnits == QString("Celsius")) { - } else if (m_tempUnits == QString("Fahrenheit")) { + if (m_tempUnits == "Celsius") { + } else if (m_tempUnits == "Fahrenheit") { converted = temp * 9.0f / 5.0f + 32.0f; - } else if (m_tempUnits == QString("Kelvin")) { + } else if (m_tempUnits == "Kelvin") { converted = temp + 273.15f; - } else if (m_tempUnits == QString("Reaumur")) { + } else if (m_tempUnits == "Reaumur") { converted = temp * 0.8f; - } else if (m_tempUnits == QString("cm^-1")) { + } else if (m_tempUnits == "cm^-1") { converted = (temp + 273.15f) * 0.695f; - } else if (m_tempUnits == QString("kJ/mol")) { + } else if (m_tempUnits == "kJ/mol") { converted = (temp + 273.15f) * 8.31f; - } else if (m_tempUnits == QString("kcal/mol")) { + } else if (m_tempUnits == "kcal/mol") { converted = (temp + 273.15f) * 1.98f; } else { qCWarning(LOG_AW) << "Invalid units" << m_tempUnits; diff --git a/sources/awesome-widget/plugin/awkeysaggregator.h b/sources/awesome-widget/plugin/awkeysaggregator.h index aa79b75..d29672e 100644 --- a/sources/awesome-widget/plugin/awkeysaggregator.h +++ b/sources/awesome-widget/plugin/awkeysaggregator.h @@ -67,29 +67,29 @@ class AWKeysAggregator : public QObject }; public: - explicit AWKeysAggregator(QObject *parent = nullptr); + explicit AWKeysAggregator(QObject *_parent = nullptr); virtual ~AWKeysAggregator(); void initFormatters(); // get methods - QString formatter(const QVariant &data, const QString &key) const; - QStringList keysFromSource(const QString &source) const; + QString formatter(const QVariant &_data, const QString &_key) const; + QStringList keysFromSource(const QString &_source) const; // set methods - void setAcOffline(const QString &inactive); - void setAcOnline(const QString &active); - void setCustomTime(const QString &customTime); - void setCustomUptime(const QString &customUptime); - void setDevices(const QHash &devices); - void setTempUnits(const QString &units); - void setTranslate(const bool translate); + void setAcOffline(const QString &_inactive); + void setAcOnline(const QString &_active); + void setCustomTime(const QString &_customTime); + void setCustomUptime(const QString &_customUptime); + void setDevices(const QHash &_devices); + void setTempUnits(const QString &_units); + void setTranslate(const bool _translate); public slots: - QStringList registerSource(const QString &source, const QString &units, - const QStringList &keys); + QStringList registerSource(const QString &_source, const QString &_units, + const QStringList &_keys); private: float temperature(const float temp) const; AWFormatterHelper *m_customFormatters = nullptr; - QStringList m_timeKeys = QString(TIME_KEYS).split(QChar(',')); + QStringList m_timeKeys = QString(TIME_KEYS).split(','); // variables QString m_acOffline; QString m_acOnline; diff --git a/sources/awesome-widget/plugin/awpatternfunctions.cpp b/sources/awesome-widget/plugin/awpatternfunctions.cpp index fdbc9c7..b3d5ad5 100644 --- a/sources/awesome-widget/plugin/awpatternfunctions.cpp +++ b/sources/awesome-widget/plugin/awpatternfunctions.cpp @@ -24,52 +24,51 @@ #include "awkeysaggregator.h" -QString AWPatternFunctions::expandLambdas(QString code, - AWKeysAggregator *aggregator, - const QVariantHash &metadata, - const QStringList &usedKeys) +QString AWPatternFunctions::expandLambdas(QString _code, + AWKeysAggregator *_aggregator, + const QVariantHash &_metadata, + const QStringList &_usedKeys) { - qCDebug(LOG_AW) << "Expand lamdas in" << code; + qCDebug(LOG_AW) << "Expand lamdas in" << _code; QJSEngine engine; // apply $this values - code.replace(QString("$this"), metadata[code].toString()); + _code.replace("$this", _metadata[_code].toString()); // parsed values - for (auto &lambdaKey : usedKeys) - code.replace(QString("$%1").arg(lambdaKey), - aggregator->formatter(metadata[lambdaKey], lambdaKey)); - qCInfo(LOG_AW) << "Expression" << code; - QJSValue result = engine.evaluate(code); + for (auto &lambdaKey : _usedKeys) + _code.replace(QString("$%1").arg(lambdaKey), + _aggregator->formatter(_metadata[lambdaKey], lambdaKey)); + qCInfo(LOG_AW) << "Expression" << _code; + QJSValue result = engine.evaluate(_code); if (result.isError()) { qCWarning(LOG_AW) << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); - return QString(); + return ""; } else { return result.toString(); } } -QString AWPatternFunctions::expandTemplates(QString code) +QString AWPatternFunctions::expandTemplates(QString _code) { - qCDebug(LOG_AW) << "Expand templates in" << code; + qCDebug(LOG_AW) << "Expand templates in" << _code; // match the following construction $template{{some code here}} - QRegularExpression templatesRegexp( - QString("\\$template\\{\\{(?.*?)\\}\\}")); + QRegularExpression templatesRegexp("\\$template\\{\\{(?.*?)\\}\\}"); templatesRegexp.setPatternOptions( QRegularExpression::DotMatchesEverythingOption); - QRegularExpressionMatchIterator it = templatesRegexp.globalMatch(code); + QRegularExpressionMatchIterator it = templatesRegexp.globalMatch(_code); while (it.hasNext()) { QRegularExpressionMatch match = it.next(); - QString body = match.captured(QString("body")); + QString body = match.captured("body"); QJSEngine engine; qCInfo(LOG_AW) << "Expression" << body; QJSValue result = engine.evaluate(body); - QString templateResult = QString(""); + QString templateResult = ""; if (result.isError()) { qCWarning(LOG_AW) << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" @@ -79,18 +78,18 @@ QString AWPatternFunctions::expandTemplates(QString code) } // replace template - code.replace(match.captured(), templateResult); + _code.replace(match.captured(), templateResult); } - return code; + return _code; } QList -AWPatternFunctions::findFunctionCalls(const QString &function, - const QString &code) +AWPatternFunctions::findFunctionCalls(const QString &_function, + const QString &_code) { - qCDebug(LOG_AW) << "Looking for function" << function << "in" << code; + qCDebug(LOG_AW) << "Looking for function" << _function << "in" << _code; // I suggest the following regex for the internal functions // $aw_function_name{{function body}} @@ -100,34 +99,34 @@ AWPatternFunctions::findFunctionCalls(const QString &function, // by using $, e.g. ${ QRegularExpression regex( QString("\\$%1\\<(?.*?)\\>\\{\\{(?.*?)\\}\\}") - .arg(function)); + .arg(_function)); regex.setPatternOptions(QRegularExpression::DotMatchesEverythingOption); QList foundFunctions; - QRegularExpressionMatchIterator it = regex.globalMatch(code); + QRegularExpressionMatchIterator it = regex.globalMatch(_code); while (it.hasNext()) { QRegularExpressionMatch match = it.next(); AWPatternFunctions::AWFunction metadata; // work with args - QString argsString = match.captured(QString("args")); + QString argsString = match.captured("args"); if (argsString.isEmpty()) { metadata.args = QStringList(); } else { // replace '$,' to 0x1d - argsString.replace(QString("$,"), QString(0x1d)); - QStringList args = argsString.split(QChar(',')); + argsString.replace("$,", QString(0x1d)); + QStringList args = argsString.split(','); std::for_each(args.begin(), args.end(), [](QString &arg) { - arg.replace(QString(0x1d), QString(",")); + arg.replace(QString(0x1d), ","); }); metadata.args = args; } // other variables - metadata.body = match.captured(QString("body")); + metadata.body = match.captured("body"); metadata.what = match.captured(); // replace brackets - metadata.body.replace(QString("${"), QString("{")); - metadata.body.replace(QString("$}"), QString("}")); + metadata.body.replace("${", "{"); + metadata.body.replace("$}", "}"); foundFunctions.append(metadata); } @@ -135,94 +134,92 @@ AWPatternFunctions::findFunctionCalls(const QString &function, } -QString AWPatternFunctions::insertAllKeys(QString code, const QStringList &keys) +QString AWPatternFunctions::insertAllKeys(QString _code, + const QStringList &_keys) { - qCDebug(LOG_AW) << "Looking for keys in code" << code << "using list" - << keys; + qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" + << _keys; QList found - = AWPatternFunctions::findFunctionCalls(QString("aw_all"), code); + = AWPatternFunctions::findFunctionCalls("aw_all", _code); for (auto &function : found) { - QString separator - = function.args.isEmpty() ? QString(",") : function.args.at(0); - QStringList required = keys.filter(QRegExp(function.body)); + QString separator = function.args.isEmpty() ? "," : function.args.at(0); + QStringList required = _keys.filter(QRegExp(function.body)); std::for_each(required.begin(), required.end(), [](QString &value) { value = QString("%1: $%1").arg(value); }); - code.replace(function.what, required.join(separator)); + _code.replace(function.what, required.join(separator)); } - return code; + return _code; } -QString AWPatternFunctions::insertKeyCount(QString code, - const QStringList &keys) +QString AWPatternFunctions::insertKeyCount(QString _code, + const QStringList &_keys) { - qCDebug(LOG_AW) << "Looking for count in code" << code << "using list" - << keys; + qCDebug(LOG_AW) << "Looking for count in code" << _code << "using list" + << _keys; QList found - = AWPatternFunctions::findFunctionCalls(QString("aw_count"), code); + = AWPatternFunctions::findFunctionCalls("aw_count", _code); for (auto &function : found) { - int count = keys.filter(QRegExp(function.body)).count(); + int count = _keys.filter(QRegExp(function.body)).count(); - code.replace(function.what, QString::number(count)); + _code.replace(function.what, QString::number(count)); } - return code; + return _code; } -QString AWPatternFunctions::insertKeyNames(QString code, - const QStringList &keys) +QString AWPatternFunctions::insertKeyNames(QString _code, + const QStringList &_keys) { - qCDebug(LOG_AW) << "Looking for key names in code" << code << "using list" - << keys; + qCDebug(LOG_AW) << "Looking for key names in code" << _code << "using list" + << _keys; QList found - = AWPatternFunctions::findFunctionCalls(QString("aw_names"), code); + = AWPatternFunctions::findFunctionCalls("aw_names", _code); for (auto &function : found) { - QString separator - = function.args.isEmpty() ? QString(",") : function.args.at(0); - QStringList required = keys.filter(QRegExp(function.body)); + QString separator = function.args.isEmpty() ? "," : function.args.at(0); + QStringList required = _keys.filter(QRegExp(function.body)); - code.replace(function.what, required.join(separator)); + _code.replace(function.what, required.join(separator)); } - return code; + return _code; } -QString AWPatternFunctions::insertKeys(QString code, const QStringList &keys) +QString AWPatternFunctions::insertKeys(QString _code, const QStringList &_keys) { - qCDebug(LOG_AW) << "Looking for keys in code" << code << "using list" - << keys; + qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" + << _keys; QList found - = AWPatternFunctions::findFunctionCalls(QString("aw_keys"), code); + = AWPatternFunctions::findFunctionCalls("aw_keys", _code); for (auto &function : found) { - QString separator - = function.args.isEmpty() ? QString(",") : function.args.at(0); - QStringList required = keys.filter(QRegExp(function.body)); + QString separator = function.args.isEmpty() ? "," : function.args.at(0); + QStringList required = _keys.filter(QRegExp(function.body)); std::for_each(required.begin(), required.end(), [](QString &value) { value = QString("$%1").arg(value); }); - code.replace(function.what, required.join(separator)); + _code.replace(function.what, required.join(separator)); } - return code; + return _code; } -QString AWPatternFunctions::insertMacros(QString code) +QString AWPatternFunctions::insertMacros(QString _code) { - qCDebug(LOG_AW) << "Looking for macros in code" << code; + qCDebug(LOG_AW) << "Looking for macros in code" << _code; QList found - = AWPatternFunctions::findFunctionCalls(QString("aw_macro"), code); + = AWPatternFunctions::findFunctionCalls("aw_macro", _code); for (auto ¯o : found) { // get macro params if (macro.args.isEmpty()) { @@ -233,7 +230,7 @@ QString AWPatternFunctions::insertMacros(QString code) // find macro usage QList macroUsage = AWPatternFunctions::findFunctionCalls( - QString("aw_macro_%1").arg(name), code); + QString("aw_macro_%1").arg(name), _code); for (auto &function : macroUsage) { if (function.args.count() != macro.args.count()) { qCWarning(LOG_AW) @@ -250,31 +247,31 @@ QString AWPatternFunctions::insertMacros(QString code) function.args.at(index)); }); // do replace - code.replace(function.what, result); + _code.replace(function.what, result); } // remove macro from source pattern - code.remove(macro.what); + _code.remove(macro.what); } - return code; + return _code; } -QStringList AWPatternFunctions::findKeys(const QString &code, - const QStringList &keys, - const bool isBars) +QStringList AWPatternFunctions::findKeys(const QString &_code, + const QStringList &_keys, + const bool _isBars) { - qCDebug(LOG_AW) << "Looking for keys in code" << code << "using list" - << keys; + qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" + << _keys; QStringList selectedKeys; - QString replacedCode = code; - for (auto &key : keys) - if ((key.startsWith(QString("bar")) == isBars) + QString replacedCode = _code; + for (auto &key : _keys) + if ((key.startsWith("bar") == _isBars) && (replacedCode.contains(QString("$%1").arg(key)))) { qCInfo(LOG_AW) << "Found key" << key << "with bar enabled" - << isBars; + << _isBars; selectedKeys.append(key); replacedCode.replace(QString("$%1").arg(key), ""); } @@ -285,20 +282,20 @@ QStringList AWPatternFunctions::findKeys(const QString &code, } -QStringList AWPatternFunctions::findLambdas(const QString &code) +QStringList AWPatternFunctions::findLambdas(const QString &_code) { - qCDebug(LOG_AW) << "Looking for lambdas in code" << code; + qCDebug(LOG_AW) << "Looking for lambdas in code" << _code; QStringList selectedKeys; // match the following construction ${{some code here}} - QRegularExpression lambdaRegexp(QString("\\$\\{\\{(?.*?)\\}\\}")); + QRegularExpression lambdaRegexp("\\$\\{\\{(?.*?)\\}\\}"); lambdaRegexp.setPatternOptions( QRegularExpression::DotMatchesEverythingOption); - QRegularExpressionMatchIterator it = lambdaRegexp.globalMatch(code); + QRegularExpressionMatchIterator it = lambdaRegexp.globalMatch(_code); while (it.hasNext()) { QRegularExpressionMatch match = it.next(); - QString lambda = match.captured(QString("body")); + QString lambda = match.captured("body"); // append qCInfo(LOG_AW) << "Found lambda" << lambda; diff --git a/sources/awesome-widget/plugin/awpatternfunctions.h b/sources/awesome-widget/plugin/awpatternfunctions.h index 75f051d..6c3f0ba 100644 --- a/sources/awesome-widget/plugin/awpatternfunctions.h +++ b/sources/awesome-widget/plugin/awpatternfunctions.h @@ -34,21 +34,21 @@ typedef struct { } AWFunction; // insert methods -QString expandLambdas(QString code, AWKeysAggregator *aggregator, - const QVariantHash &metadata, - const QStringList &usedKeys); -QString expandTemplates(QString code); -QList findFunctionCalls(const QString &function, - const QString &code); -QString insertAllKeys(QString code, const QStringList &keys); -QString insertKeyCount(QString code, const QStringList &keys); -QString insertKeyNames(QString code, const QStringList &keys); -QString insertKeys(QString code, const QStringList &keys); -QString insertMacros(QString code); +QString expandLambdas(QString _code, AWKeysAggregator *_aggregator, + const QVariantHash &_metadata, + const QStringList &_usedKeys); +QString expandTemplates(QString _code); +QList findFunctionCalls(const QString &_function, + const QString &_code); +QString insertAllKeys(QString _code, const QStringList &_keys); +QString insertKeyCount(QString _code, const QStringList &_keys); +QString insertKeyNames(QString _code, const QStringList &_keys); +QString insertKeys(QString _code, const QStringList &_keys); +QString insertMacros(QString _code); // find methods -QStringList findKeys(const QString &code, const QStringList &keys, - const bool isBars); -QStringList findLambdas(const QString &code); +QStringList findKeys(const QString &_code, const QStringList &_keys, + const bool _isBars); +QStringList findLambdas(const QString &_code); }; diff --git a/sources/awesome-widget/plugin/awtelemetryhandler.cpp b/sources/awesome-widget/plugin/awtelemetryhandler.cpp index 9d33455..c0e3a51 100644 --- a/sources/awesome-widget/plugin/awtelemetryhandler.cpp +++ b/sources/awesome-widget/plugin/awtelemetryhandler.cpp @@ -29,8 +29,9 @@ #include "awdebug.h" -AWTelemetryHandler::AWTelemetryHandler(QObject *parent, const QString &clientId) - : QObject(parent) +AWTelemetryHandler::AWTelemetryHandler(QObject *_parent, + const QString &_clientId) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -39,8 +40,8 @@ AWTelemetryHandler::AWTelemetryHandler(QObject *parent, const QString &clientId) QStandardPaths::GenericDataLocation)); // override client id if any - if (!clientId.isEmpty()) - m_clientId = clientId; + if (!_clientId.isEmpty()) + m_clientId = _clientId; } @@ -50,14 +51,14 @@ AWTelemetryHandler::~AWTelemetryHandler() } -QStringList AWTelemetryHandler::get(const QString &group) const +QStringList AWTelemetryHandler::get(const QString &_group) const { - qCDebug(LOG_AW) << "Get stored data for group" << group; + qCDebug(LOG_AW) << "Get stored data for group" << _group; QStringList values; QSettings settings(m_localFile, QSettings::IniFormat); - settings.beginGroup(group); + settings.beginGroup(_group); for (auto &key : settings.childKeys()) values.append(settings.value(key).toString()); settings.endGroup(); @@ -66,53 +67,54 @@ QStringList AWTelemetryHandler::get(const QString &group) const } -QString AWTelemetryHandler::getLast(const QString &group) const +QString AWTelemetryHandler::getLast(const QString &_group) const { - qCDebug(LOG_AW) << "Get last stored data for group" << group; + qCDebug(LOG_AW) << "Get last stored data for group" << _group; - return get(group).last(); + return get(_group).last(); } -void AWTelemetryHandler::init(const int count, const bool enableRemote, - const QString &clientId) +void AWTelemetryHandler::init(const int _count, const bool _enableRemote, + const QString &_clientId) { - qCDebug(LOG_AW) << "Init telemetry with count" << count << "enable remote" - << enableRemote << "client ID" << clientId; + qCDebug(LOG_AW) << "Init telemetry with count" << _count << "enable remote" + << _enableRemote << "client ID" << _clientId; - m_storeCount = count; - m_uploadEnabled = enableRemote; - m_clientId = clientId; + m_storeCount = _count; + m_uploadEnabled = _enableRemote; + m_clientId = _clientId; } -bool AWTelemetryHandler::put(const QString &group, const QString &value) const +bool AWTelemetryHandler::put(const QString &_group, const QString &_value) const { - qCDebug(LOG_AW) << "Store data with group" << group << "and value" << value; + qCDebug(LOG_AW) << "Store data with group" << _group << "and value" + << _value; QSettings settings(m_localFile, QSettings::IniFormat); - settings.beginGroup(group); + settings.beginGroup(_group); // values will be stored as num=value inside specified group // load all values to memory QStringList saved; for (auto &key : settings.childKeys()) saved.append(settings.value(key).toString()); // check if this value is already saved - if (saved.contains(value)) { - qCInfo(LOG_AW) << "Configuration" << value << "for group" << group + if (saved.contains(_value)) { + qCInfo(LOG_AW) << "Configuration" << _value << "for group" << _group << "is already saved"; return false; } - saved.append(value); + saved.append(_value); // remove old ones while (saved.count() > m_storeCount) saved.takeFirst(); // clear group - settings.remove(QString("")); + settings.remove(""); // and save now - for (auto &value : saved) { + for (auto &val : saved) { QString key = getKey(settings.childKeys().count()); - settings.setValue(key, value); + settings.setValue(key, val); } // sync settings @@ -123,11 +125,11 @@ bool AWTelemetryHandler::put(const QString &group, const QString &value) const } -void AWTelemetryHandler::uploadTelemetry(const QString &group, - const QString &value) +void AWTelemetryHandler::uploadTelemetry(const QString &_group, + const QString &_value) { - qCDebug(LOG_AW) << "Upload data with group" << group << "and value" - << value; + qCDebug(LOG_AW) << "Upload data with group" << _group << "and value" + << _value; if (!m_uploadEnabled) { qCInfo(LOG_AW) << "Upload disabled by configuration"; return; @@ -143,10 +145,10 @@ void AWTelemetryHandler::uploadTelemetry(const QString &group, // generate payload QVariantMap payload; - payload[QString("api")] = AW_TELEMETRY_API; - payload[QString("client_id")] = m_clientId; - payload[QString("metadata")] = value; - payload[QString("type")] = group; + payload["api"] = AW_TELEMETRY_API; + payload["client_id"] = m_clientId; + payload["metadata"] = _value; + payload["type"] = _group; // convert to QByteArray to send request QByteArray data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact); @@ -157,34 +159,34 @@ void AWTelemetryHandler::uploadTelemetry(const QString &group, } -void AWTelemetryHandler::telemetryReplyRecieved(QNetworkReply *reply) +void AWTelemetryHandler::telemetryReplyRecieved(QNetworkReply *_reply) { - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); return; } QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); + QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error); if (error.error != QJsonParseError::NoError) { qCWarning(LOG_AW) << "Parse error" << error.errorString(); return; } - reply->deleteLater(); + _reply->deleteLater(); // convert to map QVariantMap response = jsonDoc.toVariant().toMap(); - QString message = response[QString("message")].toString(); + QString message = response["message"].toString(); qCInfo(LOG_AW) << "Server reply on telemetry" << message; return emit(replyReceived(message)); } -QString AWTelemetryHandler::getKey(const int count) const +QString AWTelemetryHandler::getKey(const int _count) const { - qCDebug(LOG_AW) << "Get key for keys count" << count; + qCDebug(LOG_AW) << "Get key for keys count" << _count; - return QString("%1").arg(count, 3, 10, QChar('0')); + return QString("%1").arg(_count, 3, 10, QChar('0')); } diff --git a/sources/awesome-widget/plugin/awtelemetryhandler.h b/sources/awesome-widget/plugin/awtelemetryhandler.h index a77c571..3fdab9c 100644 --- a/sources/awesome-widget/plugin/awtelemetryhandler.h +++ b/sources/awesome-widget/plugin/awtelemetryhandler.h @@ -33,25 +33,25 @@ class AWTelemetryHandler : public QObject public: const char *REMOTE_TELEMETRY_URL = "https://arcanis.me/telemetry"; - explicit AWTelemetryHandler(QObject *parent = nullptr, - const QString &clientId = QString()); + explicit AWTelemetryHandler(QObject *_parent = nullptr, + const QString &_clientId = ""); virtual ~AWTelemetryHandler(); - Q_INVOKABLE QStringList get(const QString &group) const; - Q_INVOKABLE QString getLast(const QString &group) const; - Q_INVOKABLE void init(const int count, const bool enableRemote, - const QString &clientId); - Q_INVOKABLE bool put(const QString &group, const QString &value) const; - Q_INVOKABLE void uploadTelemetry(const QString &group, - const QString &value); + Q_INVOKABLE QStringList get(const QString &_group) const; + Q_INVOKABLE QString getLast(const QString &_group) const; + Q_INVOKABLE void init(const int _count, const bool _enableRemote, + const QString &_clientId); + Q_INVOKABLE bool put(const QString &_group, const QString &_value) const; + Q_INVOKABLE void uploadTelemetry(const QString &_group, + const QString &_value); signals: - void replyReceived(const QString &message); + void replyReceived(const QString &_message); private slots: - void telemetryReplyRecieved(QNetworkReply *reply); + void telemetryReplyRecieved(QNetworkReply *_reply); private: - QString getKey(const int count) const; + QString getKey(const int _count) const; QString m_clientId; QString m_localFile; int m_storeCount = 0; diff --git a/sources/awesome-widget/plugin/awupdatehelper.cpp b/sources/awesome-widget/plugin/awupdatehelper.cpp index ea9764f..f6b5338 100644 --- a/sources/awesome-widget/plugin/awupdatehelper.cpp +++ b/sources/awesome-widget/plugin/awupdatehelper.cpp @@ -30,8 +30,8 @@ #include "awdebug.h" -AWUpdateHelper::AWUpdateHelper(QObject *parent) - : QObject(parent) +AWUpdateHelper::AWUpdateHelper(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_AW) << __PRETTY_FUNCTION__; @@ -48,16 +48,16 @@ AWUpdateHelper::~AWUpdateHelper() } -void AWUpdateHelper::checkUpdates(const bool showAnyway) +void AWUpdateHelper::checkUpdates(const bool _showAnyway) { - qCDebug(LOG_AW) << "Show anyway" << showAnyway; + qCDebug(LOG_AW) << "Show anyway" << _showAnyway; // showAnyway options requires to show message if no updates found on direct // request. In case of automatic check no message will be shown QNetworkAccessManager *manager = new QNetworkAccessManager(nullptr); connect(manager, &QNetworkAccessManager::finished, - [showAnyway, this](QNetworkReply *reply) { - return versionReplyRecieved(reply, showAnyway); + [_showAnyway, this](QNetworkReply *reply) { + return versionReplyRecieved(reply, _showAnyway); }); manager->get(QNetworkRequest(QUrl(VERSION_API))); @@ -68,17 +68,16 @@ bool AWUpdateHelper::checkVersion() { QSettings settings(m_genericConfig, QSettings::IniFormat); QVersionNumber version = QVersionNumber::fromString( - settings.value(QString("Version"), QString(VERSION)).toString()); + settings.value("Version", QString(VERSION)).toString()); // update version - settings.setValue(QString("Version"), QString(VERSION)); + settings.setValue("Version", QString(VERSION)); settings.sync(); qCInfo(LOG_AW) << "Found version" << version << "actual one is" << m_foundVersion; if ((version != m_foundVersion) && (!QString(CHANGELOG).isEmpty())) { - genMessageBox(i18n("Changelog of %1", QString(VERSION)), - QString(CHANGELOG).replace(QChar('@'), QChar('\n')), - QMessageBox::Ok) + genMessageBox(i18n("Changelog of %1", VERSION), + QString(CHANGELOG).replace('@', '\n'), QMessageBox::Ok) ->open(); return true; } else if (version != m_foundVersion) { @@ -92,12 +91,12 @@ bool AWUpdateHelper::checkVersion() } -void AWUpdateHelper::showInfo(const QVersionNumber &version) +void AWUpdateHelper::showInfo(const QVersionNumber &_version) { - qCDebug(LOG_AW) << "Version" << version; + qCDebug(LOG_AW) << "Version" << _version; QString text - = i18n("You are using the actual version %1", version.toString()); + = i18n("You are using the actual version %1", _version.toString()); if (!QString(COMMIT_SHA).isEmpty()) text += QString(" (%1)").arg(QString(COMMIT_SHA)); return genMessageBox(i18n("No new version found"), text, QMessageBox::Ok) @@ -105,16 +104,16 @@ void AWUpdateHelper::showInfo(const QVersionNumber &version) } -void AWUpdateHelper::showUpdates(const QVersionNumber &version) +void AWUpdateHelper::showUpdates(const QVersionNumber &_version) { - qCDebug(LOG_AW) << "Version" << version; + qCDebug(LOG_AW) << "Version" << _version; QString text; - text += i18n("Current version : %1", QString(VERSION)); + text += i18n("Current version : %1", VERSION); text += QString(COMMIT_SHA).isEmpty() - ? QString("\n") + ? "\n" : QString(" (%1)\n").arg(QString(COMMIT_SHA)); - text += i18n("New version : %1", version.toString()) + QString("\n\n"); + text += i18n("New version : %1", _version.toString()) + "\n\n"; text += i18n("Click \"Ok\" to download"); genMessageBox(i18n("There are updates"), text, @@ -123,10 +122,10 @@ void AWUpdateHelper::showUpdates(const QVersionNumber &version) } -void AWUpdateHelper::userReplyOnUpdates(QAbstractButton *button) +void AWUpdateHelper::userReplyOnUpdates(QAbstractButton *_button) { QMessageBox::ButtonRole ret - = static_cast(sender())->buttonRole(button); + = static_cast(sender())->buttonRole(_button); qCInfo(LOG_AW) << "User select" << ret; switch (ret) { @@ -141,53 +140,53 @@ void AWUpdateHelper::userReplyOnUpdates(QAbstractButton *button) } -void AWUpdateHelper::versionReplyRecieved(QNetworkReply *reply, - const bool showAnyway) +void AWUpdateHelper::versionReplyRecieved(QNetworkReply *_reply, + const bool _showAnyway) { - qCDebug(LOG_AW) << "Show message anyway" << showAnyway; - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); + qCDebug(LOG_AW) << "Show message anyway" << _showAnyway; + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); return; } QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); + QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error); if (error.error != QJsonParseError::NoError) { qCWarning(LOG_AW) << "Parse error" << error.errorString(); return; } - reply->deleteLater(); + _reply->deleteLater(); // convert to map QVariantMap firstRelease = jsonDoc.toVariant().toList().first().toMap(); - QString version = firstRelease[QString("tag_name")].toString(); - version.remove(QString("V.")); + QString version = firstRelease["tag_name"].toString(); + version.remove("V."); m_foundVersion = QVersionNumber::fromString(version); qCInfo(LOG_AW) << "Update found version to" << m_foundVersion; QVersionNumber oldVersion = QVersionNumber::fromString(VERSION); if (oldVersion < m_foundVersion) return showUpdates(m_foundVersion); - else if (showAnyway) + else if (_showAnyway) return showInfo(m_foundVersion); } // additional method which is used to show message box which does not block UI QMessageBox * -AWUpdateHelper::genMessageBox(const QString &title, const QString &body, - const QMessageBox::StandardButtons buttons) +AWUpdateHelper::genMessageBox(const QString &_title, const QString &_body, + const QMessageBox::StandardButtons _buttons) { - qCDebug(LOG_AW) << "Construct message box with title" << title << "and body" - << body; + qCDebug(LOG_AW) << "Construct message box with title" << _title + << "and body" << _body; QMessageBox *msgBox = new QMessageBox(nullptr); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setModal(false); - msgBox->setWindowTitle(title); - msgBox->setText(body); - msgBox->setStandardButtons(buttons); + msgBox->setWindowTitle(_title); + msgBox->setText(_body); + msgBox->setStandardButtons(_buttons); msgBox->setIcon(QMessageBox::Information); return msgBox; diff --git a/sources/awesome-widget/plugin/awupdatehelper.h b/sources/awesome-widget/plugin/awupdatehelper.h index 213384a..cfd26e7 100644 --- a/sources/awesome-widget/plugin/awupdatehelper.h +++ b/sources/awesome-widget/plugin/awupdatehelper.h @@ -31,20 +31,20 @@ class AWUpdateHelper : public QObject Q_OBJECT public: - explicit AWUpdateHelper(QObject *parent = nullptr); + explicit AWUpdateHelper(QObject *_parent = nullptr); virtual ~AWUpdateHelper(); - void checkUpdates(const bool showAnyway = false); + void checkUpdates(const bool _showAnyway = false); bool checkVersion(); private slots: - void showInfo(const QVersionNumber &version); - void showUpdates(const QVersionNumber &version); - void userReplyOnUpdates(QAbstractButton *button); - void versionReplyRecieved(QNetworkReply *reply, const bool showAnyway); + void showInfo(const QVersionNumber &_version); + void showUpdates(const QVersionNumber &_version); + void userReplyOnUpdates(QAbstractButton *_button); + void versionReplyRecieved(QNetworkReply *_reply, const bool _showAnyway); private: - QMessageBox *genMessageBox(const QString &title, const QString &body, - const QMessageBox::StandardButtons buttons); + QMessageBox *genMessageBox(const QString &_title, const QString &_body, + const QMessageBox::StandardButtons _buttons); QVersionNumber m_foundVersion; QString m_genericConfig; }; diff --git a/sources/awesomewidgets/abstractextitem.cpp b/sources/awesomewidgets/abstractextitem.cpp index 4e925f6..6595d73 100644 --- a/sources/awesomewidgets/abstractextitem.cpp +++ b/sources/awesomewidgets/abstractextitem.cpp @@ -28,13 +28,13 @@ #include "qcronscheduler.h" -AbstractExtItem::AbstractExtItem(QWidget *parent, const QString &filePath) - : QDialog(parent) - , m_fileName(filePath) +AbstractExtItem::AbstractExtItem(QWidget *_parent, const QString &_filePath) + : QDialog(_parent) + , m_fileName(_filePath) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - qCDebug(LOG_LIB) << "Desktop name" << filePath; + qCDebug(LOG_LIB) << "Desktop name" << _filePath; m_name = m_fileName; } @@ -299,18 +299,15 @@ void AbstractExtItem::readConfiguration() { QSettings settings(m_fileName, QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setName(settings.value(QString("Name"), name()).toString()); - setComment(settings.value(QString("Comment"), comment()).toString()); - setApiVersion( - settings.value(QString("X-AW-ApiVersion"), apiVersion()).toInt()); - setActive( - settings.value(QString("X-AW-Active"), QVariant(isActive())).toString() - == QString("true")); - setInterval(settings.value(QString("X-AW-Interval"), interval()).toInt()); - setNumber(settings.value(QString("X-AW-Number"), number()).toInt()); - setCron(settings.value(QString("X-AW-Schedule"), cron()).toString()); - setSocket(settings.value(QString("X-AW-Socket"), socket()).toString()); + settings.beginGroup("Desktop Entry"); + setName(settings.value("Name", name()).toString()); + setComment(settings.value("Comment", comment()).toString()); + setApiVersion(settings.value("X-AW-ApiVersion", apiVersion()).toInt()); + setActive(settings.value("X-AW-Active", isActive()).toBool()); + setInterval(settings.value("X-AW-Interval", interval()).toInt()); + setNumber(settings.value("X-AW-Number", number()).toInt()); + setCron(settings.value("X-AW-Schedule", cron()).toString()); + setSocket(settings.value("X-AW-Socket", socket()).toString()); settings.endGroup(); } @@ -329,18 +326,16 @@ void AbstractExtItem::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("Encoding"), QString("UTF-8")); - settings.setValue(QString("Name"), name()); - settings.setValue(QString("Comment"), comment()); - settings.setValue(QString("X-AW-ApiVersion"), apiVersion()); - settings.setValue(QString("X-AW-Active"), QVariant(isActive()).toString()); - settings.setValue(QString("X-AW-Interval"), - cron().isEmpty() ? QVariant(interval()) - : QVariant(cron())); - settings.setValue(QString("X-AW-Number"), number()); - settings.setValue(QString("X-AW-Schedule"), cron()); - settings.setValue(QString("X-AW-Socket"), socket()); + settings.beginGroup("Desktop Entry"); + settings.setValue("Encoding", "UTF-8"); + settings.setValue("Name", name()); + settings.setValue("Comment", comment()); + settings.setValue("X-AW-ApiVersion", apiVersion()); + settings.setValue("X-AW-Active", isActive()); + settings.setValue("X-AW-Interval", interval()); + settings.setValue("X-AW-Number", number()); + settings.setValue("X-AW-Schedule", cron()); + settings.setValue("X-AW-Socket", socket()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/abstractextitem.h b/sources/awesomewidgets/abstractextitem.h index efafcca..1408f0b 100644 --- a/sources/awesomewidgets/abstractextitem.h +++ b/sources/awesomewidgets/abstractextitem.h @@ -40,8 +40,8 @@ class AbstractExtItem : public QDialog Q_PROPERTY(QString uniq READ uniq) public: - explicit AbstractExtItem(QWidget *parent, - const QString &filePath = QString()); + explicit AbstractExtItem(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AbstractExtItem(); virtual void bumpApi(const int _newVer); virtual AbstractExtItem *copy(const QString &_fileName, const int _number) @@ -62,17 +62,17 @@ public: QString tag(const QString &_type) const; virtual QString uniq() const = 0; // set methods - void setApiVersion(const int _apiVersion = 0); - void setActive(const bool _state = true); - void setComment(const QString &_comment = QString("empty")); - void setCron(const QString &_cron = ""); - void setInterval(const int _interval = 1); - void setName(const QString &_name = QString("none")); - void setNumber(int _number = -1); - void setSocket(const QString &_socket = QString("")); + void setApiVersion(const int _apiVersion); + void setActive(const bool _state); + void setComment(const QString &_comment); + void setCron(const QString &_cron); + void setInterval(const int _interval); + void setName(const QString &_name); + void setNumber(int _number); + void setSocket(const QString &_socket); signals: - void dataReceived(const QVariantHash &data); + void dataReceived(const QVariantHash &_data); void requestDataUpdate(); public slots: @@ -80,7 +80,7 @@ public slots: virtual void initSocket(); virtual void readConfiguration(); virtual QVariantHash run() = 0; - virtual int showConfiguration(const QVariant &args = QVariant()) = 0; + virtual int showConfiguration(const QVariant &_args) = 0; virtual bool tryDelete() const; virtual void writeConfiguration() const; @@ -89,19 +89,19 @@ private slots: private: QCronScheduler *m_scheduler = nullptr; - QString m_fileName = QString("/dev/null"); + QString m_fileName = "/dev/null"; int m_times = 0; virtual void translate() = 0; // properties int m_apiVersion = 0; bool m_active = true; - QString m_comment = QString("empty"); + QString m_comment = "empty"; QString m_cron = ""; int m_interval = 1; - QString m_name = QString("none"); + QString m_name = "none"; int m_number = -1; QLocalServer *m_socket = nullptr; - QString m_socketFile = QString(""); + QString m_socketFile = ""; }; diff --git a/sources/awesomewidgets/abstractextitemaggregator.cpp b/sources/awesomewidgets/abstractextitemaggregator.cpp index 3a601e1..f68535a 100644 --- a/sources/awesomewidgets/abstractextitemaggregator.cpp +++ b/sources/awesomewidgets/abstractextitemaggregator.cpp @@ -25,11 +25,11 @@ #include -AbstractExtItemAggregator::AbstractExtItemAggregator(QWidget *parent, - const QString &type) - : QDialog(parent) +AbstractExtItemAggregator::AbstractExtItemAggregator(QWidget *_parent, + const QString &_type) + : QDialog(_parent) , ui(new Ui::AbstractExtItemAggregator) - , m_type(type) + , m_type(_type) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; @@ -113,13 +113,13 @@ void AbstractExtItemAggregator::editItem() QString AbstractExtItemAggregator::getName() { bool ok; - QString name = QInputDialog::getText(this, i18n("Enter file name"), - i18n("File name"), QLineEdit::Normal, - QString(""), &ok); + QString name + = QInputDialog::getText(this, i18n("Enter file name"), + i18n("File name"), QLineEdit::Normal, "", &ok); if ((!ok) || (name.isEmpty())) - return QString(""); - if (!name.endsWith(QString(".desktop"))) - name += QString(".desktop"); + return ""; + if (!name.endsWith(".desktop")) + name += ".desktop"; return name; } @@ -157,7 +157,7 @@ void AbstractExtItemAggregator::repaintList() tooltip.append(i18n("Name: %1", _item->name())); tooltip.append(i18n("Comment: %1", _item->comment())); tooltip.append(i18n("Identity: %1", _item->uniq())); - item->setToolTip(tooltip.join(QChar('\n'))); + item->setToolTip(tooltip.join('\n')); ui->listWidget->addItem(item); } } @@ -202,14 +202,14 @@ void AbstractExtItemAggregator::editItemActivated(QListWidgetItem *) } -void AbstractExtItemAggregator::editItemButtonPressed(QAbstractButton *button) +void AbstractExtItemAggregator::editItemButtonPressed(QAbstractButton *_button) { - if (static_cast(button) == copyButton) + if (static_cast(_button) == copyButton) return copyItem(); - else if (static_cast(button) == createButton) + else if (static_cast(_button) == createButton) return doCreateItem(); - else if (static_cast(button) == deleteButton) + else if (static_cast(_button) == deleteButton) return deleteItem(); - else if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) + else if (ui->buttonBox->buttonRole(_button) == QDialogButtonBox::AcceptRole) return editItem(); } diff --git a/sources/awesomewidgets/abstractextitemaggregator.h b/sources/awesomewidgets/abstractextitemaggregator.h index 69afa9e..207a43e 100644 --- a/sources/awesomewidgets/abstractextitemaggregator.h +++ b/sources/awesomewidgets/abstractextitemaggregator.h @@ -39,7 +39,7 @@ class AbstractExtItemAggregator : public QDialog Q_PROPERTY(QVariant type READ type) public: - explicit AbstractExtItemAggregator(QWidget *parent, const QString &type); + explicit AbstractExtItemAggregator(QWidget *_parent, const QString &_type); virtual ~AbstractExtItemAggregator(); // methods void copyItem(); @@ -79,7 +79,7 @@ public: private slots: void editItemActivated(QListWidgetItem *); - void editItemButtonPressed(QAbstractButton *button); + void editItemButtonPressed(QAbstractButton *_button); private: // ui diff --git a/sources/awesomewidgets/abstractweatherprovider.h b/sources/awesomewidgets/abstractweatherprovider.h index dab7de5..32fbaed 100644 --- a/sources/awesomewidgets/abstractweatherprovider.h +++ b/sources/awesomewidgets/abstractweatherprovider.h @@ -28,14 +28,14 @@ class AbstractWeatherProvider : public QObject Q_PROPERTY(int number READ number) public: - explicit AbstractWeatherProvider(QObject *parent, const int number) - : QObject(parent) - , m_number(number){}; + explicit AbstractWeatherProvider(QObject *_parent, const int _number) + : QObject(_parent) + , m_number(_number){}; virtual ~AbstractWeatherProvider(){}; - virtual void initUrl(const QString &city, const QString &country, - const int ts) + virtual void initUrl(const QString &_city, const QString &_country, + const int _ts) = 0; - virtual QVariantHash parse(const QVariantMap &json) const = 0; + virtual QVariantHash parse(const QVariantMap &_json) const = 0; virtual QUrl url() const = 0; int number() const { return m_number; }; diff --git a/sources/awesomewidgets/awabstractformatter.cpp b/sources/awesomewidgets/awabstractformatter.cpp index d0f3d13..0ecfde1 100644 --- a/sources/awesomewidgets/awabstractformatter.cpp +++ b/sources/awesomewidgets/awabstractformatter.cpp @@ -22,9 +22,9 @@ #include "awdebug.h" -AWAbstractFormatter::AWAbstractFormatter(QWidget *parent, - const QString &filePath) - : AbstractExtItem(parent, filePath) +AWAbstractFormatter::AWAbstractFormatter(QWidget *_parent, + const QString &_filePath) + : AbstractExtItem(_parent, _filePath) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; } @@ -55,25 +55,25 @@ QString AWAbstractFormatter::strType() const QString value; switch (m_type) { case FormatterClass::DateTime: - value = QString("DateTime"); + value = "DateTime"; break; case FormatterClass::Float: - value = QString("Float"); + value = "Float"; break; case FormatterClass::List: - value = QString("List"); + value = "List"; break; case FormatterClass::Script: - value = QString("Script"); + value = "Script"; break; case FormatterClass::String: - value = QString("String"); + value = "String"; break; case FormatterClass::Json: - value = QString("Json"); + value = "Json"; break; case FormatterClass::NoFormat: - value = QString("NoFormat"); + value = "NoFormat"; break; } @@ -91,17 +91,17 @@ void AWAbstractFormatter::setStrType(const QString &_type) { qCDebug(LOG_LIB) << "Type" << _type; - if (_type == QString("DateTime")) + if (_type == "DateTime") m_type = FormatterClass::DateTime; - else if (_type == QString("Float")) + else if (_type == "Float") m_type = FormatterClass::Float; - else if (_type == QString("List")) + else if (_type == "List") m_type = FormatterClass::List; - else if (_type == QString("Script")) + else if (_type == "Script") m_type = FormatterClass::Script; - else if (_type == QString("String")) + else if (_type == "String") m_type = FormatterClass::String; - else if (_type == QString("Json")) + else if (_type == "Json") m_type = FormatterClass::Json; else m_type = FormatterClass::NoFormat; @@ -123,8 +123,8 @@ void AWAbstractFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setStrType(settings.value(QString("X-AW-Type"), strType()).toString()); + settings.beginGroup("Desktop Entry"); + setStrType(settings.value("X-AW-Type", strType()).toString()); settings.endGroup(); } @@ -136,8 +136,8 @@ void AWAbstractFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Type"), strType()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Type", strType()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/awabstractformatter.h b/sources/awesomewidgets/awabstractformatter.h index 5e6014b..f575494 100644 --- a/sources/awesomewidgets/awabstractformatter.h +++ b/sources/awesomewidgets/awabstractformatter.h @@ -38,8 +38,8 @@ public: Json }; - explicit AWAbstractFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWAbstractFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWAbstractFormatter(); virtual QString convert(const QVariant &_value) const = 0; void copyDefaults(AbstractExtItem *_other) const; @@ -47,8 +47,8 @@ public: // properties QString strType() const; FormatterClass type() const; - void setStrType(const QString &type); - void setType(const FormatterClass _type = FormatterClass::NoFormat); + void setStrType(const QString &_type); + void setType(const FormatterClass _type); public slots: virtual void readConfiguration(); diff --git a/sources/awesomewidgets/awdatetimeformatter.cpp b/sources/awesomewidgets/awdatetimeformatter.cpp index b1da52e..0575d95 100644 --- a/sources/awesomewidgets/awdatetimeformatter.cpp +++ b/sources/awesomewidgets/awdatetimeformatter.cpp @@ -28,14 +28,14 @@ #include "awdebug.h" -AWDateTimeFormatter::AWDateTimeFormatter(QWidget *parent, - const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWDateTimeFormatter::AWDateTimeFormatter(QWidget *_parent, + const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWDateTimeFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -109,23 +109,23 @@ void AWDateTimeFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setFormat(settings.value(QString("X-AW-Format"), format()).toString()); + settings.beginGroup("Desktop Entry"); + setFormat(settings.value("X-AW-Format", format()).toString()); setTranslateString( - settings.value(QString("X-AW-Translate"), translateString()).toBool()); + settings.value("X-AW-Translate", translateString()).toBool()); settings.endGroup(); bumpApi(AW_FORMATTER_API); } -int AWDateTimeFormatter::showConfiguration(const QVariant &args) +int AWDateTimeFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("DateTime")); + ui->label_typeValue->setText("DateTime"); ui->lineEdit_format->setText(format()); ui->checkBox_translate->setCheckState(translateString() ? Qt::Checked : Qt::Unchecked); @@ -152,9 +152,9 @@ void AWDateTimeFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Format"), format()); - settings.setValue(QString("X-AW-Translate"), translateString()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Format", format()); + settings.setValue("X-AW-Translate", translateString()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/awdatetimeformatter.h b/sources/awesomewidgets/awdatetimeformatter.h index b5e03be..0e023a5 100644 --- a/sources/awesomewidgets/awdatetimeformatter.h +++ b/sources/awesomewidgets/awdatetimeformatter.h @@ -35,8 +35,8 @@ class AWDateTimeFormatter : public AWAbstractFormatter bool translateString READ translateString WRITE setTranslateString) public: - explicit AWDateTimeFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWDateTimeFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWDateTimeFormatter(); QString convert(const QVariant &_value) const; AWDateTimeFormatter *copy(const QString &_fileName, const int _number); @@ -48,7 +48,7 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: @@ -57,7 +57,7 @@ private: void translate(); // properties QLocale m_locale; - QString m_format = QString(); + QString m_format = ""; bool m_translate = true; }; diff --git a/sources/awesomewidgets/awfloatformatter.cpp b/sources/awesomewidgets/awfloatformatter.cpp index 7b48b12..7fab070 100644 --- a/sources/awesomewidgets/awfloatformatter.cpp +++ b/sources/awesomewidgets/awfloatformatter.cpp @@ -27,13 +27,13 @@ #include "awdebug.h" -AWFloatFormatter::AWFloatFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWFloatFormatter::AWFloatFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWFloatFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -193,34 +193,30 @@ void AWFloatFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setCount(settings.value(QString("X-AW-Width"), count()).toInt()); - setFillChar( - settings.value(QString("X-AW-FillChar"), fillChar()).toString().at(0)); - setForceWidth( - settings.value(QString("X-AW-ForceWidth"), forceWidth()).toBool()); - setFormat(settings.value(QString("X-AW-Format"), QString(format())) + settings.beginGroup("Desktop Entry"); + setCount(settings.value("X-AW-Width", count()).toInt()); + setFillChar(settings.value("X-AW-FillChar", fillChar()).toString().at(0)); + setForceWidth(settings.value("X-AW-ForceWidth", forceWidth()).toBool()); + setFormat(settings.value("X-AW-Format", QString(format())) .toString() .at(0) .toLatin1()); - setMultiplier( - settings.value(QString("X-AW-Multiplier"), multiplier()).toDouble()); - setPrecision( - settings.value(QString("X-AW-Precision"), precision()).toInt()); - setSummand(settings.value(QString("X-AW-Summand"), summand()).toDouble()); + setMultiplier(settings.value("X-AW-Multiplier", multiplier()).toDouble()); + setPrecision(settings.value("X-AW-Precision", precision()).toInt()); + setSummand(settings.value("X-AW-Summand", summand()).toDouble()); settings.endGroup(); bumpApi(AW_FORMATTER_API); } -int AWFloatFormatter::showConfiguration(const QVariant &args) +int AWFloatFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("Float")); + ui->label_typeValue->setText("Float"); ui->comboBox_format->setCurrentIndex( ui->comboBox_format->findText(QString(format()))); ui->spinBox_precision->setValue(precision()); @@ -258,14 +254,14 @@ void AWFloatFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Width"), count()); - settings.setValue(QString("X-AW-FillChar"), fillChar()); - settings.setValue(QString("X-AW-Format"), QString(format())); - settings.setValue(QString("X-AW-ForceWidth"), forceWidth()); - settings.setValue(QString("X-AW-Multiplier"), multiplier()); - settings.setValue(QString("X-AW-Precision"), precision()); - settings.setValue(QString("X-AW-Summand"), summand()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Width", count()); + settings.setValue("X-AW-FillChar", fillChar()); + settings.setValue("X-AW-Format", QString(format())); + settings.setValue("X-AW-ForceWidth", forceWidth()); + settings.setValue("X-AW-Multiplier", multiplier()); + settings.setValue("X-AW-Precision", precision()); + settings.setValue("X-AW-Summand", summand()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/awfloatformatter.h b/sources/awesomewidgets/awfloatformatter.h index a849131..d58fec1 100644 --- a/sources/awesomewidgets/awfloatformatter.h +++ b/sources/awesomewidgets/awfloatformatter.h @@ -38,8 +38,8 @@ class AWFloatFormatter : public AWAbstractFormatter Q_PROPERTY(double summand READ summand WRITE setSummand) public: - explicit AWFloatFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWFloatFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWFloatFormatter(); QString convert(const QVariant &_value) const; AWFloatFormatter *copy(const QString &_fileName, const int _number); @@ -61,7 +61,7 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: diff --git a/sources/awesomewidgets/awjsonformatter.cpp b/sources/awesomewidgets/awjsonformatter.cpp index 613498c..c9d9e67 100644 --- a/sources/awesomewidgets/awjsonformatter.cpp +++ b/sources/awesomewidgets/awjsonformatter.cpp @@ -27,13 +27,13 @@ #include "awdebug.h" -AWJsonFormatter::AWJsonFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWJsonFormatter::AWJsonFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWJsonFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -101,8 +101,8 @@ void AWJsonFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setPath(settings.value(QString("X-AW-Path"), path()).toString()); + settings.beginGroup("Desktop Entry"); + setPath(settings.value("X-AW-Path", path()).toString()); settings.endGroup(); bumpApi(AW_FORMATTER_API); @@ -115,7 +115,7 @@ int AWJsonFormatter::showConfiguration(const QVariant &args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("Json")); + ui->label_typeValue->setText("Json"); ui->lineEdit_path->setText(path()); int ret = exec(); @@ -139,53 +139,52 @@ void AWJsonFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Path"), path()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Path", path()); settings.endGroup(); settings.sync(); } -QVariant AWJsonFormatter::getFromJson(const QVariant &value, - const QVariant &element) const +QVariant AWJsonFormatter::getFromJson(const QVariant &_value, + const QVariant &_element) const { - qCDebug(LOG_LIB) << "Looking for element" << element << "in" << value; + qCDebug(LOG_LIB) << "Looking for element" << _element << "in" << _value; - if (element.type() == QVariant::String) { - return getFromMap(value, element.toString()); - } else if (element.type() == QVariant::Int) { - return getFromList(value, element.toInt()); + if (_element.type() == QVariant::String) { + return getFromMap(_value, _element.toString()); + } else if (_element.type() == QVariant::Int) { + return getFromList(_value, _element.toInt()); } else { - qCWarning(LOG_LIB) << "Unknown type" << element.typeName(); - return value; + qCWarning(LOG_LIB) << "Unknown type" << _element.typeName(); + return _value; } } -QVariant AWJsonFormatter::getFromList(const QVariant &value, - const int index) const +QVariant AWJsonFormatter::getFromList(const QVariant &_value, + const int _index) const { - qCDebug(LOG_LIB) << "Looking for index" << index << "in" << value; + qCDebug(LOG_LIB) << "Looking for index" << _index << "in" << _value; - return value.toList()[index]; + return _value.toList()[_index]; } -QVariant AWJsonFormatter::getFromMap(const QVariant &value, - const QString &key) const +QVariant AWJsonFormatter::getFromMap(const QVariant &_value, + const QString &_key) const { - qCDebug(LOG_LIB) << "Looking for key" << key << "in" << value; + qCDebug(LOG_LIB) << "Looking for key" << _key << "in" << _value; - return value.toMap()[key]; + return _value.toMap()[_key]; } void AWJsonFormatter::initPath() { m_splittedPath.clear(); - QStringList splittedByDot - = m_path.split(QChar('.'), QString::SkipEmptyParts); + QStringList splittedByDot = m_path.split('.', QString::SkipEmptyParts); for (auto &element : splittedByDot) { bool ok; diff --git a/sources/awesomewidgets/awjsonformatter.h b/sources/awesomewidgets/awjsonformatter.h index 7e37d89..56a673a 100644 --- a/sources/awesomewidgets/awjsonformatter.h +++ b/sources/awesomewidgets/awjsonformatter.h @@ -32,8 +32,8 @@ class AWJsonFormatter : public AWAbstractFormatter Q_PROPERTY(QString path READ path WRITE setPath) public: - explicit AWJsonFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWJsonFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWJsonFormatter(); QString convert(const QVariant &_value) const; AWJsonFormatter *copy(const QString &_fileName, const int _number); @@ -43,14 +43,15 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: Ui::AWJsonFormatter *ui = nullptr; - QVariant getFromJson(const QVariant &value, const QVariant &element) const; - QVariant getFromList(const QVariant &value, const int index) const; - QVariant getFromMap(const QVariant &value, const QString &key) const; + QVariant getFromJson(const QVariant &_value, + const QVariant &_element) const; + QVariant getFromList(const QVariant &_value, const int _index) const; + QVariant getFromMap(const QVariant &_value, const QString &_key) const; void initPath(); void translate(); // properties diff --git a/sources/awesomewidgets/awlistformatter.cpp b/sources/awesomewidgets/awlistformatter.cpp index 792e5cf..c646d6c 100644 --- a/sources/awesomewidgets/awlistformatter.cpp +++ b/sources/awesomewidgets/awlistformatter.cpp @@ -26,13 +26,13 @@ #include "awdebug.h" -AWListFormatter::AWListFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWListFormatter::AWListFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWListFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -125,24 +125,23 @@ void AWListFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setFilter(settings.value(QString("X-AW-Filter"), filter()).toString()); - setSeparator( - settings.value(QString("X-AW-Separator"), separator()).toString()); - setSorted(settings.value(QString("X-AW-Sort"), isSorted()).toBool()); + settings.beginGroup("Desktop Entry"); + setFilter(settings.value("X-AW-Filter", filter()).toString()); + setSeparator(settings.value("X-AW-Separator", separator()).toString()); + setSorted(settings.value("X-AW-Sort", isSorted()).toBool()); settings.endGroup(); bumpApi(AW_FORMATTER_API); } -int AWListFormatter::showConfiguration(const QVariant &args) +int AWListFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("NoFormat")); + ui->label_typeValue->setText("List"); ui->lineEdit_filter->setText(filter()); ui->lineEdit_separator->setText(separator()); ui->checkBox_sorted->setCheckState(isSorted() ? Qt::Checked @@ -171,10 +170,10 @@ void AWListFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Filter"), filter()); - settings.setValue(QString("X-AW-Separator"), separator()); - settings.setValue(QString("X-AW-Sort"), isSorted()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Filter", filter()); + settings.setValue("X-AW-Separator", separator()); + settings.setValue("X-AW-Sort", isSorted()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/awlistformatter.h b/sources/awesomewidgets/awlistformatter.h index 4ca509e..e785b81 100644 --- a/sources/awesomewidgets/awlistformatter.h +++ b/sources/awesomewidgets/awlistformatter.h @@ -34,8 +34,8 @@ class AWListFormatter : public AWAbstractFormatter Q_PROPERTY(bool sorted READ isSorted WRITE setSorted) public: - explicit AWListFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWListFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWListFormatter(); QString convert(const QVariant &_value) const; AWListFormatter *copy(const QString &_fileName, const int _number); @@ -49,15 +49,15 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: Ui::AWListFormatter *ui = nullptr; void translate(); // properties - QString m_filter = QString(); - QString m_separator = QString(); + QString m_filter = ""; + QString m_separator = ""; bool m_sorted = false; QRegExp m_regex; }; diff --git a/sources/awesomewidgets/awnoformatter.cpp b/sources/awesomewidgets/awnoformatter.cpp index 96f7486..42ecfeb 100644 --- a/sources/awesomewidgets/awnoformatter.cpp +++ b/sources/awesomewidgets/awnoformatter.cpp @@ -24,13 +24,13 @@ #include "awdebug.h" -AWNoFormatter::AWNoFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWNoFormatter::AWNoFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWNoFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -66,13 +66,13 @@ AWNoFormatter *AWNoFormatter::copy(const QString &_fileName, const int _number) } -int AWNoFormatter::showConfiguration(const QVariant &args) +int AWNoFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("NoFormat")); + ui->label_typeValue->setText("NoFormat"); int ret = exec(); if (ret != 1) diff --git a/sources/awesomewidgets/awnoformatter.h b/sources/awesomewidgets/awnoformatter.h index 4c965b4..4768e9e 100644 --- a/sources/awesomewidgets/awnoformatter.h +++ b/sources/awesomewidgets/awnoformatter.h @@ -31,13 +31,14 @@ class AWNoFormatter : public AWAbstractFormatter Q_OBJECT public: - explicit AWNoFormatter(QWidget *parent, const QString &filePath = QString()); + explicit AWNoFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWNoFormatter(); QString convert(const QVariant &_value) const; AWNoFormatter *copy(const QString &_fileName, const int _number); public slots: - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); private: Ui::AWNoFormatter *ui = nullptr; diff --git a/sources/awesomewidgets/awscriptformatter.cpp b/sources/awesomewidgets/awscriptformatter.cpp index 68e762c..965088a 100644 --- a/sources/awesomewidgets/awscriptformatter.cpp +++ b/sources/awesomewidgets/awscriptformatter.cpp @@ -28,13 +28,13 @@ #include "awdebug.h" -AWScriptFormatter::AWScriptFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWScriptFormatter::AWScriptFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWScriptFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -63,7 +63,7 @@ QString AWScriptFormatter::convert(const QVariant &_value) const qCWarning(LOG_LIB) << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); - return QString(); + return ""; } else { return result.toString(); } @@ -144,25 +144,23 @@ void AWScriptFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setAppendCode( - settings.value(QString("X-AW-AppendCode"), appendCode()).toBool()); - setCode(settings.value(QString("X-AW-Code"), code()).toString()); - setHasReturn( - settings.value(QString("X-AW-HasReturn"), hasReturn()).toBool()); + settings.beginGroup("Desktop Entry"); + setAppendCode(settings.value("X-AW-AppendCode", appendCode()).toBool()); + setCode(settings.value("X-AW-Code", code()).toString()); + setHasReturn(settings.value("X-AW-HasReturn", hasReturn()).toBool()); settings.endGroup(); bumpApi(AW_FORMATTER_API); } -int AWScriptFormatter::showConfiguration(const QVariant &args) +int AWScriptFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("Script")); + ui->label_typeValue->setText("Script"); ui->checkBox_appendCode->setCheckState(appendCode() ? Qt::Checked : Qt::Unchecked); ui->checkBox_hasReturn->setCheckState(hasReturn() ? Qt::Checked @@ -193,10 +191,10 @@ void AWScriptFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-AppendCode"), appendCode()); - settings.setValue(QString("X-AW-Code"), code()); - settings.setValue(QString("X-AW-HasReturn"), hasReturn()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-AppendCode", appendCode()); + settings.setValue("X-AW-Code", code()); + settings.setValue("X-AW-HasReturn", hasReturn()); settings.endGroup(); settings.sync(); @@ -207,10 +205,9 @@ void AWScriptFormatter::initProgram() { // init JS code if (appendCode()) - m_program - = QString("(function(value) { %1%2 })") - .arg(code()) - .arg(hasReturn() ? QString("") : QString("; return output;")); + m_program = QString("(function(value) { %1%2 })") + .arg(code()) + .arg(hasReturn() ? "" : "; return output;"); else m_program = code(); diff --git a/sources/awesomewidgets/awscriptformatter.h b/sources/awesomewidgets/awscriptformatter.h index ca85603..45ef6b4 100644 --- a/sources/awesomewidgets/awscriptformatter.h +++ b/sources/awesomewidgets/awscriptformatter.h @@ -35,8 +35,8 @@ class AWScriptFormatter : public AWAbstractFormatter Q_PROPERTY(QString program READ program) public: - explicit AWScriptFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWScriptFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWScriptFormatter(); QString convert(const QVariant &_value) const; AWScriptFormatter *copy(const QString &_fileName, const int _number); @@ -51,7 +51,7 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: @@ -60,7 +60,7 @@ private: void translate(); // properties bool m_appendCode = true; - QString m_code = QString(); + QString m_code = ""; bool m_hasReturn = false; QString m_program; }; diff --git a/sources/awesomewidgets/awstringformatter.cpp b/sources/awesomewidgets/awstringformatter.cpp index 4654435..92e08e0 100644 --- a/sources/awesomewidgets/awstringformatter.cpp +++ b/sources/awesomewidgets/awstringformatter.cpp @@ -27,13 +27,13 @@ #include "awdebug.h" -AWStringFormatter::AWStringFormatter(QWidget *parent, const QString &filePath) - : AWAbstractFormatter(parent, filePath) +AWStringFormatter::AWStringFormatter(QWidget *_parent, const QString &_filePath) + : AWAbstractFormatter(_parent, _filePath) , ui(new Ui::AWStringFormatter) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -125,25 +125,23 @@ void AWStringFormatter::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setCount(settings.value(QString("X-AW-Width"), count()).toInt()); - setFillChar( - settings.value(QString("X-AW-FillChar"), fillChar()).toString().at(0)); - setForceWidth( - settings.value(QString("X-AW-ForceWidth"), forceWidth()).toBool()); + settings.beginGroup("Desktop Entry"); + setCount(settings.value("X-AW-Width", count()).toInt()); + setFillChar(settings.value("X-AW-FillChar", fillChar()).toString().at(0)); + setForceWidth(settings.value("X-AW-ForceWidth", forceWidth()).toBool()); settings.endGroup(); bumpApi(AW_FORMATTER_API); } -int AWStringFormatter::showConfiguration(const QVariant &args) +int AWStringFormatter::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); - ui->label_typeValue->setText(QString("String")); + ui->label_typeValue->setText("String"); ui->spinBox_width->setValue(count()); ui->lineEdit_fill->setText(QString(fillChar())); ui->checkBox_forceWidth->setCheckState(forceWidth() ? Qt::Checked @@ -172,10 +170,10 @@ void AWStringFormatter::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Width"), count()); - settings.setValue(QString("X-AW-FillChar"), fillChar()); - settings.setValue(QString("X-AW-ForceWidth"), forceWidth()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Width", count()); + settings.setValue("X-AW-FillChar", fillChar()); + settings.setValue("X-AW-ForceWidth", forceWidth()); settings.endGroup(); settings.sync(); diff --git a/sources/awesomewidgets/awstringformatter.h b/sources/awesomewidgets/awstringformatter.h index c99fbfe..b08583e 100644 --- a/sources/awesomewidgets/awstringformatter.h +++ b/sources/awesomewidgets/awstringformatter.h @@ -34,8 +34,8 @@ class AWStringFormatter : public AWAbstractFormatter Q_PROPERTY(bool forceWidth READ forceWidth WRITE setForceWidth) public: - explicit AWStringFormatter(QWidget *parent, - const QString &filePath = QString()); + explicit AWStringFormatter(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~AWStringFormatter(); QString convert(const QVariant &_value) const; AWStringFormatter *copy(const QString &_fileName, const int _number); @@ -49,7 +49,7 @@ public: public slots: void readConfiguration(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private: diff --git a/sources/awesomewidgets/extitemaggregator.h b/sources/awesomewidgets/extitemaggregator.h index 4180798..f16a913 100644 --- a/sources/awesomewidgets/extitemaggregator.h +++ b/sources/awesomewidgets/extitemaggregator.h @@ -31,15 +31,15 @@ template class ExtItemAggregator : public AbstractExtItemAggregator { public: - explicit ExtItemAggregator(QWidget *parent, const QString &type) - : AbstractExtItemAggregator(parent, type) + explicit ExtItemAggregator(QWidget *_parent, const QString &_type) + : AbstractExtItemAggregator(_parent, _type) { qSetMessagePattern(AWDebug::LOG_FORMAT); qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; for (auto &metadata : AWDebug::getBuildData()) qCDebug(LOG_LIB) << metadata; - qCDebug(LOG_LIB) << "Type" << type; + qCDebug(LOG_LIB) << "Type" << _type; initItems(); }; @@ -132,8 +132,7 @@ private: for (auto &dir : dirs) { QStringList files = QDir(dir).entryList(QDir::Files, QDir::Name); for (auto &file : files) { - if ((!file.endsWith(QString(".desktop"))) - || (names.contains(file))) + if ((!file.endsWith(".desktop")) || (names.contains(file))) continue; qCInfo(LOG_LIB) << "Found file" << file << "in" << dir; names.append(file); diff --git a/sources/awesomewidgets/extnetworkrequest.cpp b/sources/awesomewidgets/extnetworkrequest.cpp index 0a2a8f8..14fa1de 100644 --- a/sources/awesomewidgets/extnetworkrequest.cpp +++ b/sources/awesomewidgets/extnetworkrequest.cpp @@ -31,18 +31,18 @@ #include "awdebug.h" -ExtNetworkRequest::ExtNetworkRequest(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +ExtNetworkRequest::ExtNetworkRequest(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::ExtNetworkRequest) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); - m_values[tag(QString("response"))] = QString(); + m_values[tag("response")] = ""; // HACK declare as child of nullptr to avoid crash with plasmawindowed // in the destructor @@ -109,8 +109,8 @@ void ExtNetworkRequest::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setStringUrl(settings.value(QString("X-AW-Url"), stringUrl()).toString()); + settings.beginGroup("Desktop Entry"); + setStringUrl(settings.value("X-AW-Url", stringUrl()).toString()); settings.endGroup(); bumpApi(AW_EXTNETREQUEST_API); @@ -127,9 +127,9 @@ QVariantHash ExtNetworkRequest::run() } -int ExtNetworkRequest::showConfiguration(const QVariant &args) +int ExtNetworkRequest::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -166,24 +166,24 @@ void ExtNetworkRequest::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Url"), stringUrl()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Url", stringUrl()); settings.endGroup(); settings.sync(); } -void ExtNetworkRequest::networkReplyReceived(QNetworkReply *reply) +void ExtNetworkRequest::networkReplyReceived(QNetworkReply *_reply) { - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); return; } m_isRunning = false; - m_values[tag(QString("response"))] - = QTextCodec::codecForMib(106)->toUnicode(reply->readAll()).trimmed(); + m_values[tag("response")] + = QTextCodec::codecForMib(106)->toUnicode(_reply->readAll()).trimmed(); emit(dataReceived(m_values)); } diff --git a/sources/awesomewidgets/extnetworkrequest.h b/sources/awesomewidgets/extnetworkrequest.h index 4828862..7a35331 100644 --- a/sources/awesomewidgets/extnetworkrequest.h +++ b/sources/awesomewidgets/extnetworkrequest.h @@ -34,24 +34,24 @@ class ExtNetworkRequest : public AbstractExtItem Q_PROPERTY(QString stringUrl READ stringUrl WRITE setStringUrl) public: - explicit ExtNetworkRequest(QWidget *parent, - const QString &filePath = QString()); + explicit ExtNetworkRequest(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~ExtNetworkRequest(); ExtNetworkRequest *copy(const QString &_fileName, const int _number); // get methods QString stringUrl() const; QString uniq() const; // set methods - void setStringUrl(const QString &_url = QString("https://httpbin.org/get")); + void setStringUrl(const QString &_url); public slots: void readConfiguration(); QVariantHash run(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: - void networkReplyReceived(QNetworkReply *reply); + void networkReplyReceived(QNetworkReply *_reply); void sendRequest(); private: @@ -62,9 +62,8 @@ private: void initUrl(); void translate(); // properties - QString m_stringUrl = QString("https://httpbin.org/get"); + QString m_stringUrl = "https://httpbin.org/get"; // values - int m_times = 0; QVariantHash m_values; }; diff --git a/sources/awesomewidgets/extquotes.cpp b/sources/awesomewidgets/extquotes.cpp index 6b10bda..5841f5f 100644 --- a/sources/awesomewidgets/extquotes.cpp +++ b/sources/awesomewidgets/extquotes.cpp @@ -33,26 +33,26 @@ #include "awdebug.h" -ExtQuotes::ExtQuotes(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +ExtQuotes::ExtQuotes(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::ExtQuotes) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); - m_values[tag(QString("ask"))] = 0.0; - m_values[tag(QString("askchg"))] = 0.0; - m_values[tag(QString("percaskchg"))] = 0.0; - m_values[tag(QString("bid"))] = 0.0; - m_values[tag(QString("bidchg"))] = 0.0; - m_values[tag(QString("percbidchg"))] = 0.0; - m_values[tag(QString("price"))] = 0.0; - m_values[tag(QString("pricechg"))] = 0.0; - m_values[tag(QString("percpricechg"))] = 0.0; + m_values[tag("ask")] = 0.0; + m_values[tag("askchg")] = 0.0; + m_values[tag("percaskchg")] = 0.0; + m_values[tag("bid")] = 0.0; + m_values[tag("bidchg")] = 0.0; + m_values[tag("percbidchg")] = 0.0; + m_values[tag("price")] = 0.0; + m_values[tag("pricechg")] = 0.0; + m_values[tag("percpricechg")] = 0.0; // HACK declare as child of nullptr to avoid crash with plasmawindowed // in the destructor @@ -118,8 +118,8 @@ void ExtQuotes::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setTicker(settings.value(QString("X-AW-Ticker"), ticker()).toString()); + settings.beginGroup("Desktop Entry"); + setTicker(settings.value("X-AW-Ticker", ticker()).toString()); settings.endGroup(); bumpApi(AW_EXTQUOTES_API); @@ -136,9 +136,9 @@ QVariantHash ExtQuotes::run() } -int ExtQuotes::showConfiguration(const QVariant &args) +int ExtQuotes::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -175,67 +175,59 @@ void ExtQuotes::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Ticker"), ticker()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Ticker", ticker()); settings.endGroup(); settings.sync(); } -void ExtQuotes::quotesReplyReceived(QNetworkReply *reply) +void ExtQuotes::quotesReplyReceived(QNetworkReply *_reply) { - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); return; } m_isRunning = false; QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); - reply->deleteLater(); + QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error); + _reply->deleteLater(); if (error.error != QJsonParseError::NoError) { qCWarning(LOG_LIB) << "Parse error" << error.errorString(); return; } - QVariantMap jsonQuotes - = jsonDoc.toVariant().toMap()[QString("query")].toMap(); - jsonQuotes - = jsonQuotes[QString("results")].toMap()[QString("quote")].toMap(); + QVariantMap jsonQuotes = jsonDoc.toVariant().toMap()["query"].toMap(); + jsonQuotes = jsonQuotes["results"].toMap()["quote"].toMap(); double value; // ask - value = jsonQuotes[QString("Ask")].toString().toDouble(); - m_values[tag(QString("askchg"))] - = m_values[tag(QString("ask"))].toDouble() == 0.0 - ? 0.0 - : value - m_values[tag(QString("ask"))].toDouble(); - m_values[tag(QString("percaskchg"))] - = 100.0 * m_values[tag(QString("askchg"))].toDouble() - / m_values[tag(QString("ask"))].toDouble(); - m_values[tag(QString("ask"))] = value; + value = jsonQuotes["Ask"].toString().toDouble(); + m_values[tag("askchg")] = m_values[tag("ask")].toDouble() == 0.0 + ? 0.0 + : value - m_values[tag("ask")].toDouble(); + m_values[tag("percaskchg")] = 100.0 * m_values[tag("askchg")].toDouble() + / m_values[tag("ask")].toDouble(); + m_values[tag("ask")] = value; // bid - value = jsonQuotes[QString("Bid")].toString().toDouble(); - m_values[tag(QString("bidchg"))] - = m_values[tag(QString("bid"))].toDouble() == 0.0 - ? 0.0 - : value - m_values[tag(QString("bid"))].toDouble(); - m_values[tag(QString("percbidchg"))] - = 100.0 * m_values[tag(QString("bidchg"))].toDouble() - / m_values[tag(QString("bid"))].toDouble(); - m_values[tag(QString("bid"))] = value; + value = jsonQuotes["Bid"].toString().toDouble(); + m_values[tag("bidchg")] = m_values[tag("bid")].toDouble() == 0.0 + ? 0.0 + : value - m_values[tag("bid")].toDouble(); + m_values[tag("percbidchg")] = 100.0 * m_values[tag("bidchg")].toDouble() + / m_values[tag("bid")].toDouble(); + m_values[tag("bid")] = value; // last trade - value = jsonQuotes[QString("LastTradePriceOnly")].toString().toDouble(); - m_values[tag(QString("pricechg"))] - = m_values[tag(QString("price"))].toDouble() == 0.0 - ? 0.0 - : value - m_values[tag(QString("price"))].toDouble(); - m_values[tag(QString("percpricechg"))] - = 100.0 * m_values[tag(QString("pricechg"))].toDouble() - / m_values[tag(QString("price"))].toDouble(); - m_values[tag(QString("price"))] = value; + value = jsonQuotes["LastTradePriceOnly"].toString().toDouble(); + m_values[tag("pricechg")] = m_values[tag("price")].toDouble() == 0.0 + ? 0.0 + : value - m_values[tag("price")].toDouble(); + m_values[tag("percpricechg")] = 100.0 * m_values[tag("pricechg")].toDouble() + / m_values[tag("price")].toDouble(); + m_values[tag("price")] = value; emit(dataReceived(m_values)); } @@ -254,11 +246,9 @@ void ExtQuotes::initUrl() // init query m_url = QUrl(YAHOO_QUOTES_URL); QUrlQuery params; - params.addQueryItem(QString("format"), QString("json")); - params.addQueryItem(QString("env"), - QString("store://datatables.org/alltableswithkeys")); - params.addQueryItem(QString("q"), - QString(YAHOO_QUOTES_QUERY).arg(ticker())); + params.addQueryItem("format", "json"); + params.addQueryItem("env", "store://datatables.org/alltableswithkeys"); + params.addQueryItem("q", QString(YAHOO_QUOTES_QUERY).arg(ticker())); m_url.setQuery(params); } diff --git a/sources/awesomewidgets/extquotes.h b/sources/awesomewidgets/extquotes.h index 42aedc4..ed7b31a 100644 --- a/sources/awesomewidgets/extquotes.h +++ b/sources/awesomewidgets/extquotes.h @@ -38,23 +38,24 @@ public: const char *YAHOO_QUOTES_QUERY = "select * from yahoo.finance.quotes where symbol='%1'"; - explicit ExtQuotes(QWidget *parent, const QString &filePath = QString()); + explicit ExtQuotes(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~ExtQuotes(); ExtQuotes *copy(const QString &_fileName, const int _number); // get methods QString ticker() const; QString uniq() const; // set methods - void setTicker(const QString &_ticker = QString("EURUSD=X")); + void setTicker(const QString &_ticker); public slots: void readConfiguration(); QVariantHash run(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: - void quotesReplyReceived(QNetworkReply *reply); + void quotesReplyReceived(QNetworkReply *_reply); void sendRequest(); private: @@ -65,9 +66,8 @@ private: void initUrl(); void translate(); // properties - QString m_ticker = QString("EURUSD=X"); + QString m_ticker = "EURUSD=X"; // values - int m_times = 0; QVariantHash m_values; }; diff --git a/sources/awesomewidgets/extscript.cpp b/sources/awesomewidgets/extscript.cpp index e0fc119..928f5b7 100644 --- a/sources/awesomewidgets/extscript.cpp +++ b/sources/awesomewidgets/extscript.cpp @@ -30,19 +30,19 @@ #include "awdebug.h" -ExtScript::ExtScript(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +ExtScript::ExtScript(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::ExtScript) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); readJsonFilters(); ui->setupUi(this); translate(); - m_values[tag(QString("custom"))] = QString(""); + m_values[tag("custom")] = ""; m_process = new QProcess(nullptr); connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, @@ -87,8 +87,7 @@ QString ExtScript::jsonFiltersFile() const { QString fileName = QStandardPaths::locate( QStandardPaths::GenericDataLocation, - QString( - "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json")); + "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"); qCInfo(LOG_LIB) << "Filters file" << fileName; return fileName; @@ -130,16 +129,16 @@ QString ExtScript::strRedirect() const QString value; switch (redirect()) { case Redirect::stdout2stderr: - value = QString("stdout2stderr"); + value = "stdout2stderr"; break; case Redirect::stderr2stdout: - value = QString("stderr2stdout"); + value = "stderr2stdout"; break; case Redirect::swap: - value = QString("swap"); + value = "swap"; break; case Redirect::nothing: - value = QString("nothing"); + value = "nothing"; break; } @@ -159,8 +158,9 @@ void ExtScript::setFilters(const QStringList &_filters) { qCDebug(LOG_LIB) << "Filters" << _filters; - std::for_each(_filters.cbegin(), _filters.cend(), - [this](QString filter) { return updateFilter(filter); }); + std::for_each( + _filters.cbegin(), _filters.cend(), + [this](const QString &filter) { return updateFilter(filter, true); }); } @@ -184,11 +184,11 @@ void ExtScript::setStrRedirect(const QString &_redirect) { qCDebug(LOG_LIB) << "Redirect" << _redirect; - if (_redirect == QString("stdout2sdterr")) + if (_redirect == "stdout2sdterr") setRedirect(Redirect::stdout2stderr); - else if (_redirect == QString("stderr2sdtout")) + else if (_redirect == "stderr2sdtout") setRedirect(Redirect::stderr2stdout); - else if (_redirect == QString("swap")) + else if (_redirect == "swap") setRedirect(Redirect::swap); else setRedirect(Redirect::nothing); @@ -235,15 +235,14 @@ void ExtScript::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setExecutable(settings.value(QString("Exec"), executable()).toString()); - setPrefix(settings.value(QString("X-AW-Prefix"), prefix()).toString()); - setStrRedirect( - settings.value(QString("X-AW-Redirect"), strRedirect()).toString()); + settings.beginGroup("Desktop Entry"); + setExecutable(settings.value("Exec", executable()).toString()); + setPrefix(settings.value("X-AW-Prefix", prefix()).toString()); + setStrRedirect(settings.value("X-AW-Redirect", strRedirect()).toString()); // api == 3 - setFilters(settings.value(QString("X-AW-Filters"), filters()) + setFilters(settings.value("X-AW-Filters", filters()) .toString() - .split(QChar(','), QString::SkipEmptyParts)); + .split(',', QString::SkipEmptyParts)); settings.endGroup(); bumpApi(AW_EXTSCRIPT_API); @@ -283,9 +282,9 @@ QVariantHash ExtScript::run() } -int ExtScript::showConfiguration(const QVariant &args) +int ExtScript::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -300,11 +299,11 @@ int ExtScript::showConfiguration(const QVariant &args) ui->spinBox_interval->setValue(interval()); // filters ui->checkBox_colorFilter->setCheckState( - filters().contains(QString("color")) ? Qt::Checked : Qt::Unchecked); + filters().contains("color") ? Qt::Checked : Qt::Unchecked); ui->checkBox_linesFilter->setCheckState( - filters().contains(QString("newline")) ? Qt::Checked : Qt::Unchecked); + filters().contains("newline") ? Qt::Checked : Qt::Unchecked); ui->checkBox_spaceFilter->setCheckState( - filters().contains(QString("space")) ? Qt::Checked : Qt::Unchecked); + filters().contains("space") ? Qt::Checked : Qt::Unchecked); int ret = exec(); if (ret != 1) @@ -321,11 +320,11 @@ int ExtScript::showConfiguration(const QVariant &args) setSocket(ui->lineEdit_socket->text()); setInterval(ui->spinBox_interval->value()); // filters - updateFilter(QString("color"), + updateFilter("color", ui->checkBox_colorFilter->checkState() == Qt::Checked); - updateFilter(QString("newline"), + updateFilter("newline", ui->checkBox_linesFilter->checkState() == Qt::Checked); - updateFilter(QString("space"), + updateFilter("space", ui->checkBox_spaceFilter->checkState() == Qt::Checked); writeConfiguration(); @@ -340,11 +339,11 @@ void ExtScript::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("Exec"), executable()); - settings.setValue(QString("X-AW-Prefix"), prefix()); - settings.setValue(QString("X-AW-Redirect"), strRedirect()); - settings.setValue(QString("X-AW-Filters"), filters().join(QChar(','))); + settings.beginGroup("Desktop Entry"); + settings.setValue("Exec", executable()); + settings.setValue("X-AW-Prefix", prefix()); + settings.setValue("X-AW-Redirect", strRedirect()); + settings.setValue("X-AW-Filters", filters().join(',')); settings.endGroup(); settings.sync(); @@ -357,8 +356,8 @@ void ExtScript::startProcess() if (!prefix().isEmpty()) cmdList.append(prefix()); cmdList.append(executable()); - qCInfo(LOG_LIB) << "Run cmd" << cmdList.join(QChar(' ')); - m_process->start(cmdList.join(QChar(' '))); + qCInfo(LOG_LIB) << "Run cmd" << cmdList.join(' '); + m_process->start(cmdList.join(' ')); } @@ -390,7 +389,7 @@ void ExtScript::updateValue() } // filters - m_values[tag(QString("custom"))] = applyFilters(strValue); + m_values[tag("custom")] = applyFilters(strValue); emit(dataReceived(m_values)); } diff --git a/sources/awesomewidgets/extscript.h b/sources/awesomewidgets/extscript.h index efbf725..de50223 100644 --- a/sources/awesomewidgets/extscript.h +++ b/sources/awesomewidgets/extscript.h @@ -44,7 +44,8 @@ public: swap = 3 }; - explicit ExtScript(QWidget *parent, const QString &filePath = QString()); + explicit ExtScript(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~ExtScript(); ExtScript *copy(const QString &_fileName, const int _number); QString jsonFiltersFile() const; @@ -57,20 +58,20 @@ public: // derivatives QString strRedirect() const; // set methods - void setExecutable(const QString &_executable = QString("/usr/bin/true")); - void setFilters(const QStringList &_filters = QStringList()); - void setPrefix(const QString &_prefix = QString("")); - void setRedirect(const Redirect _redirect = Redirect::nothing); - void setStrRedirect(const QString &_redirect = QString("nothing")); + void setExecutable(const QString &_executable); + void setFilters(const QStringList &_filters); + void setPrefix(const QString &_prefix); + void setRedirect(const Redirect _redirect); + void setStrRedirect(const QString &_redirect); // filters QString applyFilters(QString _value) const; - void updateFilter(const QString &_filter, const bool _add = true); + void updateFilter(const QString &_filter, const bool _add); public slots: void readConfiguration(); void readJsonFilters(); QVariantHash run(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: @@ -82,13 +83,12 @@ private: Ui::ExtScript *ui = nullptr; void translate(); // properties - QString m_executable = QString("/usr/bin/true"); + QString m_executable = "/usr/bin/true"; QStringList m_filters = QStringList(); - QString m_prefix = QString(""); + QString m_prefix = ""; Redirect m_redirect = Redirect::nothing; // internal properties - QVariantMap m_jsonFilters = QVariantMap(); - int m_times = 0; + QVariantMap m_jsonFilters; QVariantHash m_values; }; diff --git a/sources/awesomewidgets/extupgrade.cpp b/sources/awesomewidgets/extupgrade.cpp index c4809a4..302fb02 100644 --- a/sources/awesomewidgets/extupgrade.cpp +++ b/sources/awesomewidgets/extupgrade.cpp @@ -28,18 +28,18 @@ #include "awdebug.h" -ExtUpgrade::ExtUpgrade(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +ExtUpgrade::ExtUpgrade(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::ExtUpgrade) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); - m_values[tag(QString("pkgcount"))] = 0; + m_values[tag("pkgcount")] = 0; m_process = new QProcess(nullptr); connect(m_process, SIGNAL(finished(int)), this, SLOT(updateValue())); @@ -132,11 +132,11 @@ void ExtUpgrade::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setExecutable(settings.value(QString("Exec"), executable()).toString()); - setNull(settings.value(QString("X-AW-Null"), null()).toInt()); + settings.beginGroup("Desktop Entry"); + setExecutable(settings.value("Exec", executable()).toString()); + setNull(settings.value("X-AW-Null", null()).toInt()); // api == 3 - setFilter(settings.value(QString("X-AW-Filter"), filter()).toString()); + setFilter(settings.value("X-AW-Filter", filter()).toString()); settings.endGroup(); bumpApi(AW_EXTUPGRADE_API); @@ -153,9 +153,9 @@ QVariantHash ExtUpgrade::run() } -int ExtUpgrade::showConfiguration(const QVariant &args) +int ExtUpgrade::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -196,10 +196,10 @@ void ExtUpgrade::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("Exec"), executable()); - settings.setValue(QString("X-AW-Filter"), filter()); - settings.setValue(QString("X-AW-Null"), null()); + settings.beginGroup("Desktop Entry"); + settings.setValue("Exec", executable()); + settings.setValue("X-AW-Filter", filter()); + settings.setValue("X-AW-Null", null()); settings.endGroup(); settings.sync(); @@ -222,11 +222,11 @@ void ExtUpgrade::updateValue() QString qoutput = QTextCodec::codecForMib(106) ->toUnicode(m_process->readAllStandardOutput()) .trimmed(); - m_values[tag(QString("pkgcount"))] = [this](QString output) { + m_values[tag("pkgcount")] = [this](QString output) { return filter().isEmpty() - ? output.split(QChar('\n'), QString::SkipEmptyParts).count() + ? output.split('\n', QString::SkipEmptyParts).count() - null() - : output.split(QChar('\n'), QString::SkipEmptyParts) + : output.split('\n', QString::SkipEmptyParts) .filter(QRegExp(filter())) .count(); }(qoutput); diff --git a/sources/awesomewidgets/extupgrade.h b/sources/awesomewidgets/extupgrade.h index 3dd3068..e2783bd 100644 --- a/sources/awesomewidgets/extupgrade.h +++ b/sources/awesomewidgets/extupgrade.h @@ -36,7 +36,8 @@ class ExtUpgrade : public AbstractExtItem Q_PROPERTY(int null READ null WRITE setNull) public: - explicit ExtUpgrade(QWidget *parent, const QString &filePath = QString()); + explicit ExtUpgrade(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~ExtUpgrade(); ExtUpgrade *copy(const QString &_fileName, const int _number); // get methods @@ -45,14 +46,14 @@ public: int null() const; QString uniq() const; // set methods - void setExecutable(const QString &_executable = QString("/usr/bin/true")); - void setFilter(const QString &_filter = QString()); - void setNull(const int _null = 0); + void setExecutable(const QString &_executable); + void setFilter(const QString &_filter); + void setNull(const int _null); public slots: void readConfiguration(); QVariantHash run(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: @@ -64,11 +65,10 @@ private: Ui::ExtUpgrade *ui = nullptr; void translate(); // properties - QString m_executable = QString("/usr/bin/true"); - QString m_filter = QString(""); + QString m_executable = "/usr/bin/true"; + QString m_filter = ""; int m_null = 0; // internal properties - int m_times = 0; QVariantHash m_values; }; diff --git a/sources/awesomewidgets/extweather.cpp b/sources/awesomewidgets/extweather.cpp index 624f543..625e501 100644 --- a/sources/awesomewidgets/extweather.cpp +++ b/sources/awesomewidgets/extweather.cpp @@ -35,23 +35,23 @@ #include "yahooweatherprovider.h" -ExtWeather::ExtWeather(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +ExtWeather::ExtWeather(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::ExtWeather) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); readJsonMap(); ui->setupUi(this); translate(); - m_values[tag(QString("weatherId"))] = 0; - m_values[tag(QString("weather"))] = QString(""); - m_values[tag(QString("humidity"))] = 0; - m_values[tag(QString("pressure"))] = 0.0; - m_values[tag(QString("temperature"))] = 0.0; + m_values[tag("weatherId")] = 0; + m_values[tag("weather")] = ""; + m_values[tag("humidity")] = 0; + m_values[tag("pressure")] = 0.0; + m_values[tag("temperature")] = 0.0; // HACK declare as child of nullptr to avoid crash with plasmawindowed // in the destructor @@ -99,7 +99,7 @@ QString ExtWeather::jsonMapFile() const { QString fileName = QStandardPaths::locate( QStandardPaths::GenericDataLocation, - QString("awesomewidgets/weather/awesomewidgets-extweather-ids.json")); + "awesomewidgets/weather/awesomewidgets-extweather-ids.json"); qCInfo(LOG_LIB) << "Map file" << fileName; return fileName; @@ -110,9 +110,8 @@ QString ExtWeather::weatherFromInt(const int _id) const { qCDebug(LOG_LIB) << "Weather ID" << _id; - QVariantMap map - = m_jsonMap[m_image ? QString("image") : QString("text")].toMap(); - return map.value(QString::number(_id), map[QString("default")]).toString(); + QVariantMap map = m_jsonMap[m_image ? "image" : "text"].toMap(); + return map.value(QString::number(_id), map["default"]).toString(); } @@ -145,10 +144,10 @@ QString ExtWeather::strProvider() const QString value; switch (m_provider) { case Provider::OWM: - value = QString("OWM"); + value = "OWM"; break; case Provider::Yahoo: - value = QString("Yahoo"); + value = "Yahoo"; break; } @@ -207,7 +206,7 @@ void ExtWeather::setStrProvider(const QString &_provider) { qCDebug(LOG_LIB) << "Provider" << _provider; - if (_provider == QString("Yahoo")) + if (_provider == "Yahoo") setProvider(Provider::Yahoo); else setProvider(Provider::OWM); @@ -229,16 +228,14 @@ void ExtWeather::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setCity(settings.value(QString("X-AW-City"), city()).toString()); - setCountry(settings.value(QString("X-AW-Country"), country()).toString()); - setTs(settings.value(QString("X-AW-TS"), ts()).toInt()); + settings.beginGroup("Desktop Entry"); + setCity(settings.value("X-AW-City", city()).toString()); + setCountry(settings.value("X-AW-Country", country()).toString()); + setTs(settings.value("X-AW-TS", ts()).toInt()); // api == 2 - setImage(settings.value(QString("X-AW-Image"), QVariant(image())).toString() - == QString("true")); + setImage(settings.value("X-AW-Image", image()).toBool()); // api == 3 - setStrProvider( - settings.value(QString("X-AW-Provider"), strProvider()).toString()); + setStrProvider(settings.value("X-AW-Provider", strProvider()).toString()); settings.endGroup(); bumpApi(AW_EXTWEATHER_API); @@ -278,9 +275,9 @@ QVariantHash ExtWeather::run() } -int ExtWeather::showConfiguration(const QVariant &args) +int ExtWeather::showConfiguration(const QVariant &_args) { - Q_UNUSED(args) + Q_UNUSED(_args) ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -325,12 +322,12 @@ void ExtWeather::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-City"), city()); - settings.setValue(QString("X-AW-Country"), country()); - settings.setValue(QString("X-AW-Image"), image()); - settings.setValue(QString("X-AW-Provider"), strProvider()); - settings.setValue(QString("X-AW-TS"), ts()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-City", city()); + settings.setValue("X-AW-Country", country()); + settings.setValue("X-AW-Image", image()); + settings.setValue("X-AW-Provider", strProvider()); + settings.setValue("X-AW-TS", ts()); settings.endGroup(); settings.sync(); @@ -346,18 +343,18 @@ void ExtWeather::sendRequest() } -void ExtWeather::weatherReplyReceived(QNetworkReply *reply) +void ExtWeather::weatherReplyReceived(QNetworkReply *_reply) { - if (reply->error() != QNetworkReply::NoError) { - qCWarning(LOG_AW) << "An error occurs" << reply->error() - << "with message" << reply->errorString(); + if (_reply->error() != QNetworkReply::NoError) { + qCWarning(LOG_AW) << "An error occurs" << _reply->error() + << "with message" << _reply->errorString(); return; } m_isRunning = false; QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); - reply->deleteLater(); + QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error); + _reply->deleteLater(); if (error.error != QJsonParseError::NoError) { qCWarning(LOG_LIB) << "Parse error" << error.errorString(); return; @@ -367,8 +364,8 @@ void ExtWeather::weatherReplyReceived(QNetworkReply *reply) if (data.isEmpty()) return; m_values = data; - m_values[tag(QString("weather"))] - = weatherFromInt(m_values[tag(QString("weatherId"))].toInt()); + m_values[tag("weather")] + = weatherFromInt(m_values[tag("weatherId")].toInt()); emit(dataReceived(m_values)); } diff --git a/sources/awesomewidgets/extweather.h b/sources/awesomewidgets/extweather.h index eb45d7b..3908ce1 100644 --- a/sources/awesomewidgets/extweather.h +++ b/sources/awesomewidgets/extweather.h @@ -42,7 +42,8 @@ class ExtWeather : public AbstractExtItem public: enum class Provider { OWM = 0, Yahoo = 1 }; - explicit ExtWeather(QWidget *parent, const QString &filePath = QString()); + explicit ExtWeather(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~ExtWeather(); ExtWeather *copy(const QString &_fileName, const int _number); QString jsonMapFile() const; @@ -56,23 +57,23 @@ public: int ts() const; QString uniq() const; // set methods - void setCity(const QString &_city = QString("London")); - void setCountry(const QString &_country = QString("uk")); - void setImage(const bool _image = false); - void setProvider(const Provider _provider = Provider::OWM); - void setStrProvider(const QString &_provider = QString("OWM")); - void setTs(const int _ts = 0); + void setCity(const QString &_city); + void setCountry(const QString &_country); + void setImage(const bool _image); + void setProvider(const Provider _provider); + void setStrProvider(const QString &_provider); + void setTs(const int _ts); public slots: void readConfiguration(); void readJsonMap(); QVariantHash run(); - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: void sendRequest(); - void weatherReplyReceived(QNetworkReply *reply); + void weatherReplyReceived(QNetworkReply *_reply); private: QNetworkAccessManager *m_manager = nullptr; @@ -82,14 +83,13 @@ private: void initProvider(); void translate(); // properties - QString m_city = QString("London"); - QString m_country = QString("uk"); + QString m_city = "London"; + QString m_country = "uk"; bool m_image = false; Provider m_provider = Provider::OWM; int m_ts = 0; - QVariantMap m_jsonMap = QVariantMap(); + QVariantMap m_jsonMap; // values - int m_times = 0; QVariantHash m_values; }; diff --git a/sources/awesomewidgets/graphicalitem.cpp b/sources/awesomewidgets/graphicalitem.cpp index a9380a6..759a603 100644 --- a/sources/awesomewidgets/graphicalitem.cpp +++ b/sources/awesomewidgets/graphicalitem.cpp @@ -32,13 +32,13 @@ #include "graphicalitemhelper.h" -GraphicalItem::GraphicalItem(QWidget *parent, const QString &filePath) - : AbstractExtItem(parent, filePath) +GraphicalItem::GraphicalItem(QWidget *_parent, const QString &_filePath) + : AbstractExtItem(_parent, _filePath) , ui(new Ui::GraphicalItem) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; - if (!filePath.isEmpty()) + if (!_filePath.isEmpty()) readConfiguration(); ui->setupUi(this); translate(); @@ -150,7 +150,7 @@ void GraphicalItem::initScene() m_scene->setBackgroundBrush(QBrush(Qt::NoBrush)); // init view m_view = new QGraphicsView(m_scene); - m_view->setStyleSheet(QString("background: transparent")); + m_view->setStyleSheet("background: transparent"); m_view->setContentsMargins(0, 0, 0, 0); m_view->setFrameShape(QFrame::NoFrame); m_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -229,19 +229,19 @@ QString GraphicalItem::strType() const QString value; switch (type()) { case Type::Vertical: - value = QString("Vertical"); + value = "Vertical"; break; case Type::Circle: - value = QString("Circle"); + value = "Circle"; break; case Type::Graph: - value = QString("Graph"); + value = "Graph"; break; case Type::Bars: - value = QString("Bars"); + value = "Bars"; break; case Type::Horizontal: - value = QString("Horizontal"); + value = "Horizontal"; break; } @@ -260,10 +260,10 @@ QString GraphicalItem::strDirection() const QString value; switch (direction()) { case Direction::RightToLeft: - value = QString("RightToLeft"); + value = "RightToLeft"; break; case Direction::LeftToRight: - value = QString("LeftToRight"); + value = "LeftToRight"; break; } @@ -373,13 +373,13 @@ void GraphicalItem::setStrType(const QString &_type) { qCDebug(LOG_LIB) << "Type" << _type; - if (_type == QString("Vertical")) + if (_type == "Vertical") setType(Type::Vertical); - else if (_type == QString("Circle")) + else if (_type == "Circle") setType(Type::Circle); - else if (_type == QString("Graph")) + else if (_type == "Graph") setType(Type::Graph); - else if (_type == QString("Bars")) + else if (_type == "Bars") setType(Type::Bars); else setType(Type::Horizontal); @@ -398,7 +398,7 @@ void GraphicalItem::setStrDirection(const QString &_direction) { qCDebug(LOG_LIB) << "Direction" << _direction; - if (_direction == QString("RightToLeft")) + if (_direction == "RightToLeft") setDirection(Direction::RightToLeft); else setDirection(Direction::LeftToRight); @@ -426,31 +426,29 @@ void GraphicalItem::readConfiguration() QSettings settings(fileName(), QSettings::IniFormat); - settings.beginGroup(QString("Desktop Entry")); - setCount(settings.value(QString("X-AW-Count"), count()).toInt()); - setCustom(settings.value(QString("X-AW-Custom"), isCustom()).toBool()); - setBar(settings.value(QString("X-AW-Value"), bar()).toString()); - setMaxValue(settings.value(QString("X-AW-Max"), maxValue()).toFloat()); - setMinValue(settings.value(QString("X-AW-Min"), minValue()).toFloat()); + settings.beginGroup("Desktop Entry"); + setCount(settings.value("X-AW-Count", count()).toInt()); + setCustom(settings.value("X-AW-Custom", isCustom()).toBool()); + setBar(settings.value("X-AW-Value", bar()).toString()); + setMaxValue(settings.value("X-AW-Max", maxValue()).toFloat()); + setMinValue(settings.value("X-AW-Min", minValue()).toFloat()); setActiveColor( - settings.value(QString("X-AW-ActiveColor"), activeColor()).toString()); + settings.value("X-AW-ActiveColor", activeColor()).toString()); setInactiveColor( - settings.value(QString("X-AW-InactiveColor"), inactiveColor()) - .toString()); - setStrType(settings.value(QString("X-AW-Type"), strType()).toString()); + settings.value("X-AW-InactiveColor", inactiveColor()).toString()); + setStrType(settings.value("X-AW-Type", strType()).toString()); setStrDirection( - settings.value(QString("X-AW-Direction"), strDirection()).toString()); - setItemHeight(settings.value(QString("X-AW-Height"), itemHeight()).toInt()); - setItemWidth(settings.value(QString("X-AW-Width"), itemWidth()).toInt()); + settings.value("X-AW-Direction", strDirection()).toString()); + setItemHeight(settings.value("X-AW-Height", itemHeight()).toInt()); + setItemWidth(settings.value("X-AW-Width", itemWidth()).toInt()); // api == 5 if (apiVersion() < 5) { QString prefix; - prefix = activeColor().startsWith(QString("/")) ? QString("file://%1") - : QString("color://%1"); + prefix = activeColor().startsWith("/") ? QString("file://%1") + : QString("color://%1"); m_activeColor = prefix.arg(activeColor()); - prefix = inactiveColor().startsWith(QString("/")) - ? QString("file://%1") - : QString("color://%1"); + prefix = inactiveColor().startsWith("/") ? QString("file://%1") + : QString("color://%1"); m_inactiveColor = prefix.arg(inactiveColor()); } settings.endGroup(); @@ -460,10 +458,10 @@ void GraphicalItem::readConfiguration() } -int GraphicalItem::showConfiguration(const QVariant &args) +int GraphicalItem::showConfiguration(const QVariant &_args) { - qCDebug(LOG_LIB) << "Combobox arguments" << args; - QStringList tags = args.toStringList(); + qCDebug(LOG_LIB) << "Combobox arguments" << _args; + QStringList tags = _args.toStringList(); ui->lineEdit_name->setText(name()); ui->lineEdit_comment->setText(comment()); @@ -531,18 +529,18 @@ void GraphicalItem::writeConfiguration() const QSettings settings(writtableConfig(), QSettings::IniFormat); qCInfo(LOG_LIB) << "Configuration file" << settings.fileName(); - settings.beginGroup(QString("Desktop Entry")); - settings.setValue(QString("X-AW-Value"), bar()); - settings.setValue(QString("X-AW-Count"), count()); - settings.setValue(QString("X-AW-Custom"), isCustom()); - settings.setValue(QString("X-AW-Max"), maxValue()); - settings.setValue(QString("X-AW-Min"), minValue()); - settings.setValue(QString("X-AW-ActiveColor"), activeColor()); - settings.setValue(QString("X-AW-InactiveColor"), inactiveColor()); - settings.setValue(QString("X-AW-Type"), strType()); - settings.setValue(QString("X-AW-Direction"), strDirection()); - settings.setValue(QString("X-AW-Height"), itemHeight()); - settings.setValue(QString("X-AW-Width"), itemWidth()); + settings.beginGroup("Desktop Entry"); + settings.setValue("X-AW-Value", bar()); + settings.setValue("X-AW-Count", count()); + settings.setValue("X-AW-Custom", isCustom()); + settings.setValue("X-AW-Max", maxValue()); + settings.setValue("X-AW-Min", minValue()); + settings.setValue("X-AW-ActiveColor", activeColor()); + settings.setValue("X-AW-InactiveColor", inactiveColor()); + settings.setValue("X-AW-Type", strType()); + settings.setValue("X-AW-Direction", strDirection()); + settings.setValue("X-AW-Height", itemHeight()); + settings.setValue("X-AW-Width", itemWidth()); settings.endGroup(); settings.sync(); @@ -566,7 +564,7 @@ void GraphicalItem::changeColor() if (state == 0) { QColor color = m_helper->stringToColor(lineEdit->text()); QColor newColor = QColorDialog::getColor( - color, this, tr("Select color"), QColorDialog::ShowAlphaChannel); + color, this, i18n("Select color"), QColorDialog::ShowAlphaChannel); if (!newColor.isValid()) return; qCInfo(LOG_LIB) << "Selected color" << newColor; @@ -577,13 +575,13 @@ void GraphicalItem::changeColor() colorText.append(QString("%1").arg(newColor.blue())); colorText.append(QString("%1").arg(newColor.alpha())); - outputColor = QString("color://%1").arg(colorText.join(QChar(','))); + outputColor = QString("color://%1").arg(colorText.join(',')); } else if (state == 1) { QString path = lineEdit->text(); QString directory = QFileInfo(path).absolutePath(); outputColor = QFileDialog::getOpenFileUrl( - this, tr("Select path"), directory, - tr("Images (*.png *.bpm *.jpg);;All files (*.*)")) + this, i18n("Select path"), directory, + i18n("Images (*.png *.bpm *.jpg);;All files (*.*)")) .toString(); qCInfo(LOG_LIB) << "Selected path" << outputColor; @@ -597,21 +595,21 @@ void GraphicalItem::changeColor() } -void GraphicalItem::changeCountState(const int state) +void GraphicalItem::changeCountState(const int _state) { - qCDebug(LOG_LIB) << "Current state is" << state; + qCDebug(LOG_LIB) << "Current state is" << _state; // 3 is magic number. Actually 3 is Graph mode - ui->widget_count->setHidden(state != 3); + ui->widget_count->setHidden(_state != 3); } -void GraphicalItem::changeValue(const int state) +void GraphicalItem::changeValue(const int _state) { - qCDebug(LOG_LIB) << "Current state is" << state; + qCDebug(LOG_LIB) << "Current state is" << _state; - ui->widget_value->setHidden(state != Qt::Unchecked); - ui->widget_customValue->setHidden(state == Qt::Unchecked); + ui->widget_value->setHidden(_state != Qt::Unchecked); + ui->widget_customValue->setHidden(_state == Qt::Unchecked); } diff --git a/sources/awesomewidgets/graphicalitem.h b/sources/awesomewidgets/graphicalitem.h index e9c0750..c30b757 100644 --- a/sources/awesomewidgets/graphicalitem.h +++ b/sources/awesomewidgets/graphicalitem.h @@ -58,7 +58,8 @@ public: Bars = 4 }; - explicit GraphicalItem(QWidget *parent, const QString &filePath = QString()); + explicit GraphicalItem(QWidget *_parent = nullptr, + const QString &_filePath = ""); virtual ~GraphicalItem(); GraphicalItem *copy(const QString &_fileName, const int _number); QString image(const QVariant &value); @@ -80,32 +81,31 @@ public: QStringList usedKeys() const; QString uniq() const; // set methods - void setBar(const QString &_bar = QString("cpu")); - void setActiveColor(const QString &_color = QString("color://0,0,0,130")); - void setCount(const int _count = 100); - void setCustom(const bool _custom = false); - void setInactiveColor(const QString &_color - = QString("color://255,255,255,130")); - void setItemHeight(const int _height = 100); - void setItemWidth(const int _width = 100); - void setMinValue(const float _value = 0.0); - void setMaxValue(const float _value = 100.0); - void setType(const Type _type = Type::Horizontal); - void setStrType(const QString &_type = QString("Horizontal")); - void setDirection(const Direction _direction = Direction::LeftToRight); - void setStrDirection(const QString &_direction = QString("LeftToRight")); - void setUsedKeys(const QStringList &_usedKeys = QStringList()); + void setBar(const QString &_bar); + void setActiveColor(const QString &_color); + void setCount(const int _count); + void setCustom(const bool _custom); + void setInactiveColor(const QString &_color); + void setItemHeight(const int _height); + void setItemWidth(const int _width); + void setMinValue(const float _value); + void setMaxValue(const float _value); + void setType(const Type _type); + void setStrType(const QString &_type); + void setDirection(const Direction _direction); + void setStrDirection(const QString &_direction); + void setUsedKeys(const QStringList &_usedKeys); public slots: void readConfiguration(); QVariantHash run() { return QVariantHash(); }; - int showConfiguration(const QVariant &args = QVariant()); + int showConfiguration(const QVariant &_args); void writeConfiguration() const; private slots: void changeColor(); - void changeCountState(const int state); - void changeValue(const int state); + void changeCountState(const int _state); + void changeValue(const int _state); private: GraphicalItemHelper *m_helper = nullptr; @@ -114,11 +114,11 @@ private: Ui::GraphicalItem *ui = nullptr; void translate(); // properties - QString m_bar = QString("cpu"); + QString m_bar = "cpu"; int m_count = 100; bool m_custom = false; - QString m_activeColor = QString("color://0,0,0,130"); - QString m_inactiveColor = QString("color://255,255,255,130"); + QString m_activeColor = "color://0,0,0,130"; + QString m_inactiveColor = "color://255,255,255,130"; float m_minValue = 0.0f; float m_maxValue = 100.0f; Type m_type = Type::Horizontal; diff --git a/sources/awesomewidgets/graphicalitemhelper.cpp b/sources/awesomewidgets/graphicalitemhelper.cpp index 7debada..1a3a474 100644 --- a/sources/awesomewidgets/graphicalitemhelper.cpp +++ b/sources/awesomewidgets/graphicalitemhelper.cpp @@ -27,9 +27,10 @@ #include "awdebug.h" -GraphicalItemHelper::GraphicalItemHelper(QObject *parent, QGraphicsScene *scene) - : QObject(parent) - , m_scene(scene) +GraphicalItemHelper::GraphicalItemHelper(QObject *_parent, + QGraphicsScene *_scene) + : QObject(_parent) + , m_scene(_scene) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; } @@ -41,54 +42,56 @@ GraphicalItemHelper::~GraphicalItemHelper() } -void GraphicalItemHelper::setParameters(const QString &active, - const QString &inactive, const int width, - const int height, const int count) +void GraphicalItemHelper::setParameters(const QString &_active, + const QString &_inactive, + const int _width, const int _height, + const int _count) { - qCDebug(LOG_LIB) << "Use active color" << active << ", inactive" << inactive - << ", width" << width << ", height" << height << ", count" - << count; + qCDebug(LOG_LIB) << "Use active color" << _active << ", inactive" + << _inactive << ", width" << _width << ", height" + << _height << ", count" << _count; // put images to pens if any otherwise set pen colors // Images resize to content here as well - if (isColor(active)) { - m_activePen.setBrush(QBrush(stringToColor(active))); + if (isColor(_active)) { + m_activePen.setBrush(QBrush(stringToColor(_active))); } else { - qCInfo(LOG_LIB) << "Found path, trying to load Pixmap from" << active; - QPixmap pixmap = QPixmap(QUrl(active).toLocalFile()); + qCInfo(LOG_LIB) << "Found path, trying to load Pixmap from" << _active; + QPixmap pixmap = QPixmap(QUrl(_active).toLocalFile()); if (pixmap.isNull()) { - qCWarning(LOG_LIB) << "Invalid pixmap found" << active; + qCWarning(LOG_LIB) << "Invalid pixmap found" << _active; m_activePen.setBrush(QBrush(QColor(0, 0, 0, 130))); } else { - m_activePen.setBrush(QBrush(pixmap.scaled(width, height))); + m_activePen.setBrush(QBrush(pixmap.scaled(_width, _height))); } } - if (isColor(inactive)) { - m_inactivePen.setBrush(QBrush(stringToColor(inactive))); + if (isColor(_inactive)) { + m_inactivePen.setBrush(QBrush(stringToColor(_inactive))); } else { - qCInfo(LOG_LIB) << "Found path, trying to load Pixmap from" << inactive; - QPixmap pixmap = QPixmap(QUrl(inactive).toLocalFile()); + qCInfo(LOG_LIB) << "Found path, trying to load Pixmap from" + << _inactive; + QPixmap pixmap = QPixmap(QUrl(_inactive).toLocalFile()); if (pixmap.isNull()) { - qCWarning(LOG_LIB) << "Invalid pixmap found" << inactive; + qCWarning(LOG_LIB) << "Invalid pixmap found" << _inactive; m_inactivePen.setBrush(QBrush(QColor(255, 255, 255, 130))); } else { - m_inactivePen.setBrush(QBrush(pixmap.scaled(width, height))); + m_inactivePen.setBrush(QBrush(pixmap.scaled(_width, _height))); } } - m_width = width; - m_height = height; - m_count = count; + m_width = _width; + m_height = _height; + m_count = _count; } -void GraphicalItemHelper::paintBars(const float value) +void GraphicalItemHelper::paintBars(const float _value) { - qCDebug(LOG_LIB) << "Paint with value" << value; + qCDebug(LOG_LIB) << "Paint with value" << _value; // refresh background image m_scene->setBackgroundBrush(m_inactivePen.brush()); - storeValue(value); + storeValue(_value); // default norms float normX @@ -105,9 +108,9 @@ void GraphicalItemHelper::paintBars(const float value) } -void GraphicalItemHelper::paintCircle(const float percent) +void GraphicalItemHelper::paintCircle(const float _percent) { - qCDebug(LOG_LIB) << "Paint with percent" << percent; + qCDebug(LOG_LIB) << "Paint with percent" << _percent; m_activePen.setWidth(1); m_inactivePen.setWidth(1); @@ -118,24 +121,24 @@ void GraphicalItemHelper::paintCircle(const float percent) // inactive circle = m_scene->addEllipse(0.0, 0.0, m_width, m_height, m_inactivePen, m_inactivePen.brush()); - circle->setSpanAngle(-(1.0f - percent) * 360.0f * 16.0f); - circle->setStartAngle(90.0f * 16.0f - percent * 360.0f * 16.0f); + circle->setSpanAngle(-(1.0f - _percent) * 360.0f * 16.0f); + circle->setStartAngle(90.0f * 16.0f - _percent * 360.0f * 16.0f); // active circle = m_scene->addEllipse(0.0, 0.0, m_width, m_height, m_activePen, m_activePen.brush()); - circle->setSpanAngle(-percent * 360.0f * 16.0f); + circle->setSpanAngle(-_percent * 360.0f * 16.0f); circle->setStartAngle(90 * 16); } -void GraphicalItemHelper::paintGraph(const float value) +void GraphicalItemHelper::paintGraph(const float _value) { - qCDebug(LOG_LIB) << "Paint with value" << value; + qCDebug(LOG_LIB) << "Paint with value" << _value; // refresh background image m_scene->setBackgroundBrush(m_inactivePen.brush()); - storeValue(value); + storeValue(_value); // default norms float normX @@ -153,66 +156,67 @@ void GraphicalItemHelper::paintGraph(const float value) } -void GraphicalItemHelper::paintHorizontal(const float percent) +void GraphicalItemHelper::paintHorizontal(const float _percent) { - qCDebug(LOG_LIB) << "Paint with percent" << percent; + qCDebug(LOG_LIB) << "Paint with percent" << _percent; m_activePen.setWidth(m_height); m_inactivePen.setWidth(m_height); // inactive - m_scene->addLine(percent * m_width + 0.5 * m_height, 0.5 * m_height, + m_scene->addLine(_percent * m_width + 0.5 * m_height, 0.5 * m_height, m_width + 0.5 * m_height, 0.5 * m_height, m_inactivePen); // active m_scene->addLine(-0.5 * m_height, 0.5 * m_height, - percent * m_width - 0.5 * m_height, 0.5 * m_height, + _percent * m_width - 0.5 * m_height, 0.5 * m_height, m_activePen); } -void GraphicalItemHelper::paintVertical(const float percent) +void GraphicalItemHelper::paintVertical(const float _percent) { - qCDebug(LOG_LIB) << "Paint with percent" << percent; + qCDebug(LOG_LIB) << "Paint with percent" << _percent; m_activePen.setWidth(m_height); m_inactivePen.setWidth(m_height); // inactive m_scene->addLine(0.5 * m_width, -0.5 * m_width, 0.5 * m_width, - (1.0 - percent) * m_height - 0.5 * m_width, m_inactivePen); + (1.0 - _percent) * m_height - 0.5 * m_width, + m_inactivePen); // active - m_scene->addLine(0.5 * m_width, (1.0 - percent) * m_height + 0.5 * m_width, + m_scene->addLine(0.5 * m_width, (1.0 - _percent) * m_height + 0.5 * m_width, 0.5 * m_width, m_height + 0.5 * m_width, m_activePen); } -float GraphicalItemHelper::getPercents(const float value, const float min, - const float max) +float GraphicalItemHelper::getPercents(const float _value, const float _min, + const float _max) { - qCDebug(LOG_LIB) << "Get percent value from" << value; + qCDebug(LOG_LIB) << "Get percent value from" << _value; // newest Qt crashes here if value is nan - if (std::isnan(value)) + if (std::isnan(_value)) return 0.0; - return (value - min) / (max - min); + return (_value - _min) / (_max - _min); } -bool GraphicalItemHelper::isColor(const QString &input) +bool GraphicalItemHelper::isColor(const QString &_input) { - qCDebug(LOG_LIB) << "Define input type in" << input; + qCDebug(LOG_LIB) << "Define input type in" << _input; - return input.startsWith(QString("color://")); + return _input.startsWith("color://"); } -QColor GraphicalItemHelper::stringToColor(const QString &color) +QColor GraphicalItemHelper::stringToColor(const QString &_color) { - qCDebug(LOG_LIB) << "Color" << color; + qCDebug(LOG_LIB) << "Color" << _color; - QStringList listColor = color.split(QChar(',')); + QStringList listColor = _color.split(','); while (listColor.count() < 4) - listColor.append(QString("0")); + listColor.append("0"); // remove prefix - listColor[0].remove(QString("color://")); + listColor[0].remove("color://"); // init color QColor qColor; qColor.setRed(listColor.at(0).toInt()); @@ -224,14 +228,14 @@ QColor GraphicalItemHelper::stringToColor(const QString &color) } -void GraphicalItemHelper::storeValue(const float value) +void GraphicalItemHelper::storeValue(const float _value) { - qCDebug(LOG_LIB) << "Save value to array" << value; + qCDebug(LOG_LIB) << "Save value to array" << _value; if (m_values.count() == 0) m_values.append(1.0); else if (m_values.count() > m_count) m_values.removeFirst(); - m_values.append(value); + m_values.append(_value); } diff --git a/sources/awesomewidgets/graphicalitemhelper.h b/sources/awesomewidgets/graphicalitemhelper.h index b0fca4d..5070e9a 100644 --- a/sources/awesomewidgets/graphicalitemhelper.h +++ b/sources/awesomewidgets/graphicalitemhelper.h @@ -30,25 +30,25 @@ class GraphicalItemHelper : public QObject Q_OBJECT public: - explicit GraphicalItemHelper(QObject *parent = nullptr, - QGraphicsScene *scene = nullptr); + explicit GraphicalItemHelper(QObject *_parent = nullptr, + QGraphicsScene *_scene = nullptr); virtual ~GraphicalItemHelper(); // parameters - void setParameters(const QString &active, const QString &inactive, - const int width, const int height, const int count); + void setParameters(const QString &_active, const QString &_inactive, + const int _width, const int _height, const int _count); // paint methods - void paintBars(const float value); - void paintCircle(const float percent); - void paintGraph(const float value); - void paintHorizontal(const float percent); - void paintVertical(const float percent); + void paintBars(const float _value); + void paintCircle(const float _percent); + void paintGraph(const float _value); + void paintHorizontal(const float _percent); + void paintVertical(const float _percent); // additional conversion methods - float getPercents(const float value, const float min, const float max); - bool isColor(const QString &input); - QColor stringToColor(const QString &color); + float getPercents(const float _value, const float _min, const float _max); + bool isColor(const QString &_input); + QColor stringToColor(const QString &_color); private: - void storeValue(const float value); + void storeValue(const float _value); QGraphicsScene *m_scene = nullptr; int m_count = 100; QPen m_activePen; diff --git a/sources/awesomewidgets/owmweatherprovider.cpp b/sources/awesomewidgets/owmweatherprovider.cpp index 67289db..7cf67d5 100644 --- a/sources/awesomewidgets/owmweatherprovider.cpp +++ b/sources/awesomewidgets/owmweatherprovider.cpp @@ -23,8 +23,8 @@ #include "awdebug.h" -OWMWeatherProvider::OWMWeatherProvider(QObject *parent, const int number) - : AbstractWeatherProvider(parent, number) +OWMWeatherProvider::OWMWeatherProvider(QObject *_parent, const int _number) + : AbstractWeatherProvider(_parent, _number) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; } @@ -36,10 +36,11 @@ OWMWeatherProvider::~OWMWeatherProvider() } -void OWMWeatherProvider::initUrl(const QString &city, const QString &country, +void OWMWeatherProvider::initUrl(const QString &_city, const QString &_country, const int ts) { - qCDebug(LOG_LIB) << "Init query for" << city << country << "with ts" << ts; + qCDebug(LOG_LIB) << "Init query for" << _city << _country << "with ts" + << ts; m_ts = ts; @@ -48,26 +49,26 @@ void OWMWeatherProvider::initUrl(const QString &city, const QString &country, else m_url = QUrl(OWM_FORECAST_URL); QUrlQuery params; - params.addQueryItem(QString("q"), QString("%1,%2").arg(city, country)); - params.addQueryItem(QString("units"), QString("metric")); + params.addQueryItem("q", QString("%1,%2").arg(_city, _country)); + params.addQueryItem("units", "metric"); m_url.setQuery(params); } -QVariantHash OWMWeatherProvider::parse(const QVariantMap &json) const +QVariantHash OWMWeatherProvider::parse(const QVariantMap &_json) const { - qCDebug(LOG_LIB) << "Parse json" << json; + qCDebug(LOG_LIB) << "Parse json" << _json; - if (json[QString("cod")].toInt() != 200) { + if (_json["cod"].toInt() != 200) { qCWarning(LOG_LIB) << "Invalid OpenWeatherMap return code" - << json[QString("cod")].toInt(); + << _json["cod"].toInt(); return QVariantHash(); } if (m_ts == 0) { - return parseSingleJson(json); + return parseSingleJson(_json); } else { - QVariantList list = json[QString("list")].toList(); + QVariantList list = _json["list"].toList(); return parseSingleJson(list.count() <= m_ts ? list.at(m_ts - 1).toMap() : list.last().toMap()); } @@ -80,33 +81,33 @@ QUrl OWMWeatherProvider::url() const } -QVariantHash OWMWeatherProvider::parseSingleJson(const QVariantMap &json) const +QVariantHash OWMWeatherProvider::parseSingleJson(const QVariantMap &_json) const { - qCDebug(LOG_LIB) << "Single json data" << json; + qCDebug(LOG_LIB) << "Single json data" << _json; QVariantHash output; // weather status - QVariantList weather = json[QString("weather")].toList(); + QVariantList weather = _json["weather"].toList(); if (!weather.isEmpty()) { - int id = weather.first().toMap()[QString("id")].toInt(); + int id = weather.first().toMap()["id"].toInt(); output[QString("weatherId%1").arg(number())] = id; } // main data - QVariantMap mainWeather = json[QString("main")].toMap(); + QVariantMap mainWeather = _json["main"].toMap(); if (!weather.isEmpty()) { output[QString("humidity%1").arg(number())] - = mainWeather[QString("humidity")].toFloat(); + = mainWeather["humidity"].toFloat(); output[QString("pressure%1").arg(number())] - = mainWeather[QString("pressure")].toFloat(); + = mainWeather["pressure"].toFloat(); output[QString("temperature%1").arg(number())] - = mainWeather[QString("temp")].toFloat(); + = mainWeather["temp"].toFloat(); } // timestamp output[QString("timestamp%1").arg(number())] - = QDateTime::fromTime_t(json[QString("dt")].toUInt()).toUTC(); + = QDateTime::fromTime_t(_json["dt"].toUInt()).toUTC(); return output; } diff --git a/sources/awesomewidgets/owmweatherprovider.h b/sources/awesomewidgets/owmweatherprovider.h index c4071a5..e9e5ed1 100644 --- a/sources/awesomewidgets/owmweatherprovider.h +++ b/sources/awesomewidgets/owmweatherprovider.h @@ -31,14 +31,14 @@ public: const char *OWM_WEATHER_URL = "https://arcanis.me/weather"; const char *OWM_FORECAST_URL = "https://arcanis.me/forecast"; - explicit OWMWeatherProvider(QObject *parent, const int number); + explicit OWMWeatherProvider(QObject *_parent, const int _number); virtual ~OWMWeatherProvider(); - void initUrl(const QString &city, const QString &country, const int); - QVariantHash parse(const QVariantMap &json) const; + void initUrl(const QString &_city, const QString &_country, const int); + QVariantHash parse(const QVariantMap &_json) const; QUrl url() const; private: - QVariantHash parseSingleJson(const QVariantMap &json) const; + QVariantHash parseSingleJson(const QVariantMap &_json) const; int m_ts = 0; QUrl m_url; }; diff --git a/sources/awesomewidgets/qcronscheduler.cpp b/sources/awesomewidgets/qcronscheduler.cpp index 436616d..bae48a8 100644 --- a/sources/awesomewidgets/qcronscheduler.cpp +++ b/sources/awesomewidgets/qcronscheduler.cpp @@ -24,8 +24,8 @@ #include "awdebug.h" -QCronScheduler::QCronScheduler(QObject *parent) - : QObject(parent) +QCronScheduler::QCronScheduler(QObject *_parent) + : QObject(_parent) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; @@ -48,11 +48,11 @@ QCronScheduler::~QCronScheduler() } -void QCronScheduler::parse(const QString &timer) +void QCronScheduler::parse(const QString &_timer) { - qCDebug(LOG_LIB) << "Parse timer string" << timer; + qCDebug(LOG_LIB) << "Parse timer string" << _timer; - QStringList fields = timer.split(' '); + QStringList fields = _timer.split(' '); if (fields.count() != 5) return; @@ -77,17 +77,17 @@ void QCronScheduler::expired() } -QList QCronScheduler::parseField(const QString &value, const int min, - const int max) const +QList QCronScheduler::parseField(const QString &_value, const int _min, + const int _max) const { - qCDebug(LOG_LIB) << "Parse field" << value << "with corner values" << min - << max; + qCDebug(LOG_LIB) << "Parse field" << _value << "with corner values" << _min + << _max; QList parsed; - auto fields = value.split(','); + auto fields = _value.split(','); for (auto &field : fields) { QCronField parsedField; - parsedField.fromRange(field.split('/').first(), min, max); + parsedField.fromRange(field.split('/').first(), _min, _max); if (field.contains('/')) { bool status; parsedField.div = field.split('/', QString::SkipEmptyParts) @@ -104,26 +104,26 @@ QList QCronScheduler::parseField(const QString &value, const int min, } -void QCronScheduler::QCronField::fromRange(const QString &range, const int min, - const int max) +void QCronScheduler::QCronField::fromRange(const QString &_range, + const int _min, const int _max) { - qCDebug(LOG_LIB) << "Parse field from range" << range - << "with corner values" << min << max; + qCDebug(LOG_LIB) << "Parse field from range" << _range + << "with corner values" << _min << _max; - if (range == '*') { - minValue = min; - maxValue = max; - } else if (range.contains('-')) { - auto interval = range.split('-', QString::SkipEmptyParts); + if (_range == '*') { + minValue = _min; + maxValue = _max; + } else if (_range.contains('-')) { + auto interval = _range.split('-', QString::SkipEmptyParts); if (interval.count() != 2) return; bool status; // minimal value - minValue = std::max(min, interval.at(0).toInt(&status)); + minValue = std::max(_min, interval.at(0).toInt(&status)); if (!status) minValue = -1; // maximal value - maxValue = std::min(max, interval.at(1).toInt(&status)); + maxValue = std::min(_max, interval.at(1).toInt(&status)); if (!status) maxValue = -1; // error check @@ -131,8 +131,8 @@ void QCronScheduler::QCronField::fromRange(const QString &range, const int min, std::swap(minValue, maxValue); } else { bool status; - int value = range.toInt(&status); - if (!status || (value < min) || (value > max)) + int value = _range.toInt(&status); + if (!status || (value < _min) || (value > _max)) value = -1; minValue = value; maxValue = value; diff --git a/sources/awesomewidgets/qcronscheduler.h b/sources/awesomewidgets/qcronscheduler.h index e03d34c..185c076 100644 --- a/sources/awesomewidgets/qcronscheduler.h +++ b/sources/awesomewidgets/qcronscheduler.h @@ -39,13 +39,13 @@ public: int minValue = -1; int maxValue = -1; int div = 1; - void fromRange(const QString &range, const int min, const int max); + void fromRange(const QString &_range, const int _min, const int _max); QList toList(); } QCronField; - explicit QCronScheduler(QObject *parent); + explicit QCronScheduler(QObject *_parent = nullptr); virtual ~QCronScheduler(); - void parse(const QString &timer); + void parse(const QString &_timer); signals: void activated(); @@ -56,8 +56,8 @@ private slots: private: QCronRunSchedule m_schedule; QTimer *m_timer = nullptr; - QList parseField(const QString &value, const int min, - const int max) const; + QList parseField(const QString &_value, const int _min, + const int _max) const; }; diff --git a/sources/awesomewidgets/yahooweatherprovider.cpp b/sources/awesomewidgets/yahooweatherprovider.cpp index ebad1b1..37729b4 100644 --- a/sources/awesomewidgets/yahooweatherprovider.cpp +++ b/sources/awesomewidgets/yahooweatherprovider.cpp @@ -22,8 +22,8 @@ #include "awdebug.h" -YahooWeatherProvider::YahooWeatherProvider(QObject *parent, const int number) - : AbstractWeatherProvider(parent, number) +YahooWeatherProvider::YahooWeatherProvider(QObject *_parent, const int _number) + : AbstractWeatherProvider(_parent, _number) { qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; } @@ -35,38 +35,36 @@ YahooWeatherProvider::~YahooWeatherProvider() } -void YahooWeatherProvider::initUrl(const QString &city, const QString &country, - const int ts) +void YahooWeatherProvider::initUrl(const QString &_city, + const QString &_country, const int ts) { - qCDebug(LOG_LIB) << "Init query for" << city << country << "with ts" << ts; + qCDebug(LOG_LIB) << "Init query for" << _city << _country << "with ts" + << ts; m_ts = ts; m_url = QUrl(YAHOO_WEATHER_URL); QUrlQuery params; - params.addQueryItem(QString("format"), QString("json")); - params.addQueryItem(QString("env"), - QString("store://datatables.org/alltableswithkeys")); - params.addQueryItem(QString("q"), - QString(YAHOO_WEATHER_QUERY).arg(city, country)); + params.addQueryItem("format", "json"); + params.addQueryItem("env", "store://datatables.org/alltableswithkeys"); + params.addQueryItem("q", QString(YAHOO_WEATHER_QUERY).arg(_city, _country)); m_url.setQuery(params); } -QVariantHash YahooWeatherProvider::parse(const QVariantMap &json) const +QVariantHash YahooWeatherProvider::parse(const QVariantMap &_json) const { - qCDebug(LOG_LIB) << "Parse json" << json; + qCDebug(LOG_LIB) << "Parse json" << _json; - QVariantMap jsonMap = json[QString("query")].toMap(); - if (jsonMap[QString("count")].toInt() != 1) { - qCWarning(LOG_LIB) << "Found data count" - << json[QString("count")].toInt() << "is not 1"; + QVariantMap jsonMap = _json["query"].toMap(); + if (jsonMap["count"].toInt() != 1) { + qCWarning(LOG_LIB) << "Found data count" << _json["count"].toInt() + << "is not 1"; return QVariantHash(); } - QVariantMap results - = jsonMap[QString("results")].toMap()[QString("channel")].toMap(); - QVariantMap item = results[QString("item")].toMap(); - QVariantMap atmosphere = results[QString("atmosphere")].toMap(); + QVariantMap results = jsonMap["results"].toMap()["channel"].toMap(); + QVariantMap item = results["item"].toMap(); + QVariantMap atmosphere = results["atmosphere"].toMap(); return m_ts == 0 ? parseCurrent(item, atmosphere) : parseForecast(item); } @@ -79,46 +77,44 @@ QUrl YahooWeatherProvider::url() const QVariantHash -YahooWeatherProvider::parseCurrent(const QVariantMap &json, - const QVariantMap &atmosphere) const +YahooWeatherProvider::parseCurrent(const QVariantMap &_json, + const QVariantMap &_atmosphere) const { - qCDebug(LOG_LIB) << "Parse current weather from" << json; + qCDebug(LOG_LIB) << "Parse current weather from" << _json; + + auto condition = _json["condition"].toMap(); QVariantHash values; - int id = json[QString("condition")].toMap()[QString("code")].toInt(); + int id = _json["condition"].toMap()["code"].toInt(); values[QString("weatherId%1").arg(number())] = id; - values[QString("temperature%1").arg(number())] - = json[QString("condition")].toMap()[QString("temp")].toInt(); - values[QString("timestamp%1").arg(number())] - = json[QString("condition")].toMap()[QString("date")].toString(); + values[QString("temperature%1").arg(number())] = condition["temp"].toInt(); + values[QString("timestamp%1").arg(number())] = condition["date"].toString(); values[QString("humidity%1").arg(number())] - = atmosphere[QString("humidity")].toInt(); + = _atmosphere["humidity"].toInt(); // HACK temporary fix of invalid values on Yahoo! side - values[QString("pressure%1").arg(number())] = static_cast( - atmosphere[QString("pressure")].toFloat() / 33.863753); + values[QString("pressure%1").arg(number())] + = static_cast(_atmosphere["pressure"].toFloat() / 33.863753); return values; } -QVariantHash YahooWeatherProvider::parseForecast(const QVariantMap &json) const +QVariantHash YahooWeatherProvider::parseForecast(const QVariantMap &_json) const { - qCDebug(LOG_LIB) << "Parse forecast from" << json; + qCDebug(LOG_LIB) << "Parse forecast from" << _json; QVariantHash values; - QVariantList weatherList = json[QString("forecast")].toList(); + QVariantList weatherList = _json["forecast"].toList(); QVariantMap weatherMap = weatherList.count() < m_ts ? weatherList.last().toMap() : weatherList.at(m_ts).toMap(); - int id = weatherMap[QString("code")].toInt(); + int id = weatherMap["code"].toInt(); values[QString("weatherId%1").arg(number())] = id; values[QString("timestamp%1").arg(number())] - = weatherMap[QString("date")].toString(); + = weatherMap["date"].toString(); // yahoo provides high and low temperatures. Lets calculate average one values[QString("temperature%1").arg(number())] - = (weatherMap[QString("high")].toFloat() - + weatherMap[QString("low")].toFloat()) - / 2.0; + = (weatherMap["high"].toFloat() + weatherMap["low"].toFloat()) / 2.0; // ... and no forecast data for humidity and pressure values[QString("humidity%1").arg(number())] = 0; values[QString("pressure%1").arg(number())] = 0.0; diff --git a/sources/awesomewidgets/yahooweatherprovider.h b/sources/awesomewidgets/yahooweatherprovider.h index f309860..342b8b9 100644 --- a/sources/awesomewidgets/yahooweatherprovider.h +++ b/sources/awesomewidgets/yahooweatherprovider.h @@ -31,16 +31,16 @@ public: "u='c' and woeid in (select woeid from " "geo.places(1) where text='%1, %2')"; - explicit YahooWeatherProvider(QObject *parent, const int number); + explicit YahooWeatherProvider(QObject *_parent, const int _number); virtual ~YahooWeatherProvider(); - void initUrl(const QString &city, const QString &country, const int); - QVariantHash parse(const QVariantMap &json) const; + void initUrl(const QString &_city, const QString &_country, const int); + QVariantHash parse(const QVariantMap &_json) const; QUrl url() const; private: - QVariantHash parseCurrent(const QVariantMap &json, - const QVariantMap &atmosphere) const; - QVariantHash parseForecast(const QVariantMap &json) const; + QVariantHash parseCurrent(const QVariantMap &_json, + const QVariantMap &_atmosphere) const; + QVariantHash parseForecast(const QVariantMap &_json) const; int m_ts = 0; QUrl m_url; }; diff --git a/sources/desktop-panel/plugin/dpadds.cpp b/sources/desktop-panel/plugin/dpadds.cpp index 9fc9a75..08149fb 100644 --- a/sources/desktop-panel/plugin/dpadds.cpp +++ b/sources/desktop-panel/plugin/dpadds.cpp @@ -36,8 +36,8 @@ #include "awdebug.h" -DPAdds::DPAdds(QObject *parent) - : QObject(parent) +DPAdds::DPAdds(QObject *_parent) + : QObject(_parent) { qSetMessagePattern(AWDebug::LOG_FORMAT); qCDebug(LOG_DP) << __PRETTY_FUNCTION__; @@ -72,21 +72,21 @@ int DPAdds::currentDesktop() const } -QStringList DPAdds::dictKeys(const bool sorted, const QString ®exp) const +QStringList DPAdds::dictKeys(const bool _sorted, const QString &_regexp) const { - qCDebug(LOG_DP) << "Should be sorted" << sorted << "and filter applied" - << regexp; + qCDebug(LOG_DP) << "Should be sorted" << _sorted << "and filter applied" + << _regexp; QStringList allKeys; - allKeys.append(QString("mark")); - allKeys.append(QString("name")); - allKeys.append(QString("number")); - allKeys.append(QString("total")); + allKeys.append("mark"); + allKeys.append("name"); + allKeys.append("number"); + allKeys.append("total"); - if (sorted) + if (_sorted) allKeys.sort(); - return allKeys.filter(QRegExp(regexp)); + return allKeys.filter(QRegExp(_regexp)); } @@ -96,32 +96,34 @@ int DPAdds::numberOfDesktops() const } -QString DPAdds::toolTipImage(const int desktop) const +QString DPAdds::toolTipImage(const int _desktop) const { - qCDebug(LOG_DP) << "Desktop" << desktop; + qCDebug(LOG_DP) << "Desktop" << _desktop; // drop if no tooltip required - if (m_tooltipType == QString("none")) - return QString(); + if (m_tooltipType == "none") + return ""; // prepare - DesktopWindowsInfo info = getInfoByDesktop(desktop); + DesktopWindowsInfo info = getInfoByDesktop(_desktop); // special tooltip format for names - if (m_tooltipType == QString("names")) { + if (m_tooltipType == "names") { QStringList windowList; std::for_each( info.windowsData.cbegin(), info.windowsData.cend(), [&windowList](WindowData data) { windowList.append(data.name); }); return QString("
    • %1
    ") - .arg(windowList.join(QString("
  • "))); + .arg(windowList.join("
  • ")); } + // init QGraphicsScene *toolTipScene = new QGraphicsScene(); QGraphicsView *toolTipView = new QGraphicsView(toolTipScene); - toolTipView->setStyleSheet(QString("background: transparent")); + toolTipView->setStyleSheet("background: transparent"); toolTipView->setContentsMargins(0, 0, 0, 0); toolTipView->setFrameShape(QFrame::NoFrame); toolTipView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); toolTipView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + // update float margin = 5.0f * info.desktop.width() / 400.0f; toolTipView->resize(info.desktop.width() + 2.0f * margin, @@ -138,7 +140,7 @@ QString DPAdds::toolTipImage(const int desktop) const info.desktop.width() + 2.0 * margin, 0); toolTipScene->addLine(info.desktop.width() + 2.0 * margin, 0, 0, 0); - if (m_tooltipType == QString("contours")) { + if (m_tooltipType == "contours") { QPen pen = QPen(); pen.setWidthF(2.0 * info.desktop.width() / 400.0); pen.setColor(QColor(m_tooltipColor)); @@ -157,24 +159,24 @@ QString DPAdds::toolTipImage(const int desktop) const rect.left() + margin, rect.bottom() + margin, pen); } - } else if (m_tooltipType == QString("clean")) { + } else if (m_tooltipType == "clean") { QScreen *screen = QGuiApplication::primaryScreen(); std::for_each(info.desktopsData.cbegin(), info.desktopsData.cend(), - [&toolTipScene, &screen](WindowData data) { + [&toolTipScene, &screen](const WindowData &data) { QPixmap desktop = screen->grabWindow(data.id); toolTipScene->addPixmap(desktop)->setOffset( data.rect.left(), data.rect.top()); }); - } else if (m_tooltipType == QString("windows")) { + } else if (m_tooltipType == "windows") { QScreen *screen = QGuiApplication::primaryScreen(); std::for_each(info.desktopsData.cbegin(), info.desktopsData.cend(), - [&toolTipScene, &screen](WindowData data) { + [&toolTipScene, &screen](const WindowData &data) { QPixmap desktop = screen->grabWindow(data.id); toolTipScene->addPixmap(desktop)->setOffset( data.rect.left(), data.rect.top()); }); std::for_each(info.windowsData.cbegin(), info.windowsData.cend(), - [&toolTipScene, &screen](WindowData data) { + [&toolTipScene, &screen](const WindowData &data) { QPixmap window = screen->grabWindow(data.id); toolTipScene->addPixmap(window)->setOffset( data.rect.left(), data.rect.top()); @@ -194,127 +196,126 @@ QString DPAdds::toolTipImage(const int desktop) const } -QString DPAdds::parsePattern(const QString &pattern, const int desktop) const +QString DPAdds::parsePattern(const QString &_pattern, const int _desktop) const { - qCDebug(LOG_DP) << "Pattern" << pattern << "for desktop" << desktop; + qCDebug(LOG_DP) << "Pattern" << _pattern << "for desktop" << _desktop; - QString parsed = pattern; - parsed.replace(QString("$$"), QString("$\\$\\")); + QString parsed = _pattern; + parsed.replace("$$", "$\\$\\"); for (auto &key : dictKeys()) - parsed.replace(QString("$%1").arg(key), valueByKey(key, desktop)); - parsed.replace(QString("$\\$\\"), QString("$$")); + parsed.replace(QString("$%1").arg(key), valueByKey(key, _desktop)); + parsed.replace("$\\$\\", "$$"); return parsed; } -void DPAdds::setMark(const QString &newMark) +void DPAdds::setMark(const QString &_newMark) { - qCDebug(LOG_DP) << "Mark" << newMark; + qCDebug(LOG_DP) << "Mark" << _newMark; - m_mark = newMark; + m_mark = _newMark; } -void DPAdds::setToolTipData(const QVariantMap &tooltipData) +void DPAdds::setToolTipData(const QVariantMap &_tooltipData) { - qCDebug(LOG_DP) << "Data" << tooltipData; + qCDebug(LOG_DP) << "Data" << _tooltipData; - m_tooltipColor = tooltipData[QString("tooltipColor")].toString(); - m_tooltipType = tooltipData[QString("tooltipType")].toString(); - m_tooltipWidth = tooltipData[QString("tooltipWidth")].toInt(); + m_tooltipColor = _tooltipData["tooltipColor"].toString(); + m_tooltipType = _tooltipData["tooltipType"].toString(); + m_tooltipWidth = _tooltipData["tooltipWidth"].toInt(); } -QString DPAdds::infoByKey(const QString &key) const +QString DPAdds::infoByKey(const QString &_key) const { - qCDebug(LOG_AW) << "Requested info for key" << key; + qCDebug(LOG_AW) << "Requested info for key" << _key; - return QString("(none)"); + return "(none)"; } -QString DPAdds::valueByKey(const QString &key, int desktop) const +QString DPAdds::valueByKey(const QString &_key, int _desktop) const { - qCDebug(LOG_DP) << "Requested key" << key << "for desktop" << desktop; - if (desktop == -1) - desktop = currentDesktop(); + qCDebug(LOG_DP) << "Requested key" << _key << "for desktop" << _desktop; + if (_desktop == -1) + _desktop = currentDesktop(); - QString currentMark = currentDesktop() == desktop ? m_mark : QString(""); - if (key == QString("mark")) + QString currentMark = currentDesktop() == _desktop ? m_mark : ""; + if (_key == "mark") return QString("%1") .arg(currentMark, m_mark.count(), QLatin1Char(' ')) - .replace(QString(" "), QString(" ")); - else if (key == QString("name")) - return KWindowSystem::desktopName(desktop).replace(QString(" "), - QString(" ")); - else if (key == QString("number")) - return QString::number(desktop); - else if (key == QString("total")) + .replace(" ", " "); + else if (_key == "name") + return KWindowSystem::desktopName(_desktop).replace(" ", " "); + else if (_key == "number") + return QString::number(_desktop); + else if (_key == "total") return QString::number(numberOfDesktops()); else - return QString(); + return ""; } // HACK: this method uses variables from version.h -QString DPAdds::getAboutText(const QString &type) const +QString DPAdds::getAboutText(const QString &_type) const { - qCDebug(LOG_DP) << "Type" << type; + qCDebug(LOG_DP) << "Type" << _type; - return AWDebug::getAboutText(type); + return AWDebug::getAboutText(_type); } -QVariantMap DPAdds::getFont(const QVariantMap &defaultFont) const +QVariantMap DPAdds::getFont(const QVariantMap &_defaultFont) const { - qCDebug(LOG_DP) << "Default font is" << defaultFont; + qCDebug(LOG_DP) << "Default font is" << _defaultFont; QVariantMap fontMap; int ret = 0; - CFont defaultCFont = CFont(defaultFont[QString("family")].toString(), - defaultFont[QString("size")].toInt(), 400, false, - defaultFont[QString("color")].toString()); + CFont defaultCFont + = CFont(_defaultFont["family"].toString(), _defaultFont["size"].toInt(), + 400, false, _defaultFont["color"].toString()); CFont font = CFontDialog::getFont(i18n("Select font"), defaultCFont, false, false, &ret); - fontMap[QString("applied")] = ret; - fontMap[QString("color")] = font.color().name(); - fontMap[QString("family")] = font.family(); - fontMap[QString("size")] = font.pointSize(); + fontMap["applied"] = ret; + fontMap["color"] = font.color().name(); + fontMap["family"] = font.family(); + fontMap["size"] = font.pointSize(); return fontMap; } // to avoid additional object definition this method is static -void DPAdds::sendNotification(const QString &eventId, const QString &message) +void DPAdds::sendNotification(const QString &_eventId, const QString &_message) { - qCDebug(LOG_DP) << "Event" << eventId << "with message" << message; + qCDebug(LOG_DP) << "Event" << _eventId << "with message" << _message; KNotification *notification = KNotification::event( - eventId, QString("Desktop Panel ::: %1").arg(eventId), message); + _eventId, QString("Desktop Panel ::: %1").arg(_eventId), _message); notification->setComponentName( - QString("plasma-applet-org.kde.plasma.desktop-panel")); + "plasma-applet-org.kde.plasma.desktop-panel"); } // slot for mouse click -void DPAdds::setCurrentDesktop(const int desktop) const +void DPAdds::setCurrentDesktop(const int _desktop) const { - qCDebug(LOG_DP) << "Desktop" << desktop; + qCDebug(LOG_DP) << "Desktop" << _desktop; - KWindowSystem::setCurrentDesktop(desktop); + KWindowSystem::setCurrentDesktop(_desktop); } -DPAdds::DesktopWindowsInfo DPAdds::getInfoByDesktop(const int desktop) const +DPAdds::DesktopWindowsInfo DPAdds::getInfoByDesktop(const int _desktop) const { - qCDebug(LOG_DP) << "Desktop" << desktop; + qCDebug(LOG_DP) << "Desktop" << _desktop; DesktopWindowsInfo info; - info.desktop = KWindowSystem::workArea(desktop); + info.desktop = KWindowSystem::workArea(_desktop); for (auto &id : KWindowSystem::windows()) { KWindowInfo winInfo = KWindowInfo( @@ -322,7 +323,7 @@ DPAdds::DesktopWindowsInfo DPAdds::getInfoByDesktop(const int desktop) const NET::Property::WMDesktop | NET::Property::WMGeometry | NET::Property::WMState | NET::Property::WMWindowType | NET::Property::WMVisibleName); - if (!winInfo.isOnDesktop(desktop)) + if (!winInfo.isOnDesktop(_desktop)) continue; WindowData data; data.id = id; diff --git a/sources/desktop-panel/plugin/dpadds.h b/sources/desktop-panel/plugin/dpadds.h index 2fac3e7..b631c61 100644 --- a/sources/desktop-panel/plugin/dpadds.h +++ b/sources/desktop-panel/plugin/dpadds.h @@ -41,41 +41,42 @@ class DPAdds : public QObject } DesktopWindowsInfo; public: - explicit DPAdds(QObject *parent = nullptr); + explicit DPAdds(QObject *_parent = nullptr); virtual ~DPAdds(); Q_INVOKABLE bool isDebugEnabled() const; Q_INVOKABLE int currentDesktop() const; - Q_INVOKABLE QStringList dictKeys(const bool sorted = true, - const QString ®exp = QString()) const; + Q_INVOKABLE QStringList dictKeys(const bool _sorted = true, + const QString &_regexp = "") const; Q_INVOKABLE int numberOfDesktops() const; - Q_INVOKABLE QString toolTipImage(const int desktop) const; - Q_INVOKABLE QString parsePattern(const QString &pattern, - const int desktop) const; + Q_INVOKABLE QString toolTipImage(const int _desktop) const; + Q_INVOKABLE QString parsePattern(const QString &_pattern, + const int _desktop) const; // values - Q_INVOKABLE void setMark(const QString &newMark); - Q_INVOKABLE void setToolTipData(const QVariantMap &tooltipData); - Q_INVOKABLE QString infoByKey(const QString &key) const; - Q_INVOKABLE QString valueByKey(const QString &key, int desktop = -1) const; + Q_INVOKABLE void setMark(const QString &_newMark); + Q_INVOKABLE void setToolTipData(const QVariantMap &_tooltipData); + Q_INVOKABLE QString infoByKey(const QString &_key) const; + Q_INVOKABLE QString valueByKey(const QString &_key, + int _desktop = -1) const; // configuration slots - Q_INVOKABLE QString getAboutText(const QString &type = "header") const; - Q_INVOKABLE QVariantMap getFont(const QVariantMap &defaultFont) const; + Q_INVOKABLE QString getAboutText(const QString &_type) const; + Q_INVOKABLE QVariantMap getFont(const QVariantMap &_defaultFont) const; signals: void desktopChanged() const; void windowListChanged() const; public slots: - Q_INVOKABLE static void sendNotification(const QString &eventId, - const QString &message); - Q_INVOKABLE void setCurrentDesktop(const int desktop) const; + Q_INVOKABLE static void sendNotification(const QString &_eventId, + const QString &_message); + Q_INVOKABLE void setCurrentDesktop(const int _desktop) const; private: - DesktopWindowsInfo getInfoByDesktop(const int desktop) const; + DesktopWindowsInfo getInfoByDesktop(const int _desktop) const; // variables int m_tooltipWidth = 200; - QString m_mark = QString("*"); - QString m_tooltipColor = QString("#000000"); - QString m_tooltipType = QString("none"); + QString m_mark = "*"; + QString m_tooltipColor = "#000000"; + QString m_tooltipType = "none"; }; diff --git a/sources/extsysmon/extsysmon.cpp b/sources/extsysmon/extsysmon.cpp index eb98ba4..2e074c6 100644 --- a/sources/extsysmon/extsysmon.cpp +++ b/sources/extsysmon/extsysmon.cpp @@ -24,14 +24,14 @@ #include "awdebug.h" #include "extsysmonaggregator.h" -#include "gputempsource.h" +#include "gpuloadsource.h" #include "hddtempsource.h" -ExtendedSysMon::ExtendedSysMon(QObject *parent, const QVariantList &args) - : Plasma::DataEngine(parent, args) +ExtendedSysMon::ExtendedSysMon(QObject *_parent, const QVariantList &_args) + : Plasma::DataEngine(_parent, _args) { - Q_UNUSED(args) + Q_UNUSED(_args) qSetMessagePattern(AWDebug::LOG_FORMAT); qCDebug(LOG_ESM) << __PRETTY_FUNCTION__; for (auto &metadata : AWDebug::getBuildData()) @@ -61,25 +61,25 @@ QStringList ExtendedSysMon::sources() const } -bool ExtendedSysMon::sourceRequestEvent(const QString &source) +bool ExtendedSysMon::sourceRequestEvent(const QString &_source) { - qCDebug(LOG_ESM) << "Source" << source; + qCDebug(LOG_ESM) << "Source" << _source; - return updateSourceEvent(source); + return updateSourceEvent(_source); } -bool ExtendedSysMon::updateSourceEvent(const QString &source) +bool ExtendedSysMon::updateSourceEvent(const QString &_source) { - qCDebug(LOG_ESM) << "Source" << source; + qCDebug(LOG_ESM) << "Source" << _source; - if (m_aggregator->hasSource(source)) { - QVariant data = m_aggregator->data(source); + if (m_aggregator->hasSource(_source)) { + QVariant data = m_aggregator->data(_source); if (data.isNull()) return false; - setData(source, QString("value"), data); + setData(_source, "value", data); } else { - qCWarning(LOG_ESM) << "Unknown source" << source; + qCWarning(LOG_ESM) << "Unknown source" << _source; return false; } @@ -89,36 +89,26 @@ bool ExtendedSysMon::updateSourceEvent(const QString &source) void ExtendedSysMon::readConfiguration() { - QString fileName - = QStandardPaths::locate(QStandardPaths::ConfigLocation, - QString("plasma-dataengine-extsysmon.conf")); + QString fileName = QStandardPaths::locate( + QStandardPaths::ConfigLocation, "plasma-dataengine-extsysmon.conf"); qCInfo(LOG_ESM) << "Configuration file" << fileName; QSettings settings(fileName, QSettings::IniFormat); QHash rawConfig; - settings.beginGroup(QString("Configuration")); - rawConfig[QString("ACPIPATH")] - = settings - .value(QString("ACPIPATH"), QString("/sys/class/power_supply/")) - .toString(); - rawConfig[QString("GPUDEV")] - = settings.value(QString("GPUDEV"), QString("auto")).toString(); - rawConfig[QString("HDDDEV")] - = settings.value(QString("HDDDEV"), QString("all")).toString(); - rawConfig[QString("HDDTEMPCMD")] - = settings.value(QString("HDDTEMPCMD"), QString("sudo smartctl -a")) - .toString(); - rawConfig[QString("MPDADDRESS")] - = settings.value(QString("MPDADDRESS"), QString("localhost")) - .toString(); - rawConfig[QString("MPDPORT")] - = settings.value(QString("MPDPORT"), QString("6600")).toString(); - rawConfig[QString("MPRIS")] - = settings.value(QString("MPRIS"), QString("auto")).toString(); - rawConfig[QString("PLAYER")] - = settings.value(QString("PLAYER"), QString("mpris")).toString(); - rawConfig[QString("PLAYERSYMBOLS")] - = settings.value(QString("PLAYERSYMBOLS"), QString("10")).toString(); + settings.beginGroup("Configuration"); + rawConfig["ACPIPATH"] + = settings.value("ACPIPATH", "/sys/class/power_supply/").toString(); + rawConfig["GPUDEV"] = settings.value("GPUDEV", "auto").toString(); + rawConfig["HDDDEV"] = settings.value("HDDDEV", "all").toString(); + rawConfig["HDDTEMPCMD"] + = settings.value("HDDTEMPCMD", "sudo smartctl -a").toString(); + rawConfig["MPDADDRESS"] + = settings.value("MPDADDRESS", "localhost").toString(); + rawConfig["MPDPORT"] = settings.value("MPDPORT", "6600").toString(); + rawConfig["MPRIS"] = settings.value("MPRIS", "auto").toString(); + rawConfig["PLAYER"] = settings.value("PLAYER", "mpris").toString(); + rawConfig["PLAYERSYMBOLS"] + = settings.value("PLAYERSYMBOLS", "10").toString(); settings.endGroup(); m_configuration = updateConfiguration(rawConfig); @@ -126,49 +116,48 @@ void ExtendedSysMon::readConfiguration() QHash -ExtendedSysMon::updateConfiguration(QHash rawConfig) const +ExtendedSysMon::updateConfiguration(QHash _rawConfig) const { - qCDebug(LOG_ESM) << "Raw configuration" << rawConfig; + qCDebug(LOG_ESM) << "Raw configuration" << _rawConfig; // gpudev - if (rawConfig[QString("GPUDEV")] == QString("disable")) - rawConfig[QString("GPUDEV")] = QString("disable"); - else if (rawConfig[QString("GPUDEV")] == QString("auto")) - rawConfig[QString("GPUDEV")] = GPUTemperatureSource::autoGpu(); - else if ((rawConfig[QString("GPUDEV")] != QString("ati")) - && (rawConfig[QString("GPUDEV")] != QString("nvidia"))) - rawConfig[QString("GPUDEV")] = GPUTemperatureSource::autoGpu(); + if (_rawConfig["GPUDEV"] == "disable") + ; + else if (_rawConfig["GPUDEV"] == "auto") + _rawConfig["GPUDEV"] = GPULoadSource::autoGpu(); + else if ((_rawConfig["GPUDEV"] != "ati") + && (_rawConfig["GPUDEV"] != "nvidia")) + _rawConfig["GPUDEV"] = GPULoadSource::autoGpu(); // hdddev QStringList allHddDevices = HDDTemperatureSource::allHdd(); - if (rawConfig[QString("HDDDEV")] == QString("all")) { - rawConfig[QString("HDDDEV")] = allHddDevices.join(QChar(',')); - } else if (rawConfig[QString("HDDDEV")] == QString("disable")) { - rawConfig[QString("HDDDEV")] = QString(""); + if (_rawConfig["HDDDEV"] == "all") { + _rawConfig["HDDDEV"] = allHddDevices.join(','); + } else if (_rawConfig["HDDDEV"] == "disable") { + _rawConfig["HDDDEV"] = ""; } else { - QStringList deviceList = rawConfig[QString("HDDDEV")].split( - QChar(','), QString::SkipEmptyParts); + QStringList deviceList + = _rawConfig["HDDDEV"].split(',', QString::SkipEmptyParts); QStringList devices; QRegExp diskRegexp = QRegExp("^/dev/[hms]d[a-z]$"); for (auto &device : deviceList) if ((QFile::exists(device)) && (device.contains(diskRegexp))) devices.append(device); if (devices.isEmpty()) - rawConfig[QString("HDDDEV")] = allHddDevices.join(QChar(',')); + _rawConfig["HDDDEV"] = allHddDevices.join(','); else - rawConfig[QString("HDDDEV")] = devices.join(QChar(',')); + _rawConfig["HDDDEV"] = devices.join(','); } // player - if ((rawConfig[QString("PLAYER")] != QString("mpd")) - && (rawConfig[QString("PLAYER")] != QString("mpris")) - && (rawConfig[QString("PLAYER")] != QString("disable"))) - rawConfig[QString("PLAYER")] = QString("mpris"); + if ((_rawConfig["PLAYER"] != "mpd") && (_rawConfig["PLAYER"] != "mpris") + && (_rawConfig["PLAYER"] != "disable")) + _rawConfig["PLAYER"] = "mpris"; // player symbols - if (rawConfig[QString("PLAYERSYMBOLS")].toInt() <= 0) - rawConfig[QString("PLAYERSYMBOLS")] = QString("10"); + if (_rawConfig["PLAYERSYMBOLS"].toInt() <= 0) + _rawConfig["PLAYERSYMBOLS"] = "10"; - for (auto &key : rawConfig.keys()) - qCInfo(LOG_ESM) << key << "=" << rawConfig[key]; - return rawConfig; + for (auto &key : _rawConfig.keys()) + qCInfo(LOG_ESM) << key << "=" << _rawConfig[key]; + return _rawConfig; } diff --git a/sources/extsysmon/extsysmon.h b/sources/extsysmon/extsysmon.h index 49d48cc..16e3224 100644 --- a/sources/extsysmon/extsysmon.h +++ b/sources/extsysmon/extsysmon.h @@ -28,13 +28,13 @@ class ExtendedSysMon : public Plasma::DataEngine Q_OBJECT public: - explicit ExtendedSysMon(QObject *parent, const QVariantList &args); + explicit ExtendedSysMon(QObject *_parent, const QVariantList &_args); virtual ~ExtendedSysMon(); protected: QStringList sources() const; - bool sourceRequestEvent(const QString &source); - bool updateSourceEvent(const QString &source); + bool sourceRequestEvent(const QString &_source); + bool updateSourceEvent(const QString &_source); private: // configuration @@ -43,7 +43,7 @@ private: // methods void readConfiguration(); QHash - updateConfiguration(QHash rawConfig) const; + updateConfiguration(QHash _rawConfig) const; }; diff --git a/sources/extsysmon/extsysmonaggregator.cpp b/sources/extsysmon/extsysmonaggregator.cpp index 6905bec..342ad75 100644 --- a/sources/extsysmon/extsysmonaggregator.cpp +++ b/sources/extsysmon/extsysmonaggregator.cpp @@ -34,13 +34,13 @@ #include "weathersource.h" -ExtSysMonAggregator::ExtSysMonAggregator(QObject *parent, - const QHash &config) - : QObject(parent) +ExtSysMonAggregator::ExtSysMonAggregator(QObject *_parent, + const QHash &_config) + : QObject(_parent) { qCDebug(LOG_ESM) << __PRETTY_FUNCTION__; - init(config); + init(_config); } @@ -52,28 +52,28 @@ ExtSysMonAggregator::~ExtSysMonAggregator() } -QVariant ExtSysMonAggregator::data(const QString &source) const +QVariant ExtSysMonAggregator::data(const QString &_source) const { - qCDebug(LOG_ESM) << "Source" << source; + qCDebug(LOG_ESM) << "Source" << _source; - return m_map[source]->data(source); + return m_map[_source]->data(_source); } -bool ExtSysMonAggregator::hasSource(const QString &source) const +bool ExtSysMonAggregator::hasSource(const QString &_source) const { - qCDebug(LOG_ESM) << "Source" << source; + qCDebug(LOG_ESM) << "Source" << _source; - return m_map.contains(source); + return m_map.contains(_source); } -QVariantMap ExtSysMonAggregator::initialData(const QString &source) const +QVariantMap ExtSysMonAggregator::initialData(const QString &_source) const { - qCDebug(LOG_ESM) << "Source" << source; + qCDebug(LOG_ESM) << "Source" << _source; - return hasSource(source) ? m_map[source]->initialData(source) - : QVariantMap(); + return hasSource(_source) ? m_map[_source]->initialData(_source) + : QVariantMap(); } @@ -83,13 +83,13 @@ QStringList ExtSysMonAggregator::sources() const } -void ExtSysMonAggregator::init(const QHash &config) +void ExtSysMonAggregator::init(const QHash &_config) { - qCDebug(LOG_ESM) << "Configuration" << config; + qCDebug(LOG_ESM) << "Configuration" << _config; // battery AbstractExtSysMonSource *batteryItem - = new BatterySource(this, QStringList() << config[QString("ACPIPATH")]); + = new BatterySource(this, QStringList() << _config["ACPIPATH"]); for (auto &source : batteryItem->sources()) m_map[source] = batteryItem; // custom @@ -103,19 +103,17 @@ void ExtSysMonAggregator::init(const QHash &config) m_map[source] = desktopItem; // gpu load AbstractExtSysMonSource *gpuLoadItem - = new GPULoadSource(this, QStringList() << config[QString("GPUDEV")]); + = new GPULoadSource(this, QStringList({_config["GPUDEV"]})); for (auto &source : gpuLoadItem->sources()) m_map[source] = gpuLoadItem; // gpu temperature - AbstractExtSysMonSource *gpuTempItem = new GPUTemperatureSource( - this, QStringList() << config[QString("GPUDEV")]); + AbstractExtSysMonSource *gpuTempItem + = new GPUTemperatureSource(this, QStringList({_config["GPUDEV"]})); for (auto &source : gpuTempItem->sources()) m_map[source] = gpuTempItem; // hdd temperature AbstractExtSysMonSource *hddTempItem = new HDDTemperatureSource( - this, - QStringList() << config[QString("HDDDEV")] - << config[QString("HDDTEMPCMD")]); + this, QStringList({_config["HDDDEV"], _config["HDDTEMPCMD"]})); for (auto &source : hddTempItem->sources()) m_map[source] = hddTempItem; // network @@ -125,11 +123,9 @@ void ExtSysMonAggregator::init(const QHash &config) m_map[source] = networkItem; // player AbstractExtSysMonSource *playerItem = new PlayerSource( - this, - QStringList() << config[QString("PLAYER")] - << config[QString("MPDADDRESS")] - << config[QString("MPDPORT")] << config[QString("MPRIS")] - << config[QString("PLAYERSYMBOLS")]); + this, QStringList({_config["PLAYER"], _config["MPDADDRESS"], + _config["MPDPORT"], _config["MPRIS"], + _config["PLAYERSYMBOLS"]})); for (auto &source : playerItem->sources()) m_map[source] = playerItem; // processes diff --git a/sources/extsysmon/extsysmonaggregator.h b/sources/extsysmon/extsysmonaggregator.h index 6d3a5a9..8153141 100644 --- a/sources/extsysmon/extsysmonaggregator.h +++ b/sources/extsysmon/extsysmonaggregator.h @@ -28,16 +28,16 @@ class ExtSysMonAggregator : public QObject Q_OBJECT public: - explicit ExtSysMonAggregator(QObject *parent, - const QHash &config); + explicit ExtSysMonAggregator(QObject *_parent, + const QHash &_config); virtual ~ExtSysMonAggregator(); - QVariant data(const QString &source) const; - bool hasSource(const QString &source) const; - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source) const; + bool hasSource(const QString &_source) const; + QVariantMap initialData(const QString &_source) const; QStringList sources() const; private: - void init(const QHash &config); + void init(const QHash &_config); QHash m_map; }; diff --git a/sources/extsysmonsources/abstractextsysmonsource.h b/sources/extsysmonsources/abstractextsysmonsource.h index 96754b8..f2d97cc 100644 --- a/sources/extsysmonsources/abstractextsysmonsource.h +++ b/sources/extsysmonsources/abstractextsysmonsource.h @@ -28,18 +28,18 @@ class AbstractExtSysMonSource : public QObject Q_OBJECT public: - explicit AbstractExtSysMonSource(QObject *parent, const QStringList &) - : QObject(parent){}; + explicit AbstractExtSysMonSource(QObject *_parent, const QStringList &) + : QObject(_parent){}; virtual ~AbstractExtSysMonSource(){}; - virtual QVariant data(const QString &source) = 0; - virtual QVariantMap initialData(const QString &source) const = 0; + virtual QVariant data(const QString &_source) = 0; + virtual QVariantMap initialData(const QString &_source) const = 0; virtual void run() = 0; virtual QStringList sources() const = 0; // used by extensions - int index(const QString &source) const + int index(const QString &_source) const { - QRegExp rx(QString("\\d+")); - rx.indexIn(source); + QRegExp rx("\\d+"); + rx.indexIn(_source); return rx.cap().toInt(); } diff --git a/sources/extsysmonsources/batterysource.cpp b/sources/extsysmonsources/batterysource.cpp index d25f39f..1219de6 100644 --- a/sources/extsysmonsources/batterysource.cpp +++ b/sources/extsysmonsources/batterysource.cpp @@ -23,13 +23,13 @@ #include "awdebug.h" -BatterySource::BatterySource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +BatterySource::BatterySource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 1); + Q_ASSERT(_args.count() == 1); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_acpiPath = args.at(0); + m_acpiPath = _args.at(0); m_sources = getSources(); } @@ -43,11 +43,11 @@ BatterySource::~BatterySource() QStringList BatterySource::getSources() { QStringList sources; - sources.append(QString("battery/ac")); - sources.append(QString("battery/bat")); + sources.append("battery/ac"); + sources.append("battery/bat"); m_batteriesCount = QDir(m_acpiPath) - .entryList(QStringList() << QString("BAT*"), + .entryList(QStringList({"BAT*"}), QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name) .count(); qCInfo(LOG_ESS) << "Init batteries count as" << m_batteriesCount; @@ -59,40 +59,40 @@ QStringList BatterySource::getSources() } -QVariant BatterySource::data(const QString &source) +QVariant BatterySource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - if (!m_values.contains(source)) + if (!m_values.contains(_source)) run(); - QVariant value = m_values.take(source); + QVariant value = m_values.take(_source); return value; } -QVariantMap BatterySource::initialData(const QString &source) const +QVariantMap BatterySource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("battery/ac")) { - data[QString("min")] = false; - data[QString("max")] = true; - data[QString("name")] = QString("Is AC online or not"); - data[QString("type")] = QString("bool"); - data[QString("units")] = QString(""); - } else if (source == QString("battery/bat")) { - data[QString("min")] = 0; - data[QString("max")] = 100; - data[QString("name")] = QString("Average battery usage"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("%"); + if (_source == "battery/ac") { + data["min"] = false; + data["max"] = true; + data["name"] = "Is AC online or not"; + data["type"] = "bool"; + data["units"] = ""; + } else if (_source == "battery/bat") { + data["min"] = 0; + data["max"] = 100; + data["name"] = "Average battery usage"; + data["type"] = "integer"; + data["units"] = "%"; } else { - data[QString("min")] = 0; - data[QString("max")] = 100; - data[QString("name")] = QString("Battery %1 usage").arg(index(source)); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("%"); + data["min"] = 0; + data["max"] = 100; + data["name"] = QString("Battery %1 usage").arg(index(_source)); + data["type"] = "integer"; + data["units"] = "%"; } return data; @@ -104,7 +104,7 @@ void BatterySource::run() // adaptor QFile acFile(QString("%1/AC/online").arg(m_acpiPath)); if (acFile.open(QIODevice::ReadOnly | QIODevice::Text)) - m_values[QString("battery/ac")] + m_values["battery/ac"] = (QString(acFile.readLine()).trimmed().toInt() == 1); acFile.close(); @@ -130,8 +130,7 @@ void BatterySource::run() currentLevelFile.close(); fullLevelFile.close(); } - m_values[QString("battery/bat")] - = static_cast(100 * currentLevel / fullLevel); + m_values["battery/bat"] = static_cast(100 * currentLevel / fullLevel); } diff --git a/sources/extsysmonsources/batterysource.h b/sources/extsysmonsources/batterysource.h index 52e4874..c914213 100644 --- a/sources/extsysmonsources/batterysource.h +++ b/sources/extsysmonsources/batterysource.h @@ -28,11 +28,11 @@ class BatterySource : public AbstractExtSysMonSource Q_OBJECT public: - explicit BatterySource(QObject *parent, const QStringList &args); + explicit BatterySource(QObject *_parent, const QStringList &_args); virtual ~BatterySource(); QStringList getSources(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(); QStringList sources() const; diff --git a/sources/extsysmonsources/customsource.cpp b/sources/extsysmonsources/customsource.cpp index 9ef1f60..07eb9a6 100644 --- a/sources/extsysmonsources/customsource.cpp +++ b/sources/extsysmonsources/customsource.cpp @@ -22,14 +22,13 @@ #include "extscript.h" -CustomSource::CustomSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +CustomSource::CustomSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_extScripts - = new ExtItemAggregator(nullptr, QString("scripts")); + m_extScripts = new ExtItemAggregator(nullptr, "scripts"); m_extScripts->initSockets(); m_sources = getSources(); } @@ -43,27 +42,30 @@ CustomSource::~CustomSource() } -QVariant CustomSource::data(const QString &source) +QVariant CustomSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; // there are only one value - return m_extScripts->itemByTagNumber(index(source))->run().values().first(); + return m_extScripts->itemByTagNumber(index(_source)) + ->run() + .values() + .first(); } -QVariantMap CustomSource::initialData(const QString &source) const +QVariantMap CustomSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Custom command '%1' output") - .arg(m_extScripts->itemByTagNumber(index(source))->uniq()); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + .arg(m_extScripts->itemByTagNumber(index(_source))->uniq()); + data["type"] = "QString"; + data["units"] = ""; return data; } @@ -79,7 +81,7 @@ QStringList CustomSource::getSources() { QStringList sources; for (auto &item : m_extScripts->activeItems()) - sources.append(QString("custom/%1").arg(item->tag(QString("custom")))); + sources.append(QString("custom/%1").arg(item->tag("custom"))); return sources; } diff --git a/sources/extsysmonsources/customsource.h b/sources/extsysmonsources/customsource.h index cf997f0..fb36c82 100644 --- a/sources/extsysmonsources/customsource.h +++ b/sources/extsysmonsources/customsource.h @@ -31,10 +31,10 @@ class CustomSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit CustomSource(QObject *parent, const QStringList &args); + explicit CustomSource(QObject *_parent, const QStringList &_args); virtual ~CustomSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; diff --git a/sources/extsysmonsources/desktopsource.cpp b/sources/extsysmonsources/desktopsource.cpp index 78237af..746e2bf 100644 --- a/sources/extsysmonsources/desktopsource.cpp +++ b/sources/extsysmonsources/desktopsource.cpp @@ -23,10 +23,10 @@ #include "awdebug.h" -DesktopSource::DesktopSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +DesktopSource::DesktopSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; } @@ -37,23 +37,23 @@ DesktopSource::~DesktopSource() } -QVariant DesktopSource::data(const QString &source) +QVariant DesktopSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; int current = KWindowSystem::currentDesktop(); int total = KWindowSystem::numberOfDesktops(); - if (source == QString("desktop/current/name")) { + if (_source == "desktop/current/name") { return KWindowSystem::desktopName(current); - } else if (source == QString("desktop/current/number")) { + } else if (_source == "desktop/current/number") { return current; - } else if (source == QString("desktop/total/name")) { + } else if (_source == "desktop/total/name") { QStringList desktops; for (int i = 1; i < total + 1; i++) desktops.append(KWindowSystem::desktopName(i)); return desktops; - } else if (source == QString("desktop/total/number")) { + } else if (_source == "desktop/total/number") { return total; } @@ -61,35 +61,35 @@ QVariant DesktopSource::data(const QString &source) } -QVariantMap DesktopSource::initialData(const QString &source) const +QVariantMap DesktopSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("desktop/current/name")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] = QString("Current desktop name"); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("desktop/current/number")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Current desktop number"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString(""); - } else if (source == QString("desktop/total/name")) { - data[QString("min")] = QStringList(); - data[QString("max")] = QStringList(); - data[QString("name")] = QString("All desktops by name"); - data[QString("type")] = QString("QStringList"); - data[QString("units")] = QString(""); - } else if (source == QString("desktop/total/number")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Desktops count"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString(""); + if (_source == "desktop/current/name") { + data["min"] = ""; + data["max"] = ""; + data["name"] = "Current desktop name"; + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "desktop/current/number") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Current desktop number"; + data["type"] = "integer"; + data["units"] = ""; + } else if (_source == "desktop/total/name") { + data["min"] = QStringList(); + data["max"] = QStringList(); + data["name"] = "All desktops by name"; + data["type"] = "QStringList"; + data["units"] = ""; + } else if (_source == "desktop/total/number") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Desktops count"; + data["type"] = "integer"; + data["units"] = ""; } return data; @@ -99,10 +99,10 @@ QVariantMap DesktopSource::initialData(const QString &source) const QStringList DesktopSource::sources() const { QStringList sources; - sources.append(QString("desktop/current/name")); - sources.append(QString("desktop/current/number")); - sources.append(QString("desktop/total/name")); - sources.append(QString("desktop/total/number")); + sources.append("desktop/current/name"); + sources.append("desktop/current/number"); + sources.append("desktop/total/name"); + sources.append("desktop/total/number"); return sources; } diff --git a/sources/extsysmonsources/desktopsource.h b/sources/extsysmonsources/desktopsource.h index 3935b26..2fab1e9 100644 --- a/sources/extsysmonsources/desktopsource.h +++ b/sources/extsysmonsources/desktopsource.h @@ -28,10 +28,10 @@ class DesktopSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit DesktopSource(QObject *parent, const QStringList &args); + explicit DesktopSource(QObject *_parent, const QStringList &_args); virtual ~DesktopSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; }; diff --git a/sources/extsysmonsources/gpuloadsource.cpp b/sources/extsysmonsources/gpuloadsource.cpp index 1354f8c..72840fa 100644 --- a/sources/extsysmonsources/gpuloadsource.cpp +++ b/sources/extsysmonsources/gpuloadsource.cpp @@ -25,13 +25,13 @@ #include "awdebug.h" -GPULoadSource::GPULoadSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +GPULoadSource::GPULoadSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 1); + Q_ASSERT(_args.count() == 1); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_device = args.at(0); + m_device = _args.at(0); m_process = new QProcess(nullptr); // fucking magic from http://doc.qt.io/qt-5/qprocess.html#finished @@ -54,8 +54,8 @@ GPULoadSource::~GPULoadSource() QString GPULoadSource::autoGpu() { - QString gpu = QString("disable"); - QFile moduleFile(QString("/proc/modules")); + QString gpu = "disable"; + QFile moduleFile("/proc/modules"); if (!moduleFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qCWarning(LOG_AW) << "Could not open file as text" << moduleFile.fileName(); @@ -64,38 +64,38 @@ QString GPULoadSource::autoGpu() QString output = moduleFile.readAll(); moduleFile.close(); - if (output.contains(QString("fglrx"))) - gpu = QString("ati"); - else if (output.contains(QString("nvidia"))) - gpu = QString("nvidia"); + if (output.contains("fglrx")) + gpu = "ati"; + else if (output.contains("nvidia")) + gpu = "nvidia"; qCInfo(LOG_ESM) << "Device" << gpu; return gpu; } -QVariant GPULoadSource::data(const QString &source) +QVariant GPULoadSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - if (source == QString("gpu/load")) + if (_source == "gpu/load") run(); - return m_values[source]; + return m_values[_source]; } -QVariantMap GPULoadSource::initialData(const QString &source) const +QVariantMap GPULoadSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("gpu/load")) { - data[QString("min")] = 0.0; - data[QString("max")] = 100.0; - data[QString("name")] = QString("GPU usage"); - data[QString("type")] = QString("float"); - data[QString("units")] = QString("%"); + if (_source == "gpu/load") { + data["min"] = 0.0; + data["max"] = 100.0; + data["name"] = "GPU usage"; + data["type"] = "float"; + data["units"] = "%"; } return data; @@ -104,12 +104,11 @@ QVariantMap GPULoadSource::initialData(const QString &source) const void GPULoadSource::run() { - if ((m_device != QString("nvidia")) && (m_device != QString("ati"))) + if ((m_device != "nvidia") && (m_device != "ati")) return; // build cmd - QString cmd = m_device == QString("nvidia") - ? QString("nvidia-smi -q -x") - : QString("aticonfig --od-getclocks"); + QString cmd = m_device == "nvidia" ? "nvidia-smi -q -x" + : "aticonfig --od-getclocks"; qCInfo(LOG_ESS) << "cmd" << cmd; m_process->start(cmd); @@ -119,7 +118,7 @@ void GPULoadSource::run() QStringList GPULoadSource::sources() const { QStringList sources; - sources.append(QString("gpu/load")); + sources.append("gpu/load"); return sources; } @@ -137,24 +136,22 @@ void GPULoadSource::updateValue() .trimmed(); qCInfo(LOG_ESS) << "Output" << qoutput; - if (m_device == QString("nvidia")) { - for (auto &str : qoutput.split(QChar('\n'), QString::SkipEmptyParts)) { - if (!str.contains(QString(""))) + if (m_device == "nvidia") { + for (auto &str : qoutput.split('\n', QString::SkipEmptyParts)) { + if (!str.contains("")) continue; - QString load = str.remove(QString("")) - .remove(QString("")) - .remove(QChar('%')); - m_values[QString("gpu/load")] = load.toFloat(); + auto load + = str.remove("").remove("").remove('%'); + m_values["gpu/load"] = load.toFloat(); break; } - } else if (m_device == QString("ati")) { - for (auto &str : qoutput.split(QChar('\n'), QString::SkipEmptyParts)) { - if (!str.contains(QString("load"))) + } else if (m_device == "ati") { + for (auto &str : qoutput.split('\n', QString::SkipEmptyParts)) { + if (!str.contains("load")) continue; QString load - = str.split(QChar(' '), QString::SkipEmptyParts)[3].remove( - QChar('%')); - m_values[QString("gpu/load")] = load.toFloat(); + = str.split(' ', QString::SkipEmptyParts)[3].remove('%'); + m_values["gpu/load"] = load.toFloat(); break; } } diff --git a/sources/extsysmonsources/gpuloadsource.h b/sources/extsysmonsources/gpuloadsource.h index bee30d2..9cced01 100644 --- a/sources/extsysmonsources/gpuloadsource.h +++ b/sources/extsysmonsources/gpuloadsource.h @@ -30,11 +30,11 @@ class GPULoadSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit GPULoadSource(QObject *parent, const QStringList &args); + explicit GPULoadSource(QObject *_parent, const QStringList &_args); virtual ~GPULoadSource(); static QString autoGpu(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(); QStringList sources() const; diff --git a/sources/extsysmonsources/gputempsource.cpp b/sources/extsysmonsources/gputempsource.cpp index bf2540b..1b6e401 100644 --- a/sources/extsysmonsources/gputempsource.cpp +++ b/sources/extsysmonsources/gputempsource.cpp @@ -25,14 +25,14 @@ #include "awdebug.h" -GPUTemperatureSource::GPUTemperatureSource(QObject *parent, - const QStringList &args) - : AbstractExtSysMonSource(parent, args) +GPUTemperatureSource::GPUTemperatureSource(QObject *_parent, + const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 1); + Q_ASSERT(_args.count() == 1); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_device = args.at(0); + m_device = _args.at(0); m_process = new QProcess(nullptr); // fucking magic from http://doc.qt.io/qt-5/qprocess.html#finished @@ -53,50 +53,28 @@ GPUTemperatureSource::~GPUTemperatureSource() } -QString GPUTemperatureSource::autoGpu() +QVariant GPUTemperatureSource::data(const QString &_source) { - QString gpu = QString("disable"); - QFile moduleFile(QString("/proc/modules")); - if (!moduleFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - qCWarning(LOG_AW) << "Could not open file as text" - << moduleFile.fileName(); - return gpu; - } + qCDebug(LOG_ESS) << "Source" << _source; - QString output = moduleFile.readAll(); - moduleFile.close(); - if (output.contains(QString("fglrx"))) - gpu = QString("ati"); - else if (output.contains(QString("nvidia"))) - gpu = QString("nvidia"); - - qCInfo(LOG_ESM) << "Device" << gpu; - return gpu; -} - - -QVariant GPUTemperatureSource::data(const QString &source) -{ - qCDebug(LOG_ESS) << "Source" << source; - - if (source == QString("gpu/temperature")) + if (_source == "gpu/temperature") run(); - return m_values[source]; + return m_values[_source]; } -QVariantMap GPUTemperatureSource::initialData(const QString &source) const +QVariantMap GPUTemperatureSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("gpu/temperature")) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] = QString("GPU temperature"); - data[QString("type")] = QString("float"); - data[QString("units")] = QString("°C"); + if (_source == "gpu/temperature") { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = "GPU temperature"; + data["type"] = "float"; + data["units"] = "°C"; } return data; @@ -105,12 +83,11 @@ QVariantMap GPUTemperatureSource::initialData(const QString &source) const void GPUTemperatureSource::run() { - if ((m_device != QString("nvidia")) && (m_device != QString("ati"))) + if ((m_device != "nvidia") && (m_device != "ati")) return; // build cmd - QString cmd = m_device == QString("nvidia") - ? QString("nvidia-smi -q -x") - : QString("aticonfig --od-gettemperature"); + QString cmd = m_device == "nvidia" ? "nvidia-smi -q -x" + : "aticonfig --od-gettemperature"; qCInfo(LOG_ESS) << "cmd" << cmd; m_process->start(cmd); @@ -120,7 +97,7 @@ void GPUTemperatureSource::run() QStringList GPUTemperatureSource::sources() const { QStringList sources; - sources.append(QString("gpu/temperature")); + sources.append("gpu/temperature"); return sources; } @@ -138,21 +115,20 @@ void GPUTemperatureSource::updateValue() .trimmed(); qCInfo(LOG_ESS) << "Output" << qoutput; - if (m_device == QString("nvidia")) { - for (auto &str : qoutput.split(QChar('\n'), QString::SkipEmptyParts)) { - if (!str.contains(QString(""))) + if (m_device == "nvidia") { + for (auto &str : qoutput.split('\n', QString::SkipEmptyParts)) { + if (!str.contains("")) continue; - QString temp = str.remove(QString("")) - .remove(QString("C")); - m_values[QString("gpu/temperature")] = temp.toFloat(); + QString temp = str.remove("").remove("C"); + m_values["gpu/temperature"] = temp.toFloat(); break; } - } else if (m_device == QString("ati")) { - for (auto &str : qoutput.split(QChar('\n'), QString::SkipEmptyParts)) { - if (!str.contains(QString("Temperature"))) + } else if (m_device == "ati") { + for (auto &str : qoutput.split('\n', QString::SkipEmptyParts)) { + if (!str.contains("Temperature")) continue; - QString temp = str.split(QChar(' '), QString::SkipEmptyParts).at(4); - m_values[QString("gpu/temperature")] = temp.toFloat(); + QString temp = str.split(' ', QString::SkipEmptyParts).at(4); + m_values["gpu/temperature"] = temp.toFloat(); break; } } diff --git a/sources/extsysmonsources/gputempsource.h b/sources/extsysmonsources/gputempsource.h index ae1b2c2..e570e32 100644 --- a/sources/extsysmonsources/gputempsource.h +++ b/sources/extsysmonsources/gputempsource.h @@ -30,11 +30,10 @@ class GPUTemperatureSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit GPUTemperatureSource(QObject *parent, const QStringList &args); + explicit GPUTemperatureSource(QObject *_parent, const QStringList &_args); virtual ~GPUTemperatureSource(); - static QString autoGpu(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(); QStringList sources() const; diff --git a/sources/extsysmonsources/hddtempsource.cpp b/sources/extsysmonsources/hddtempsource.cpp index aca5805..ef67deb 100644 --- a/sources/extsysmonsources/hddtempsource.cpp +++ b/sources/extsysmonsources/hddtempsource.cpp @@ -25,17 +25,17 @@ #include "awdebug.h" -HDDTemperatureSource::HDDTemperatureSource(QObject *parent, - const QStringList &args) - : AbstractExtSysMonSource(parent, args) +HDDTemperatureSource::HDDTemperatureSource(QObject *_parent, + const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 2); + Q_ASSERT(_args.count() == 2); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_devices = args.at(0).split(QChar(','), QString::SkipEmptyParts); - m_cmd = args.at(1); + m_devices = _args.at(0).split(',', QString::SkipEmptyParts); + m_cmd = _args.at(1); - m_smartctl = m_cmd.contains(QString("smartctl")); + m_smartctl = m_cmd.contains("smartctl"); qCInfo(LOG_ESS) << "Parse as smartctl" << m_smartctl; for (auto &device : m_devices) { @@ -65,9 +65,8 @@ HDDTemperatureSource::~HDDTemperatureSource() QStringList HDDTemperatureSource::allHdd() { - QStringList allDevices - = QDir(QString("/dev")).entryList(QDir::System, QDir::Name); - QStringList devices = allDevices.filter(QRegExp(QString("^[hms]d[a-z]$"))); + QStringList allDevices = QDir("/dev").entryList(QDir::System, QDir::Name); + QStringList devices = allDevices.filter(QRegExp("^[hms]d[a-z]$")); for (int i = 0; i < devices.count(); i++) devices[i] = QString("/dev/%1").arg(devices.at(i)); @@ -76,11 +75,11 @@ QStringList HDDTemperatureSource::allHdd() } -QVariant HDDTemperatureSource::data(const QString &source) +QVariant HDDTemperatureSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - QString device = source; + QString device = _source; device.remove("hdd/temperature"); // run cmd if (m_processes[device]->state() == QProcess::NotRunning) @@ -90,18 +89,18 @@ QVariant HDDTemperatureSource::data(const QString &source) } -QVariantMap HDDTemperatureSource::initialData(const QString &source) const +QVariantMap HDDTemperatureSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - QString device = source; + QString device = _source; device.remove("hdd/temperature"); QVariantMap data; - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] = QString("HDD '%1' temperature").arg(device); - data[QString("type")] = QString("float"); - data[QString("units")] = QString("°C"); + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("HDD '%1' temperature").arg(device); + data["type"] = "float"; + data["units"] = "°C"; return data; } @@ -117,41 +116,40 @@ QStringList HDDTemperatureSource::sources() const } -void HDDTemperatureSource::updateValue(const QString &device) +void HDDTemperatureSource::updateValue(const QString &_device) { - qCDebug(LOG_ESS) << "Called with device" << device; + qCDebug(LOG_ESS) << "Called with device" << _device; - qCInfo(LOG_ESS) << "Cmd returns" << m_processes[device]->exitCode(); + qCInfo(LOG_ESS) << "Cmd returns" << m_processes[_device]->exitCode(); QString qdebug = QTextCodec::codecForMib(106) - ->toUnicode(m_processes[device]->readAllStandardError()) + ->toUnicode(m_processes[_device]->readAllStandardError()) .trimmed(); qCInfo(LOG_ESS) << "Error" << qdebug; QString qoutput = QTextCodec::codecForMib(106) - ->toUnicode(m_processes[device]->readAllStandardOutput()) + ->toUnicode(m_processes[_device]->readAllStandardOutput()) .trimmed(); qCInfo(LOG_ESS) << "Output" << qoutput; // parse if (m_smartctl) { - QStringList lines = qoutput.split(QChar('\n'), QString::SkipEmptyParts); + QStringList lines = qoutput.split('\n', QString::SkipEmptyParts); for (auto &str : lines) { - if (!str.startsWith(QString("194"))) + if (!str.startsWith("194")) continue; - if (str.split(QChar(' '), QString::SkipEmptyParts).count() < 9) + if (str.split(' ', QString::SkipEmptyParts).count() < 9) continue; - m_values[device] = str.split(QChar(' '), QString::SkipEmptyParts) - .at(9) - .toFloat(); + m_values[_device] + = str.split(' ', QString::SkipEmptyParts).at(9).toFloat(); break; } } else { - QStringList lines = qoutput.split(QChar(':'), QString::SkipEmptyParts); + QStringList lines = qoutput.split(':', QString::SkipEmptyParts); if (lines.count() >= 3) { QString temp = lines.at(2); - temp.remove(QChar(0260)).remove(QChar('C')); - m_values[device] = temp.toFloat(); + temp.remove(QChar(0260)).remove('C'); + m_values[_device] = temp.toFloat(); } } diff --git a/sources/extsysmonsources/hddtempsource.h b/sources/extsysmonsources/hddtempsource.h index 82a5ac3..6116c12 100644 --- a/sources/extsysmonsources/hddtempsource.h +++ b/sources/extsysmonsources/hddtempsource.h @@ -30,16 +30,16 @@ class HDDTemperatureSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit HDDTemperatureSource(QObject *parent, const QStringList &args); + explicit HDDTemperatureSource(QObject *_parent, const QStringList &_args); virtual ~HDDTemperatureSource(); static QStringList allHdd(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; private slots: - void updateValue(const QString &device); + void updateValue(const QString &_device); private: // properties diff --git a/sources/extsysmonsources/loadsource.cpp b/sources/extsysmonsources/loadsource.cpp index 31fdedc..49547ef 100644 --- a/sources/extsysmonsources/loadsource.cpp +++ b/sources/extsysmonsources/loadsource.cpp @@ -18,14 +18,18 @@ #include "loadsource.h" +#include + #include "awdebug.h" -LoadSource::LoadSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +LoadSource::LoadSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; + + qsrand(static_cast(QTime::currentTime().msec())); } @@ -35,27 +39,25 @@ LoadSource::~LoadSource() } -QVariant LoadSource::data(const QString &source) +QVariant LoadSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - auto data = source; - data.remove("load/load"); - return data.toInt(); + return qrand(); } -QVariantMap LoadSource::initialData(const QString &source) const +QVariantMap LoadSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source.startsWith(QString("load/load"))) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Simple sources for load tests"); - data[QString("type")] = QString("int"); - data[QString("units")] = QString(""); + if (_source.startsWith("load/load")) { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Simple sources for load tests"; + data["type"] = "int"; + data["units"] = ""; } return data; diff --git a/sources/extsysmonsources/loadsource.h b/sources/extsysmonsources/loadsource.h index 6cea0ab..a0990a9 100644 --- a/sources/extsysmonsources/loadsource.h +++ b/sources/extsysmonsources/loadsource.h @@ -28,10 +28,10 @@ class LoadSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit LoadSource(QObject *parent, const QStringList &args); + explicit LoadSource(QObject *_parent, const QStringList &_args); virtual ~LoadSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; }; diff --git a/sources/extsysmonsources/networksource.cpp b/sources/extsysmonsources/networksource.cpp index f284899..754b14a 100644 --- a/sources/extsysmonsources/networksource.cpp +++ b/sources/extsysmonsources/networksource.cpp @@ -23,10 +23,10 @@ #include "awdebug.h" -NetworkSource::NetworkSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +NetworkSource::NetworkSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; } @@ -37,12 +37,12 @@ NetworkSource::~NetworkSource() } -QVariant NetworkSource::data(const QString &source) +QVariant NetworkSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - if (source == QString("network/current/name")) { - QString device = QString("lo"); + if (_source == "network/current/name") { + QString device = "lo"; QList rawInterfaceList = QNetworkInterface::allInterfaces(); qCInfo(LOG_ESS) << "Devices" << rawInterfaceList; @@ -63,17 +63,17 @@ QVariant NetworkSource::data(const QString &source) } -QVariantMap NetworkSource::initialData(const QString &source) const +QVariantMap NetworkSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("network/current/name")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] = QString("Current network device name"); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + if (_source == "network/current/name") { + data["min"] = ""; + data["max"] = ""; + data["name"] = "Current network device name"; + data["type"] = "QString"; + data["units"] = ""; } return data; @@ -83,7 +83,7 @@ QVariantMap NetworkSource::initialData(const QString &source) const QStringList NetworkSource::sources() const { QStringList sources; - sources.append(QString("network/current/name")); + sources.append("network/current/name"); return sources; } diff --git a/sources/extsysmonsources/networksource.h b/sources/extsysmonsources/networksource.h index 8a4d199..1041605 100644 --- a/sources/extsysmonsources/networksource.h +++ b/sources/extsysmonsources/networksource.h @@ -28,10 +28,10 @@ class NetworkSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit NetworkSource(QObject *parent, const QStringList &args); + explicit NetworkSource(QObject *_parent, const QStringList &_args); virtual ~NetworkSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; }; diff --git a/sources/extsysmonsources/playersource.cpp b/sources/extsysmonsources/playersource.cpp index 2d85e2a..b8a0ec1 100644 --- a/sources/extsysmonsources/playersource.cpp +++ b/sources/extsysmonsources/playersource.cpp @@ -28,17 +28,17 @@ #include "awdebug.h" -PlayerSource::PlayerSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +PlayerSource::PlayerSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 5); + Q_ASSERT(_args.count() == 5); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_player = args.at(0); - m_mpdAddress = args.at(1); - m_mpdPort = args.at(2).toInt(); - m_mpris = args.at(3); - m_symbols = args.at(4).toInt(); + m_player = _args.at(0); + m_mpdAddress = _args.at(1); + m_mpdPort = _args.at(2).toInt(); + m_mpris = _args.at(3); + m_symbols = _args.at(4).toInt(); connect(&m_mpdSocket, SIGNAL(connected()), this, SLOT(mpdSocketConnected())); @@ -58,13 +58,13 @@ PlayerSource::~PlayerSource() } -QVariant PlayerSource::data(const QString &source) +QVariant PlayerSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - if (!m_values.contains(source)) + if (!m_values.contains(_source)) run(); - QVariant value = m_values.take(source); + QVariant value = m_values.take(_source); return value; } @@ -72,104 +72,101 @@ QVariant PlayerSource::data(const QString &source) QString PlayerSource::getAutoMpris() const { QDBusMessage listServices = QDBusConnection::sessionBus().interface()->call( - QDBus::BlockWithGui, QString("ListNames")); + QDBus::BlockWithGui, "ListNames"); if (listServices.arguments().isEmpty()) - return QString(); + return ""; QStringList arguments = listServices.arguments().first().toStringList(); for (auto &arg : arguments) { - if (!arg.startsWith(QString("org.mpris.MediaPlayer2."))) + if (!arg.startsWith("org.mpris.MediaPlayer2.")) continue; qCInfo(LOG_ESS) << "Service found" << arg; QString service = arg; - service.remove(QString("org.mpris.MediaPlayer2.")); + service.remove("org.mpris.MediaPlayer2."); return service; } - return QString(); + return ""; } -QVariantMap PlayerSource::initialData(const QString &source) const +QVariantMap PlayerSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("player/album")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] = QString("Current song album"); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/salbum")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] + if (_source == "player/album") { + data["min"] = ""; + data["max"] = ""; + data["name"] = "Current song album"; + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/salbum") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song album (%1 symbols)").arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/dalbum")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("Current song album (%1 symbols, dynamic)") - .arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/artist")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] = QString("Current song artist"); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/sartist")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/dalbum") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song album (%1 symbols, dynamic)") + .arg(m_symbols); + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/artist") { + data["min"] = ""; + data["max"] = ""; + data["name"] = "Current song artist"; + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/sartist") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song artist (%1 symbols)").arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/dartist")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("Current song artist (%1 symbols, dynamic)") - .arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/duration")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Current song duration"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("s"); - } else if (source == QString("player/progress")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Current song progress"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("s"); - } else if (source == QString("player/title")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] = QString("Current song title"); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/stitle")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/dartist") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song artist (%1 symbols, dynamic)") + .arg(m_symbols); + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/duration") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Current song duration"; + data["type"] = "integer"; + data["units"] = "s"; + } else if (_source == "player/progress") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Current song progress"; + data["type"] = "integer"; + data["units"] = "s"; + } else if (_source == "player/title") { + data["min"] = ""; + data["max"] = ""; + data["name"] = "Current song title"; + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/stitle") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song title (%1 symbols)").arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source == QString("player/dtitle")) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("Current song title (%1 symbols, dynamic)") - .arg(m_symbols); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + data["type"] = "QString"; + data["units"] = ""; + } else if (_source == "player/dtitle") { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Current song title (%1 symbols, dynamic)") + .arg(m_symbols); + data["type"] = "QString"; + data["units"] = ""; } return data; @@ -179,14 +176,13 @@ QVariantMap PlayerSource::initialData(const QString &source) const void PlayerSource::run() { // initial data - if (m_player == QString("mpd")) { + if (m_player == "mpd") { // mpd m_values = getPlayerMpdInfo(); - } else if (m_player == QString("mpris")) { + } else if (m_player == "mpris") { // players which supports mpris if (m_dbusMutex.tryLock()) { - QString mpris - = m_mpris == QString("auto") ? getAutoMpris() : m_mpris; + QString mpris = m_mpris == "auto" ? getAutoMpris() : m_mpris; m_values = getPlayerMprisInfo(mpris); m_dbusMutex.unlock(); } @@ -194,64 +190,65 @@ void PlayerSource::run() // dymanic properties // solid - m_values[QString("player/salbum")] - = stripString(m_values[QString("player/album")].toString(), m_symbols); - m_values[QString("player/sartist")] - = stripString(m_values[QString("player/artist")].toString(), m_symbols); - m_values[QString("player/stitle")] - = stripString(m_values[QString("player/title")].toString(), m_symbols); + m_values["player/salbum"] + = stripString(m_values["player/album"].toString(), m_symbols); + m_values["player/sartist"] + = stripString(m_values["player/artist"].toString(), m_symbols); + m_values["player/stitle"] + = stripString(m_values["player/title"].toString(), m_symbols); // dynamic - m_values[QString("player/dalbum")] - = buildString(m_values[QString("player/dalbum")].toString(), - m_values[QString("player/album")].toString(), m_symbols); - m_values[QString("player/dartist")] - = buildString(m_values[QString("player/dartist")].toString(), - m_values[QString("player/artist")].toString(), m_symbols); - m_values[QString("player/dtitle")] - = buildString(m_values[QString("player/dtitle")].toString(), - m_values[QString("player/title")].toString(), m_symbols); + m_values["player/dalbum"] + = buildString(m_values["player/dalbum"].toString(), + m_values["player/album"].toString(), m_symbols); + m_values["player/dartist"] + = buildString(m_values["player/dartist"].toString(), + m_values["player/artist"].toString(), m_symbols); + m_values["player/dtitle"] + = buildString(m_values["player/dtitle"].toString(), + m_values["player/title"].toString(), m_symbols); } QStringList PlayerSource::sources() const { QStringList sources; - sources.append(QString("player/album")); - sources.append(QString("player/dalbum")); - sources.append(QString("player/salbum")); - sources.append(QString("player/artist")); - sources.append(QString("player/dartist")); - sources.append(QString("player/sartist")); - sources.append(QString("player/duration")); - sources.append(QString("player/progress")); - sources.append(QString("player/title")); - sources.append(QString("player/dtitle")); - sources.append(QString("player/stitle")); + sources.append("player/album"); + sources.append("player/dalbum"); + sources.append("player/salbum"); + sources.append("player/artist"); + sources.append("player/dartist"); + sources.append("player/sartist"); + sources.append("player/duration"); + sources.append("player/progress"); + sources.append("player/title"); + sources.append("player/dtitle"); + sources.append("player/stitle"); return sources; } -QString PlayerSource::buildString(const QString ¤t, const QString &value, - const int s) +QString PlayerSource::buildString(const QString &_current, + const QString &_value, const int _s) { - qCDebug(LOG_ESS) << "Current value" << current << "received" << value - << "will be stripped after" << s; + qCDebug(LOG_ESS) << "Current value" << _current << "received" << _value + << "will be stripped after" << _s; - int index = value.indexOf(current); - if ((current.isEmpty()) || ((index + s + 1) > value.count())) - return QString("%1").arg(value.left(s), -s, QLatin1Char(' ')); + int index = _value.indexOf(_current); + if ((_current.isEmpty()) || ((index + _s + 1) > _value.count())) + return QString("%1").arg(_value.left(_s), -_s, QLatin1Char(' ')); else - return QString("%1").arg(value.mid(index + 1, s), -s, QLatin1Char(' ')); + return QString("%1").arg(_value.mid(index + 1, _s), -_s, + QLatin1Char(' ')); } -QString PlayerSource::stripString(const QString &value, const int s) +QString PlayerSource::stripString(const QString &_value, const int _s) { - qCDebug(LOG_ESS) << "New value" << value << "will be stripped after" << s; + qCDebug(LOG_ESS) << "New value" << _value << "will be stripped after" << _s; - return value.count() > s ? QString("%1\u2026").arg(value.left(s - 1)) - : value.leftJustified(s, QLatin1Char(' ')); + return _value.count() > _s ? QString("%1\u2026").arg(_value.left(_s - 1)) + : _value.leftJustified(_s, QLatin1Char(' ')); } @@ -276,20 +273,18 @@ void PlayerSource::mpdSocketReadyRead() qCInfo(LOG_ESS) << "Output" << qoutput; // parse - for (auto &str : qoutput.split(QChar('\n'), QString::SkipEmptyParts)) { - if (str.split(QString(": "), QString::SkipEmptyParts).count() == 2) { + for (auto &str : qoutput.split('\n', QString::SkipEmptyParts)) { + if (str.split(": ", QString::SkipEmptyParts).count() == 2) { // "Metadata: data" - QString metadata = str.split(QString(": "), QString::SkipEmptyParts) - .first() - .toLower(); - QString data = str.split(QString(": "), QString::SkipEmptyParts) - .last() - .trimmed(); + QString metadata + = str.split(": ", QString::SkipEmptyParts).first().toLower(); + QString data + = str.split(": ", QString::SkipEmptyParts).last().trimmed(); // there are one more time... - if ((metadata == QString("time")) && (data.contains(QChar(':')))) { - QStringList times = data.split(QString(":")); - m_mpdCached[QString("player/duration")] = times.at(0).toInt(); - m_mpdCached[QString("player/progress")] = times.at(1).toInt(); + if ((metadata == "time") && (data.contains(':'))) { + QStringList times = data.split(':'); + m_mpdCached["player/duration"] = times.at(0).toInt(); + m_mpdCached["player/progress"] = times.at(1).toInt(); } else if (m_metadata.contains(metadata)) { m_mpdCached[QString("player/%1").arg(metadata)] = data; } @@ -300,9 +295,9 @@ void PlayerSource::mpdSocketReadyRead() } -void PlayerSource::mpdSocketWritten(const qint64 bytes) +void PlayerSource::mpdSocketWritten(const qint64 _bytes) { - qCDebug(LOG_ESS) << "Bytes written" << bytes << "to" + qCDebug(LOG_ESS) << "Bytes written" << _bytes << "to" << m_mpdSocket.peerName(); } @@ -310,11 +305,11 @@ void PlayerSource::mpdSocketWritten(const qint64 bytes) QVariantHash PlayerSource::defaultInfo() const { QVariantHash info; - info[QString("player/album")] = QString("unknown"); - info[QString("player/artist")] = QString("unknown"); - info[QString("player/duration")] = 0; - info[QString("player/progress")] = 0; - info[QString("player/title")] = QString("unknown"); + info["player/album"] = "unknown"; + info["player/artist"] = "unknown"; + info["player/duration"] = 0; + info["player/progress"] = 0; + info["player/title"] = "unknown"; return info; } @@ -337,12 +332,12 @@ QVariantHash PlayerSource::getPlayerMpdInfo() } -QVariantHash PlayerSource::getPlayerMprisInfo(const QString &mpris) const +QVariantHash PlayerSource::getPlayerMprisInfo(const QString &_mpris) const { - qCDebug(LOG_ESS) << "MPRIS" << mpris; + qCDebug(LOG_ESS) << "MPRIS" << _mpris; QVariantHash info = defaultInfo(); - if (mpris.isEmpty()) + if (_mpris.isEmpty()) return info; QDBusConnection bus = QDBusConnection::sessionBus(); @@ -354,12 +349,11 @@ QVariantHash PlayerSource::getPlayerMprisInfo(const QString &mpris) const // dbus-send --print-reply --session --dest=org.mpris.MediaPlayer2.vlc // /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get // string:'org.mpris.MediaPlayer2.Player' string:'Metadata' - QVariantList args = QVariantList() - << QString("org.mpris.MediaPlayer2.Player") - << QString("Metadata"); + QVariantList args + = QVariantList({"org.mpris.MediaPlayer2.Player", "Metadata"}); QDBusMessage request = QDBusMessage::createMethodCall( - QString("org.mpris.MediaPlayer2.%1").arg(mpris), - QString("/org/mpris/MediaPlayer2"), QString(""), QString("Get")); + QString("org.mpris.MediaPlayer2.%1").arg(_mpris), + "/org/mpris/MediaPlayer2", "", "Get"); request.setArguments(args); QDBusMessage response = bus.call(request, QDBus::BlockWithGui, REQUEST_TIMEOUT); @@ -374,19 +368,16 @@ QVariantHash PlayerSource::getPlayerMprisInfo(const QString &mpris) const .value() .variant() .value()); - info[QString("player/album")] - = map.value(QString("xesam:album"), QString("unknown")); + info["player/album"] = map.value("xesam:album", "unknown"); // artist is array - info[QString("player/artist")] - = map.value(QString("xesam:artist"), QString("unknown")).toString(); - info[QString("player/duration")] - = map.value(QString("mpris:length"), 0).toInt() / (1000 * 1000); - info[QString("player/title")] - = map.value(QString("xesam:title"), QString("unknown")); + info["player/artist"] = map.value("xesam:artist", "unknown").toString(); + info["player/duration"] + = map.value("mpris:length", 0).toInt() / (1000 * 1000); + info["player/title"] = map.value("xesam:title", "unknown"); } // position - args[1] = QString("Position"); + args[1] = "Position"; request.setArguments(args); response = bus.call(request, QDBus::BlockWithGui); if ((response.type() != QDBusMessage::ReplyMessage) @@ -394,12 +385,12 @@ QVariantHash PlayerSource::getPlayerMprisInfo(const QString &mpris) const qCWarning(LOG_ESS) << "Error message" << response.errorMessage(); } else { // this cast is simpler than the previous one ;) - info[QString("player/progress")] = response.arguments() - .first() - .value() - .variant() - .toLongLong() - / (1000 * 1000); + info["player/progress"] = response.arguments() + .first() + .value() + .variant() + .toLongLong() + / (1000 * 1000); } return info; diff --git a/sources/extsysmonsources/playersource.h b/sources/extsysmonsources/playersource.h index 70a7cb0..84ed556 100644 --- a/sources/extsysmonsources/playersource.h +++ b/sources/extsysmonsources/playersource.h @@ -34,29 +34,29 @@ class PlayerSource : public AbstractExtSysMonSource public: const char *MPD_STATUS_REQUEST = "currentsong\nstatus\n"; - explicit PlayerSource(QObject *parent, const QStringList &args); + explicit PlayerSource(QObject *_parent, const QStringList &_args); virtual ~PlayerSource(); - QVariant data(const QString &source); + QVariant data(const QString &_source); QString getAutoMpris() const; - QVariantMap initialData(const QString &source) const; + QVariantMap initialData(const QString &_source) const; void run(); QStringList sources() const; // additional method to build dynamic tags - static QString buildString(const QString ¤t, const QString &value, - const int s); - static QString stripString(const QString &value, const int s); + static QString buildString(const QString &_current, const QString &_value, + const int _s); + static QString stripString(const QString &_value, const int _s); // additional test method bool isMpdSocketConnected() const; private slots: void mpdSocketConnected(); void mpdSocketReadyRead(); - void mpdSocketWritten(const qint64 bytes); + void mpdSocketWritten(const qint64 _bytes); private: inline QVariantHash defaultInfo() const; QVariantHash getPlayerMpdInfo(); - QVariantHash getPlayerMprisInfo(const QString &mpris) const; + QVariantHash getPlayerMprisInfo(const QString &_mpris) const; QTcpSocket m_mpdSocket; // configuration and values QString m_mpdAddress; @@ -66,9 +66,7 @@ private: QMutex m_dbusMutex; QString m_player; int m_symbols; - QStringList m_metadata = QStringList() - << QString("album") << QString("artist") - << QString("title"); + QStringList m_metadata = QStringList({"album", "artist", "title"}); QVariantHash m_values; }; diff --git a/sources/extsysmonsources/processessource.cpp b/sources/extsysmonsources/processessource.cpp index 59bb2ef..20c868e 100644 --- a/sources/extsysmonsources/processessource.cpp +++ b/sources/extsysmonsources/processessource.cpp @@ -23,10 +23,10 @@ #include "awdebug.h" -ProcessesSource::ProcessesSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +ProcessesSource::ProcessesSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; } @@ -37,40 +37,40 @@ ProcessesSource::~ProcessesSource() } -QVariant ProcessesSource::data(const QString &source) +QVariant ProcessesSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - if (!m_values.contains(source)) + if (!m_values.contains(_source)) run(); - QVariant value = m_values.take(source); + QVariant value = m_values.take(_source); return value; } -QVariantMap ProcessesSource::initialData(const QString &source) const +QVariantMap ProcessesSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - if (source == QString("ps/running/count")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Count of running processes"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString(""); - } else if (source == QString("ps/running/list")) { - data[QString("min")] = QStringList(); - data[QString("max")] = QStringList(); - data[QString("name")] = QString("All running processes list"); - data[QString("type")] = QString("QStringList"); - data[QString("units")] = QString(""); - } else if (source == QString("ps/total/count")) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] = QString("Total count of processes"); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString(""); + if (_source == "ps/running/count") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Count of running processes"; + data["type"] = "integer"; + data["units"] = ""; + } else if (_source == "ps/running/list") { + data["min"] = QStringList(); + data["max"] = QStringList(); + data["name"] = "All running processes list"; + data["type"] = "QStringList"; + data["units"] = ""; + } else if (_source == "ps/total/count") { + data["min"] = 0; + data["max"] = 0; + data["name"] = "Total count of processes"; + data["type"] = "integer"; + data["units"] = ""; } return data; @@ -79,10 +79,9 @@ QVariantMap ProcessesSource::initialData(const QString &source) const void ProcessesSource::run() { - QStringList allDirectories - = QDir(QString("/proc")) - .entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); - QStringList directories = allDirectories.filter(QRegExp(QString("(\\d+)"))); + QStringList allDirectories = QDir("/proc").entryList( + QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); + QStringList directories = allDirectories.filter(QRegExp("(\\d+)")); QStringList running; for (auto &dir : directories) { @@ -94,24 +93,24 @@ void ProcessesSource::run() continue; QString output = statusFile.readAll(); - if (output.contains(QString("running"))) + if (output.contains("running")) running.append(cmdFile.readAll()); statusFile.close(); cmdFile.close(); } - m_values[QString("ps/running/count")] = running.count(); - m_values[QString("ps/running/list")] = running; - m_values[QString("ps/total/count")] = directories.count(); + m_values["ps/running/count"] = running.count(); + m_values["ps/running/list"] = running; + m_values["ps/total/count"] = directories.count(); } QStringList ProcessesSource::sources() const { QStringList sources; - sources.append(QString("ps/running/count")); - sources.append(QString("ps/running/list")); - sources.append(QString("ps/total/count")); + sources.append("ps/running/count"); + sources.append("ps/running/list"); + sources.append("ps/total/count"); return sources; } diff --git a/sources/extsysmonsources/processessource.h b/sources/extsysmonsources/processessource.h index 63fad65..3193cab 100644 --- a/sources/extsysmonsources/processessource.h +++ b/sources/extsysmonsources/processessource.h @@ -28,10 +28,10 @@ class ProcessesSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit ProcessesSource(QObject *parent, const QStringList &args); + explicit ProcessesSource(QObject *_parent, const QStringList &_args); virtual ~ProcessesSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(); QStringList sources() const; diff --git a/sources/extsysmonsources/quotessource.cpp b/sources/extsysmonsources/quotessource.cpp index 6bb193c..f759c36 100644 --- a/sources/extsysmonsources/quotessource.cpp +++ b/sources/extsysmonsources/quotessource.cpp @@ -22,13 +22,13 @@ #include "extquotes.h" -QuotesSource::QuotesSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +QuotesSource::QuotesSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_extQuotes = new ExtItemAggregator(nullptr, QString("quotes")); + m_extQuotes = new ExtItemAggregator(nullptr, "quotes"); m_extQuotes->initSockets(); m_sources = getSources(); } @@ -42,13 +42,13 @@ QuotesSource::~QuotesSource() } -QVariant QuotesSource::data(const QString &source) +QVariant QuotesSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); - auto service = source; - service.remove(QString("quotes/")); + int ind = index(_source); + auto service = _source; + service.remove("quotes/"); if (!m_values.contains(service)) { QVariantHash data = m_extQuotes->itemByTagNumber(ind)->run(); for (auto &key : data.keys()) @@ -59,84 +59,75 @@ QVariant QuotesSource::data(const QString &source) } -QVariantMap QuotesSource::initialData(const QString &source) const +QVariantMap QuotesSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); + int ind = index(_source); QVariantMap data; - if (source.startsWith(QString("quotes/askchg"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Absolute ask changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/ask"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Ask for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/percaskchg"))) { - data[QString("min")] = -100.0; - data[QString("max")] = 100.0; - data[QString("name")] - = QString("Ask changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/bidchg"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Absolute bid changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/bid"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Bid for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/percbidchg"))) { - data[QString("min")] = -100.0; - data[QString("max")] = 100.0; - data[QString("name")] - = QString("Bid changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/pricechg"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Absolute prie changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/price"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Price for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("quotes/percpricechg"))) { - data[QString("min")] = -100.0; - data[QString("max")] = 100.0; - data[QString("name")] - = QString("Price changes for '%1'") - .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("double"); - data[QString("units")] = QString(""); + if (_source.startsWith("quotes/askchg")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Absolute ask changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/ask")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Ask for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/percaskchg")) { + data["min"] = -100.0; + data["max"] = 100.0; + data["name"] = QString("Ask changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/bidchg")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Absolute bid changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/bid")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Bid for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/percbidchg")) { + data["min"] = -100.0; + data["max"] = 100.0; + data["name"] = QString("Bid changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/pricechg")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Absolute prie changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/price")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Price for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; + } else if (_source.startsWith("quotes/percpricechg")) { + data["min"] = -100.0; + data["max"] = 100.0; + data["name"] = QString("Price changes for '%1'") + .arg(m_extQuotes->itemByTagNumber(ind)->uniq()); + data["type"] = "double"; + data["units"] = ""; } return data; @@ -153,19 +144,15 @@ QStringList QuotesSource::getSources() { QStringList sources; for (auto &item : m_extQuotes->activeItems()) { - sources.append(QString("quotes/%1").arg(item->tag(QString("ask")))); - sources.append(QString("quotes/%1").arg(item->tag(QString("askchg")))); - sources.append( - QString("quotes/%1").arg(item->tag(QString("percaskchg")))); - sources.append(QString("quotes/%1").arg(item->tag(QString("bid")))); - sources.append(QString("quotes/%1").arg(item->tag(QString("bidchg")))); - sources.append( - QString("quotes/%1").arg(item->tag(QString("percbidchg")))); - sources.append(QString("quotes/%1").arg(item->tag(QString("price")))); - sources.append( - QString("quotes/%1").arg(item->tag(QString("pricechg")))); - sources.append( - QString("quotes/%1").arg(item->tag(QString("percpricechg")))); + sources.append(QString("quotes/%1").arg(item->tag("ask"))); + sources.append(QString("quotes/%1").arg(item->tag("askchg"))); + sources.append(QString("quotes/%1").arg(item->tag("percaskchg"))); + sources.append(QString("quotes/%1").arg(item->tag("bid"))); + sources.append(QString("quotes/%1").arg(item->tag("bidchg"))); + sources.append(QString("quotes/%1").arg(item->tag("percbidchg"))); + sources.append(QString("quotes/%1").arg(item->tag("price"))); + sources.append(QString("quotes/%1").arg(item->tag("pricechg"))); + sources.append(QString("quotes/%1").arg(item->tag("percpricechg"))); } return sources; diff --git a/sources/extsysmonsources/quotessource.h b/sources/extsysmonsources/quotessource.h index f32df8a..ad250b1 100644 --- a/sources/extsysmonsources/quotessource.h +++ b/sources/extsysmonsources/quotessource.h @@ -31,10 +31,10 @@ class QuotesSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit QuotesSource(QObject *parent, const QStringList &args); + explicit QuotesSource(QObject *_parent, const QStringList &_args); virtual ~QuotesSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; diff --git a/sources/extsysmonsources/requestsource.cpp b/sources/extsysmonsources/requestsource.cpp index 252a006..e72cfaf 100644 --- a/sources/extsysmonsources/requestsource.cpp +++ b/sources/extsysmonsources/requestsource.cpp @@ -22,14 +22,14 @@ #include "extnetworkrequest.h" -RequestSource::RequestSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +RequestSource::RequestSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_extNetRequest = new ExtItemAggregator( - nullptr, QString("requests")); + m_extNetRequest + = new ExtItemAggregator(nullptr, "requests"); m_extNetRequest->initSockets(); m_sources = getSources(); } @@ -43,12 +43,12 @@ RequestSource::~RequestSource() } -QVariant RequestSource::data(const QString &source) +QVariant RequestSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); - auto service = source; + int ind = index(_source); + auto service = _source; service.remove("network/"); if (!m_values.contains(service)) { QVariantHash data = m_extNetRequest->itemByTagNumber(ind)->run(); @@ -60,20 +60,19 @@ QVariant RequestSource::data(const QString &source) } -QVariantMap RequestSource::initialData(const QString &source) const +QVariantMap RequestSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); + int ind = index(_source); QVariantMap data; - if (source.startsWith(QString("network/response"))) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("Network response for %1") - .arg(m_extNetRequest->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + if (_source.startsWith("network/response")) { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Network response for %1") + .arg(m_extNetRequest->itemByTagNumber(ind)->uniq()); + data["type"] = "QString"; + data["units"] = ""; } return data; @@ -90,8 +89,7 @@ QStringList RequestSource::getSources() { QStringList sources; for (auto &item : m_extNetRequest->activeItems()) - sources.append( - QString("network/%1").arg(item->tag(QString("response")))); + sources.append(QString("network/%1").arg(item->tag("response"))); return sources; } diff --git a/sources/extsysmonsources/requestsource.h b/sources/extsysmonsources/requestsource.h index 2448728..dd87ec0 100644 --- a/sources/extsysmonsources/requestsource.h +++ b/sources/extsysmonsources/requestsource.h @@ -31,10 +31,10 @@ class RequestSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit RequestSource(QObject *parent, const QStringList &args); + explicit RequestSource(QObject *_parent, const QStringList &_args); virtual ~RequestSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; diff --git a/sources/extsysmonsources/upgradesource.cpp b/sources/extsysmonsources/upgradesource.cpp index c438e03..62dd975 100644 --- a/sources/extsysmonsources/upgradesource.cpp +++ b/sources/extsysmonsources/upgradesource.cpp @@ -22,14 +22,13 @@ #include "extupgrade.h" -UpgradeSource::UpgradeSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +UpgradeSource::UpgradeSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_extUpgrade - = new ExtItemAggregator(nullptr, QString("upgrade")); + m_extUpgrade = new ExtItemAggregator(nullptr, "upgrade"); m_extUpgrade->initSockets(); m_sources = getSources(); } @@ -43,27 +42,30 @@ UpgradeSource::~UpgradeSource() } -QVariant UpgradeSource::data(const QString &source) +QVariant UpgradeSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; // there are only one value - return m_extUpgrade->itemByTagNumber(index(source))->run().values().first(); + return m_extUpgrade->itemByTagNumber(index(_source)) + ->run() + .values() + .first(); } -QVariantMap UpgradeSource::initialData(const QString &source) const +QVariantMap UpgradeSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; QVariantMap data; - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Package manager '%1' metadata") - .arg(m_extUpgrade->itemByTagNumber(index(source))->uniq()); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + .arg(m_extUpgrade->itemByTagNumber(index(_source))->uniq()); + data["type"] = "QString"; + data["units"] = ""; return data; } @@ -79,8 +81,7 @@ QStringList UpgradeSource::getSources() { QStringList sources; for (auto &item : m_extUpgrade->activeItems()) - sources.append( - QString("upgrade/%1").arg(item->tag(QString("pkgcount")))); + sources.append(QString("upgrade/%1").arg(item->tag("pkgcount"))); return sources; } diff --git a/sources/extsysmonsources/upgradesource.h b/sources/extsysmonsources/upgradesource.h index ffdb959..99510ed 100644 --- a/sources/extsysmonsources/upgradesource.h +++ b/sources/extsysmonsources/upgradesource.h @@ -31,10 +31,10 @@ class UpgradeSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit UpgradeSource(QObject *parent, const QStringList &args); + explicit UpgradeSource(QObject *_parent, const QStringList &_args); virtual ~UpgradeSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; diff --git a/sources/extsysmonsources/weathersource.cpp b/sources/extsysmonsources/weathersource.cpp index 445deea..89ac0aa 100644 --- a/sources/extsysmonsources/weathersource.cpp +++ b/sources/extsysmonsources/weathersource.cpp @@ -22,14 +22,13 @@ #include "extweather.h" -WeatherSource::WeatherSource(QObject *parent, const QStringList &args) - : AbstractExtSysMonSource(parent, args) +WeatherSource::WeatherSource(QObject *_parent, const QStringList &_args) + : AbstractExtSysMonSource(_parent, _args) { - Q_ASSERT(args.count() == 0); + Q_ASSERT(_args.count() == 0); qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; - m_extWeather - = new ExtItemAggregator(nullptr, QString("weather")); + m_extWeather = new ExtItemAggregator(nullptr, "weather"); m_extWeather->initSockets(); m_sources = getSources(); } @@ -43,12 +42,12 @@ WeatherSource::~WeatherSource() } -QVariant WeatherSource::data(const QString &source) +QVariant WeatherSource::data(const QString &_source) { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); - auto service = source; + int ind = index(_source); + auto service = _source; service.remove("weather/"); if (!m_values.contains(service)) { QVariantHash data = m_extWeather->itemByTagNumber(ind)->run(); @@ -60,60 +59,54 @@ QVariant WeatherSource::data(const QString &source) } -QVariantMap WeatherSource::initialData(const QString &source) const +QVariantMap WeatherSource::initialData(const QString &_source) const { - qCDebug(LOG_ESS) << "Source" << source; + qCDebug(LOG_ESS) << "Source" << _source; - int ind = index(source); + int ind = index(_source); QVariantMap data; - if (source.startsWith(QString("weather/weatherId"))) { - data[QString("min")] = 0; - data[QString("max")] = 1000; - data[QString("name")] - = QString("Numeric weather ID for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("weather/weather"))) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("ID string map for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); - } else if (source.startsWith(QString("weather/humidity"))) { - data[QString("min")] = 0; - data[QString("max")] = 100; - data[QString("name")] - = QString("Humidity for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("%"); - } else if (source.startsWith(QString("weather/pressure"))) { - data[QString("min")] = 0; - data[QString("max")] = 0; - data[QString("name")] - = QString("Atmospheric pressure for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("integer"); - data[QString("units")] = QString("mb"); - } else if (source.startsWith(QString("weather/temperature"))) { - data[QString("min")] = 0.0; - data[QString("max")] = 0.0; - data[QString("name")] - = QString("Temperature for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("float"); - data[QString("units")] = QString("°C"); - } else if (source.startsWith(QString("weather/timestamp"))) { - data[QString("min")] = QString(""); - data[QString("max")] = QString(""); - data[QString("name")] - = QString("Timestamp for '%1'") - .arg(m_extWeather->itemByTagNumber(ind)->uniq()); - data[QString("type")] = QString("QString"); - data[QString("units")] = QString(""); + if (_source.startsWith("weather/weatherId")) { + data["min"] = 0; + data["max"] = 1000; + data["name"] = QString("Numeric weather ID for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "integer"; + data["units"] = ""; + } else if (_source.startsWith("weather/weather")) { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("ID string map for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "QString"; + data["units"] = ""; + } else if (_source.startsWith("weather/humidity")) { + data["min"] = 0; + data["max"] = 100; + data["name"] = QString("Humidity for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "integer"; + data["units"] = "%"; + } else if (_source.startsWith("weather/pressure")) { + data["min"] = 0; + data["max"] = 0; + data["name"] = QString("Atmospheric pressure for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "integer"; + data["units"] = "mb"; + } else if (_source.startsWith("weather/temperature")) { + data["min"] = 0.0; + data["max"] = 0.0; + data["name"] = QString("Temperature for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "float"; + data["units"] = "°C"; + } else if (_source.startsWith("weather/timestamp")) { + data["min"] = ""; + data["max"] = ""; + data["name"] = QString("Timestamp for '%1'") + .arg(m_extWeather->itemByTagNumber(ind)->uniq()); + data["type"] = "QString"; + data["units"] = ""; } return data; @@ -130,18 +123,12 @@ QStringList WeatherSource::getSources() { QStringList sources; for (auto &item : m_extWeather->activeItems()) { - sources.append( - QString("weather/%1").arg(item->tag(QString("weatherId")))); - sources.append( - QString("weather/%1").arg(item->tag(QString("weather")))); - sources.append( - QString("weather/%1").arg(item->tag(QString("humidity")))); - sources.append( - QString("weather/%1").arg(item->tag(QString("pressure")))); - sources.append( - QString("weather/%1").arg(item->tag(QString("temperature")))); - sources.append( - QString("weather/%1").arg(item->tag(QString("timestamp")))); + sources.append(QString("weather/%1").arg(item->tag("weatherId"))); + sources.append(QString("weather/%1").arg(item->tag("weather"))); + sources.append(QString("weather/%1").arg(item->tag("humidity"))); + sources.append(QString("weather/%1").arg(item->tag("pressure"))); + sources.append(QString("weather/%1").arg(item->tag("temperature"))); + sources.append(QString("weather/%1").arg(item->tag("timestamp"))); } return sources; diff --git a/sources/extsysmonsources/weathersource.h b/sources/extsysmonsources/weathersource.h index cd19b82..52983ad 100644 --- a/sources/extsysmonsources/weathersource.h +++ b/sources/extsysmonsources/weathersource.h @@ -31,10 +31,10 @@ class WeatherSource : public AbstractExtSysMonSource Q_OBJECT public: - explicit WeatherSource(QObject *parent, const QStringList &args); + explicit WeatherSource(QObject *_parent, const QStringList &_args); virtual ~WeatherSource(); - QVariant data(const QString &source); - QVariantMap initialData(const QString &source) const; + QVariant data(const QString &_source); + QVariantMap initialData(const QString &_source) const; void run(){}; QStringList sources() const; diff --git a/sources/test/awtestlibrary.cpp b/sources/test/awtestlibrary.cpp index d602173..4ba9ce2 100644 --- a/sources/test/awtestlibrary.cpp +++ b/sources/test/awtestlibrary.cpp @@ -73,29 +73,29 @@ QPair AWTestLibrary::randomFilenames() } -int AWTestLibrary::randomInt(const int max) +int AWTestLibrary::randomInt(const int _max) { - return qrand() % max; + return qrand() % _max; } -QString AWTestLibrary::randomString(const int min, const int max) +QString AWTestLibrary::randomString(const int _min, const int _max) { QString output; - int count = min + randomInt(max - min); + int count = _min + randomInt(_max - _min); for (int i = 0; i < count; i++) - output += QChar(randomChar()); + output += randomChar(); return output; } -QStringList AWTestLibrary::randomStringList(const int max) +QStringList AWTestLibrary::randomStringList(const int _max) { QStringList output; - int count = 1 + randomInt(max); + int count = 1 + randomInt(_max); for (int i = 0; i < count; i++) output.append(randomString()); @@ -103,14 +103,14 @@ QStringList AWTestLibrary::randomStringList(const int max) } -QStringList AWTestLibrary::randomSelect(const QStringList available) +QStringList AWTestLibrary::randomSelect(const QStringList &_available) { QSet output; - int count = 1 + randomInt(available.count()); + int count = 1 + randomInt(_available.count()); for (int i = 0; i < count; i++) { - int index = randomInt(available.count()); - output << available.at(index); + int index = randomInt(_available.count()); + output << _available.at(index); } return output.toList(); diff --git a/sources/test/awtestlibrary.h b/sources/test/awtestlibrary.h index d422344..4e3405f 100644 --- a/sources/test/awtestlibrary.h +++ b/sources/test/awtestlibrary.h @@ -30,10 +30,10 @@ bool isKWinActive(); char randomChar(); double randomDouble(); QPair randomFilenames(); -int randomInt(const int max = 100); -QString randomString(const int min = 1, const int max = 100); -QStringList randomStringList(const int max = 100); -QStringList randomSelect(const QStringList available); +int randomInt(const int _max = 100); +QString randomString(const int _min = 1, const int _max = 100); +QStringList randomStringList(const int _max = 100); +QStringList randomSelect(const QStringList &_available); }; diff --git a/sources/test/testabstractextitem.cpp b/sources/test/testabstractextitem.cpp index e4bc093..8dfd953 100644 --- a/sources/test/testabstractextitem.cpp +++ b/sources/test/testabstractextitem.cpp @@ -109,7 +109,7 @@ void TestAbstractExtItem::test_delete() void TestAbstractExtItem::test_copy() { - ExtUpgrade *newExtItem = extItem->copy(QString("/dev/null"), 1); + ExtUpgrade *newExtItem = extItem->copy("/dev/null", 1); QCOMPARE(newExtItem->isActive(), extItem->isActive()); QCOMPARE(newExtItem->apiVersion(), extItem->apiVersion()); diff --git a/sources/test/testabstractformatter.cpp b/sources/test/testabstractformatter.cpp index ba27ed9..ac356f3 100644 --- a/sources/test/testabstractformatter.cpp +++ b/sources/test/testabstractformatter.cpp @@ -49,14 +49,14 @@ void TestAbstractFormatter::test_type() formatter->setStrType(type); QCOMPARE(formatter->strType(), type); - formatter->setStrType(QString("NoFormat")); + formatter->setStrType("NoFormat"); QCOMPARE(formatter->strType(), QString("NoFormat")); } void TestAbstractFormatter::test_copy() { - AWNoFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWNoFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->type(), formatter->type()); QCOMPARE(newFormatter->name(), formatter->name()); diff --git a/sources/test/testawkeys.cpp b/sources/test/testawkeys.cpp index e93d232..f51de28 100644 --- a/sources/test/testawkeys.cpp +++ b/sources/test/testawkeys.cpp @@ -34,34 +34,34 @@ void TestAWKeys::initTestCase() // tooltip init QVariantMap tooltipSettings; - tooltipSettings[QString("tooltipNumber")] = 1000; - tooltipSettings[QString("useTooltipBackground")] = true; - tooltipSettings[QString("tooltipBackground")] = QString("#ffffff"); - tooltipSettings[QString("cpuTooltip")] = true; - tooltipSettings[QString("cpuclTooltip")] = true; - tooltipSettings[QString("memTooltip")] = true; - tooltipSettings[QString("swapTooltip")] = true; - tooltipSettings[QString("downkbTooltip")] = true; - tooltipSettings[QString("upkbTooltip")] = true; - tooltipSettings[QString("batTooltip")] = true; - tooltipSettings[QString("cpuTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("cpuclTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("memTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("swapTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("downkbTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("upkbTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("batTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("batInTooltipColor")] = QString("#ffffff"); - tooltipSettings[QString("acOnline")] = QString("(*)"); - tooltipSettings[QString("notify")] = false; + tooltipSettings["tooltipNumber"] = 1000; + tooltipSettings["useTooltipBackground"] = true; + tooltipSettings["tooltipBackground"] = "#ffffff"; + tooltipSettings["cpuTooltip"] = true; + tooltipSettings["cpuclTooltip"] = true; + tooltipSettings["memTooltip"] = true; + tooltipSettings["swapTooltip"] = true; + tooltipSettings["downkbTooltip"] = true; + tooltipSettings["upkbTooltip"] = true; + tooltipSettings["batTooltip"] = true; + tooltipSettings["cpuTooltipColor"] = "#ffffff"; + tooltipSettings["cpuclTooltipColor"] = "#ffffff"; + tooltipSettings["memTooltipColor"] = "#ffffff"; + tooltipSettings["swapTooltipColor"] = "#ffffff"; + tooltipSettings["downkbTooltipColor"] = "#ffffff"; + tooltipSettings["upkbTooltipColor"] = "#ffffff"; + tooltipSettings["batTooltipColor"] = "#ffffff"; + tooltipSettings["batInTooltipColor"] = "#ffffff"; + tooltipSettings["acOnline"] = "(*)"; + tooltipSettings["notify"] = false; plugin->initDataAggregator(tooltipSettings); // aggregator init - plugin->setAggregatorProperty("acOffline", QString("( )")); - plugin->setAggregatorProperty("acOnline", QString("(*)")); - plugin->setAggregatorProperty("customTime", QString("$hh")); - plugin->setAggregatorProperty("customUptime", QString("$hh")); - plugin->setAggregatorProperty("tempUnits", QString("Celsius")); + plugin->setAggregatorProperty("acOffline", "( )"); + plugin->setAggregatorProperty("acOnline", "(*)"); + plugin->setAggregatorProperty("customTime", "$hh"); + plugin->setAggregatorProperty("customUptime", "$hh"); + plugin->setAggregatorProperty("tempUnits", "Celsius"); plugin->setAggregatorProperty("translate", false); plugin->initKeys(pattern, interval, 0, false); @@ -90,7 +90,7 @@ void TestAWKeys::test_dictKeys() QEXPECT_FAIL("", "Sorted and non-sorted lists should differ", Continue); QCOMPARE(keys, sorted); - pattern = QString("$%1").arg(sorted.join(QString("\n$"))); + pattern = QString("$%1").arg(sorted.join("\n$")); } @@ -120,7 +120,7 @@ void TestAWKeys::test_tooltip() QVERIFY(spy.wait(5 * interval)); QString text = spy.takeFirst().at(0).toString(); - QVERIFY(text.startsWith(QString("infoByKey(key); QVERIFY(!info.isEmpty()); // append non-empty field count - if (info != QString("(none)")) + if (info != "(none)") notEmpty++; } QVERIFY(notEmpty > 0); @@ -176,9 +176,8 @@ void TestAWKeys::test_dbus() // create connection and message QDBusConnection bus = QDBusConnection::sessionBus(); - QDBusMessage request - = QDBusMessage::createMethodCall(AWDBUS_SERVICE, QString("/%1").arg(id), - AWDBUS_SERVICE, QString("WhoAmI")); + QDBusMessage request = QDBusMessage::createMethodCall( + AWDBUS_SERVICE, QString("/%1").arg(id), AWDBUS_SERVICE, "WhoAmI"); // send message to dbus QDBusMessage response = bus.call(request, QDBus::BlockWithGui); diff --git a/sources/test/testawpatternfunctions.cpp b/sources/test/testawpatternfunctions.cpp index 0a47d43..a57e457 100644 --- a/sources/test/testawpatternfunctions.cpp +++ b/sources/test/testawpatternfunctions.cpp @@ -40,10 +40,8 @@ void TestAWPatternFunctions::test_findFunctionCalls() QString name = QString("aw_%1").arg(AWTestLibrary::randomString(1, 10)); QString code = AWTestLibrary::randomString(1, 20); QStringList args = AWTestLibrary::randomStringList(20); - QString function = QString("$%1<%2>{{%3}}") - .arg(name) - .arg(args.join(QChar(','))) - .arg(code); + QString function + = QString("$%1<%2>{{%3}}").arg(name).arg(args.join(',')).arg(code); QString pattern = AWTestLibrary::randomString() + function + AWTestLibrary::randomString(); @@ -72,10 +70,9 @@ void TestAWPatternFunctions::test_findKeys() auto keys = AWTestLibrary::randomSelect(allKeys); auto bars = AWTestLibrary::randomSelect(allKeys); std::for_each(bars.begin(), bars.end(), - [](QString &bar) { bar.prepend(QString("bar")); }); - QString pattern = QString("$%1 $%2") - .arg(keys.join(QString(" $"))) - .arg(bars.join(QString(" $"))); + [](QString &bar) { bar.prepend("bar"); }); + QString pattern + = QString("$%1 $%2").arg(keys.join(" $")).arg(bars.join(" $")); allKeys.append(bars); allKeys.sort(); @@ -99,7 +96,7 @@ void TestAWPatternFunctions::test_findLambdas() { QStringList lambdas = AWTestLibrary::randomStringList(20); QString pattern = AWTestLibrary::randomString() - + QString("${{%1}}").arg(lambdas.join(QString("}}${{"))) + + QString("${{%1}}").arg(lambdas.join("}}${{")) + AWTestLibrary::randomString(); QCOMPARE(AWPatternFunctions::findLambdas(pattern), lambdas); diff --git a/sources/test/testawtelemetryhandler.cpp b/sources/test/testawtelemetryhandler.cpp index be93605..b4181e0 100644 --- a/sources/test/testawtelemetryhandler.cpp +++ b/sources/test/testawtelemetryhandler.cpp @@ -64,13 +64,13 @@ void TestAWTelemetryHandler::test_getLast() void TestAWTelemetryHandler::test_uploadTelemetry() { - QSignalSpy spy(plugin, SIGNAL(replyReceived(QString &))); + QSignalSpy spy(plugin, SIGNAL(replyReceived(const QString &))); plugin->uploadTelemetry(telemetryValidGroup, telemetryData); QVERIFY(spy.wait(5000)); QVariantList arguments = spy.takeFirst(); - QCOMPARE(arguments.at(0).toString(), QString("saved")); + QCOMPARE(arguments.at(0).toString(), telemetryStatus); } diff --git a/sources/test/testawtelemetryhandler.h b/sources/test/testawtelemetryhandler.h index f55498e..cfbf89d 100644 --- a/sources/test/testawtelemetryhandler.h +++ b/sources/test/testawtelemetryhandler.h @@ -42,8 +42,9 @@ private: AWTelemetryHandler *plugin = nullptr; QString telemetryData; QString telemetryGroup; - QString telemetryId = QString("autotest"); - QString telemetryValidGroup = QString("awwidgetconfig"); + QString telemetryId = "autotest"; + QString telemetryStatus = "saved"; + QString telemetryValidGroup = "awwidgetconfig"; }; diff --git a/sources/test/testbatterysource.cpp b/sources/test/testbatterysource.cpp index 8e1640a..843d986 100644 --- a/sources/test/testbatterysource.cpp +++ b/sources/test/testbatterysource.cpp @@ -52,7 +52,7 @@ void TestBatterySource::test_battery() std::for_each(batteries.begin(), batteries.end(), [this](const QString bat) { QVariant value = source->data(bat); - if (bat == QString("battery/ac")) + if (bat == "battery/ac") QCOMPARE(value.type(), QVariant::Bool); else QVERIFY((value.toFloat() >= battery.first) diff --git a/sources/test/testbatterysource.h b/sources/test/testbatterysource.h index b6bc22c..7af3af1 100644 --- a/sources/test/testbatterysource.h +++ b/sources/test/testbatterysource.h @@ -39,7 +39,7 @@ private slots: private: BatterySource *source = nullptr; - QString acpiPath = QString("/sys/class/power_supply/"); + QString acpiPath = "/sys/class/power_supply/"; QPair battery = QPair(0, 100); }; diff --git a/sources/test/testdatetimeformatter.cpp b/sources/test/testdatetimeformatter.cpp index 62050f2..57dfa3a 100644 --- a/sources/test/testdatetimeformatter.cpp +++ b/sources/test/testdatetimeformatter.cpp @@ -28,8 +28,8 @@ void TestAWDateTimeFormatter::initTestCase() { AWTestLibrary::init(); - format = AWTestLibrary::randomSelect(QString(TIME_KEYS).split(QChar(','))) - .join(QChar(' ')); + format + = AWTestLibrary::randomSelect(QString(TIME_KEYS).split(',')).join(' '); formatter = new AWDateTimeFormatter(nullptr); formatter->setFormat(format); @@ -58,8 +58,7 @@ void TestAWDateTimeFormatter::test_conversion() void TestAWDateTimeFormatter::test_copy() { formatter->setTranslateString(false); - AWDateTimeFormatter *newFormatter - = formatter->copy(QString("/dev/null"), 1); + AWDateTimeFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->format(), formatter->format()); QCOMPARE(newFormatter->translateString(), formatter->translateString()); diff --git a/sources/test/testdesktopsource.cpp b/sources/test/testdesktopsource.cpp index 2471ca5..4f7b1f8 100644 --- a/sources/test/testdesktopsource.cpp +++ b/sources/test/testdesktopsource.cpp @@ -45,12 +45,10 @@ void TestDesktopSource::test_sources() void TestDesktopSource::test_values() { - QVERIFY(source->data(QString("desktop/current/name")).toString().count() - > 0); - QVERIFY(source->data(QString("desktop/current/number")).toInt() >= 0); - QVERIFY(source->data(QString("desktop/total/name")).toStringList().count() - > 0); - QVERIFY(source->data(QString("desktop/total/number")).toInt() > 0); + QVERIFY(source->data("desktop/current/name").toString().count() > 0); + QVERIFY(source->data("desktop/current/number").toInt() >= 0); + QVERIFY(source->data("desktop/total/name").toStringList().count() > 0); + QVERIFY(source->data("desktop/total/number").toInt() > 0); } diff --git a/sources/test/testdpplugin.cpp b/sources/test/testdpplugin.cpp index fc684ab..aa84c3b 100644 --- a/sources/test/testdpplugin.cpp +++ b/sources/test/testdpplugin.cpp @@ -71,7 +71,7 @@ void TestDPPlugin::test_dictKeys() QSKIP("KWin inactive, skip Destkop panel tests"); QCOMPARE(plugin->dictKeys().count(), 4); - pattern += plugin->dictKeys().join(QString(" $")); + pattern += plugin->dictKeys().join(" $"); } @@ -104,14 +104,14 @@ void TestDPPlugin::test_tooltipImage() QSKIP("KWin inactive, skip Destkop panel tests"); QVariantMap data; - data[QString("tooltipColor")] = QString("#000000"); - data[QString("tooltipType")] = QString("windows"); - data[QString("tooltipWidth")] = 300; + data["tooltipColor"] = "#000000"; + data["tooltipType"] = "windows"; + data["tooltipWidth"] = 300; plugin->setToolTipData(data); QString image = plugin->toolTipImage(plugin->currentDesktop()); - QVERIFY(image.startsWith(QString(""))); + QVERIFY(image.startsWith("")); } diff --git a/sources/test/testdpplugin.h b/sources/test/testdpplugin.h index 65dd9b7..4d4b0f7 100644 --- a/sources/test/testdpplugin.h +++ b/sources/test/testdpplugin.h @@ -42,7 +42,7 @@ private slots: private: DPAdds *plugin = nullptr; bool m_isKwinActive = false; - QString pattern = QString("$"); + QString pattern = "$"; }; diff --git a/sources/test/testextitemaggregator.h b/sources/test/testextitemaggregator.h index 022e501..c5237cd 100644 --- a/sources/test/testextitemaggregator.h +++ b/sources/test/testextitemaggregator.h @@ -38,7 +38,7 @@ private slots: private: ExtItemAggregator *aggregator = nullptr; - QString type = QString("tmp"); + QString type = "tmp"; }; diff --git a/sources/test/testextquotes.cpp b/sources/test/testextquotes.cpp index 2ae1506..10a8df1 100644 --- a/sources/test/testextquotes.cpp +++ b/sources/test/testextquotes.cpp @@ -94,7 +94,7 @@ void TestExtQuotes::test_derivatives() void TestExtQuotes::test_copy() { - ExtQuotes *newExtQuotes = extQuotes->copy(QString("/dev/null"), 1); + ExtQuotes *newExtQuotes = extQuotes->copy("/dev/null", 1); QCOMPARE(newExtQuotes->interval(), extQuotes->interval()); QCOMPARE(newExtQuotes->ticker(), extQuotes->ticker()); diff --git a/sources/test/testextquotes.h b/sources/test/testextquotes.h index 5eed05d..df5c16d 100644 --- a/sources/test/testextquotes.h +++ b/sources/test/testextquotes.h @@ -42,9 +42,10 @@ private slots: private: ExtQuotes *extQuotes = nullptr; QVariantHash cache; - QString ticker = QString("EURUSD=X"); - QStringList types = QStringList() - << QString("ask") << QString("bid") << QString("price"); + QString ticker = "EURUSD=X"; + QStringList types = QStringList() << "ask" + << "bid" + << "price"; // we assume that price will not be differ more than in 2 times QPair price = QPair(0.5, 2.0); }; diff --git a/sources/test/testextscript.cpp b/sources/test/testextscript.cpp index 5198946..1586a83 100644 --- a/sources/test/testextscript.cpp +++ b/sources/test/testextscript.cpp @@ -34,7 +34,7 @@ void TestExtScript::initTestCase() extScript->setExecutable(randomString); extScript->setNumber(0); extScript->setRedirect(ExtScript::Redirect::stderr2stdout); - extScript->setPrefix(QString("echo")); + extScript->setPrefix("echo"); extScript->run(); } @@ -66,11 +66,9 @@ void TestExtScript::test_run() QVERIFY(spy.wait(5000)); QList arguments = spy.takeFirst(); - QCOMPARE(firstValue[extScript->tag(QString("custom"))].toString(), - QString("")); - QCOMPARE( - arguments.at(0).toHash()[extScript->tag(QString("custom"))].toString(), - QString("\n%1").arg(randomString)); + QCOMPARE(firstValue[extScript->tag("custom")].toString(), QString()); + QCOMPARE(arguments.at(0).toHash()[extScript->tag("custom")].toString(), + QString("\n%1").arg(randomString)); } @@ -79,7 +77,7 @@ void TestExtScript::test_filters() if (extScript->jsonFiltersFile().isEmpty()) QSKIP("No json filters found for scripts, skip fitlers test"); - extScript->setFilters(QStringList() << QString("newline")); + extScript->setFilters(QStringList() << "newline"); // init spy QSignalSpy spy(extScript, SIGNAL(dataReceived(const QVariantHash &))); extScript->run(); @@ -87,15 +85,14 @@ void TestExtScript::test_filters() // check values QVERIFY(spy.wait(5000)); QList arguments = spy.takeFirst(); - QCOMPARE( - arguments.at(0).toHash()[extScript->tag(QString("custom"))].toString(), - QString("
    %1").arg(randomString)); + QCOMPARE(arguments.at(0).toHash()[extScript->tag("custom")].toString(), + QString("
    %1").arg(randomString)); } void TestExtScript::test_copy() { - ExtScript *newExtScript = extScript->copy(QString("/dev/null"), 1); + ExtScript *newExtScript = extScript->copy("/dev/null", 1); QCOMPARE(newExtScript->interval(), extScript->interval()); QCOMPARE(newExtScript->executable(), extScript->executable()); diff --git a/sources/test/testextupgrade.cpp b/sources/test/testextupgrade.cpp index b87ca0f..7e35e7a 100644 --- a/sources/test/testextupgrade.cpp +++ b/sources/test/testextupgrade.cpp @@ -28,7 +28,7 @@ void TestExtUpgrade::initTestCase() { AWTestLibrary::init(); randomStrings = AWTestLibrary::randomStringList(); - cmd = QString("echo -e '%1'").arg(randomStrings.join(QString("\n"))); + cmd = QString("echo -e '%1'").arg(randomStrings.join("\n")); extUpgrade = new ExtUpgrade(nullptr); extUpgrade->setInterval(1); @@ -63,10 +63,9 @@ void TestExtUpgrade::test_run() QVERIFY(spy.wait(5000)); QList arguments = spy.takeFirst(); - QCOMPARE(firstValue[extUpgrade->tag(QString("pkgcount"))].toInt(), 0); - QCOMPARE( - arguments.at(0).toHash()[extUpgrade->tag(QString("pkgcount"))].toInt(), - randomStrings.count()); + QCOMPARE(firstValue[extUpgrade->tag("pkgcount")].toInt(), 0); + QCOMPARE(arguments.at(0).toHash()[extUpgrade->tag("pkgcount")].toInt(), + randomStrings.count()); } @@ -80,16 +79,15 @@ void TestExtUpgrade::test_null() // check values QVERIFY(spy.wait(5000)); QList arguments = spy.takeFirst(); - QCOMPARE( - arguments.at(0).toHash()[extUpgrade->tag(QString("pkgcount"))].toInt(), - randomStrings.count() - null); + QCOMPARE(arguments.at(0).toHash()[extUpgrade->tag("pkgcount")].toInt(), + randomStrings.count() - null); } void TestExtUpgrade::test_filter() { QStringList filters = AWTestLibrary::randomSelect(randomStrings); - extUpgrade->setFilter(QString("(^%1$)").arg(filters.join(QString("$|^")))); + extUpgrade->setFilter(QString("(^%1$)").arg(filters.join("$|^"))); // init spy QSignalSpy spy(extUpgrade, SIGNAL(dataReceived(const QVariantHash &))); extUpgrade->run(); @@ -97,15 +95,14 @@ void TestExtUpgrade::test_filter() // check values QVERIFY(spy.wait(5000)); QList arguments = spy.takeFirst(); - QCOMPARE( - arguments.at(0).toHash()[extUpgrade->tag(QString("pkgcount"))].toInt(), - filters.count()); + QCOMPARE(arguments.at(0).toHash()[extUpgrade->tag("pkgcount")].toInt(), + filters.count()); } void TestExtUpgrade::test_copy() { - ExtUpgrade *newExtUpgrade = extUpgrade->copy(QString("/dev/null"), 1); + ExtUpgrade *newExtUpgrade = extUpgrade->copy("/dev/null", 1); QCOMPARE(newExtUpgrade->interval(), extUpgrade->interval()); QCOMPARE(newExtUpgrade->executable(), extUpgrade->executable()); diff --git a/sources/test/testextweather.cpp b/sources/test/testextweather.cpp index 0ffa2b1..869704a 100644 --- a/sources/test/testextweather.cpp +++ b/sources/test/testextweather.cpp @@ -89,14 +89,13 @@ void TestExtWeather::test_image() QVERIFY(spy.wait(5000)); QVariantHash arguments = spy.takeFirst().at(0).toHash(); QVERIFY( - arguments[extWeather->tag(QString("weather"))].toString().startsWith( - QString("tag("weather")].toString().startsWith("copy(QString("/dev/null"), 1); + ExtWeather *newExtWeather = extWeather->copy("/dev/null", 1); QCOMPARE(newExtWeather->interval(), extWeather->interval()); QCOMPARE(newExtWeather->city(), extWeather->city()); @@ -120,24 +119,20 @@ void TestExtWeather::run() QVERIFY(spy.wait(5000)); QVariantHash arguments = spy.takeFirst().at(0).toHash(); QEXPECT_FAIL("", "WeatherID should not be 0", Continue); - QCOMPARE(arguments[extWeather->tag(QString("weatherId"))].toInt(), 0); - QVERIFY((arguments[extWeather->tag(QString("humidity"))].toInt() - >= humidity.first) - && (arguments[extWeather->tag(QString("humidity"))].toInt() - <= humidity.second)); - QVERIFY((arguments[extWeather->tag(QString("pressure"))].toInt() - > pressure.first) - && (arguments[extWeather->tag(QString("pressure"))].toInt() - < pressure.second)); - QVERIFY((arguments[extWeather->tag(QString("temperature"))].toFloat() - > temp.first) - && (arguments[extWeather->tag(QString("temperature"))].toFloat() - < temp.second)); + QCOMPARE(arguments[extWeather->tag("weatherId")].toInt(), 0); + QVERIFY( + (arguments[extWeather->tag("humidity")].toInt() >= humidity.first) + && (arguments[extWeather->tag("humidity")].toInt() <= humidity.second)); + QVERIFY( + (arguments[extWeather->tag("pressure")].toInt() > pressure.first) + && (arguments[extWeather->tag("pressure")].toInt() < pressure.second)); + QVERIFY( + (arguments[extWeather->tag("temperature")].toFloat() > temp.first) + && (arguments[extWeather->tag("temperature")].toFloat() < temp.second)); // image should be only one symbol here if (extWeather->jsonMapFile().isEmpty()) QSKIP("No json map found for weather, skip image test"); - QCOMPARE(arguments[extWeather->tag(QString("weather"))].toString().count(), - 1); + QCOMPARE(arguments[extWeather->tag("weather")].toString().count(), 1); } diff --git a/sources/test/testextweather.h b/sources/test/testextweather.h index ef2d88e..9e179f7 100644 --- a/sources/test/testextweather.h +++ b/sources/test/testextweather.h @@ -44,8 +44,8 @@ private slots: private: void run(); ExtWeather *extWeather = nullptr; - QString city = QString("London"); - QString country = QString("uk"); + QString city = "London"; + QString country = "uk"; // humidity is in percents QPair humidity = QPair(0, 100); // pressure should be about 1 atm diff --git a/sources/test/testfloatformatter.cpp b/sources/test/testfloatformatter.cpp index 2a8993d..2e4a855 100644 --- a/sources/test/testfloatformatter.cpp +++ b/sources/test/testfloatformatter.cpp @@ -62,13 +62,13 @@ void TestAWFloatFormatter::test_fillChar() { // assign char c = AWTestLibrary::randomChar(); - formatter->setFillChar(QChar(c)); + formatter->setFillChar(c); QCOMPARE(formatter->fillChar(), QChar(c)); formatter->setCount(101); // test QString output = formatter->convert(AWTestLibrary::randomInt()); - QVERIFY(output.startsWith(QChar(c))); + QVERIFY(output.startsWith(c)); // reset formatter->setFillChar(QChar()); @@ -121,7 +121,7 @@ void TestAWFloatFormatter::test_precision() // test QString output = formatter->convert(AWTestLibrary::randomDouble()); - output.remove(QString("0.")); + output.remove("0."); QCOMPARE(output.count(), precision); // reset @@ -168,7 +168,7 @@ void TestAWFloatFormatter::test_summand() void TestAWFloatFormatter::test_copy() { doRandom(); - AWFloatFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWFloatFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->count(), formatter->count()); QCOMPARE(newFormatter->fillChar(), formatter->fillChar()); @@ -186,7 +186,7 @@ void TestAWFloatFormatter::test_copy() void TestAWFloatFormatter::doRandom() { formatter->setCount(AWTestLibrary::randomInt()); - formatter->setFillChar(QChar(AWTestLibrary::randomChar())); + formatter->setFillChar(AWTestLibrary::randomChar()); formatter->setForceWidth(AWTestLibrary::randomInt() % 2); formatter->setFormat(AWTestLibrary::randomChar()); formatter->setMultiplier(AWTestLibrary::randomDouble()); diff --git a/sources/test/testgpuloadsource.cpp b/sources/test/testgpuloadsource.cpp index 311428e..f6d6461 100644 --- a/sources/test/testgpuloadsource.cpp +++ b/sources/test/testgpuloadsource.cpp @@ -48,7 +48,7 @@ void TestGPULoadSource::test_sources() void TestGPULoadSource::test_gpuload() { - if (device == QString("disable")) + if (device == "disable") QSKIP("Not supported device, test will be skipped"); QSignalSpy spy(source, SIGNAL(dataReceived(const QVariantHash &))); diff --git a/sources/test/testgpuloadsource.h b/sources/test/testgpuloadsource.h index 7ac1725..93ee7ce 100644 --- a/sources/test/testgpuloadsource.h +++ b/sources/test/testgpuloadsource.h @@ -40,7 +40,7 @@ private slots: private: GPULoadSource *source = nullptr; QString device; - QString src = QString("gpu/load"); + QString src = "gpu/load"; QPair load = QPair(0.0f, 100.0f); }; diff --git a/sources/test/testgputempsource.cpp b/sources/test/testgputempsource.cpp index aaa08c9..efad21d 100644 --- a/sources/test/testgputempsource.cpp +++ b/sources/test/testgputempsource.cpp @@ -21,13 +21,14 @@ #include #include "awtestlibrary.h" +#include "gpuloadsource.h" #include "gputempsource.h" void TestGPUTemperatureSource::initTestCase() { AWTestLibrary::init(); - device = GPUTemperatureSource::autoGpu(); + device = GPULoadSource::autoGpu(); QVERIFY(!device.isEmpty()); source = new GPUTemperatureSource(this, QStringList() << device); @@ -48,7 +49,7 @@ void TestGPUTemperatureSource::test_sources() void TestGPUTemperatureSource::test_gputemp() { - if (device == QString("disable")) + if (device == "disable") QSKIP("Not supported device, test will be skipped"); QSignalSpy spy(source, SIGNAL(dataReceived(const QVariantHash &))); diff --git a/sources/test/testgputempsource.h b/sources/test/testgputempsource.h index a9c8f98..3f7ce9b 100644 --- a/sources/test/testgputempsource.h +++ b/sources/test/testgputempsource.h @@ -40,7 +40,7 @@ private slots: private: GPUTemperatureSource *source = nullptr; QString device; - QString src = QString("gpu/temperature"); + QString src = "gpu/temperature"; QPair temp = QPair(0.0f, 120.0f); }; diff --git a/sources/test/testhddtempsource.cpp b/sources/test/testhddtempsource.cpp index 0be6c7a..6c6e34e 100644 --- a/sources/test/testhddtempsource.cpp +++ b/sources/test/testhddtempsource.cpp @@ -31,9 +31,9 @@ void TestHDDTemperatureSource::initTestCase() QVERIFY(devices.count() > 0); hddtempSource = new HDDTemperatureSource( - this, QStringList() << devices.join(QChar(',')) << hddtempCmd); + this, QStringList() << devices.join(',') << hddtempCmd); smartctlSource = new HDDTemperatureSource( - this, QStringList() << devices.join(QChar(',')) << smartctlCmd); + this, QStringList() << devices.join(',') << smartctlCmd); } @@ -46,9 +46,8 @@ void TestHDDTemperatureSource::cleanupTestCase() void TestHDDTemperatureSource::test_sources() { - std::for_each(devices.begin(), devices.end(), [](QString &device) { - device.prepend(QString("hdd/temperature")); - }); + std::for_each(devices.begin(), devices.end(), + [](QString &device) { device.prepend("hdd/temperature"); }); QCOMPARE(hddtempSource->sources(), devices); QCOMPARE(smartctlSource->sources(), devices); @@ -64,7 +63,7 @@ void TestHDDTemperatureSource::test_hddtemp() QVERIFY(spy.wait(5000)); QVariantHash arguments = spy.takeFirst().at(0).toHash(); - device.remove(QString("hdd/temperature")); + device.remove("hdd/temperature"); float secondValue = arguments[device].toFloat(); QCOMPARE(firstValue, 0.0f); @@ -82,7 +81,7 @@ void TestHDDTemperatureSource::test_smartctl() QVERIFY(spy.wait(5000)); QVariantHash arguments = spy.takeFirst().at(0).toHash(); - device.remove(QString("hdd/temperature")); + device.remove("hdd/temperature"); float secondValue = arguments[device].toFloat(); QCOMPARE(firstValue, 0.0f); diff --git a/sources/test/testhddtempsource.h b/sources/test/testhddtempsource.h index 3bb075a..f687c0a 100644 --- a/sources/test/testhddtempsource.h +++ b/sources/test/testhddtempsource.h @@ -42,8 +42,8 @@ private: HDDTemperatureSource *hddtempSource = nullptr; HDDTemperatureSource *smartctlSource = nullptr; QStringList devices; - QString hddtempCmd = QString("sudo hddtemp"); - QString smartctlCmd = QString("sudo smartctl -a"); + QString hddtempCmd = "sudo hddtemp"; + QString smartctlCmd = "sudo smartctl -a"; QPair temp = QPair(0.0f, 120.0f); }; diff --git a/sources/test/testjsonformatter.cpp b/sources/test/testjsonformatter.cpp index c1611ff..b926560 100644 --- a/sources/test/testjsonformatter.cpp +++ b/sources/test/testjsonformatter.cpp @@ -54,7 +54,7 @@ void TestAWJsonFormatter::test_conversion() void TestAWJsonFormatter::test_copy() { - AWJsonFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWJsonFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->path(), formatter->path()); QCOMPARE(newFormatter->number(), 1); diff --git a/sources/test/testlistformatter.cpp b/sources/test/testlistformatter.cpp index e85a3fa..353624c 100644 --- a/sources/test/testlistformatter.cpp +++ b/sources/test/testlistformatter.cpp @@ -71,7 +71,7 @@ void TestAWListFormatter::test_filter() QStringList value = AWTestLibrary::randomStringList(); QStringList filters = AWTestLibrary::randomSelect(value); value.sort(); - formatter->setFilter(QString("(^%1$)").arg(filters.join(QString("$|^")))); + formatter->setFilter(QString("(^%1$)").arg(filters.join("$|^"))); QCOMPARE(formatter->convert(value).split(separator).count(), filters.count()); @@ -80,7 +80,7 @@ void TestAWListFormatter::test_filter() void TestAWListFormatter::test_copy() { - AWListFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWListFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->number(), 1); QCOMPARE(newFormatter->filter(), formatter->filter()); diff --git a/sources/test/testnetworksource.h b/sources/test/testnetworksource.h index e69334c..c467e3f 100644 --- a/sources/test/testnetworksource.h +++ b/sources/test/testnetworksource.h @@ -38,7 +38,7 @@ private slots: private: NetworkSource *source = nullptr; - QString src = QString("network/current/name"); + QString src = "network/current/name"; }; diff --git a/sources/test/testnoformatter.cpp b/sources/test/testnoformatter.cpp index 7eda3c0..1f005da 100644 --- a/sources/test/testnoformatter.cpp +++ b/sources/test/testnoformatter.cpp @@ -57,7 +57,7 @@ void TestAWNoFormatter::test_conversion() void TestAWNoFormatter::test_copy() { - AWNoFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWNoFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->number(), 1); diff --git a/sources/test/testplayersource.cpp b/sources/test/testplayersource.cpp index e932941..b4e5b6b 100644 --- a/sources/test/testplayersource.cpp +++ b/sources/test/testplayersource.cpp @@ -35,44 +35,42 @@ void TestPlayerSource::cleanupTestCase() } -void TestPlayerSource::_test_sources(const PlayerSource *source) +void TestPlayerSource::_test_sources(const PlayerSource *_source) { - QVERIFY(source->sources().count() == 11); + QVERIFY(_source->sources().count() == 11); } void TestPlayerSource::test_buildString() { QString randomString = AWTestLibrary::randomString(1, 40); - QString str = PlayerSource::buildString(QString(), randomString, 20); + QString str = PlayerSource::buildString("", randomString, 20); QCOMPARE(str.count(), 20); str = PlayerSource::buildString(str, randomString, 20); QCOMPARE(str.count(), 20); - str = PlayerSource::buildString(QString(), - AWTestLibrary::randomString(1, 10), 20); + str = PlayerSource::buildString("", AWTestLibrary::randomString(1, 10), 20); QCOMPARE(str.count(), 20); } void TestPlayerSource::test_stripString() { - QString str = PlayerSource::buildString( - QString(), AWTestLibrary::randomString(1, 40), 20); + QString str + = PlayerSource::buildString("", AWTestLibrary::randomString(1, 40), 20); QCOMPARE(str.count(), 20); - str = PlayerSource::buildString(QString(), - AWTestLibrary::randomString(1, 10), 20); + str = PlayerSource::buildString("", AWTestLibrary::randomString(1, 10), 20); QCOMPARE(str.count(), 20); } void TestPlayerSource::test_autoMpris() { - QStringList args(QStringList() << QString("mpris") << mpdAddress - << QString::number(mpdPort) - << QString("auto") << QString::number(10)); + QStringList args(QStringList() + << "mpris" << mpdAddress << QString::number(mpdPort) + << "auto" << QString::number(10)); PlayerSource *source = new PlayerSource(this, args); bool empty = source->getAutoMpris().isEmpty(); @@ -86,14 +84,14 @@ void TestPlayerSource::test_autoMpris() void TestPlayerSource::test_mpd() { QStringList args(QStringList() - << QString("mpd") << mpdAddress << QString::number(mpdPort) - << QString("auto") << QString::number(10)); + << "mpd" << mpdAddress << QString::number(mpdPort) + << "auto" << QString::number(10)); PlayerSource *source = new PlayerSource(this, args); _test_sources(source); // init spy QSignalSpy spy(source, SIGNAL(dataReceived(const QVariantHash &))); - QVariant firstValue = source->data(QString("player/title")); + QVariant firstValue = source->data("player/title"); if (!source->isMpdSocketConnected()) QSKIP("No mpd found"); @@ -103,28 +101,28 @@ void TestPlayerSource::test_mpd() QVariantHash secondValue = arguments.at(0).toHash(); // actually nothing to test here just print warning if no information found - if (secondValue[QString("player/title")].toString() == QString("unknown")) + if (secondValue["player/title"].toString() == "unknown") QSKIP("No mpd found"); - QVERIFY(secondValue[QString("player/progress")].toInt() - < secondValue[QString("player/duration")].toInt()); + QVERIFY(secondValue["player/progress"].toInt() + < secondValue["player/duration"].toInt()); } void TestPlayerSource::test_mpris() { - QStringList args(QStringList() << QString("mpris") << mpdAddress - << QString::number(mpdPort) - << QString("auto") << QString::number(10)); + QStringList args(QStringList() + << "mpris" << mpdAddress << QString::number(mpdPort) + << "auto" << QString::number(10)); PlayerSource *source = new PlayerSource(this, args); _test_sources(source); - QString value = source->data(QString("player/title")).toString(); - int progress = source->data(QString("player/progress")).toInt(); - int duration = source->data(QString("player/duration")).toInt(); + QString value = source->data("player/title").toString(); + int progress = source->data("player/progress").toInt(); + int duration = source->data("player/duration").toInt(); // actually nothing to test here just print warning if no information found - if (value == QString("unknown")) + if (value == "unknown") QSKIP("No mpris found"); QVERIFY(progress < duration); diff --git a/sources/test/testplayersource.h b/sources/test/testplayersource.h index ef70b6d..0b11bf5 100644 --- a/sources/test/testplayersource.h +++ b/sources/test/testplayersource.h @@ -33,7 +33,7 @@ private slots: void initTestCase(); void cleanupTestCase(); // test - void _test_sources(const PlayerSource *source); + void _test_sources(const PlayerSource *_source); void test_buildString(); void test_stripString(); void test_autoMpris(); @@ -41,7 +41,7 @@ private slots: void test_mpris(); private: - QString mpdAddress = QString("localhost"); + QString mpdAddress = "localhost"; int mpdPort = 6600; }; diff --git a/sources/test/testprocessessource.cpp b/sources/test/testprocessessource.cpp index a6a3180..1fdce78 100644 --- a/sources/test/testprocessessource.cpp +++ b/sources/test/testprocessessource.cpp @@ -45,10 +45,9 @@ void TestProcessesSource::test_sources() void TestProcessesSource::test_values() { - QVERIFY(source->data(QString("ps/running/count")).toInt() > 0); - QVERIFY(source->data(QString("ps/running/list")).toStringList().count() - > 0); - QVERIFY(source->data(QString("ps/total/count")).toInt() > 0); + QVERIFY(source->data("ps/running/count").toInt() > 0); + QVERIFY(source->data("ps/running/list").toStringList().count() > 0); + QVERIFY(source->data("ps/total/count").toInt() > 0); } diff --git a/sources/test/testscriptformatter.cpp b/sources/test/testscriptformatter.cpp index 22b02ae..3ae01f5 100644 --- a/sources/test/testscriptformatter.cpp +++ b/sources/test/testscriptformatter.cpp @@ -93,7 +93,7 @@ void TestAWScriptFormatter::test_hasReturn() void TestAWScriptFormatter::test_copy() { - AWScriptFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWScriptFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->appendCode(), formatter->appendCode()); QCOMPARE(newFormatter->code(), formatter->code()); diff --git a/sources/test/testscriptformatter.h b/sources/test/testscriptformatter.h index 6b23e71..e99aa9c 100644 --- a/sources/test/testscriptformatter.h +++ b/sources/test/testscriptformatter.h @@ -41,7 +41,7 @@ private slots: private: AWScriptFormatter *formatter = nullptr; - QString code = QString("output = value"); + QString code = "output = value"; QString codeWithReturn = QString("%1; return output;").arg(code); QString fullCode = QString("(function(value) { %1 })").arg(codeWithReturn); }; diff --git a/sources/test/teststringformatter.cpp b/sources/test/teststringformatter.cpp index 1619cba..62bcb5d 100644 --- a/sources/test/teststringformatter.cpp +++ b/sources/test/teststringformatter.cpp @@ -65,13 +65,13 @@ void TestAWStringFormatter::test_fillChar() { // assign char c = AWTestLibrary::randomChar(); - formatter->setFillChar(QChar(c)); + formatter->setFillChar(c); QCOMPARE(formatter->fillChar(), QChar(c)); formatter->setCount(101); // test QString output = formatter->convert(AWTestLibrary::randomString()); - QVERIFY(output.startsWith(QChar(c))); + QVERIFY(output.startsWith(c)); // reset formatter->setFillChar(QChar()); @@ -100,7 +100,7 @@ void TestAWStringFormatter::test_forceWidth() void TestAWStringFormatter::test_copy() { doRandom(); - AWStringFormatter *newFormatter = formatter->copy(QString("/dev/null"), 1); + AWStringFormatter *newFormatter = formatter->copy("/dev/null", 1); QCOMPARE(newFormatter->count(), formatter->count()); QCOMPARE(newFormatter->fillChar(), formatter->fillChar()); @@ -114,7 +114,7 @@ void TestAWStringFormatter::test_copy() void TestAWStringFormatter::doRandom() { formatter->setCount(AWTestLibrary::randomInt()); - formatter->setFillChar(QChar(AWTestLibrary::randomChar())); + formatter->setFillChar(AWTestLibrary::randomChar()); formatter->setForceWidth(AWTestLibrary::randomInt() % 2); }