massive refactoring

This commit is contained in:
2017-05-05 17:55:52 +03:00
parent 6e62ceaac7
commit d0c96ce829
152 changed files with 3041 additions and 3219 deletions

View File

@ -21,16 +21,16 @@
#include "awdebug.h"
AWAbstractSelector::AWAbstractSelector(QWidget *parent,
const QPair<bool, bool> &editable)
: QWidget(parent)
AWAbstractSelector::AWAbstractSelector(QWidget *_parent,
const QPair<bool, bool> &_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<QString, QString> AWAbstractSelector::current() const
}
void AWAbstractSelector::init(const QStringList &keys,
const QStringList &values,
const QPair<QString, QString> &current)
void AWAbstractSelector::init(const QStringList &_keys,
const QStringList &_values,
const QPair<QString, QString> &_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);
}

View File

@ -32,13 +32,13 @@ class AWAbstractSelector : public QWidget
Q_OBJECT
public:
explicit AWAbstractSelector(QWidget *parent = nullptr,
const QPair<bool, bool> &editable
explicit AWAbstractSelector(QWidget *_parent = nullptr,
const QPair<bool, bool> &_editable
= {false, false});
virtual ~AWAbstractSelector();
QPair<QString, QString> current() const;
void init(const QStringList &keys, const QStringList &values,
const QPair<QString, QString> &current);
void init(const QStringList &_keys, const QStringList &_values,
const QPair<QString, QString> &_current);
signals:
void selectionChanged();

View File

@ -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");
}

View File

@ -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;

View File

@ -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<QMessageBox *>(sender())->buttonRole(button);
= static_cast<QMessageBox *>(sender())->buttonRole(_button);
qCInfo(LOG_AW) << "User select" << ret;
switch (ret) {

View File

@ -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;

View File

@ -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<const QQmlPropertyMap *>(nativeConfig);
settings.beginGroup(QString("plasmoid"));
= static_cast<const QQmlPropertyMap *>(_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 {

View File

@ -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";
};

View File

@ -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<float> AWDataAggregator::getData(const QString &key) const
QList<float> 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("<img src=\"data:image/png;base64,%1\"/>")
.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<QVariantHash>(settings);
m_configuration = qvariant_cast<QVariantHash>(_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 &current,
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<float> netValues = m_values[QString("downkbTooltip")]
+ m_values[QString("upkbTooltip")];
m_values[_source].append(_value);
if (_source == "downkbTooltip") {
QList<float> 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);
}

View File

@ -33,42 +33,43 @@ class AWDataAggregator : public QObject
Q_OBJECT
public:
explicit AWDataAggregator(QObject *parent = nullptr);
explicit AWDataAggregator(QObject *_parent = nullptr);
virtual ~AWDataAggregator();
QList<float> getData(const QString &key) const;
QString htmlImage(const QPixmap &source) const;
void setParameters(const QVariantMap &settings);
QList<float> 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 &current,
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<QString, float> m_boundaries;
QHash<QString, QList<float>> m_values;
bool m_enablePopup = false;

View File

@ -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

View File

@ -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();

View File

@ -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));
}

View File

@ -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";
};

View File

@ -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<QString, QString> &current)
void AWFormatterConfig::addSelector(const QStringList &_keys,
const QStringList &_values,
const QPair<QString, QString> &_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<QStringList, QStringList> 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();

View File

@ -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<QString, QString> &current);
void addSelector(const QStringList &_keys, const QStringList &_values,
const QPair<QString, QString> &_current);
void clearSelectors();
void execDialog();
void init();

View File

@ -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();
}

View File

@ -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:
};

View File

@ -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<QString, QString> &configuration) const
const QHash<QString, QString> &_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<QString, AWAbstractFormatter::FormatterClass>
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);

View File

@ -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<QString, QString> getFormatters() const;
QList<AbstractExtItem *> items() const;
QStringList knownFormatters() const;
bool removeUnusedFormatters(const QStringList &keys) const;
bool writeFormatters(const QHash<QString, QString> &configuration) const;
bool removeUnusedFormatters(const QStringList &_keys) const;
bool writeFormatters(const QHash<QString, QString> &_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<QString, AWAbstractFormatter::FormatterClass>
readMetadata(const QString &filePath) const;
readMetadata(const QString &_filePath) const;
// parent methods
void doCreateItem();
void initItems();

View File

@ -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<QNetworkInterface> 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<QString> used = QSet<QString>::fromList(keys);
used.unite(QSet<QString>::fromList(bars));
QSet<QString> used = QSet<QString>::fromList(_keys);
used.unite(QSet<QString>::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();
}

View File

@ -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<QString, QStringList> loadKeysFromCache();
};

