Replace yahoo finance to stooq (#131)

Old code is dropped to separated provider
This commit is contained in:
2017-12-15 02:01:34 +03:00
parent eb911551eb
commit e5a9e99438
134 changed files with 1213 additions and 1597 deletions

View File

@ -26,8 +26,7 @@
#include "awdebug.h"
AWAbstractPairConfig::AWAbstractPairConfig(QWidget *_parent,
const bool _hasEdit,
AWAbstractPairConfig::AWAbstractPairConfig(QWidget *_parent, const bool _hasEdit,
const QStringList &_keys)
: QDialog(_parent)
, ui(new Ui::AWAbstractPairConfig)
@ -43,8 +42,7 @@ AWAbstractPairConfig::AWAbstractPairConfig(QWidget *_parent,
// edit feature
if (m_hasEdit) {
m_editButton = ui->buttonBox->addButton(i18n("Edit"),
QDialogButtonBox::ActionRole);
m_editButton = ui->buttonBox->addButton(i18n("Edit"), QDialogButtonBox::ActionRole);
connect(m_editButton, SIGNAL(clicked(bool)), this, SLOT(edit()));
}
}
@ -86,10 +84,8 @@ void AWAbstractPairConfig::edit()
void AWAbstractPairConfig::updateUi()
{
QPair<QString, QString> current
= static_cast<AWAbstractSelector *>(sender())->current();
int index
= m_selectors.indexOf(static_cast<AWAbstractSelector *>(sender()));
QPair<QString, QString> current = static_cast<AWAbstractSelector *>(sender())->current();
int index = m_selectors.indexOf(static_cast<AWAbstractSelector *>(sender()));
if ((current.first.isEmpty()) && (current.second.isEmpty())) {
// remove current selector if it is empty and does not last
@ -108,15 +104,13 @@ void AWAbstractPairConfig::updateUi()
}
void AWAbstractPairConfig::addSelector(const QStringList &_keys,
const QStringList &_values,
void AWAbstractPairConfig::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;
AWAbstractSelector *selector
= new AWAbstractSelector(ui->scrollAreaWidgetContents, m_editable);
AWAbstractSelector *selector = new AWAbstractSelector(ui->scrollAreaWidgetContents, m_editable);
selector->init(_keys, _values, _current);
ui->verticalLayout->insertWidget(ui->verticalLayout->count() - 1, selector);
connect(selector, SIGNAL(selectionChanged()), this, SLOT(updateUi()));
@ -127,8 +121,7 @@ void AWAbstractPairConfig::addSelector(const QStringList &_keys,
void AWAbstractPairConfig::clearSelectors()
{
for (auto &selector : m_selectors) {
disconnect(selector, SIGNAL(selectionChanged()), this,
SLOT(updateUi()));
disconnect(selector, SIGNAL(selectionChanged()), this, SLOT(updateUi()));
ui->verticalLayout->removeWidget(selector);
selector->deleteLater();
}
@ -167,8 +160,7 @@ QPair<QStringList, QStringList> AWAbstractPairConfig::initKeys() const
left.append(m_helper->leftKeys().isEmpty() ? m_keys : m_helper->leftKeys());
left.sort();
QStringList right = {""};
right.append(m_helper->rightKeys().isEmpty() ? m_keys
: m_helper->rightKeys());
right.append(m_helper->rightKeys().isEmpty() ? m_keys : m_helper->rightKeys());
right.sort();
return QPair<QStringList, QStringList>(left, right);
@ -182,8 +174,7 @@ void AWAbstractPairConfig::updateDialog()
auto keys = initKeys();
for (auto &key : m_helper->keys())
addSelector(keys.first, keys.second,
QPair<QString, QString>(key, m_helper->pairs()[key]));
addSelector(keys.first, keys.second, QPair<QString, QString>(key, m_helper->pairs()[key]));
// empty one
addSelector(keys.first, keys.second, QPair<QString, QString>());
}

View File

@ -35,8 +35,7 @@ class AWAbstractPairConfig : public QDialog
Q_OBJECT
public:
explicit AWAbstractPairConfig(QWidget *_parent = nullptr,
const bool _hasEdit = false,
explicit AWAbstractPairConfig(QWidget *_parent = nullptr, const bool _hasEdit = false,
const QStringList &_keys = QStringList());
virtual ~AWAbstractPairConfig();
template <class T> void initHelper()

View File

@ -23,8 +23,7 @@
#include "awdebug.h"
AWAbstractPairHelper::AWAbstractPairHelper(const QString &_filePath,
const QString &_section)
AWAbstractPairHelper::AWAbstractPairHelper(const QString &_filePath, const QString &_section)
: m_filePath(_filePath)
, m_section(_section)
{
@ -62,8 +61,8 @@ void AWAbstractPairHelper::initItems()
{
m_pairs.clear();
QStringList configs = QStandardPaths::locateAll(
QStandardPaths::GenericDataLocation, m_filePath);
QStringList configs
= QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, m_filePath);
for (auto &fileName : configs) {
QSettings settings(fileName, QSettings::IniFormat);
@ -86,15 +85,14 @@ void AWAbstractPairHelper::initItems()
}
bool AWAbstractPairHelper::writeItems(
const QHash<QString, QString> &_configuration) const
bool AWAbstractPairHelper::writeItems(const QHash<QString, QString> &_configuration) const
{
qCDebug(LOG_AW) << "Write configuration" << _configuration;
QString fileName = QString("%1/%2")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QString fileName
= QString("%1/%2")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << fileName;
@ -113,10 +111,10 @@ bool AWAbstractPairHelper::removeUnusedKeys(const QStringList &_keys) const
{
qCDebug(LOG_AW) << "Remove keys" << _keys;
QString fileName = QString("%1/%2")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QString fileName
= QString("%1/%2")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << fileName;

View File

@ -25,16 +25,14 @@
class AWAbstractPairHelper
{
public:
explicit AWAbstractPairHelper(const QString &_filePath = "",
const QString &_section = "");
explicit AWAbstractPairHelper(const QString &_filePath = "", const QString &_section = "");
virtual ~AWAbstractPairHelper();
QStringList keys() const;
QHash<QString, QString> pairs() const;
QStringList values() const;
// read-write methods
virtual void initItems();
virtual bool
writeItems(const QHash<QString, QString> &_configuration) const;
virtual bool writeItems(const QHash<QString, QString> &_configuration) const;
virtual bool removeUnusedKeys(const QStringList &_keys) const;
// configuration related
virtual void editPairs() = 0;

View File

@ -21,8 +21,7 @@
#include "awdebug.h"
AWAbstractSelector::AWAbstractSelector(QWidget *_parent,
const QPair<bool, bool> &_editable)
AWAbstractSelector::AWAbstractSelector(QWidget *_parent, const QPair<bool, bool> &_editable)
: QWidget(_parent)
, ui(new Ui::AWAbstractSelector)
{
@ -32,10 +31,8 @@ AWAbstractSelector::AWAbstractSelector(QWidget *_parent,
ui->comboBox_key->setEditable(_editable.first);
ui->comboBox_value->setEditable(_editable.second);
connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this,
SIGNAL(selectionChanged()));
connect(ui->comboBox_value, SIGNAL(currentIndexChanged(int)), this,
SIGNAL(selectionChanged()));
connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this, SIGNAL(selectionChanged()));
connect(ui->comboBox_value, SIGNAL(currentIndexChanged(int)), this, SIGNAL(selectionChanged()));
}
@ -56,18 +53,15 @@ QPair<QString, QString> AWAbstractSelector::current() const
}
void AWAbstractSelector::init(const QStringList &_keys,
const QStringList &_values,
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
<< "not found in default ones";
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();

View File

@ -33,8 +33,7 @@ class AWAbstractSelector : public QWidget
public:
explicit AWAbstractSelector(QWidget *_parent = nullptr,
const QPair<bool, bool> &_editable
= {false, false});
const QPair<bool, bool> &_editable = {false, false});
virtual ~AWAbstractSelector();
QPair<QString, QString> current() const;
void init(const QStringList &_keys, const QStringList &_values,

View File

@ -61,8 +61,7 @@ QString AWActions::getFileContent(const QString &_path) const
QFile inputFile(_path);
if (!inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCWarning(LOG_AW) << "Could not open file as text"
<< inputFile.fileName();
qCWarning(LOG_AW) << "Could not open file as text" << inputFile.fileName();
return "";
}
@ -102,8 +101,7 @@ void AWActions::showLegacyInfo() const
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->setModal(false);
msgBox->setWindowTitle(i18n("Not supported"));
msgBox->setText(
i18n("You are using mammoth's Qt version, try to update it first"));
msgBox->setText(i18n("You are using mammoth's Qt version, try to update it first"));
msgBox->setStandardButtons(QMessageBox::Ok);
msgBox->setIcon(QMessageBox::Information);
@ -126,11 +124,9 @@ QVariantMap AWActions::getFont(const QVariantMap &_defaultFont) const
QVariantMap fontMap;
int ret = 0;
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);
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["applied"] = ret;
fontMap["color"] = font.color().name();
@ -142,13 +138,11 @@ QVariantMap AWActions::getFont(const QVariantMap &_defaultFont) const
// 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;
KNotification *notification = KNotification::event(
_eventId, QString("Awesome Widget ::: %1").arg(_eventId), _message);
notification->setComponentName(
"plasma-applet-org.kde.plasma.awesome-widget");
KNotification *notification
= KNotification::event(_eventId, QString("Awesome Widget ::: %1").arg(_eventId), _message);
notification->setComponentName("plasma-applet-org.kde.plasma.awesome-widget");
}

View File

@ -43,8 +43,7 @@ public:
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

@ -49,22 +49,18 @@ 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;
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("**Version**\n\n%1\n\n")
.arg(AWDebug::getBuildData().join(QString("\n")));
output += QString("**Version**\n\n%1\n\n").arg(AWDebug::getBuildData().join(QString("\n")));
// append _logs
output += QString("**Logs**\n\n%1").arg(_logs);
@ -74,8 +70,7 @@ QString AWBugReporter::generateText(const QString &_description,
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,
@ -90,10 +85,8 @@ void AWBugReporter::sendBugReport(const QString &_title, const QString &_body)
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"
<< data.size();
QByteArray data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact);
qCInfo(LOG_AW) << "Send request with _body" << data.data() << "and size" << data.size();
manager->post(request, data);
}
@ -102,8 +95,8 @@ void AWBugReporter::sendBugReport(const QString &_title, const QString &_body)
void AWBugReporter::issueReplyRecieved(QNetworkReply *_reply)
{
if (_reply->error() != QNetworkReply::NoError) {
qCWarning(LOG_AW) << "An error occurs" << _reply->error()
<< "with message" << _reply->errorString();
qCWarning(LOG_AW) << "An error occurs" << _reply->error() << "with message"
<< _reply->errorString();
return emit(replyReceived(0, ""));
}
@ -126,8 +119,7 @@ void AWBugReporter::issueReplyRecieved(QNetworkReply *_reply)
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;
@ -146,8 +138,7 @@ void AWBugReporter::showInformation(const int _number, const QString &_url)
void AWBugReporter::userReplyOnBugReport(QAbstractButton *_button)
{
QMessageBox::ButtonRole ret
= static_cast<QMessageBox *>(sender())->buttonRole(_button);
QMessageBox::ButtonRole ret = static_cast<QMessageBox *>(sender())->buttonRole(_button);
qCInfo(LOG_AW) << "User select" << ret;
switch (ret) {

View File

@ -33,10 +33,8 @@ public:
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 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:

View File

@ -34,8 +34,7 @@ AWConfigHelper::AWConfigHelper(QObject *_parent)
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_baseDir = QString("%1/awesomewidgets")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation));
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
}
@ -48,14 +47,13 @@ AWConfigHelper::~AWConfigHelper()
QString AWConfigHelper::configurationDirectory() const
{
// get readable directory
QString localDir = QString("%1/awesomewidgets/configs")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation));
QString localDir
= QString("%1/awesomewidgets/configs")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
// create directory and copy files from default settings
QDir localDirectory;
if ((!localDirectory.exists(localDir))
&& (localDirectory.mkpath(localDir))) {
if ((!localDirectory.exists(localDir)) && (localDirectory.mkpath(localDir))) {
qCInfo(LOG_AW) << "Created directory" << localDir;
copyConfigs(localDir);
}
@ -66,23 +64,21 @@ QString AWConfigHelper::configurationDirectory() const
bool AWConfigHelper::dropCache() const
{
QString fileName = QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericCacheLocation));
QString fileName
= QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation));
return QFile(fileName).remove();
}
bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig,
const QString &_fileName) const
bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig, const QString &_fileName) const
{
qCDebug(LOG_AW) << "Selected filename" << _fileName;
QSettings settings(_fileName, QSettings::IniFormat);
// plasmoid configuration
const QQmlPropertyMap *configuration
= static_cast<const QQmlPropertyMap *>(_nativeConfig);
const QQmlPropertyMap *configuration = static_cast<const QQmlPropertyMap *>(_nativeConfig);
settings.beginGroup("plasmoid");
for (auto &key : configuration->keys()) {
QVariant value = configuration->value(key);
@ -94,9 +90,8 @@ bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig,
// extensions
for (auto &item : m_dirs) {
QStringList items
= QDir(QString("%1/%2").arg(m_baseDir).arg(item))
.entryList(QStringList() << "*.desktop", QDir::Files);
QStringList items = QDir(QString("%1/%2").arg(m_baseDir).arg(item))
.entryList(QStringList() << "*.desktop", QDir::Files);
settings.beginGroup(item);
for (auto &it : items)
copyExtensions(it, item, settings, false);
@ -107,18 +102,15 @@ bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig,
settings.beginGroup("json");
// script filters
readFile(settings, "filters",
QString("%1/scripts/awesomewidgets-extscripts-filters.json")
.arg(m_baseDir));
QString("%1/scripts/awesomewidgets-extscripts-filters.json").arg(m_baseDir));
// weather icon settings
readFile(settings, "weathers",
QString("%1/weather/awesomewidgets-extweather-ids.json")
.arg(m_baseDir));
QString("%1/weather/awesomewidgets-extweather-ids.json").arg(m_baseDir));
settings.endGroup();
settings.beginGroup("ini");
// formatter settings
readFile(settings, "formatters",
QString("%1/formatters/formatters.ini").arg(m_baseDir));
readFile(settings, "formatters", QString("%1/formatters/formatters.ini").arg(m_baseDir));
// custom keys settings
readFile(settings, "custom", QString("%1/custom.ini").arg(m_baseDir));
settings.endGroup();
@ -155,18 +147,15 @@ QVariantMap AWConfigHelper::importConfiguration(const QString &_fileName,
settings.beginGroup("json");
// script filters
writeFile(settings, "filters",
QString("%1/scripts/awesomewidgets-extscripts-filters.json")
.arg(m_baseDir));
QString("%1/scripts/awesomewidgets-extscripts-filters.json").arg(m_baseDir));
// weather icon settings
writeFile(settings, "weathers",
QString("%1/weather/awesomewidgets-extweather-ids.json")
.arg(m_baseDir));
QString("%1/weather/awesomewidgets-extweather-ids.json").arg(m_baseDir));
settings.endGroup();
settings.beginGroup("ini");
// formatter settings
writeFile(settings, "formatters",
QString("%1/formatters/formatters.ini").arg(m_baseDir));
writeFile(settings, "formatters", QString("%1/formatters/formatters.ini").arg(m_baseDir));
// custom keys settings
writeFile(settings, "custom", QString("%1/custom.ini").arg(m_baseDir));
settings.endGroup();
@ -186,19 +175,17 @@ QVariantMap AWConfigHelper::importConfiguration(const QString &_fileName,
QVariantMap AWConfigHelper::readDataEngineConfiguration() const
{
QString fileName = QStandardPaths::locate(
QStandardPaths::ConfigLocation, "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("Configuration");
configuration["ACPIPATH"]
= settings.value("ACPIPATH", "/sys/class/power_supply/");
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["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");
@ -212,14 +199,12 @@ QVariantMap AWConfigHelper::readDataEngineConfiguration() const
}
bool AWConfigHelper::writeDataEngineConfiguration(
const QVariantMap &_configuration) const
bool AWConfigHelper::writeDataEngineConfiguration(const QVariantMap &_configuration) const
{
qCDebug(LOG_AW) << "Configuration" << _configuration;
QString fileName = QString("%1/plasma-dataengine-extsysmon.conf")
.arg(QStandardPaths::writableLocation(
QStandardPaths::ConfigLocation));
.arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation));
QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << settings.fileName();
@ -245,35 +230,31 @@ void AWConfigHelper::copyConfigs(const QString &_localDir) const
{
qCDebug(LOG_AW) << "Local directory" << _localDir;
QStringList dirs = QStandardPaths::locateAll(
QStandardPaths::GenericDataLocation, "awesomewidgets/configs",
QStandardPaths::LocateDirectory);
QStringList dirs
= QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "awesomewidgets/configs",
QStandardPaths::LocateDirectory);
for (auto &dir : dirs) {
if (dir == _localDir)
continue;
QStringList files = QDir(dir).entryList(QDir::Files);
for (auto &source : files) {
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"
<< destination << "with status" << status;
bool status = QFile::copy(QString("%1/%2").arg(dir).arg(source), destination);
qCInfo(LOG_AW) << "File" << source << "has been copied to" << destination
<< "with status" << status;
}
}
}
void AWConfigHelper::copyExtensions(const QString &_item, const QString &_type,
QSettings &_settings,
const bool _inverse) const
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);
QSettings itemSettings(
QString("%1/%2/%3").arg(m_baseDir).arg(_type).arg(_item),
QSettings::IniFormat);
QSettings itemSettings(QString("%1/%2/%3").arg(m_baseDir).arg(_type).arg(_item),
QSettings::IniFormat);
itemSettings.beginGroup("Desktop Entry");
if (_inverse)
copySettings(_settings, itemSettings);

View File

@ -34,31 +34,26 @@ public:
virtual ~AWConfigHelper();
Q_INVOKABLE QString configurationDirectory() const;
Q_INVOKABLE bool dropCache() const;
Q_INVOKABLE bool exportConfiguration(QObject *_nativeConfig,
const QString &_fileName) 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;
Q_INVOKABLE bool 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 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 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;
QStringList m_dirs
= {"desktops", "quotes", "scripts", "upgrade", "weather", "formatters"};
QStringList m_dirs = {"desktops", "quotes", "scripts", "upgrade", "weather", "formatters"};
};

View File

@ -21,8 +21,7 @@
#include "awdebug.h"
AWCustomKeysConfig::AWCustomKeysConfig(QWidget *_parent,
const QStringList &_keys)
AWCustomKeysConfig::AWCustomKeysConfig(QWidget *_parent, const QStringList &_keys)
: AWAbstractPairConfig(_parent, false, _keys)
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;

View File

@ -60,10 +60,9 @@ QString AWDataAggregator::htmlImage(const QPixmap &_source) const
QBuffer buffer(&byteArray);
_source.save(&buffer, "PNG");
return byteArray.isEmpty()
? ""
: QString("<img src=\"data:image/png;base64,%1\"/>")
.arg(QString(byteArray.toBase64()));
return byteArray.isEmpty() ? ""
: QString("<img src=\"data:image/png;base64,%1\"/>")
.arg(QString(byteArray.toBase64()));
}
@ -125,8 +124,7 @@ QPixmap AWDataAggregator::tooltipImage()
shift -= 100.0;
// apply pen color
if (key != "batTooltip")
pen.setColor(QColor(
m_configuration[QString("%1Color").arg(key)].toString()));
pen.setColor(QColor(m_configuration[QString("%1Color").arg(key)].toString()));
// paint data inside frame
for (int j = 0; j < m_values[key].count() - 1; j++) {
// some magic here
@ -136,11 +134,9 @@ QPixmap AWDataAggregator::tooltipImage()
float y2 = -std::fabs(m_values[key].at(j + 1)) * normY + 5.0f;
if (key == "batTooltip") {
if (m_values[key].at(j + 1) > 0)
pen.setColor(
QColor(m_configuration["batTooltipColor"].toString()));
pen.setColor(QColor(m_configuration["batTooltipColor"].toString()));
else
pen.setColor(QColor(
m_configuration["batInTooltipColor"].toString()));
pen.setColor(QColor(m_configuration["batInTooltipColor"].toString()));
}
m_toolTipScene->addLine(x1, y1, x2, y2, pen);
}
@ -163,33 +159,27 @@ void AWDataAggregator::dataUpdate(const QVariantHash &_values)
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(
"event", notificationText(_source, _value));
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(
"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,
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(
"event", notificationText(_source, _received));
return AWActions::sendNotification("event", notificationText(_source, _received));
}
@ -205,11 +195,9 @@ 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 == "batTooltip")
@ -227,11 +215,9 @@ QString AWDataAggregator::notificationText(const QString &_source,
}
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 == "netdev")
@ -245,8 +231,8 @@ void AWDataAggregator::setData(const QVariantHash &_values)
{
// do not log these arguments
// battery update requires info is AC online or not
setData(_values["ac"].toString() == m_configuration["acOnline"],
"batTooltip", _values["bat"].toFloat());
setData(_values["ac"].toString() == m_configuration["acOnline"], "batTooltip",
_values["bat"].toFloat());
// usual case
setData("cpuTooltip", _values["cpu"].toFloat(), 90.0);
setData("cpuclTooltip", _values["cpucl"].toFloat());
@ -267,16 +253,13 @@ void AWDataAggregator::setData(const QVariantHash &_values)
}
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["tooltipNumber"].toInt())
else if (m_values[_source].count() > m_configuration["tooltipNumber"].toInt())
m_values[_source].removeFirst();
if (std::isnan(_value))
_value = 0.0;
@ -286,8 +269,7 @@ void AWDataAggregator::setData(const QString &_source, float _value,
m_values[_source].append(_value);
if (_source == "downkbTooltip") {
QList<float> netValues
= m_values["downkbTooltip"] + m_values["upkbTooltip"];
QList<float> netValues = m_values["downkbTooltip"] + m_values["upkbTooltip"];
// to avoid inf value of normY
netValues << 1.0;
m_boundaries["downkbTooltip"]
@ -297,11 +279,10 @@ void AWDataAggregator::setData(const QString &_source, float _value,
}
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;

View File

@ -49,18 +49,15 @@ 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 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 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 QString &_source, float _value, const float _extremum = -1.0f);
// different signature for battery device
void setData(const bool _dontInvert, const QString &_source, float _value);
// variables

View File

@ -34,13 +34,12 @@ AWDataEngineAggregator::AWDataEngineAggregator(QObject *_parent)
m_dataEngines["time"] = m_consumer->dataEngine("time");
// additional method required by systemmonitor structure
m_newSourceConnection = connect(
m_dataEngines["systemmonitor"], &Plasma::DataEngine::sourceAdded,
[this](const QString source) {
emit(deviceAdded(source));
m_dataEngines["systemmonitor"]->connectSource(source, parent(),
1000);
});
m_newSourceConnection
= connect(m_dataEngines["systemmonitor"], &Plasma::DataEngine::sourceAdded,
[this](const QString source) {
emit(deviceAdded(source));
m_dataEngines["systemmonitor"]->connectSource(source, parent(), 1000);
});
// required to define Qt::QueuedConnection for signal-slot connection
qRegisterMetaType<Plasma::DataEngine::Data>("Plasma::DataEngine::Data");
@ -74,13 +73,12 @@ void AWDataEngineAggregator::reconnectSources(const int _interval)
m_dataEngines["extsysmon"]->connectAllSources(parent(), _interval);
m_dataEngines["time"]->connectSource("Local", parent(), 1000);
m_newSourceConnection = connect(
m_dataEngines["systemmonitor"], &Plasma::DataEngine::sourceAdded,
[this, _interval](const QString source) {
emit(deviceAdded(source));
m_dataEngines["systemmonitor"]->connectSource(source, parent(),
_interval);
});
m_newSourceConnection
= connect(m_dataEngines["systemmonitor"], &Plasma::DataEngine::sourceAdded,
[this, _interval](const QString source) {
emit(deviceAdded(source));
m_dataEngines["systemmonitor"]->connectSource(source, parent(), _interval);
});
#ifdef BUILD_FUTURE
createQueuedConnection();
@ -105,24 +103,18 @@ 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 = dataEngine == "time"
? QStringList() << "Local"
: m_dataEngines[dataEngine]->sources();
QStringList sources = dataEngine == "time" ? QStringList() << "Local"
: m_dataEngines[dataEngine]->sources();
// reconnect sources
for (auto &source : sources) {
Plasma::DataContainer *container
= m_dataEngines[dataEngine]->containerForSource(source);
// disconnect old connections first
disconnect(container,
SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data)),
parent(),
disconnect(container, SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data)), parent(),
SLOT(dataUpdated(QString, Plasma::DataEngine::Data)));
// and now reconnect with Qt::QueuedConnection type
connect(container,
SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data)),
parent(),
SLOT(dataUpdated(QString, Plasma::DataEngine::Data)),
Qt::QueuedConnection);
connect(container, SIGNAL(dataUpdated(QString, Plasma::DataEngine::Data)), parent(),
SLOT(dataUpdated(QString, Plasma::DataEngine::Data)), Qt::QueuedConnection);
}
}
}