View File

@ -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<QString, QStringList> 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 &currentPattern)
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<GraphicalItem>(nullptr, QString("desktops"));
m_extNetRequest = new ExtItemAggregator<ExtNetworkRequest>(
nullptr, QString("requests"));
m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, QString("quotes"));
m_extScripts
= new ExtItemAggregator<ExtScript>(nullptr, QString("scripts"));
m_extUpgrade
= new ExtItemAggregator<ExtUpgrade>(nullptr, QString("upgrade"));
m_extWeather
= new ExtItemAggregator<ExtWeather>(nullptr, QString("weather"));
= new ExtItemAggregator<GraphicalItem>(nullptr, "desktops");
m_extNetRequest
= new ExtItemAggregator<ExtNetworkRequest>(nullptr, "requests");
m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, "quotes");
m_extScripts = new ExtItemAggregator<ExtScript>(nullptr, "scripts");
m_extUpgrade = new ExtItemAggregator<ExtUpgrade>(nullptr, "upgrade");
m_extWeather = new ExtItemAggregator<ExtWeather>(nullptr, "weather");
// init
QStringList allKeys = dictKeys();

View File

@ -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<QString, QStringList> 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 &currentPattern);
void setPattern(const QString &_currentPattern);
// configuration
void editItem(const QString &type);
void editItem(const QString &_type);
signals:
void updateKeys(const QStringList &currentKeys);
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<GraphicalItem> *m_graphicalItems = nullptr;

View File

@ -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 &currentPattern, 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 &regexp) 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 &currentKeys)
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 &currentKeys)
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("&nbsp;"));
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(" ", "&nbsp;");
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("<br>"));
_pattern.replace("\n", "<br>");
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();
}

View File

@ -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 &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);
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 &regexp = 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 &currentKeys);
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;

View File

@ -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<int>(data.toFloat()));
}(m_formatter[_key] == FormatterType::Uptime ? "$ddd$hhh$mmm"
: m_customUptime,
static_cast<int>(_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<QString, QStringList> &devices)
void AWKeysAggregator::setDevices(const QHash<QString, QStringList> &_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;

View File

@ -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<QString, QStringList> &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<QString, QStringList> &_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;

View File

@ -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\\{\\{(?<body>.*?)\\}\\}"));
QRegularExpression templatesRegexp("\\$template\\{\\{(?<body>.*?)\\}\\}");
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::AWFunction>
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<some args here if any>{{function body}}
@ -100,34 +99,34 @@ AWPatternFunctions::findFunctionCalls(const QString &function,
// by using $, e.g. ${
QRegularExpression regex(
QString("\\$%1\\<(?<args>.*?)\\>\\{\\{(?<body>.*?)\\}\\}")
.arg(function));
.arg(_function));
regex.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QList<AWPatternFunctions::AWFunction> 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<AWPatternFunctions::AWFunction> 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<AWPatternFunctions::AWFunction> 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<AWPatternFunctions::AWFunction> 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<AWPatternFunctions::AWFunction> 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<AWPatternFunctions::AWFunction> found
= AWPatternFunctions::findFunctionCalls(QString("aw_macro"), code);
= AWPatternFunctions::findFunctionCalls("aw_macro", _code);
for (auto &macro : found) {
// get macro params
if (macro.args.isEmpty()) {
@ -233,7 +230,7 @@ QString AWPatternFunctions::insertMacros(QString code)
// find macro usage
QList<AWPatternFunctions::AWFunction> 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("\\$\\{\\{(?<body>.*?)\\}\\}"));
QRegularExpression lambdaRegexp("\\$\\{\\{(?<body>.*?)\\}\\}");
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;

View File

@ -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<AWFunction> 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<AWFunction> 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);
};

View File

@ -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'));
}

View File

@ -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;

View File

@ -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<QMessageBox *>(sender())->buttonRole(button);
= static_cast<QMessageBox *>(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;

View File

@ -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;
};