View File

@ -23,8 +23,7 @@
#include "awformatterhelper.h"
AWDataEngineMapper::AWDataEngineMapper(QObject *_parent,
AWFormatterHelper *_custom)
AWDataEngineMapper::AWDataEngineMapper(QObject *_parent, AWFormatterHelper *_custom)
: QObject(_parent)
, m_customFormatters(_custom)
{
@ -59,8 +58,7 @@ AWDataEngineMapper::~AWDataEngineMapper()
}
AWKeysAggregator::FormatterType
AWDataEngineMapper::formatter(const QString &_key) const
AWKeysAggregator::FormatterType AWDataEngineMapper::formatter(const QString &_key) const
{
qCDebug(LOG_AW) << "Get formatter for key" << _key;
@ -78,8 +76,7 @@ QStringList AWDataEngineMapper::keysFromSource(const QString &_source) const
// HACK units required to define should the value be calculated as temperature
// or fan data
QStringList AWDataEngineMapper::registerSource(const QString &_source,
const QString &_units,
QStringList AWDataEngineMapper::registerSource(const QString &_source, const QString &_units,
const QStringList &_keys)
{
qCDebug(LOG_AW) << "Source" << _source << "with units" << _units;
@ -92,10 +89,8 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source,
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$");
QRegExp netRegExp = QRegExp("network/interfaces/.*/(receiver|transmitter)/data$");
QRegExp netTotalRegExp = QRegExp("network/interfaces/.*/(receiver|transmitter)/dataTotal$");
if (_source == "battery/ac") {
// AC
@ -106,9 +101,8 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source,
QString key = _source;
key.remove("battery/");
m_map[_source] = key;
m_formatter[key] = _source.contains("rate")
? AWKeysAggregator::FormatterType::Float
: AWKeysAggregator::FormatterType::IntegerThree;
m_formatter[key] = _source.contains("rate") ? AWKeysAggregator::FormatterType::Float
: AWKeysAggregator::FormatterType::IntegerThree;
} else if (_source == "cpu/system/TotalLoad") {
// cpu
m_map[_source] = "cpu";
@ -338,12 +332,10 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source,
// free swap
// mb
m_map[_source] = "swapfreemb";
m_formatter["swapfreemb"]
= AWKeysAggregator::FormatterType::MemMBFormat;
m_formatter["swapfreemb"] = AWKeysAggregator::FormatterType::MemMBFormat;
// gb
m_map.insertMulti(_source, "swapfreegb");
m_formatter["swapfreegb"]
= AWKeysAggregator::FormatterType::MemGBFormat;
m_formatter["swapfreegb"] = AWKeysAggregator::FormatterType::MemGBFormat;
} else if (_source == "mem/swap/used") {
// used swap
// mb
@ -361,9 +353,8 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source,
if (index > -1) {
QString key = QString("temp%1").arg(index);
m_map[_source] = key;
m_formatter[key]
= _units == "°C" ? AWKeysAggregator::FormatterType::Temperature
: AWKeysAggregator::FormatterType::Integer;
m_formatter[key] = _units == "°C" ? AWKeysAggregator::FormatterType::Temperature
: AWKeysAggregator::FormatterType::Integer;
}
} else if (_source == "Local") {
// time
@ -417,8 +408,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source,
QStringList customFormattersKeys;
if (m_customFormatters)
customFormattersKeys = m_customFormatters->definedFormatters();
qCInfo(LOG_AW) << "Looking for formatters" << foundKeys << "in"
<< customFormattersKeys;
qCInfo(LOG_AW) << "Looking for formatters" << foundKeys << "in" << customFormattersKeys;
for (auto &key : foundKeys) {
if (!customFormattersKeys.contains(key))
continue;
@ -427,11 +417,9 @@ QStringList AWDataEngineMapper::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;
bool required
= _keys.isEmpty() || std::any_of(foundKeys.cbegin(), foundKeys.cend(),
[&_keys](const QString &key) {
return _keys.contains(key);
});
bool required = _keys.isEmpty()
|| std::any_of(foundKeys.cbegin(), foundKeys.cend(),
[&_keys](const QString &key) { return _keys.contains(key); });
if (!required) {
m_map.remove(_source);
for (auto &key : foundKeys)

View File

@ -32,8 +32,7 @@ class AWDataEngineMapper : public QObject
Q_OBJECT
public:
explicit AWDataEngineMapper(QObject *_parent = nullptr,
AWFormatterHelper *_custom = nullptr);
explicit AWDataEngineMapper(QObject *_parent = nullptr, AWFormatterHelper *_custom = nullptr);
virtual ~AWDataEngineMapper();
// get methods
AWKeysAggregator::FormatterType formatter(const QString &_key) const;

View File

@ -40,8 +40,8 @@ AWDBusAdaptor::~AWDBusAdaptor()
QStringList AWDBusAdaptor::ActiveServices() const
{
QDBusMessage listServices = QDBusConnection::sessionBus().interface()->call(
QDBus::BlockWithGui, "ListNames");
QDBusMessage listServices
= QDBusConnection::sessionBus().interface()->call(QDBus::BlockWithGui, "ListNames");
if (listServices.arguments().isEmpty()) {
qCWarning(LOG_DBUS) << "Could not find any DBus service";
return {};
@ -86,8 +86,8 @@ void AWDBusAdaptor::SetLogLevel(const QString &what, const int level)
qCDebug(LOG_DBUS) << "Set log level" << level << "for" << what;
if (level >= m_logLevels.count()) {
qCDebug(LOG_DBUS) << "Invalid logging level" << level
<< "should be less than" << m_logLevels.count();
qCDebug(LOG_DBUS) << "Invalid logging level" << level << "should be less than"
<< m_logLevels.count();
return;
}
@ -96,19 +96,15 @@ void AWDBusAdaptor::SetLogLevel(const QString &what, const int level)
}
void AWDBusAdaptor::SetLogLevel(const QString &what, const QString &level,
const bool enabled)
void AWDBusAdaptor::SetLogLevel(const QString &what, const QString &level, const bool enabled)
{
qCDebug(LOG_DBUS) << "Set log level" << level << "enabled" << enabled
<< "for" << what;
qCDebug(LOG_DBUS) << "Set log level" << level << "enabled" << enabled << "for" << what;
if (!m_logLevels.contains(level)) {
qCDebug(LOG_DBUS) << "Invalid logging level" << level << "should be in"
<< m_logLevels;
qCDebug(LOG_DBUS) << "Invalid logging level" << level << "should be in" << m_logLevels;
return;
}
QString state = enabled ? "true" : "false";
QLoggingCategory::setFilterRules(
QString("%1.%2=%3").arg(what).arg(level).arg(state));
QLoggingCategory::setFilterRules(QString("%1.%2=%3").arg(what).arg(level).arg(state));
}

View File

@ -44,8 +44,7 @@ public slots:
qlonglong WhoAmI() const;
// set methods
void SetLogLevel(const QString &what, const int level);
void SetLogLevel(const QString &what, const QString &level,
const bool enabled);
void SetLogLevel(const QString &what, const QString &level, const bool enabled);
private:
AWKeys *m_plugin = nullptr;

View File

@ -35,8 +35,7 @@
AWFormatterHelper::AWFormatterHelper(QWidget *_parent)
: AbstractExtItemAggregator(_parent, "formatters")
, AWAbstractPairHelper("awesomewidgets/formatters/formatters.ini",
"Formatters")
, AWAbstractPairHelper("awesomewidgets/formatters/formatters.ini", "Formatters")
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
@ -63,8 +62,7 @@ void AWFormatterHelper::initItems()
for (auto &key : pairs().keys()) {
auto name = pairs()[key];
if (!m_formattersClasses.contains(name)) {
qCWarning(LOG_AW)
<< "Invalid formatter" << name << "found in" << key;
qCWarning(LOG_AW) << "Invalid formatter" << name << "found in" << key;
continue;
}
@ -73,13 +71,11 @@ void AWFormatterHelper::initItems()
}
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;
return m_formatters.contains(_name) ? m_formatters[_name]->convert(_value)
: _value.toString();
return m_formatters.contains(_name) ? m_formatters[_name]->convert(_value) : _value.toString();
}
@ -130,8 +126,7 @@ AWFormatterHelper::defineFormatterClass(const QString &_stringType) const
{
qCDebug(LOG_AW) << "Define formatter class for" << _stringType;
AWAbstractFormatter::FormatterClass formatter
= AWAbstractFormatter::FormatterClass::NoFormat;
AWAbstractFormatter::FormatterClass formatter = AWAbstractFormatter::FormatterClass::NoFormat;
if (_stringType == "DateTime")
formatter = AWAbstractFormatter::FormatterClass::DateTime;
else if (_stringType == "Float")
@ -177,32 +172,25 @@ void AWFormatterHelper::initFormatters()
auto metadata = readMetadata(filePath);
switch (metadata.second) {
case AWAbstractFormatter::FormatterClass::DateTime:
m_formattersClasses[metadata.first]
= new AWDateTimeFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWDateTimeFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::Float:
m_formattersClasses[metadata.first]
= new AWFloatFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWFloatFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::List:
m_formattersClasses[metadata.first]
= new AWListFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWListFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::Script:
m_formattersClasses[metadata.first]
= new AWScriptFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWScriptFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::String:
m_formattersClasses[metadata.first]
= new AWStringFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWStringFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::Json:
m_formattersClasses[metadata.first]
= new AWJsonFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWJsonFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::NoFormat:
m_formattersClasses[metadata.first]
= new AWNoFormatter(this, filePath);
m_formattersClasses[metadata.first] = new AWNoFormatter(this, filePath);
break;
}
}
@ -228,19 +216,17 @@ AWFormatterHelper::readMetadata(const QString &_filePath) const
void AWFormatterHelper::doCreateItem()
{
QStringList selection
= {"NoFormat", "DateTime", "Float", "List", "Script", "String", "Json"};
QStringList selection = {"NoFormat", "DateTime", "Float", "List", "Script", "String", "Json"};
bool ok;
QString select = QInputDialog::getItem(
this, i18n("Select type"), i18n("Type:"), selection, 0, false, &ok);
QString select
= QInputDialog::getItem(this, i18n("Select type"), i18n("Type:"), selection, 0, false, &ok);
if (!ok) {
qCWarning(LOG_AW) << "No type selected";
return;
}
qCInfo(LOG_AW) << "Selected type" << select;
AWAbstractFormatter::FormatterClass formatter
= defineFormatterClass(select);
AWAbstractFormatter::FormatterClass formatter = defineFormatterClass(select);
switch (formatter) {
case AWAbstractFormatter::FormatterClass::DateTime:
return createItem<AWDateTimeFormatter>();

View File

@ -24,8 +24,7 @@
#include "awabstractpairhelper.h"
class AWFormatterHelper : public AbstractExtItemAggregator,
public AWAbstractPairHelper
class AWFormatterHelper : public AbstractExtItemAggregator, public AWAbstractPairHelper
{
Q_OBJECT
@ -48,8 +47,7 @@ public slots:
private:
// methods
AWAbstractFormatter::FormatterClass
defineFormatterClass(const QString &_stringType) const;
AWAbstractFormatter::FormatterClass defineFormatterClass(const QString &_stringType) const;
void initFormatters();
QPair<QString, AWAbstractFormatter::FormatterClass>
readMetadata(const QString &_filePath) const;

View File

@ -29,9 +29,9 @@ bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key)
{
qCDebug(LOG_AW) << "Key" << _key << "with type" << _type;
QString fileName = QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericCacheLocation));
QString fileName
= QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation));
qCInfo(LOG_AW) << "Cache file" << fileName;
QSettings cache(fileName, QSettings::IniFormat);
@ -41,8 +41,7 @@ bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key)
cachedValues.append(cache.value(number).toString());
if (_type == "hdd") {
QStringList allDevices
= QDir("/dev").entryList(QDir::System, QDir::Name);
QStringList allDevices = 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);
@ -50,30 +49,23 @@ bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key)
continue;
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);
cache.setValue(QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), device);
}
} else if (_type == "net") {
QList<QNetworkInterface> rawInterfaceList
= QNetworkInterface::allInterfaces();
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;
cachedValues.append(device);
cache.setValue(
QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')),
device);
cache.setValue(QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), device);
}
} else {
if (cachedValues.contains(_key))
return false;
qCInfo(LOG_AW) << "Found new key" << _key << "for type" << _type;
cache.setValue(
QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')),
_key);
cache.setValue(QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), _key);
}
cache.endGroup();
@ -82,14 +74,12 @@ bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key)
}
QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys,
const QStringList &_bars,
const QVariantMap &_tooltip,
const QStringList &_userKeys,
QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys, const QStringList &_bars,
const QVariantMap &_tooltip, const QStringList &_userKeys,
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);
@ -110,8 +100,7 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys,
continue;
key.remove("hddtotmb");
int index = key.toInt();
used << QString("hddfreemb%1").arg(index)
<< QString("hddmb%1").arg(index);
used << QString("hddfreemb%1").arg(index) << QString("hddmb%1").arg(index);
}
// hddtotgb*
for (auto &key : _allKeys.filter(QRegExp("^hddtotgb"))) {
@ -119,8 +108,7 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys,
continue;
key.remove("hddtotgb");
int index = key.toInt();
used << QString("hddfreegb%1").arg(index)
<< QString("hddgb%1").arg(index);
used << QString("hddfreegb%1").arg(index) << QString("hddgb%1").arg(index);
}
// mem
if (used.contains("mem"))
@ -147,13 +135,12 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys,
used << "swapgb"
<< "swapfreegb";
// network keys
QStringList netKeys({"up", "upkb", "uptot", "uptotkb", "upunits", "down",
"downkb", "downtot", "downtotkb", "downunits"});
QStringList netKeys({"up", "upkb", "uptot", "uptotkb", "upunits", "down", "downkb", "downtot",
"downtotkb", "downunits"});
for (auto &key : netKeys) {
if (!used.contains(key))
continue;
QStringList filt
= _allKeys.filter(QRegExp(QString("^%1[0-9]{1,}").arg(key)));
QStringList filt = _allKeys.filter(QRegExp(QString("^%1[0-9]{1,}").arg(key)));
for (auto &filtered : filt)
used << filtered;
}
@ -173,9 +160,9 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys,
QHash<QString, QStringList> AWKeyCache::loadKeysFromCache()
{
QString fileName = QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericCacheLocation));
QString fileName
= QString("%1/awesomewidgets.ndx")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation));
qCInfo(LOG_AW) << "Cache file" << fileName;
QSettings cache(fileName, QSettings::IniFormat);

View File

@ -28,8 +28,7 @@ namespace AWKeyCache
{
bool addKeyToCache(const QString &_type, const QString &_key = "");
QStringList getRequiredKeys(const QStringList &_keys, const QStringList &_bars,
const QVariantMap &_tooltip,
const QStringList &_userKeys,
const QVariantMap &_tooltip, const QStringList &_userKeys,
const QStringList &_allKeys);
QHash<QString, QStringList> loadKeysFromCache();
};

View File

@ -41,10 +41,8 @@ AWKeyOperations::AWKeyOperations(QObject *_parent)
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_customKeys = new AWCustomKeysHelper(this);
m_graphicalItems
= new ExtItemAggregator<GraphicalItem>(nullptr, "desktops");
m_extNetRequest
= new ExtItemAggregator<ExtNetworkRequest>(nullptr, "requests");
m_graphicalItems = 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");
@ -134,8 +132,7 @@ QStringList AWKeyOperations::dictKeys() const
// battery
QStringList allBatteryDevices
= QDir("/sys/class/power_supply")
.entryList(QStringList({"BAT*"}),
QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
.entryList(QStringList({"BAT*"}), QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (int i = 0; i < allBatteryDevices.count(); i++) {
allKeys.append(QString("bat%1").arg(i));
allKeys.append(QString("batleft%1").arg(i));
@ -148,15 +145,12 @@ QStringList AWKeyOperations::dictKeys() const
allKeys.append(item->tag("pkgcount"));
// quotes
for (auto &item : m_extQuotes->activeItems()) {
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"));
allKeys.append(item->tag("volume"));
allKeys.append(item->tag("volumechg"));
allKeys.append(item->tag("percvolumechg"));
}
// custom
for (auto &item : m_extScripts->activeItems())
@ -228,8 +222,7 @@ QString AWKeyOperations::infoByKey(const QString &_key) const
QString index = _key;
index.remove(QRegExp("hdd[rw]"));
output = m_devices["disk"][index.toInt()];
} else if (_key.contains(
QRegExp("^hdd([0-9]|mb|gb|freemb|freegb|totmb|totgb)"))) {
} 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["mount"][index.toInt()];
@ -249,8 +242,7 @@ QString AWKeyOperations::infoByKey(const QString &_key) const
AbstractExtItem *item = m_extQuotes->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.contains(QRegExp(
"(weather|weatherId|humidity|pressure|temperature)"))) {
} else if (_key.contains(QRegExp("(weather|weatherId|humidity|pressure|temperature)"))) {
AbstractExtItem *item = m_extWeather->itemByTag(_key, stripped);
if (item)
output = item->uniq();
@ -289,8 +281,8 @@ void AWKeyOperations::editItem(const QString &_type)
qCDebug(LOG_AW) << "Item type" << _type;
if (_type == "graphicalitem") {
QStringList keys = dictKeys().filter(
QRegExp("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)"));
QStringList keys
= dictKeys().filter(QRegExp("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)"));
keys.sort();
m_graphicalItems->setConfigArgs(keys);
return m_graphicalItems->editItems();

View File

@ -62,11 +62,11 @@ AWKeys::AWKeys(QObject *_parent)
// transfer signal from AWDataAggregator object to QML ui
connect(m_dataAggregator, SIGNAL(toolTipPainted(const QString &)), this,
SIGNAL(needToolTipToBeUpdated(const QString &)));
connect(this, SIGNAL(dropSourceFromDataengine(const QString &)),
m_dataEngineAggregator, SLOT(dropSource(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 &)));
connect(m_dataEngineAggregator, SIGNAL(deviceAdded(const QString &)), m_keyOperator,
SLOT(addDevice(const QString &)));
}
@ -91,17 +91,15 @@ void AWKeys::initDataAggregator(const QVariantMap &_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_threadPool->setMaxThreadCount(_limit == 0 ? QThread::idealThreadCount() : _limit);
// child objects
m_aggregator->initFormatters();
m_keyOperator->setPattern(_currentPattern);
@ -138,8 +136,7 @@ void AWKeys::updateCache()
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 == "functions")
@ -190,8 +187,7 @@ QString AWKeys::valueByKey(const QString &_key) const
{
qCDebug(LOG_AW) << "Requested value for key" << _key;
QString trueKey
= _key.startsWith("bar") ? m_keyOperator->infoByKey(_key) : _key;
QString trueKey = _key.startsWith("bar") ? m_keyOperator->infoByKey(_key) : _key;
return m_aggregator->formatter(m_values[trueKey], trueKey);
}
@ -205,12 +201,10 @@ void AWKeys::editItem(const QString &_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);
}
@ -219,28 +213,24 @@ void AWKeys::reinitKeys(const QStringList &_currentKeys)
qCDebug(LOG_AW) << "Update found keys by using list" << _currentKeys;
// append lists
m_foundBars = AWPatternFunctions::findKeys(m_keyOperator->pattern(),
_currentKeys, true);
m_foundKeys = AWPatternFunctions::findKeys(m_keyOperator->pattern(),
_currentKeys, false);
m_foundBars = AWPatternFunctions::findKeys(m_keyOperator->pattern(), _currentKeys, true);
m_foundKeys = AWPatternFunctions::findKeys(m_keyOperator->pattern(), _currentKeys, false);
m_foundLambdas = AWPatternFunctions::findLambdas(m_keyOperator->pattern());
// generate list of required keys for bars
QStringList barKeys;
for (auto &bar : m_foundBars) {
GraphicalItem *item = m_keyOperator->giByKey(bar);
if (item->isCustom())
item->setUsedKeys(
AWPatternFunctions::findKeys(item->bar(), _currentKeys, false));
item->setUsedKeys(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,
m_keyOperator->requiredUserKeys(), _currentKeys)
: QStringList();
m_requiredKeys
= m_optimize ? AWKeyCache::getRequiredKeys(m_foundKeys, barKeys, m_tooltipParams,
m_keyOperator->requiredUserKeys(), _currentKeys)
: QStringList();
// set key data to m_aggregator
m_aggregator->setDevices(m_keyOperator->devices());
@ -278,17 +268,13 @@ void AWKeys::calculateValues()
}
// memtot*
m_values["memtotmb"]
= m_values["memusedmb"].toInt() + m_values["memfreemb"].toInt();
m_values["memtotgb"]
= m_values["memusedgb"].toFloat() + m_values["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["mem"]
= 100.0f * m_values["memmb"].toFloat() / m_values["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("net").indexOf(m_values["netdev"].toString());
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["downtot"] = m_values[QString("downtot%1").arg(netIndex)];
@ -301,13 +287,10 @@ void AWKeys::calculateValues()
m_values["upunits"] = m_values[QString("upunits%1").arg(netIndex)];
// swaptot*
m_values["swaptotmb"]
= m_values["swapmb"].toInt() + m_values["swapfreemb"].toInt();
m_values["swaptotgb"]
= m_values["swapgb"].toFloat() + m_values["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["swap"] = 100.0f * m_values["swapmb"].toFloat()
/ m_values["swaptotmb"].toFloat();
m_values["swap"] = 100.0f * m_values["swapmb"].toFloat() / m_values["swaptotmb"].toFloat();
// user defined keys
for (auto &key : m_keyOperator->userKeys())
@ -315,8 +298,7 @@ void AWKeys::calculateValues()
// lambdas
for (auto &key : m_foundLambdas)
m_values[key] = AWPatternFunctions::expandLambdas(
key, m_aggregator, m_values, m_foundKeys);
m_values[key] = AWPatternFunctions::expandLambdas(key, m_aggregator, m_values, m_foundKeys);
}
@ -329,8 +311,7 @@ void AWKeys::createDBusInterface()
QDBusConnection instanceBus = QDBusConnection::sessionBus();
// HACK we are going to use different services because it binds to
// application
if (instanceBus.registerService(
QString("%1.i%2").arg(AWDBUS_SERVICE).arg(id))) {
if (instanceBus.registerService(QString("%1.i%2").arg(AWDBUS_SERVICE).arg(id))) {
if (!instanceBus.registerObject(AWDBUS_PATH, new AWDBusAdaptor(this),
QDBusConnection::ExportAllContents))
qCWarning(LOG_AW) << "Could not register DBus object, last error"
@ -359,17 +340,15 @@ QString AWKeys::parsePattern(QString _pattern) const
// main keys
for (auto &key : m_foundKeys)
_pattern.replace(QString("$%1").arg(key),
m_aggregator->formatter(m_values[key], key));
_pattern.replace(QString("$%1").arg(key), m_aggregator->formatter(m_values[key], key));
// bars
for (auto &bar : m_foundBars) {
GraphicalItem *item = m_keyOperator->giByKey(bar);
QString image
= item->isCustom()
? item->image(AWPatternFunctions::expandLambdas(
item->bar(), m_aggregator, m_values, item->usedKeys()))
: item->image(m_values[item->bar()]);
QString image = item->isCustom()
? 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);
}
@ -382,16 +361,14 @@ QString AWKeys::parsePattern(QString _pattern) const
}
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;
// first list init
QStringList tags = m_aggregator->keysFromSource(_sourceName);
if (tags.isEmpty())
tags = m_aggregator->registerSource(
_sourceName, _data["units"].toString(), m_requiredKeys);
tags = m_aggregator->registerSource(_sourceName, _data["units"].toString(), m_requiredKeys);
// update data or drop source if there are no matches and exit
if (tags.isEmpty()) {
@ -401,10 +378,8 @@ void AWKeys::setDataBySource(const QString &_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 == "Local" ? _data["DateTime"]
: _data["value"];
});
std::for_each(tags.cbegin(), tags.cend(), [this, &_data, &_sourceName](const QString &tag) {
m_values[tag] = _sourceName == "Local" ? _data["DateTime"] : _data["value"];
});
m_mutex.unlock();
}

View File

@ -40,18 +40,15 @@ public:
explicit AWKeys(QObject *_parent = nullptr);
virtual ~AWKeys();
Q_INVOKABLE void initDataAggregator(const QVariantMap &_tooltipParams);
Q_INVOKABLE void initKeys(const QString &_currentPattern,
const int _interval, const int _limit,
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 setAggregatorProperty(const QString &_key, const QVariant &_value);
Q_INVOKABLE void setWrapNewLines(const bool _wrap);
// 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 = "") 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;
@ -60,8 +57,7 @@ public:
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 *){};

View File

@ -55,8 +55,7 @@ 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;
@ -86,8 +85,7 @@ QString AWKeysAggregator::formatter(const QVariant &_data,
output = _data.toBool() ? m_acOnline : m_acOffline;
break;
case FormatterType::MemGBFormat:
output
= QString("%1").arg(_data.toFloat() / (1024.0 * 1024.0), 5, 'f', 1);
output = 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);
@ -134,8 +132,7 @@ QString AWKeysAggregator::formatter(const QVariant &_data,
output = loc.toString(_data.toDateTime(), QLocale::ShortFormat);
break;
case FormatterType::Timestamp:
output = QString("%1").arg(
_data.toDateTime().toMSecsSinceEpoch() / 1000.0, 10, 'f', 0);
output = QString("%1").arg(_data.toDateTime().toMSecsSinceEpoch() / 1000.0, 10, 'f', 0);
break;
case FormatterType::Uptime:
case FormatterType::UptimeCustom:
@ -145,19 +142,14 @@ 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("$dd",
QString("%1").arg(days, 3, 10, QChar('0')));
source.replace("$dd", QString("%1").arg(days, 3, 10, QChar('0')));
source.replace("$d", QString("%1").arg(days));
source.replace("$hh",
QString("%1").arg(hours, 2, 10, QChar('0')));
source.replace("$hh", QString("%1").arg(hours, 2, 10, QChar('0')));
source.replace("$h", QString("%1").arg(hours));
source.replace("$mm",
QString("%1").arg(minutes, 2, 10, QChar('0')));
source.replace("$mm", QString("%1").arg(minutes, 2, 10, QChar('0')));
source.replace("$m", QString("%1").arg(minutes));
return source;
}(m_mapper->formatter(_key) == FormatterType::Uptime
? "$ddd$hhh$mmm"
: m_customUptime,
}(m_mapper->formatter(_key) == FormatterType::Uptime ? "$ddd$hhh$mmm" : m_customUptime,
static_cast<int>(_data.toFloat()));
break;
case FormatterType::NoFormat:
@ -241,8 +233,7 @@ void AWKeysAggregator::setTranslate(const bool _translate)
}
QStringList AWKeysAggregator::registerSource(const QString &_source,
const QString &_units,
QStringList AWKeysAggregator::registerSource(const QString &_source, const QString &_units,
const QStringList &_keys)
{
qCDebug(LOG_AW) << "Source" << _source << "with units" << _units;

View File

@ -32,8 +32,7 @@ class AWKeysAggregator : public QObject
Q_PROPERTY(QString acOffline MEMBER m_acOffline WRITE setAcOffline);
Q_PROPERTY(QString acOnline MEMBER m_acOnline WRITE setAcOnline);
Q_PROPERTY(QString customTime MEMBER m_customTime WRITE setCustomTime);
Q_PROPERTY(
QString customUptime MEMBER m_customUptime WRITE setCustomUptime);
Q_PROPERTY(QString customUptime MEMBER m_customUptime WRITE setCustomUptime);
Q_PROPERTY(QString tempUnits MEMBER m_tempUnits WRITE setTempUnits);
Q_PROPERTY(bool translate MEMBER m_translate WRITE setTranslate);

View File

@ -24,8 +24,7 @@
#include "awkeysaggregator.h"
QString AWPatternFunctions::expandLambdas(QString _code,
AWKeysAggregator *_aggregator,
QString AWPatternFunctions::expandLambdas(QString _code, AWKeysAggregator *_aggregator,
const QVariantHash &_metadata,
const QStringList &_usedKeys)
{
@ -41,9 +40,8 @@ QString AWPatternFunctions::expandLambdas(QString _code,
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();
qCWarning(LOG_AW) << "Uncaught exception at line" << result.property("lineNumber").toInt()
<< ":" << result.toString();
return "";
} else {
return result.toString();
@ -57,8 +55,7 @@ QString AWPatternFunctions::expandTemplates(QString _code)
// match the following construction $template{{some code here}}
QRegularExpression templatesRegexp("\\$template\\{\\{(?<body>.*?)\\}\\}");
templatesRegexp.setPatternOptions(
QRegularExpression::DotMatchesEverythingOption);
templatesRegexp.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator it = templatesRegexp.globalMatch(_code);
while (it.hasNext()) {
@ -71,8 +68,7 @@ QString AWPatternFunctions::expandTemplates(QString _code)
QString templateResult = "";
if (result.isError()) {
qCWarning(LOG_AW) << "Uncaught exception at line"
<< result.property("lineNumber").toInt() << ":"
<< result.toString();
<< result.property("lineNumber").toInt() << ":" << result.toString();
} else {
templateResult = result.toString();
}
@ -86,8 +82,7 @@ QString AWPatternFunctions::expandTemplates(QString _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;
@ -98,8 +93,7 @@ AWPatternFunctions::findFunctionCalls(const QString &_function,
// * body depends on the function name, double brackets should be screened
// by using $, e.g. ${
QRegularExpression regex(
QString("\\$%1\\<(?<args>.*?)\\>\\{\\{(?<body>.*?)\\}\\}")
.arg(_function));
QString("\\$%1\\<(?<args>.*?)\\>\\{\\{(?<body>.*?)\\}\\}").arg(_function));
regex.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QList<AWPatternFunctions::AWFunction> foundFunctions;
@ -116,9 +110,8 @@ AWPatternFunctions::findFunctionCalls(const QString &_function,
// replace '$,' to 0x1d
argsString.replace("$,", QString(0x1d));
QStringList args = argsString.split(',');
std::for_each(args.begin(), args.end(), [](QString &arg) {
arg.replace(QString(0x1d), ",");
});
std::for_each(args.begin(), args.end(),
[](QString &arg) { arg.replace(QString(0x1d), ","); });
metadata.args = args;
}
// other variables
@ -134,20 +127,17 @@ 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("aw_all", _code);
for (auto &function : found) {
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);
});
std::for_each(required.begin(), required.end(),
[](QString &value) { value = QString("%1: $%1").arg(value); });
_code.replace(function.what, required.join(separator));
}
@ -156,11 +146,9 @@ QString AWPatternFunctions::insertAllKeys(QString _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("aw_count", _code);
@ -174,11 +162,9 @@ QString AWPatternFunctions::insertKeyCount(QString _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("aw_names", _code);
@ -195,17 +181,15 @@ QString AWPatternFunctions::insertKeyNames(QString _code,
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("aw_keys", _code);
for (auto &function : found) {
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);
});
std::for_each(required.begin(), required.end(),
[](QString &value) { value = QString("$%1").arg(value); });
_code.replace(function.what, required.join(separator));
}
@ -229,13 +213,11 @@ QString AWPatternFunctions::insertMacros(QString _code)
QString name = macro.args.takeFirst();
// find macro usage
QList<AWPatternFunctions::AWFunction> macroUsage
= AWPatternFunctions::findFunctionCalls(
QString("aw_macro_%1").arg(name), _code);
= AWPatternFunctions::findFunctionCalls(QString("aw_macro_%1").arg(name), _code);
for (auto &function : macroUsage) {
if (function.args.count() != macro.args.count()) {
qCWarning(LOG_AW)
<< "Invalid args count found for call" << function.what
<< "with macro" << macro.what;
qCWarning(LOG_AW) << "Invalid args count found for call" << function.what
<< "with macro" << macro.what;
continue;
}
// generate body to replace
@ -243,8 +225,7 @@ QString AWPatternFunctions::insertMacros(QString _code)
std::for_each(macro.args.cbegin(), macro.args.cend(),
[&result, macro, function](const QString &arg) {
int index = macro.args.indexOf(arg);
result.replace(QString("$%1").arg(arg),
function.args.at(index));
result.replace(QString("$%1").arg(arg), function.args.at(index));
});
// do replace
_code.replace(function.what, result);
@ -258,20 +239,17 @@ QString AWPatternFunctions::insertMacros(QString _code)
}
QStringList AWPatternFunctions::findKeys(const QString &_code,
const QStringList &_keys,
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("bar") == _isBars)
&& (replacedCode.contains(QString("$%1").arg(key)))) {
qCInfo(LOG_AW) << "Found key" << key << "with bar enabled"
<< _isBars;
qCInfo(LOG_AW) << "Found key" << key << "with bar enabled" << _isBars;
selectedKeys.append(key);
replacedCode.replace(QString("$%1").arg(key), "");
}
@ -289,8 +267,7 @@ QStringList AWPatternFunctions::findLambdas(const QString &_code)
QStringList selectedKeys;
// match the following construction ${{some code here}}
QRegularExpression lambdaRegexp("\\$\\{\\{(?<body>.*?)\\}\\}");
lambdaRegexp.setPatternOptions(
QRegularExpression::DotMatchesEverythingOption);
lambdaRegexp.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator it = lambdaRegexp.globalMatch(_code);
while (it.hasNext()) {

View File

@ -34,20 +34,17 @@ typedef struct {
} AWFunction;
// insert methods
QString expandLambdas(QString _code, AWKeysAggregator *_aggregator,
const QVariantHash &_metadata,
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);
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 findKeys(const QString &_code, const QStringList &_keys, const bool _isBars);
QStringList findLambdas(const QString &_code);
};

View File

@ -27,15 +27,13 @@
#include "awdebug.h"
AWTelemetryHandler::AWTelemetryHandler(QObject *_parent,
const QString &_clientId)
AWTelemetryHandler::AWTelemetryHandler(QObject *_parent, const QString &_clientId)
: QObject(_parent)
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_localFile = QString("%1/awesomewidgets/telemetry.ini")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation));
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
// override client id if any
if (!_clientId.isEmpty())
@ -73,11 +71,10 @@ QString AWTelemetryHandler::getLast(const QString &_group) const
}
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;
@ -87,8 +84,7 @@ void AWTelemetryHandler::init(const int _count, const bool _enableRemote,
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);
@ -99,8 +95,7 @@ bool AWTelemetryHandler::put(const QString &_group, const QString &_value) const
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
<< "is already saved";
qCInfo(LOG_AW) << "Configuration" << _value << "for group" << _group << "is already saved";
return false;
}
saved.append(_value);
@ -123,11 +118,9 @@ 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;
@ -148,10 +141,8 @@ void AWTelemetryHandler::uploadTelemetry(const QString &_group,
payload["metadata"] = _value;
payload["type"] = _group;
// 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"
<< data.size();
QByteArray data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact);
qCInfo(LOG_AW) << "Send request with body" << data.data() << "and size" << data.size();
manager->post(request, data);
}
@ -160,8 +151,8 @@ void AWTelemetryHandler::uploadTelemetry(const QString &_group,
void AWTelemetryHandler::telemetryReplyRecieved(QNetworkReply *_reply)
{
if (_reply->error() != QNetworkReply::NoError) {
qCWarning(LOG_AW) << "An error occurs" << _reply->error()
<< "with message" << _reply->errorString();
qCWarning(LOG_AW) << "An error occurs" << _reply->error() << "with message"
<< _reply->errorString();
return;
}

View File

@ -31,16 +31,13 @@ class AWTelemetryHandler : public QObject
public:
const char *REMOTE_TELEMETRY_URL = "https://arcanis.me/telemetry";
explicit AWTelemetryHandler(QObject *_parent = nullptr,
const QString &_clientId = "");
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 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 void uploadTelemetry(const QString &_group, const QString &_value);
signals:
void replyReceived(const QString &_message);

View File

@ -34,9 +34,9 @@ AWUpdateHelper::AWUpdateHelper(QObject *_parent)
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_foundVersion = QVersionNumber::fromString(VERSION);
m_genericConfig = QString("%1/awesomewidgets/general.ini")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation));
m_genericConfig
= QString("%1/awesomewidgets/general.ini")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
}
@ -53,10 +53,9 @@ void AWUpdateHelper::checkUpdates(const bool _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);
});
connect(manager, &QNetworkAccessManager::finished, [_showAnyway, this](QNetworkReply *reply) {
return versionReplyRecieved(reply, _showAnyway);
});
manager->get(QNetworkRequest(QUrl(VERSION_API)));
}
@ -65,17 +64,16 @@ void AWUpdateHelper::checkUpdates(const bool _showAnyway)
bool AWUpdateHelper::checkVersion()
{
QSettings settings(m_genericConfig, QSettings::IniFormat);
QVersionNumber version = QVersionNumber::fromString(
settings.value("Version", QString(VERSION)).toString());
QVersionNumber version
= QVersionNumber::fromString(settings.value("Version", QString(VERSION)).toString());
// update version
settings.setValue("Version", QString(VERSION));
settings.sync();
qCInfo(LOG_AW) << "Found version" << version << "actual one is"
<< m_foundVersion;
qCInfo(LOG_AW) << "Found version" << version << "actual one is" << m_foundVersion;
if ((version != m_foundVersion) && (!QString(CHANGELOG).isEmpty())) {
genMessageBox(i18n("Changelog of %1", VERSION),
QString(CHANGELOG).replace('@', '\n'), QMessageBox::Ok)
genMessageBox(i18n("Changelog of %1", VERSION), QString(CHANGELOG).replace('@', '\n'),
QMessageBox::Ok)
->open();
return true;
} else if (version != m_foundVersion) {
@ -93,12 +91,10 @@ void AWUpdateHelper::showInfo(const QVersionNumber &_version)
{
qCDebug(LOG_AW) << "Version" << _version;
QString text
= i18n("You are using the actual version %1", _version.toString());
QString text = 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)
->open();
return genMessageBox(i18n("No new version found"), text, QMessageBox::Ok)->open();
}
@ -108,28 +104,23 @@ void AWUpdateHelper::showUpdates(const QVersionNumber &_version)
QString text;
text += i18n("Current version : %1", VERSION);
text += QString(COMMIT_SHA).isEmpty()
? "\n"
: QString(" (%1)\n").arg(QString(COMMIT_SHA));
text += QString(COMMIT_SHA).isEmpty() ? "\n" : QString(" (%1)\n").arg(QString(COMMIT_SHA));
text += i18n("New version : %1", _version.toString()) + "\n\n";
text += i18n("Click \"Ok\" to download");
genMessageBox(i18n("There are updates"), text,
QMessageBox::Ok | QMessageBox::Cancel)
genMessageBox(i18n("There are updates"), text, QMessageBox::Ok | QMessageBox::Cancel)
->open(this, SLOT(userReplyOnUpdates(QAbstractButton *)));
}
void AWUpdateHelper::userReplyOnUpdates(QAbstractButton *_button)
{
QMessageBox::ButtonRole ret
= static_cast<QMessageBox *>(sender())->buttonRole(_button);
QMessageBox::ButtonRole ret = static_cast<QMessageBox *>(sender())->buttonRole(_button);
qCInfo(LOG_AW) << "User select" << ret;
switch (ret) {
case QMessageBox::AcceptRole:
QDesktopServices::openUrl(QString(RELEASES)
+ m_foundVersion.toString());
QDesktopServices::openUrl(QString(RELEASES) + m_foundVersion.toString());
break;
case QMessageBox::RejectRole:
default:
@ -138,13 +129,12 @@ 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();
qCWarning(LOG_AW) << "An error occurs" << _reply->error() << "with message"
<< _reply->errorString();
return;
}
@ -172,12 +162,10 @@ void AWUpdateHelper::versionReplyRecieved(QNetworkReply *_reply,
// 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)
QMessageBox *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);